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
374
375
376
377
378
379
380
381
use super::TabContent;
use crate::ouia;
use crate::prelude::{AsClasses, ExtendClasses, Icon, Inset, OuiaComponentType, WithBreakpoints};
use crate::utils::{Ouia, OuiaSafe};
use std::borrow::Cow;
use yew::html::IntoPropValue;
use yew::prelude::*;

const OUIA: Ouia = ouia!("Tabs");
const OUIA_BUTTON: Ouia = ouia!("TabsButton");
const OUIA_ITEM: Ouia = ouia!("TabsItem");

#[derive(PartialEq, Eq, Clone)]
pub struct TabsContext<T>
where
    T: PartialEq + Eq + Clone + 'static,
{
    pub selected: T,
}

/// Properties for [`Tabs`]
#[derive(Clone, Debug, Properties, PartialEq)]
pub struct TabsProperties<T>
where
    T: PartialEq + Eq + Clone + 'static,
{
    #[prop_or_default]
    pub children: ChildrenWithProps<Tab<T>>,

    #[prop_or_default]
    pub id: String,
    #[prop_or_default]
    pub r#box: bool,
    #[prop_or_default]
    pub vertical: bool,
    #[prop_or_default]
    pub filled: bool,

    #[prop_or_default]
    pub inset: Option<TabInset>,

    /// Enable "detached" mode
    ///
    /// If enabled, the content of tabs will not be rendered.
    #[prop_or_default]
    pub detached: bool,
    #[prop_or_default]
    pub onselect: Callback<T>,

    /// Set the current active tab, overrides the internal state.
    pub selected: T,

    /// OUIA Component id
    #[prop_or_default]
    pub ouia_id: Option<String>,
    /// OUIA Component Type
    #[prop_or(OUIA.component_type())]
    pub ouia_type: OuiaComponentType,
    /// OUIA Component Safe
    #[prop_or(OuiaSafe::TRUE)]
    pub ouia_safe: OuiaSafe,

    /// OUIA Component id
    #[prop_or_default]
    pub scroll_button_ouia_id: Option<String>,
    /// OUIA Component Type
    #[prop_or(OUIA_BUTTON.component_type())]
    pub scroll_button_ouia_type: OuiaComponentType,
    /// OUIA Component Safe
    #[prop_or(OuiaSafe::TRUE)]
    pub scroll_button_ouia_safe: OuiaSafe,
}

/// Tabs component
///
/// > **Tabs** allow users to navigate between views within the same page or context.
///
/// See: <https://www.patternfly.org/components/tabs>
///
/// ## Properties
///
/// Defined by [`TabsProperties`].
///
/// ## Example
///
/// ```rust
/// use yew::prelude::*;
/// use patternfly_yew::prelude::*;
///
/// #[function_component(Example)]
/// fn example() -> Html {
///   #[derive(Clone, Copy, PartialEq, Eq)]
///   enum MyIndex {
///     Foo,
///     Bar,
///   }
///
///   let selected = use_state_eq(|| MyIndex::Foo);
///   let onselect = use_callback(selected.clone(), |index, selected| selected.set(index));
///
///   html!(
///     <Tabs<MyIndex> selected={*selected} {onselect}>
///       <Tab<MyIndex> index={MyIndex::Foo} title="Foo">
///         {"Foo"}
///       </Tab<MyIndex>>
///       <Tab<MyIndex> index={MyIndex::Bar} title="Bar">
///         {"Bar"}
///       </Tab<MyIndex>>
///     </Tabs<MyIndex>>
///   )
/// }
/// ```
///
/// For more examples, see the PatternFly Yew Quickstart project.
#[function_component(Tabs)]
pub fn tabs<T>(props: &TabsProperties<T>) -> Html
where
    T: PartialEq + Eq + Clone + 'static,
{
    let ouia_id = use_memo(props.ouia_id.clone(), |id| {
        id.clone().unwrap_or(OUIA.generated_id())
    });
    let mut class = classes!("pf-v5-c-tabs");

    if props.r#box {
        class.push(classes!("pf-m-box"));
    }

    if props.vertical {
        class.push(classes!("pf-m-vertical"));
    }

    if props.filled {
        class.push(classes!("pf-m-fill"));
    }

    class.extend_from(&props.inset);

    let context = TabsContext {
        selected: props.selected.clone(),
    };

    let button_ouia_id = use_memo(props.scroll_button_ouia_id.clone(), |id| {
        id.clone().unwrap_or(OUIA.generated_id())
    });

    html!(
        <ContextProvider<TabsContext<T>> {context}>
            <div
                {class}
                id={props.id.clone()}
                data-ouia-component-id={(*ouia_id).clone()}
                data-ouia-component-type={props.ouia_type}
                data-ouia-safe={props.ouia_safe}
            >
                <button
                    class="pf-v5-c-tabs__scroll-button"
                    disabled=true
                    aria-hidden="true"
                    aria-label="Scroll left"
                    data-ouia-component-type={props.scroll_button_ouia_type}
                    data-ouia-safe={props.scroll_button_ouia_safe}
                    data-ouia-component-id={(*button_ouia_id).clone()}
                >
                    { Icon::AngleLeft }
                </button>
                <ul class="pf-v5-c-tabs__list">
                    { for props.children.iter().map(|c| {
                        let onselect = props.onselect.clone();
                        html!(
                            <TabHeaderItem<T>
                                icon={c.props.icon}
                                index={c.props.index.clone()}
                                {onselect}
                            >
                                { c.props.title.to_html() }
                            </TabHeaderItem<T>>
                        )
                    }) }
                </ul>
                <button
                    class="pf-v5-c-tabs__scroll-button"
                    disabled=true
                    aria-hidden="true"
                    aria-label="Scroll right"
                >
                    { Icon::AngleRight }
                </button>
            </div>

            if !props.detached {
                { for props.children.iter() }
            }
        </ContextProvider<TabsContext<T>>>
    )
}

