1use std::{f32::consts::PI, rc::Rc};
2
3use gpui::{
4 AccessibleAction, App, Axis, ElementId, FocusHandle, Hsla, InteractiveElement, IntoElement,
5 ParentElement, RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window, div,
6 prelude::FluentBuilder, px, radians,
7};
8use gpui_base::{
9 Button as BaseButton, Pagination as BasePagination, PaginationItem as BasePaginationItem,
10 PaginationState as BasePaginationState, TestSupportExt,
11};
12use gpui_material_components::{ControlSize, Icon, IconButton, IconName, Text};
13use gpui_material_foundation::{
14 FocusRingPlacement, ThemeScope, color,
15 control_feedback::{activate_feedback, feedback_target},
16 current_material_theme, move_roving_focus,
17};
18use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Direction, TypeRole};
19
20use super::{feedback_overlay, keyed_feedback, keyed_focus};
21
22type PageChangeHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
23
24#[derive(Clone, Copy, Debug, Default)]
26pub struct PaginationColors {
27 pub active_container: Option<Hsla>,
29 pub active_content: Option<Hsla>,
31 pub inactive_container: Option<Hsla>,
33 pub inactive_content: Option<Hsla>,
35 pub ellipsis: Option<Hsla>,
37 pub disabled_content: Option<Hsla>,
39}
40
41#[derive(IntoElement)]
47pub struct Pagination {
48 id: ElementId,
49 current_page: usize,
50 total_pages: usize,
51 visible_pages: usize,
52 disabled: bool,
53 accessible_label: Option<SharedString>,
54 previous_label: Option<SharedString>,
55 next_label: Option<SharedString>,
56 shape: Option<CornerShape>,
57 colors: PaginationColors,
58 on_change: Option<PageChangeHandler>,
59}
60
61impl Pagination {
62 pub fn new(id: impl Into<ElementId>, current_page: usize, total_pages: usize) -> Self {
65 Self {
66 id: id.into(),
67 current_page,
68 total_pages,
69 visible_pages: 5,
70 disabled: false,
71 accessible_label: None,
72 previous_label: None,
73 next_label: None,
74 shape: None,
75 colors: PaginationColors::default(),
76 on_change: None,
77 }
78 }
79
80 pub fn visible_pages(mut self, visible_pages: usize) -> Self {
82 self.visible_pages = visible_pages.max(5);
83 self
84 }
85
86 pub fn disabled(mut self, disabled: bool) -> Self {
88 self.disabled = disabled;
89 self
90 }
91
92 pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
94 self.accessible_label = Some(label.into());
95 self
96 }
97
98 pub fn previous_label(mut self, label: impl Into<SharedString>) -> Self {
100 self.previous_label = Some(label.into());
101 self
102 }
103
104 pub fn next_label(mut self, label: impl Into<SharedString>) -> Self {
106 self.next_label = Some(label.into());
107 self
108 }
109
110 pub fn shape(mut self, shape: CornerShape) -> Self {
112 self.shape = Some(shape);
113 self
114 }
115
116 pub fn colors(mut self, colors: PaginationColors) -> Self {
118 self.colors = colors;
119 self
120 }
121
122 pub fn on_change(mut self, handler: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
124 self.on_change = Some(Rc::new(handler));
125 self
126 }
127}
128
129fn resolved_items(state: &BasePaginationState) -> Vec<BasePaginationItem> {
130 let items = state.items();
131 if items.is_empty() {
132 vec![BasePaginationItem::Page(1)]
133 } else {
134 items
135 }
136}
137
138impl RenderOnce for Pagination {
139 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
140 let theme = current_material_theme(window, cx);
141 let direction = theme.layout.direction;
142 let rtl = direction == Direction::Rtl;
143 let density = theme.layout.density;
144 let reduced_motion = cx.reduce_motion();
145
146 let on_surface = color(theme.colors.color(ColorRole::OnSurface));
147 let on_surface_variant = color(theme.colors.color(ColorRole::OnSurfaceVariant));
148 let primary_container = color(theme.colors.color(ColorRole::PrimaryContainer));
149 let on_primary_container = color(theme.colors.color(ColorRole::OnPrimaryContainer));
150 let focus_ring = color(theme.colors.color(ColorRole::Secondary));
151 let disabled_fg = self
152 .colors
153 .disabled_content
154 .unwrap_or_else(|| on_surface.opacity(0.38));
155
156 let active_bg = self.colors.active_container.unwrap_or(primary_container);
157 let active_fg = self.colors.active_content.unwrap_or(on_primary_container);
158 let inactive_fg = self.colors.inactive_content.unwrap_or(on_surface);
159 let ellipsis_fg = self.colors.ellipsis.unwrap_or(on_surface_variant);
160 let pill_shape = self.shape.unwrap_or_else(|| CornerRole::Full.shape());
161 let pill_size = px(density.visual_size(36.0).max(32.0));
162
163 let mut base_state = BasePaginationState::new(self.current_page, self.total_pages)
164 .visible_pages(self.visible_pages)
165 .disabled(self.disabled);
166 if let Some(on_change) = self.on_change {
167 base_state = base_state.on_change(move |page, window, cx| {
168 on_change(page, window, cx);
169 });
170 }
171
172 let current_page = base_state.current_page();
173 let prev_target = base_state.previous_page();
174 let next_target = base_state.next_page();
175 let items = resolved_items(&base_state);
176
177 let nav_label = self
178 .accessible_label
179 .unwrap_or_else(|| SharedString::from("Pagination"));
180 let prev_label = self
181 .previous_label
182 .unwrap_or_else(|| SharedString::from("Previous page"));
183 let next_label = self
184 .next_label
185 .unwrap_or_else(|| SharedString::from("Next page"));
186
187 let prev_id = ElementId::from((self.id.clone(), "previous"));
188 let next_id = ElementId::from((self.id.clone(), "next"));
189 let prev_focus = keyed_focus(&self.id, "previous", None, window, cx);
190 let next_focus = keyed_focus(&self.id, "next", None, window, cx);
191
192 let mut roving: Vec<(FocusHandle, bool)> = Vec::with_capacity(items.len() + 2);
193 roving.push((prev_focus.clone(), prev_target.is_some()));
194
195 let mut page_focuses: Vec<Option<FocusHandle>> = Vec::with_capacity(items.len());
196 for item in &items {
197 match item {
198 BasePaginationItem::Page(page) => {
199 let handle = keyed_focus(&self.id, format!("page-{page}"), None, window, cx);
200 roving.push((handle.clone(), !self.disabled));
201 page_focuses.push(Some(handle));
202 }
203 BasePaginationItem::Ellipsis(_) => page_focuses.push(None),
204 }
205 }
206 roving.push((next_focus.clone(), next_target.is_some()));
207
208 let prev_state = base_state.clone();
209 let prev_button = IconButton::standard(
210 prev_id,
211 prev_label,
212 Icon::new(IconName::ChevronRight)
213 .rotate(radians(PI))
214 .mirror_in_rtl(true),
215 )
216 .size(ControlSize::ExtraSmall)
217 .track_focus(&prev_focus)
218 .disabled(prev_target.is_none())
219 .on_activate(move |window, cx| {
220 if let Some(target) = prev_state.previous_page() {
221 prev_state.request_page(target, window, cx);
222 }
223 });
224
225 let next_state = base_state.clone();
226 let next_button = IconButton::standard(
227 next_id,
228 next_label,
229 Icon::new(IconName::ChevronRight).mirror_in_rtl(true),
230 )
231 .size(ControlSize::ExtraSmall)
232 .track_focus(&next_focus)
233 .disabled(next_target.is_none())
234 .on_activate(move |window, cx| {
235 if let Some(target) = next_state.next_page() {
236 next_state.request_page(target, window, cx);
237 }
238 });
239
240 let mut nav = BasePagination::new(
241 ElementId::from((self.id.clone(), "nav")),
242 base_state.clone(),
243 )
244 .accessibility_label(nav_label)
245 .flex()
246 .flex_row()
247 .items_center()
248 .gap(px(4.))
249 .when(rtl, Styled::flex_row_reverse)
250 .on_key_down(move |event, window, cx| {
251 if event.keystroke.modifiers.modified() {
252 return;
253 }
254 if !roving
255 .iter()
256 .any(|(focus, enabled)| *enabled && focus.is_focused(window))
257 {
258 return;
259 }
260 let refs: Vec<(&FocusHandle, bool)> = roving
261 .iter()
262 .map(|(focus, enabled)| (focus, *enabled))
263 .collect();
264 if move_roving_focus(
265 &refs,
266 event.keystroke.key.as_str(),
267 Axis::Horizontal,
268 direction,
269 window,
270 cx,
271 )
272 .is_some()
273 {
274 cx.stop_propagation();
275 }
276 })
277 .child(prev_button);
278
279 let pill_radius = pill_shape.radii(36., 36., direction)[0];
280 for (item, page_focus) in items.into_iter().zip(page_focuses) {
281 match item {
282 BasePaginationItem::Page(page) => {
283 let is_active = page == current_page;
284 let enabled = !self.disabled;
285 let pill_id = ElementId::from((self.id.clone(), format!("page-{page}")));
286 let focus = page_focus.expect("page item always allocates focus handle");
287 let feedback = keyed_feedback(&self.id, format!("page-{page}"), window, cx);
288 let interaction = {
289 let mut state = feedback.borrow_mut();
290 state.cancel_unavailable(enabled, window);
291 state.interaction(enabled, &focus, window)
292 };
293
294 let bg = if is_active {
295 if enabled {
296 Some(active_bg)
297 } else {
298 Some(on_surface.opacity(0.12))
299 }
300 } else {
301 self.colors.inactive_container
302 };
303 let fg = if !enabled {
304 disabled_fg
305 } else if is_active {
306 active_fg
307 } else {
308 inactive_fg
309 };
310 let aria_name: SharedString = if is_active {
311 format!("Page {page}, current page").into()
312 } else {
313 format!("Page {page}").into()
314 };
315
316 let state_for_click = base_state.clone();
317 let state_for_a11y = base_state.clone();
318 let request_click = Rc::new(ThemeScope::bind_action(
319 move |window, cx| state_for_click.request_page(page, window, cx),
320 window,
321 cx,
322 ));
323 let request_a11y = Rc::new(ThemeScope::bind_action(
324 move |window, cx| state_for_a11y.request_page(page, window, cx),
325 window,
326 cx,
327 ));
328
329 let mut pill = BaseButton::new(pill_id)
330 .accessibility_label(aria_name)
331 .disabled(!enabled)
332 .track_focus(&focus)
333 .relative()
334 .min_w(pill_size)
335 .h(pill_size)
336 .px(px(10.))
337 .rounded(px(pill_radius))
338 .when_some(bg, Styled::bg)
339 .aria_selected(is_active)
340 .when(enabled && !is_active, Styled::cursor_pointer)
341 .child(feedback_overlay(
342 feedback.clone(),
343 pill_shape,
344 direction,
345 interaction,
346 fg,
347 focus_ring,
348 FocusRingPlacement::Outer,
349 reduced_motion,
350 ))
351 .child(
352 Text::new(page.to_string())
353 .role(TypeRole::LabelLarge)
354 .emphasized(is_active)
355 .color_override(fg),
356 );
357
358 if enabled {
359 pill = feedback_target(pill, feedback.clone(), true, Some(focus.clone()));
360 let click_feedback = feedback.clone();
361 pill = pill
362 .on_click(move |event, window, cx| {
363 if click_feedback.borrow().blocks_activation(event) {
364 return;
365 }
366 activate_feedback(event, &click_feedback, window, cx);
367 request_click(window, cx);
368 cx.stop_propagation();
369 })
370 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
371 request_a11y(window, cx);
372 });
373 }
374
375 nav = nav.child(pill);
376 }
377 BasePaginationItem::Ellipsis(range) => {
378 let ellipsis_id =
379 ElementId::from((self.id.clone(), format!("ellipsis-{}", range.start)));
380 nav = nav.child(
381 div()
382 .id(ellipsis_id)
383 .test_support()
384 .min_w(pill_size)
385 .h(pill_size)
386 .flex()
387 .items_center()
388 .justify_center()
389 .child(Text::new("…").role(TypeRole::LabelLarge).color_override(
390 if self.disabled {
391 disabled_fg
392 } else {
393 ellipsis_fg
394 },
395 )),
396 );
397 }
398 }
399 }
400
401 nav = nav.child(next_button);
402
403 div().id(self.id).test_support().child(nav)
404 }
405}
406
407#[cfg(test)]
408mod tests {
409 use super::*;
410
411 #[test]
412 fn single_page_still_yields_active_page_one() {
413 let state = BasePaginationState::new(1, 1);
414 assert_eq!(resolved_items(&state), vec![BasePaginationItem::Page(1)]);
415 }
416
417 #[test]
418 fn long_page_range_inserts_ellipses() {
419 let state = BasePaginationState::new(6, 12).visible_pages(5);
420 let items = resolved_items(&state);
421 assert!(items.contains(&BasePaginationItem::Page(1)));
422 assert!(items.contains(&BasePaginationItem::Page(6)));
423 assert!(items.contains(&BasePaginationItem::Page(12)));
424 assert!(
425 items
426 .iter()
427 .filter(|item| matches!(item, BasePaginationItem::Ellipsis(_)))
428 .count()
429 == 2
430 );
431 }
432}