1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
//! Pagination controls

mod simple;
pub use simple::*;

use crate::prelude::{
    use_on_enter, AsClasses, Button, ButtonVariant, ExtendClasses, Icon, InputState, TextInput,
    TextInputType, ValidationContext, Validator,
};
use yew::prelude::*;
use yew_hooks::use_click_away;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PaginationPosition {
    Top,
    Bottom,
}

impl AsClasses for PaginationPosition {
    fn extend_classes(&self, classes: &mut Classes) {
        match self {
            Self::Top => {}
            Self::Bottom => classes.push(classes!("pf-m-top")),
        }
    }
}

impl PaginationPosition {
    fn toggle_icon(&self, expanded: bool) -> Icon {
        match (self, expanded) {
            (Self::Bottom, true) => Icon::CaretUp,
            _ => Icon::CaretDown,
        }
    }
}

/// Properties for [`Pagination`]
#[derive(Clone, PartialEq, Properties)]
pub struct PaginationProperties {
    #[prop_or_default]
    pub total_entries: Option<usize>,
    #[prop_or_default]
    pub offset: usize,
    #[prop_or(vec![10,25,50])]
    pub entries_per_page_choices: Vec<usize>,
    #[prop_or(25)]
    pub selected_choice: usize,

    /// Callback for navigation
    #[prop_or_default]
    pub onnavigation: Callback<Navigation>,

    /// Callback for change in limit (page size, per page)
    #[prop_or_default]
    pub onlimit: Callback<usize>,

    /// Element ID
    #[prop_or_default]
    pub id: Option<AttrValue>,

    /// Additional styles
    #[prop_or_default]
    pub style: AttrValue,

    #[prop_or(PaginationPosition::Top)]
    pub position: PaginationPosition,

