Page navigation with previous and next links and collapsed page ranges.
use gpui::{div, prelude::*, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::pagination::Pagination;
const TOTAL_PAGES: usize = 12;
pub struct InvoiceList {
page: usize,
}
// Pages count from 1, so `Default` is written out instead of derived.
impl Default for InvoiceList {
fn default() -> Self {
Self { page: 1 }
}
}
impl Render for InvoiceList {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
div()
.flex()
.flex_col()
.items_center()
.gap_4()
.child(
Pagination::new("invoices", self.page, TOTAL_PAGES).on_change(cx.listener(
|this, page: &usize, _, cx| {
this.page = *page;
cx.notify();
},
)),
)
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child(format!("Page {} of {TOTAL_PAGES}", self.page)),
)
}
}Installation
Copies src/ui/pagination.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Install the icons
This component draws icons from
crate::icons. Copy src/icons.rs into your project and declaremod icons;next tomod theme;.Copy the source
Paste the code below into
src/ui/pagination.rs.src/ui/pagination.rs use std::{cell::Cell, rc::Rc, sync::Arc}; use gpui::{ div, prelude::*, px, svg, AnimationExt, AnyElement, App, ElementId, Entity, FontWeight, Hsla, Interpolate, Pixels, SharedString, SpringAnimation, SpringAnimationElement, SpringConfig, Div, Stateful, Window, }; use crate::theme::ActiveTheme; use crate::icons::{CHEVRON_LEFT, CHEVRON_RIGHT, ELLIPSIS}; type ChangeHandler = Rc<dyn Fn(&usize, &mut Window, &mut App) + 'static>; /// An item's transition key, state and target colors, applied once it has its content. type Eased = (ElementId, Entity<Ease>, Paint); const ITEM: Pixels = px(36.0); /// Up to this many pages are listed in full; beyond it, runs of pages collapse into an ellipsis. const MAX_SLOTS: usize = 7; #[derive(Clone, Copy, PartialEq)] enum Slot { Page(usize), Gap, } /// Page navigation with previous/next links. Pages are numbered from 1. The parent view /// owns `page` and updates it in `on_change`; out-of-range pages are clamped for display. #[derive(IntoElement)] pub struct Pagination { id: ElementId, page: usize, total_pages: usize, on_change: Option<ChangeHandler>, controls: bool, page_numbers: bool, icon_only: bool, } impl Pagination { pub fn new(id: impl Into<ElementId>, page: usize, total_pages: usize) -> Self { Self { id: id.into(), page, total_pages, on_change: None, controls: true, page_numbers: true, icon_only: false, } } /// Shows the Previous and Next links. On by default; turn off for a bare row of page numbers. pub fn controls(mut self, controls: bool) -> Self { self.controls = controls; self } /// Shows the numbered page links. On by default; turn off to page with Previous and Next /// alone, as in data tables. pub fn page_numbers(mut self, page_numbers: bool) -> Self { self.page_numbers = page_numbers; self } /// Draws Previous and Next as square chevron buttons without their labels. pub fn icon_only(mut self, icon_only: bool) -> Self { self.icon_only = icon_only; self } pub fn on_change(mut self, handler: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self { self.on_change = Some(Rc::new(handler)); self } } /// Always `MAX_SLOTS` wide once collapsed, so the row doesn't change width as you page. fn slots(page: usize, total: usize) -> Vec<Slot> { if total <= MAX_SLOTS { return (1..=total).map(Slot::Page).collect(); } let near_start = page <= 4; let near_end = page + 3 >= total; let middle: Vec<usize> = if near_start { (2..=5).collect() } else if near_end { (total - 4..total).collect() } else { (page - 1..=page + 1).collect() }; let mut slots = vec![Slot::Page(1)]; if !near_start { slots.push(Slot::Gap); } slots.extend(middle.into_iter().map(Slot::Page)); if !near_end { slots.push(Slot::Gap); } slots.push(Slot::Page(total)); slots } impl RenderOnce for Pagination { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme().clone(); let total = self.total_pages; let page = self.page.clamp(1, total.max(1)); let handler = self.on_change; let group_id = Arc::new(self.id.clone()); let clear = gpui::transparent_black(); let icon = |data: &'static [u8]| svg().data(data).flex_none().size(px(16.0)).text_color(theme.foreground); // Every clickable item shares the ghost button look; the current page is outlined. // Colors ease between those looks and the hover, like shadcn's `transition-all`. let item = |id: SharedString, target: Option<usize>, active: bool, window: &mut Window, cx: &mut App| { let clickable = target.is_some(); // The current page isn't a link, but it shouldn't look disabled either. let disabled = !clickable && !active; let key = ElementId::NamedChild(group_id.clone(), id.clone()); let ease = ease_state(key.clone(), window, cx); let hovered = ease.read(cx).hovered && clickable; let paint = if active { Paint { bg: theme.background, fg: theme.foreground, border: theme.input } } else if hovered { Paint { bg: theme.accent, fg: theme.accent_foreground, border: clear } } else { Paint { bg: clear, fg: theme.foreground, border: clear } }; let element = div() .id(ElementId::Name(id.clone())) .flex() .flex_none() .items_center() .justify_center() .gap_1() .h(ITEM) .min_w(ITEM) .rounded(theme.radius) .text_sm() .font_weight(FontWeight::MEDIUM) // Page numbers keep a border, clear until current, so it can fade in. .when(id.starts_with("page-"), |this| this.border_1()) .when(active, |this| this.shadow_xs()) .on_hover(track_hover(&ease)) .when(disabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(clickable, |this| this.cursor_pointer()) .when_some(target.zip(handler.clone()), |this, (target, handler)| { this.on_click(move |_, window, cx| handler(&target, window, cx)) }); (element, (key, ease, paint)) }; // Adds the eased colors once the item has its content. let finish = |(element, (key, ease, paint)): (Stateful<Div>, Eased), cx: &mut App| { ease_to(element, key, &ease, paint, cx, |this, paint| { this.bg(paint.bg).text_color(paint.fg).border_color(paint.border) }) .into_any_element() }; let icon_only = self.icon_only; let mut children: Vec<AnyElement> = Vec::new(); if self.controls { let (previous, ease) = item("previous".into(), (page > 1).then(|| page - 1), false, window, cx); let previous = previous.child(icon(CHEVRON_LEFT)); let previous = if icon_only { previous } else { previous.pl(px(10.0)).pr(px(12.0)).child("Previous") }; children.push(finish((previous, ease), cx)); } if self.page_numbers { for (ix, slot) in slots(page, total).into_iter().enumerate() { children.push(match slot { Slot::Page(number) => { let active = number == page; let (element, ease) = item( format!("page-{number}").into(), (!active).then_some(number), active, window, cx, ); finish((element.child(number.to_string()), ease), cx) } Slot::Gap => div() .id(("gap", ix)) .flex() .flex_none() .items_center() .justify_center() .size(ITEM) .child(icon(ELLIPSIS)) .into_any_element(), }); } } if self.controls { let (next, ease) = item("next".into(), (page < total).then(|| page + 1), false, window, cx); let next = if icon_only { next } else { next.pl(px(12.0)).pr(px(10.0)).child("Next") }; children.push(finish((next.child(icon(CHEVRON_RIGHT)), ease), cx)); } div().id(self.id).flex().items_center().gap_1().children(children) } } /// shadcn's `transition-colors` (150ms) as a critically damped spring: quick, no overshoot. const EASE: SpringConfig = SpringConfig::new(900.0, 60.0, 1.0); /// The colors a control eases between as it is hovered or changes state. #[derive(Clone, Copy, PartialEq)] struct Paint { bg: Hsla, fg: Hsla, border: Hsla, } impl Paint { fn mix(self, to: Self, t: f32) -> Self { Self { bg: mix(self.bg, to.bg, t), fg: mix(self.fg, to.fg, t), border: mix(self.border, to.border, t), } } } /// Blends like CSS: a transparent end only fades the other color in or out, rather than /// passing through a dark gray. fn mix(from: Hsla, to: Hsla, t: f32) -> Hsla { let from = if from.a == 0.0 { to.opacity(0.0) } else { from }; let to = if to.a == 0.0 { from.opacity(0.0) } else { to }; Hsla::interpolate(from, to, t) } /// One control's hover flag and color transition, kept across frames. #[derive(Default)] struct Ease { hovered: bool, /// The colors eased from and to; `None` before the first render. from_to: Option<(Paint, Paint)>, /// Every new target moves the spring on by one, so an interrupted transition keeps its /// velocity; `start` is where the current one began. start: f32, run: f32, /// What the spring painted last and at which position, where the next transition starts. shown: Rc<Cell<Option<(Paint, f32)>>>, } fn ease_state(key: ElementId, window: &mut Window, cx: &mut App) -> Entity<Ease> { window.use_keyed_state(key, cx, |_, _| Ease::default()) } /// An `on_hover` listener that records hover in `ease`, re-rendering only on a change. fn track_hover(ease: &Entity<Ease>) -> impl Fn(&bool, &mut Window, &mut App) + 'static { let ease = ease.clone(); move |hovered, _, cx| { ease.update(cx, |ease, cx| { if ease.hovered != *hovered { ease.hovered = *hovered; cx.notify(); } }) } } /// Paints `element` with colors easing toward `target` from whatever was showing, like a CSS /// color transition. A newly mounted element starts at `target`, so nothing fades in on load. fn ease_to<E: IntoElement + 'static>( element: E, id: ElementId, ease: &Entity<Ease>, target: Paint, cx: &mut App, paint: impl FnOnce(E, Paint) -> E + 'static, ) -> SpringAnimationElement<E> { let (from, start, run, shown) = ease.update(cx, |ease, _| { match ease.from_to { Some((_, to)) if to == target => {} Some((_, to)) => { let (shown, position) = ease.shown.get().unwrap_or((to, ease.run)); ease.from_to = Some((shown, target)); ease.start = position; ease.run += 1.0; } None => ease.from_to = Some((target, target)), } let from = ease.from_to.map_or(target, |(from, _)| from); (from, ease.start, ease.run, ease.shown.clone()) }); element.with_spring(id, SpringAnimation::new(EASE).to(run), move |element, position| { let span = run - start; let t = if span > 0.0 { ((position - start) / span).clamp(0.0, 1.0) } else { 1.0 }; let now = from.mix(target, t); shown.set(Some((now, position))); paint(element, now) }) }Register the module
// src/ui/mod.rs pub mod pagination;
Usage
use crate::ui::pagination::*;Examples
Simple
controls(false) drops the Previous and Next links and leaves only the page numbers.
use gpui::{prelude::*, Context, Window};
use crate::ui::pagination::Pagination;
const TOTAL_PAGES: usize = 5;
pub struct PaginationSimple {
page: usize,
}
// Pages count from 1, so `Default` is written out instead of derived.
impl Default for PaginationSimple {
fn default() -> Self {
Self { page: 2 }
}
}
impl Render for PaginationSimple {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
Pagination::new("pagination-simple", self.page, TOTAL_PAGES)
.controls(false)
.on_change(cx.listener(|this, page: &usize, _, cx| {
this.page = *page;
cx.notify();
}))
}
}Icons Only
page_numbers(false) with icon_only(true) leaves two chevron buttons, the compact pager that sits under data tables beside a rows-per-page picker.
use gpui::{div, prelude::*, px, svg, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::ui::pagination::Pagination;
use crate::icons::CHEVRON_DOWN;
const TOTAL_ROWS: usize = 240;
const ROW_CHOICES: [usize; 3] = [10, 25, 50];
pub struct PaginationIconsOnly {
page: usize,
rows: usize,
menu_open: bool,
}
// Pages count from 1, so `Default` is written out instead of derived.
impl Default for PaginationIconsOnly {
fn default() -> Self {
Self {
page: 1,
rows: 25,
menu_open: false,
}
}
}
impl Render for PaginationIconsOnly {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme().clone();
let total_pages = TOTAL_ROWS.div_ceil(self.rows);
let trigger = div()
.id("pagination-icons-only-rows")
.h(px(32.0))
.w(px(72.0))
.px_3()
.flex()
.items_center()
.justify_between()
.rounded(theme.radius)
.border_1()
.border_color(theme.input)
.bg(theme.background)
.shadow_xs()
.cursor_pointer()
.child(self.rows.to_string())
.child(svg().data(CHEVRON_DOWN).size(px(14.0)).text_color(theme.muted_foreground));
let mut menu = DropdownMenu::new("pagination-icons-only-menu", self.menu_open)
.trigger(trigger)
.width(px(96.0))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.menu_open = *open;
cx.notify();
}));
for rows in ROW_CHOICES {
menu = menu.item(MenuItem::new(rows.to_string()).on_select(cx.listener(
move |this, _, _, cx| {
this.rows = rows;
this.page = 1;
cx.notify();
},
)));
}
// Top-aligned so the menu has room to open downward in the preview.
div()
.h(px(220.0))
.w(px(440.0))
.flex()
.items_start()
.justify_between()
.text_sm()
.text_color(theme.foreground)
.child(
div()
.flex()
.items_center()
.gap_2()
.child(div().font_weight(FontWeight::MEDIUM).child("Rows per page"))
.child(menu),
)
.child(
div()
.flex()
.items_center()
.gap_3()
.child(
div()
.text_color(theme.muted_foreground)
.child(format!("Page {} of {total_pages}", self.page)),
)
.child(
Pagination::new("pagination-icons-only", self.page, total_pages)
.page_numbers(false)
.icon_only(true)
.on_change(cx.listener(|this, page: &usize, _, cx| {
this.page = *page;
cx.notify();
})),
),
)
}
}API Reference
Pagination
Page navigation with previous/next links. Pages are numbered from 1. The parent view owns page and updates it in on_change; out-of-range pages are clamped for display.
Pagination::new(id: impl Into<ElementId>, page: usize, total_pages: usize) -> Self.controls(controls: bool)Shows the Previous and Next links. On by default; turn off for a bare row of page numbers.
.page_numbers(page_numbers: bool)Shows the numbered page links. On by default; turn off to page with Previous and Next alone, as in data tables.
.icon_only(icon_only: bool)Draws Previous and Next as square chevron buttons without their labels.
.on_change(handler: impl Fn(&usize, &mut Window, &mut App) + 'static)