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
use crate::{
    Button, GlobalClose, Icon, InputState, TextInput, ValidationContext, Validator, Variant,
};
use yew::prelude::*;

#[derive(Clone, PartialEq, Properties)]
pub struct Props {
    #[prop_or_default]
    pub total_entries: Option<u32>,
    #[prop_or_default]
    pub offset: u32,
    #[prop_or(vec![10,20,30])]
    pub entries_per_page_choices: Vec<u32>,
    #[prop_or(20)]
    pub selected_choice: u32,

    // callback for the buttons
    #[prop_or_default]
    pub navigation_callback: Callback<Navigation>,

    #[prop_or_default]
    pub limit_callback: Callback<u32>,
}

pub enum Navigation {
    First,
    Previous,
    Next,
    Last,
    Page(u32),
}

pub struct Pagination {
    expanded: bool,
    global_close: GlobalClose,
}

#[derive(Clone, Debug)]
pub enum Msg {
    ToggleMenu,
    CloseMenu,
    SetLimit(u32),

    First,
    Previous,
    Next,
    Last,
    Page(u32),
}

impl Component for Pagination {
    type Message = Msg;
    type Properties = Props;

    fn create(ctx: &Context<Self>) -> Self {
        Self {
            expanded: false,
            global_close: GlobalClose::new(
                NodeRef::default(),
                ctx.link().callback(|_| Msg::CloseMenu),
            ),
        }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            Msg::ToggleMenu => {
                self.expanded = !self.expanded;
            }
            Msg::SetLimit(limit) => {
                ctx.props().limit_callback.emit(limit);
                ctx.link().send_message(Msg::CloseMenu)
            }
            Msg::CloseMenu => self.expanded = false,
            Msg::First => ctx.props().navigation_callback.emit(Navigation::First),
            Msg::Previous => ctx.props().navigation_callback.emit(Navigation::Previous),
            Msg::Next => ctx.props().navigation_callback.emit(Navigation::Next),
            Msg::Last => ctx.props().navigation_callback.emit(Navigation::Last),
            Msg::Page(num) => ctx.props().navigation_callback.emit(Navigation::Page(num)),
        }
        true
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        // The pagination menu : "1-20 of nnn"
        let mut menu_classes = Classes::from("pf-c-options-menu");
        if self.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 = ctx
            .props()
            .total_entries
            .map(|m| (m as f64 / ctx.props().selected_choice as f64).ceil() as u32);
        let current_page =
            (ctx.props().offset as f64 / ctx.props().selected_choice as f64).ceil() as u32;

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

        let total_entries = ctx
            .props()
            .total_entries
            .map(|m| format!("{}", m))
            .unwrap_or_else(|| String::from("unknown"));
        // +1 because humans don't count from 0 :)
        let showing = format!(
            "{} - {}",
            ctx.props().offset + 1,
            ctx.props().offset + ctx.props().selected_choice
        );

        let limit_choices = ctx.props().entries_per_page_choices.clone();
        let link = ctx.link().clone();

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

        let validator_clone = page_number_field_validator.clone();
        let onchange_callback = {
            ctx.link().callback(move |input: String| {
                match validator_clone.run(ValidationContext::from(input.clone())) {
                    Some(InputState::Default) => Msg::Page(input.parse::<u32>().unwrap()),
                    _ => Msg::Page(current_page + 1),
                }
            })
        };

        return html! {

          <div class="pf-c-pagination" ref={self.global_close.clone()} >

              // the selector of how many entries per page to display
              <div class="pf-c-pagination__total-items">
                  <b>{ showing.clone() }</b> {"\u{00a0}of\u{00a0}"}
                  <b>{ total_entries.clone() }</b>
              </div>
              <div class={ menu_classes }>
                  <div class="pf-c-options-menu__toggle pf-m-text pf-m-plain">
                      <span class="pf-c-options-menu__toggle-text">
                           <b>{ showing }</b>{"\u{00a0}of\u{00a0}"}
                          <b>{ total_entries }</b>
                      </span>
                  <Button
                      class="pf-c-options-menu__toggle-button"
                      id="pagination-options-menu-top-toggle"
                      //aria-haspopup="listbox"
                      aria_label="Items per page"
                      onclick={ctx.link().callback(|_|Msg::ToggleMenu)}
                      >
                          <span class="pf-c-options-menu__toggle-button-icon">
                              { Icon::CaretDown }
                          </span>
                  </Button>
          </div>
          {{ if self.expanded {
              html! {
              <ul class="pf-c-options-menu__menu" >
                  { for limit_choices.into_iter().map(|limit|  { html!{
                        <li>
                          <Button
                              class="pf-c-options-menu__menu-item"
                                      onclick={link.callback(move |_|Msg::SetLimit(limit))}>
                                  {limit} {" per page"}
                                  {{ if ctx.props().selected_choice == limit {
                                       html!{
                                      <div class="pf-c-options-menu__menu-item-icon">
                                         { Icon::Check }
                                      </div>
                                          }
                                  } else {
                                      html!{}
                                  } }}
                          </Button>
                        </li>
                  }})}
              </ul>
              }
          } else { html! {} }
          }}
        </div>


              // the navigation buttons

              <nav class="pf-c-pagination__nav" aria-label="Pagination">
                  <div class="pf-c-pagination__nav-control pf-m-first">
                    <Button
                      variant={Variant::Plain}
                      onclick={ctx.link().callback(|_|Msg::First)}
                      disabled={ ctx.props().offset == 0 }
                      aria_label="Go to first page"
                    >
                      { Icon::AngleDoubleLeft }
                    </Button>
                  </div>
                  <div class="pf-c-pagination__nav-control pf-m-prev">
                      <Button
                          aria_label="Go to previous page"
                          variant={Variant::Plain}
                          onclick={ctx.link().callback(|_|Msg::Previous)}
                          disabled= { ctx.props().offset == 0 }
                      >
                             { Icon::AngleLeft }
                      </Button>
                  </div>
                  <div class="pf-c-pagination__nav-page-select">
                    <TextInput
                      r#type="number"
                      validator={page_number_field_validator}
                      onchange={onchange_callback}
                      value = {(current_page+1).to_string()}
                    />
                  {{
                      if let Some(max_page) = max_page {
                          html!{<span aria-hidden="true">{ "of "} { max_page }</span>}
                      } else {
                          html!{}
                      }
                  }}
                  </div>
                  <div class="pf-c-pagination__nav-control pf-m-next">
                    <Button
                      aria_label="Go to next page"
                      variant={Variant::Plain}
                      onclick={ctx.link().callback(|_|Msg::Next)}
                      disabled={max_page.map_or_else(|| false, |m| current_page >= m)}
                    >
                      { Icon::AngleRight }
                    </Button>
                  </div>
                  <div class="pf-c-pagination__nav-control pf-m-last">
                    <Button
                      aria_label="Go to last page"
                      variant={Variant::Plain}
                      onclick={ctx.link().callback(|_|Msg::Last)}
                      disabled={is_last_page}
                    >
                      { Icon::AngleDoubleRight }
                    </Button>
                  </div>
              </nav>
          </div>
              };
    }
}