    /// Disable the full control
    #[prop_or_default]
    pub disabled: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Navigation {
    First,
    Previous,
    Next,
    Last,
    /// navigate to a specific page (zero based)
    Page(usize),
}

/// Pagination component.
///
/// > A **pagination** component gives users more navigational capability on pages with content views.
///
/// See: <https://www.patternfly.org/components/pagination>
///
/// ## Properties
///
/// Defined by [`PaginationProperties`].
///
/// ## Example
///
/// See the [PatternFly Quickstart](https://github.com/ctron/patternfly-yew-quickstart) for a complete example.
#[function_component(Pagination)]
pub fn pagination(props: &PaginationProperties) -> Html {
    let expanded = use_state_eq(|| false);

    // The pagination menu : "1-20 of nnn"
    let mut menu_classes = classes!("pf-v5-c-options-menu");
    menu_classes.extend_from(&props.position);

    if *expanded {
        menu_classes.push("pf-m-expanded");
    }

    // The default rust div operator does floor(), we need ceil, so we cast to float before doing the operation
    let max_page = props
        .total_entries
        .map(|m| (m as f64 / props.selected_choice as f64).ceil() as usize);
    let current_page = (props.offset as f64 / props.selected_choice as f64).ceil() as usize;

    let is_last_page = if let Some(max) = props.total_entries {
        props.offset + props.selected_choice >= max
    } else {
        false
    };

    let total_entries = props
        .total_entries
        .map(|m| format!("{}", m))
        .unwrap_or_else(|| String::from("many"));

    // +1 because humans don't count from 0 :)
    let start = props.offset + 1;
    let mut end = props.offset + props.selected_choice;
    if let Some(total) = props.total_entries {
        end = end.min(total);
    }
    let showing = format!("{start} - {end}",);

    let limit_choices = props.entries_per_page_choices.clone();

    // todo also add max page
    let page_number_field_validator =
        Validator::from(
            |ctx: ValidationContext<String>| match ctx.value.parse::<usize>() {
                Ok(value) => {
                    if value > 0 {
                        InputState::Default
                    } else {
                        InputState::Error
                    }
                }
                Err(_) => InputState::Error,
            },
        );

    // toggle
    let ontoggle = use_callback(expanded.clone(), |_, expanded| {
        expanded.set(!**expanded);
    });

    let node = use_node_ref();
    {
        let expanded = expanded.clone();
        use_click_away(node.clone(), move |_| {
            expanded.set(false);
        });
    }

    // page input field

    // the validation state of the input
    let input_state = use_state_eq(InputState::default);
    // the parsed input (zero based)
    let input = use_state_eq(|| 0);
    // the raw input of the page number field
    let input_text = use_state_eq(|| Some((current_page + 1).to_string()));

    if input_text.is_none() {
        input_text.set(Some((current_page + 1).to_string()));
    }

    let onkeydown = use_on_enter(
        (input.clone(), props.onnavigation.clone()),
        |(input, onnavigation)| {
            let mut page: usize = **input;
            // humans start with 1, we use 0.
            page = page.saturating_sub(1);
            log::debug!("Emit page change: {page}");
            onnavigation.emit(Navigation::Page(page));
        },
    );

    let onchange = use_callback(
        (
            input.clone(),
            input_text.clone(),
            page_number_field_validator.clone(),
            input_state.clone(),
        ),
        |text: String, (input, input_text, page_number_field_validator, input_state)| {
            input_text.set(Some(text.clone()));

            let state = page_number_field_validator
                .run(ValidationContext::from(text.clone()))
                .unwrap_or_default();

            if let InputState::Default = &state {
                input.set(text.parse().unwrap_or_default());
            }

            log::debug!("New prepared page value: {:?} / {}", **input_text, **input);

            input_state.set(state);
        },
    );

    let onnavigation = use_callback(
        (props.onnavigation.clone(), input_text.clone()),
        |nav, (onnavigation, input_text)| {
            input_text.set(None);
            onnavigation.emit(nav);
        },
    );

    // Page number can be changed through props, therefore input_text should watch props
    {
        let input_text = input_text.clone();
        use_effect_with((props.offset, props.selected_choice), move |tuple| {
            let r = (tuple.0 as f64 / tuple.1 as f64).ceil() as usize;
            input_text.set(Some((r + 1).to_string()));
        });
    }

    // on limit change
    let onlimit = use_callback(
        (props.onlimit.clone(), input_text.clone()),
        |limit, (onlimit, input_text)| {
            input_text.set(None);
            onlimit.emit(limit);
        },
    );

    // The main div
    let pagination_classes = match &props.position {
        PaginationPosition::Top => classes!("pf-v5-c-pagination"),
        PaginationPosition::Bottom => classes!("pf-v5-c-pagination", "pf-m-bottom"),
    };

    let pagination_styles = format!(
        "--pf-v5-c-pagination__nav-page-select--c-form-control--width-chars: {};",
        max_page.unwrap_or_default().to_string().len().clamp(2, 10)
    );

    // render

    let unbound = props.total_entries.is_none();

    html! (

        <div
            id={&props.id}
            class={pagination_classes}
            style={[pagination_styles, props.style.to_string()].join(" ")}
            ref={node}
        >

            // the selector of how many entries per page to display
            <div class="pf-v5-c-pagination__total-items">
                <b>{ showing.clone() }</b> {"\u{00a0}of\u{00a0}"}
                <b>{ total_entries.clone() }</b>
            </div>

            <div class={ menu_classes }>
                <button
                    class="pf-v5-c-options-menu__toggle pf-m-text pf-m-plain"
                    type="button"
                    aria-haspopup="listbox"
                    aria-expanded="true"
                    onclick={ontoggle}
                    disabled={props.disabled}
                >
                    <span class="pf-v5-c-options-menu__toggle-text">
                        <b>{ showing }</b>{"\u{00a0}of\u{00a0}"}
                        <b>{ total_entries }</b>
                    </span>
                    <div class="pf-v5-c-options-menu__toggle-icon">
                        { props.position.toggle_icon(*expanded)}
                    </div>
                </button>

            if *expanded {
                <ul class="pf-v5-c-options-menu__menu" >
                    { for limit_choices.into_iter().map(|limit|  {
                        let expanded = expanded.clone();
                        let onlimit = onlimit.clone();
                        let onclick = Callback::from(move |_|{
                            onlimit.emit(limit);
                            expanded.set(false);
                        });
                        html!(
                            <li>
                                <button
                                    class="pf-v5-c-options-menu__menu-item"
                                    type="button"
                                    {onclick}
                                >
                                    {limit} {" per page"}
                                    if props.selected_choice == limit {
                                        <div class="pf-v5-c-options-menu__menu-item-icon">
                                            { Icon::Check }
                                        </div>
                                    }
                                </button>
                            </li>
                    )})}
                </ul>
            }
            </div>

            // the navigation buttons
            <nav class="pf-v5-c-pagination__nav" aria-label="Pagination">
                <div class="pf-v5-c-pagination__nav-control pf-m-first">
                    <Button
                        variant={ButtonVariant::Plain}
                        onclick={onnavigation.reform(|_|Navigation::First)}
                        disabled={ props.disabled || props.offset == 0 }
                        aria_label="Go to first page"
                    >
                      { Icon::AngleDoubleLeft }
                    </Button>
                </div>
                <div class="pf-v5-c-pagination__nav-control pf-m-prev">
                    <Button
                        aria_label="Go to previous page"
                        variant={ButtonVariant::Plain}
                        onclick={onnavigation.reform(|_|Navigation::Previous)}
                        disabled={ props.disabled || props.offset == 0 }
                    >
                       { Icon::AngleLeft }
                    </Button>
                </div>
                <div class="pf-v5-c-pagination__nav-page-select">
                    <TextInput
                        r#type={TextInputType::Number}
                        {onchange}
                        {onkeydown}
                        state={*input_state}
                        value={(*input_text).clone().unwrap_or_else(|| (current_page+1).to_string()) }
                        disabled={props.disabled}
                    />
                if let Some(max_page) = max_page {
                    <span aria-hidden="true">{ "of "} { max_page }</span>
                }
                </div>

                <div class="pf-v5-c-pagination__nav-control pf-m-next">
                    <Button
                        aria_label="Go to next page"
                        variant={ButtonVariant::Plain}
                        onclick={onnavigation.reform(|_|Navigation::Next)}
                        disabled={ props.disabled || is_last_page }
                    >
                        { Icon::AngleRight }
                    </Button>
                </div>
                <div class="pf-v5-c-pagination__nav-control pf-m-last">
                    <Button
                        aria_label="Go to last page"
                        variant={ButtonVariant::Plain}
                        onclick={onnavigation.reform(|_|Navigation::Last)}
                        disabled={ props.disabled || unbound || is_last_page}
                    >
                        { Icon::AngleDoubleRight }
                    </Button>
                </div>
            </nav>
        </div>
    )
}