#[derive(Clone, Debug, PartialEq)]
pub enum TabInset {
    Inset(WithBreakpoints<Inset>),
    Page,
}

impl AsClasses for TabInset {
    fn extend_classes(&self, classes: &mut Classes) {
        match self {
            Self::Page => classes.push("pf-m-page-insets"),
            Self::Inset(insets) => {
                insets.extend_classes(classes);
            }
        }
    }
}

#[derive(Clone, Debug, Properties, PartialEq)]
struct TabHeaderItemProperties<T>
where
    T: PartialEq + Eq + Clone + 'static,
{
    #[prop_or_default]
    pub children: Html,

    #[prop_or_default]
    pub icon: Option<Icon>,

    #[prop_or_default]
    pub onselect: Callback<T>,

    pub index: T,

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

    /// OUIA Component id
    #[prop_or_default]
    pub ouia_id: Option<String>,
    /// OUIA Component Type
    #[prop_or(OUIA_ITEM.component_type())]
    pub ouia_type: OuiaComponentType,
    /// OUIA Component Safe
    #[prop_or(OuiaSafe::TRUE)]
    pub ouia_safe: OuiaSafe,
}

#[function_component(TabHeaderItem)]
fn tab_header_item<T>(props: &TabHeaderItemProperties<T>) -> Html
where
    T: PartialEq + Eq + Clone + 'static,
{
    let ouia_id = use_memo(props.ouia_id.clone(), |id| {
        id.clone().unwrap_or(OUIA_ITEM.generated_id())
    });
    let context = use_context::<TabsContext<T>>();
    let current = context
        .map(|context| context.selected == props.index)
        .unwrap_or_default();

    let mut class = Classes::from("pf-v5-c-tabs__item");

    if current {
        class.push("pf-m-current");
    }

    let onclick = use_callback(
        (props.index.clone(), props.onselect.clone()),
        |_, (index, onselect)| {
            onselect.emit(index.clone());
        },
    );

    html!(
        <li
            {class}
            id={props.id.clone()}
            data-ouia-component-id={(*ouia_id).clone()}
            data-ouia-component-type={props.ouia_type}
            data-ouia-safe={props.ouia_safe}
        >
            <button class="pf-v5-c-tabs__link" {onclick}>
                if let Some(icon) = props.icon {
                    <span class="pf-v5-c-tabs__item-icon" aria_hidden={true.to_string()}> { icon } </span>
                }
                <span class="pf-v5-c-tabs__item-text">
                    { props.children.clone() }
                </span>
            </button>
        </li>
    )
}

#[derive(Clone, PartialEq)]
pub enum TabTitle {
    String(Cow<'static, str>),
    Html(Html),
}

impl IntoPropValue<TabTitle> for String {
    fn into_prop_value(self) -> TabTitle {
        TabTitle::String(self.into())
    }
}

impl IntoPropValue<TabTitle> for &'static str {
    fn into_prop_value(self) -> TabTitle {
        TabTitle::String(self.into())
    }
}

impl IntoPropValue<TabTitle> for Html {
    fn into_prop_value(self) -> TabTitle {
        TabTitle::Html(self)
    }
}

impl ToHtml for TabTitle {
    fn to_html(&self) -> Html {
        match self {
            TabTitle::String(s) => s.into(),
            TabTitle::Html(html) => html.clone(),
        }
    }

    fn into_html(self) -> Html
    where
        Self: Sized,
    {
        match self {
            TabTitle::String(s) => s.into(),
            TabTitle::Html(html) => html,
        }
    }
}

/// Properties for [`Tab`]
#[derive(Properties, PartialEq)]
pub struct TabProperties<T>
where
    T: PartialEq + Eq + Clone + 'static,
{
    pub title: TabTitle,

    #[prop_or_default]
    pub icon: Option<Icon>,

    #[prop_or_default]
    pub children: Html,

    pub index: T,

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

    #[prop_or_default]
    pub class: Classes,

    #[prop_or_default]
    pub style: Option<AttrValue>,
}

/// A tab in a [`Tabs`] component
#[function_component(Tab)]
pub fn tab<T>(props: &TabProperties<T>) -> Html
where
    T: PartialEq + Eq + Clone + 'static,
{
    let context = use_context::<TabsContext<T>>();
    let current = context
        .map(|context| context.selected == props.index)
        .unwrap_or_default();

    html!(
        <TabContent
            hidden={!current}
            id={props.id.clone()}
            class={props.class.clone()}
            style={props.style.clone()}
        >
            { props.children.clone() }
        </TabContent>
    )
}