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
mod column;
mod header;
mod model;

pub use column::*;
pub use header::*;
pub use model::*;

use crate::icon::Icon;
use std::fmt::Debug;
use yew::prelude::*;
use yew::virtual_dom::vnode::VNode::VComp;
use yew::virtual_dom::VChild;

const LOG_TARGET: &'static str = "table";

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum TableMode {
    Default,
    Compact,
    CompactNoBorders,
    CompactExpandable,
    Expandable,
}

impl Default for TableMode {
    fn default() -> Self {
        Self::Default
    }
}

#[derive(Debug, PartialEq, Clone, Properties)]
pub struct TableProps<M>
where
    M: TableModel + 'static,
{
    #[prop_or_default]
    pub caption: Option<String>,
    #[prop_or_default]
    pub mode: TableMode,
    #[prop_or_default]
    pub header: Option<VChild<TableHeader>>,
    #[prop_or_default]
    pub full_width_details: bool,
    #[prop_or_default]
    pub entries: M,
}

#[derive(Clone, Debug)]
pub struct Table<M>
where
    M: TableModel + 'static,
{
    props: TableProps<M>,
    link: ComponentLink<Self>,
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct ColumnIndex {
    pub index: usize,
}

#[derive(Clone, Debug, PartialEq)]
pub struct Span {
    pub cols: usize,
    pub content: Html,
}

impl Span {
    pub fn one(html: Html) -> Self {
        Self {
            cols: 1,
            content: html,
        }
    }
    pub fn max(html: Html) -> Self {
        Self {
            cols: usize::MAX,
            content: html,
        }
    }
}

/// Render table entries
pub trait TableRenderer {
    fn render(&self, column: ColumnIndex) -> Html;
    fn is_full_width_details(&self) -> Option<bool> {
        None
    }
    fn render_details(&self) -> Vec<Span> {
        vec![]
    }
}

#[derive(Clone, Debug)]
pub enum Msg {
    Collapse(usize),
    Expand(usize),
}

impl<M> Component for Table<M>
where
    M: TableModel + 'static,
{
    type Message = Msg;
    type Properties = TableProps<M>;

    fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
        let mut result = Self { props, link };
        result.sync_expandable();
        result
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        log::debug!(target: LOG_TARGET, "Update - msg: {:?}", msg);

        match msg {
            Msg::Collapse(idx) => self.set_expanded(idx, false),
            Msg::Expand(idx) => self.set_expanded(idx, true),
        }
    }

    fn change(&mut self, props: Self::Properties) -> ShouldRender {
        log::debug!(target: LOG_TARGET, "Change: {:?}", props);
        if self.props != props {
            self.props = props;

            self.sync_expandable();

            true
        } else {
            false
        }
    }

    fn view(&self) -> Html {
        let mut classes = Classes::from("pf-c-table");

        if self
            .props
            .header
            .as_ref()
            .map_or(false, |header| header.props.sticky)
        {
            classes.push("pf-m-sticky-header");
        }

        match self.props.mode {
            TableMode::Compact => {
                classes.push("pf-m-compact");
            }
            TableMode::CompactNoBorders => {
                classes.push("pf-m-compact");
                classes.push("pf-m-no-border-rows");
            }
            TableMode::CompactExpandable => {
                classes.push("pf-m-compact");
                classes.push("pf-m-expandable");
            }
            TableMode::Expandable => {
                classes.push("pf-m-expandable");
            }
            TableMode::Default => {}
        };

        return html! {
            <table class=classes role="grid">
                { self.render_caption() }
                { self.render_header() }
                { self.render_entries() }
            </table>
        };
    }
}

impl<M> Table<M>
where
    M: TableModel,
{
    fn sync_expandable(&mut self) {
        // sync down expandable state
        let expandable = self.is_expandable();
        if let Some(ref mut header) = self.props.header {
            header.props.expandable = expandable;
        }
    }

    fn render_caption(&self) -> Html {
        match &self.props.caption {
            Some(caption) => html! {
                <caption>{caption}</caption>
            },
            None => html! {},
        }
    }

    fn render_header(&self) -> Html {
        match &self.props.header {
            Some(header) => VComp(yew::virtual_dom::VComp::from(header.clone())),
            None => html! {},
        }
    }

    fn render_entries(&self) -> Vec<Html> {
        let expandable = self.is_expandable();

        let result = self.props.entries.map(|entry| match expandable {
            true => self.render_expandable_entry(&entry),
            false => self.render_normal_entry(&entry),
        });

        if expandable {
            result
        } else {
            vec![html! {
                <tbody role="rowgroup">
                    {result}
                </tbody>
            }]
        }
    }

    fn render_normal_entry(&self, entry: &TableModelEntry<M::Item>) -> Html {
        html! {
            <tr role="row">
                { self.render_row(&entry.value)}
            </tr>
        }
    }

    fn render_expandable_entry(&self, entry: &TableModelEntry<M::Item>) -> Html {
        let expanded = entry.expanded;
        let idx = entry.index;

        let onclick = match expanded {
            true => self.link.callback(move |_: MouseEvent| Msg::Collapse(idx)),
            false => self.link.callback(move |_: MouseEvent| Msg::Expand(idx)),
        };

        let mut classes = Classes::from("pf-c-button");
        classes.push("pf-m-plain");
        if expanded {
            classes.push("pf-m-expanded");
        }

        let aria_expanded = match expanded {
            true => "true",
            false => "false",
        };

        let mut expanded_class = Classes::new();
        if expanded {
            expanded_class.push("pf-m-expanded");
        }

        let mut cols = self
            .props
            .header
            .as_ref()
            .map_or(0, |header| header.props.children.len())
            + 1;

        let mut cells: Vec<Html> = Vec::with_capacity(cols);

        if !entry
            .value
            .is_full_width_details()
            .unwrap_or(self.props.full_width_details)
        {
            cells.push(html! {<td></td>});
            cols -= 1;
        }

        for cell in entry.value.render_details() {
            cells.push(html! {
                <td role="cell" colspan={cell.cols}>
                    <div class="pf-c-table__expandable-row-content">
                        { cell.content }
                    </div>
                </td>
            });
            if cols > cell.cols {
                cols -= cell.cols;
            } else {
                cols = 0;
            }
            if cols == 0 {
                break;
            }
        }

        if cols > 0 {
            cells.push(html! {
                <td colspan=cols></td>
            });
        }

        return html! {
            <tbody role="rowgroup" class=expanded_class.clone()>
                <tr role="row">
                    <td class="pf-c-table__toggle" role="cell">
                        <button class=classes onclick=onclick aria-expanded=aria_expanded>
                            <div class="pf-c-table__toggle_icon">
                                { if expanded { Icon::AngleDown } else { Icon::AngleRight }}
                            </div>
                        </button>
                    </td>

                    { self.render_row(&entry.value) }
                </tr>

                <tr class=("pf-c-table__expandable-row",expanded_class.clone()) role="row">
                    { cells }
                </tr>
            </tbody>
        };
    }

    fn set_expanded(&mut self, idx: usize, state: bool) -> ShouldRender {
        self.props.entries.set_expanded(idx, state)
    }

    fn render_row(&self, entry: &M::Item) -> Vec<Html> {
        let len = self
            .props
            .header
            .as_ref()
            .map_or(0, |header| header.props.children.len());

        let mut cells: Vec<Html> = Vec::with_capacity(len);

        let mut index = 0;
        for col in self
            .props
            .header
            .iter()
            .flat_map(|header| header.props.children.iter())
        {
            let cell = entry.render(ColumnIndex { index });
            let label = col.props.label;
            cells.push(html! {
                <td role="cell" data-label=label.unwrap_or_default()>
                    {cell}
                </td>
            });

            index += 1;
        }

        cells
    }

    fn is_expandable(&self) -> bool {
        match self.props.mode {
            TableMode::Expandable | TableMode::CompactExpandable => true,
            _ => false,
        }
    }
}