hikari-components 0.2.2

Core UI components (40+) for the Hikari design system
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// hi-components/src/navigation/tabs.rs
// Tabs component

use tairitsu_hooks::ReactiveSignal;

use crate::prelude::*;
use crate::styled::StyledComponent;

pub struct TabsComponent;
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
pub enum TabPosition {
    #[default]
    Top,
    Right,
    Bottom,
    Left,
}

#[define_props]
pub struct TabPaneProps {
    pub item_key: String,

    pub tab: String,

    #[default(false)]
    pub disabled: bool,

    pub icon: Option<Element>,

    pub children: Element,

    pub class: String,
}

#[define_props]
pub struct TabsProps {
    pub default_active: String,

    pub tab_position: TabPosition,

    #[default(true)]
    pub animated: bool,

    pub class: String,

    pub children: Element,

    pub on_change: Option<EventHandler<String>>,
}

#[derive(Clone)]
pub struct TabsContext {
    pub active_key: ReactiveSignal<String>,
    pub on_change: Option<EventHandler<String>>,
    pub tab_keys: ReactiveSignal<Vec<String>>,
}

/// Tabs component with modern, premium styling
///
/// A tabbed interface component for organizing content into separate panels.
/// Inspired by Material UI and Element Plus with smooth ink bar animations.
///
/// # Features
/// - **Smooth Ink Bar**: Animated indicator that slides between tabs (Material UI style)
/// - **Multiple Positions**: Top, Bottom, Left, Right tab placements
/// - **Type Variants**: Line (default), Card, Border Card, and Segment styles
/// - **Hover Effects**: Subtle background transitions on hover
/// - **Icons**: Support for icons alongside tab labels
/// - **Animations**: Smooth content transitions between tabs
/// - **Responsive**: Size variants (sm, lg) and mobile-optimized scrolling
///
/// # Examples
///
/// ## Basic Tabs
/// ```rust
/// use hikari_components::{Tabs, TabPane};
///
/// fn app() -> Element {
///     rsx! {
///         Tabs {
///             default_active: "1".to_string(),
///             TabPane {
///                 item_key: "1".to_string(),
///                 tab: "Overview".to_string(),
///                 "Overview content"
///             }
///             TabPane {
///                 item_key: "2".to_string(),
///                 tab: "Details".to_string(),
///                 "Details content"
///             }
///         }
///     }
/// }
/// ```
///
/// ## Tabs with Icons
/// ```rust
/// use hikari_components::{Tabs, TabPane};
///
/// fn app() -> Element {
///     rsx! {
///         Tabs {
///             TabPane {
///                 item_key: "1".to_string(),
///                 tab: "Home".to_string(),
///                 icon: rsx! {
///                     svg { /* Home icon */ }
///                 },
///                 "Home content"
///             }
///             TabPane {
///                 item_key: "2".to_string(),
///                 tab: "Profile".to_string(),
///                 icon: rsx! {
///                     svg { /* Profile icon */ }
///                 },
///                 "Profile content"
///             }
///         }
///     }
/// }
/// ```
///
/// ## Card Style Tabs
/// ```rust
/// rsx! {
///     Tabs {
///         class: "hi-tabs-card",
///         TabPane { item_key: "1".to_string(), tab: "Tab 1", "Content 1" }
///         TabPane { item_key: "2".to_string(), tab: "Tab 2", "Content 2" }
///     }
/// }
/// ```
///
/// ## Segment Style Tabs (Pill-shaped)
/// ```rust
/// rsx! {
///     Tabs {
///         class: "hi-tabs-segment",
///         TabPane { item_key: "1".to_string(), tab: "Tab 1", "Content 1" }
///         TabPane { item_key: "2".to_string(), tab: "Tab 2", "Content 2" }
///     }
/// }
/// ```
///
/// # Position Variants
/// - **Top** (`.hi-tabs-top`): Tabs above content (default)
/// - **Bottom** (`.hi-tabs-bottom`): Tabs below content
/// - **Left** (`.hi-tabs-left`): Tabs on the left side
/// - **Right** (`.hi-tabs-right`): Tabs on the right side
///
/// # Type Variants
/// - **Line** (default): Minimal style with ink bar indicator
/// - **Card** (`.hi-tabs-card`): Card-like container with background
/// - **Border Card** (`.hi-tabs-border-card`): Card with visible borders
/// - **Segment** (`.hi-tabs-segment`): Pill-shaped tab container
///
/// # Styling
/// The component uses CSS custom properties for theming:
/// - `--hi-primary-600`: Active tab and ink bar color
/// - `--hi-text-primary`: Active tab text color
/// - `--hi-text-secondary`: Inactive tab text color
/// - `--hi-border`: Border color for card variants
/// - `--hi-surface`: Background for card variants
///
/// # Size Variants
/// - **Default**: 14px font, 10px padding
/// - **Small** (`.hi-tabs-sm`): 13px font, 8px padding
/// - **Large** (`.hi-tabs-lg`): 15px font, 12px padding
///
/// # Animations
/// The component includes smooth animations:
/// - Ink bar slides between tabs (300ms cubic-bezier)
/// - Tab content fades in with slide (200ms)
/// - Hover states transition smoothly (150ms)
///
/// # Accessibility
/// - Proper `role="tablist"` and `role="tab"` attributes
/// - `aria-selected` for active tabs
/// - `aria-disabled` for disabled tabs
/// - Keyboard navigation support (Arrow keys)
/// - Focus-visible states for keyboard users
///
/// # Dark Mode
/// The component automatically adapts to dark mode when `data-theme="dark"` is set on the root element.
#[component]
pub fn Tabs(props: TabsProps) -> Element {
    let active_key = use_signal(|| props.default_active.clone());

    let on_change = props.on_change.clone();

    let tab_keys_signal = use_signal(Vec::<String>::new);
    let _ctx = use_context_provider(move || TabsContext {
        active_key,
        on_change,
        tab_keys: tab_keys_signal,
    });

    let position_class = match props.tab_position {
        TabPosition::Top => "hi-tabs-top",
        TabPosition::Right => "hi-tabs-right",
        TabPosition::Bottom => "hi-tabs-bottom",
        TabPosition::Left => "hi-tabs-left",
    };

    let animated_class = if props.animated {
        "hi-tabs-animated"
    } else {
        ""
    };

    rsx! {
        div { class: format!("hi-tabs {position_class} {animated_class} {}", props.class),

            div { class: "hi-tabs-nav",

                div { class: "hi-tabs-nav-list", role: "tablist", {props.children.clone()} }

                div {
                    class: "hi-tabs-ink-bar",
                    style: "transform: translateX(...)",
                }
            }

            div { class: "hi-tabs-content", role: "tabpanel", {props.children} }
        }
    }
}

impl StyledComponent for TabsComponent {
    fn styles() -> &'static str {
        include_str!(concat!(env!("OUT_DIR"), "/styles/tabs.css"))
    }

    fn name() -> &'static str {
        "tabs"
    }
}

/// Tab pane component
#[component]
pub fn TabPane(props: TabPaneProps) -> Element {
    use hikari_palette::classes::components::TabsClass;
    use hikari_palette::classes::{ClassesBuilder, TypedClass};

    let ctx = use_context::<TabsContext>().expect("TabsContext not found");
    let ctx = ctx.get();
    let active_key = ctx.active_key.clone();
    let on_change = ctx.on_change.clone();
    let tab_keys = ctx.tab_keys.clone();

    let item_key = props.item_key.clone();
    let is_active = *active_key.read() == item_key;

    {
        let tab_keys = tab_keys.clone();
        let key_clone = item_key.clone();
        use_effect(move || {
            let mut keys = tab_keys.write();
            if !keys.contains(&key_clone) {
                keys.push(key_clone.clone());
            }
        });
    }

    let tabindex_val = if is_active { "0" } else { "-1" };

    let tab_classes = ClassesBuilder::new()
        .add_typed(TabsClass::TabsTab)
        .add_typed_if(TabsClass::TabActive, is_active)
        .add_typed_if(TabsClass::TabDisabled, props.disabled)
        .build();

    let tabpane_classes = ClassesBuilder::new()
        .add_typed(TabsClass::TabsTabpane)
        .add_typed_if(TabsClass::TabpaneActive, is_active)
        .add_typed_if(TabsClass::TabpaneInactive, !is_active)
        .build();

    let tab_icon_class = TabsClass::TabsTabIcon.class_name();
    let tab_label_class = TabsClass::TabsTabLabel.class_name();

    let aria_hidden_val = (!is_active).to_string();

    let item_key_for_click = item_key.clone();
    let active_key_for_click = active_key.clone();
    let on_change_for_click = on_change.clone();
    let onclick_handler = move |_| {
        if !props.disabled {
            active_key_for_click.set(item_key_for_click.clone());
            if let Some(handler) = on_change_for_click.as_ref() {
                handler.call(item_key_for_click.clone());
            }
        }
    };

    let item_key_for_kb = item_key.clone();
    let active_key_for_kb = active_key.clone();
    let on_change_for_kb = on_change.clone();
    let onkeydown_handler = move |e: KeyboardEvent| {
        if props.disabled {
            return;
        }
        let keys = tab_keys.read();
        let current_idx = keys.iter().position(|k| k == &item_key_for_kb);
        let Some(idx) = current_idx else { return };
        let total = keys.len();
        if total == 0 {
            return;
        }

        let next_key = match e.get_key() {
            Key::ArrowRight | Key::ArrowDown => {
                e.prevent_default();
                let next = (idx + 1) % total;
                keys.get(next).cloned()
            }
            Key::ArrowLeft | Key::ArrowUp => {
                e.prevent_default();
                let next = (idx + total - 1) % total;
                keys.get(next).cloned()
            }
            Key::Other(s) if s == "Home" => {
                e.prevent_default();
                keys.first().cloned()
            }
            Key::Other(s) if s == "End" => {
                e.prevent_default();
                keys.last().cloned()
            }
            Key::Enter | Key::Space => {
                e.prevent_default();
                if !is_active {
                    active_key_for_kb.set(item_key_for_kb.clone());
                    if let Some(handler) = on_change_for_kb.as_ref() {
                        handler.call(item_key_for_kb.clone());
                    }
                }
                None
            }
            _ => None,
        };

        if let Some(key) = next_key {
            active_key_for_kb.set(key.clone());
            if let Some(handler) = on_change_for_kb.as_ref() {
                handler.call(key);
            }
        }
    };

    let tab_el = rsx! {
        div {
            class: tab_classes,
            role: "tab",
            "data-key": item_key.clone(),
            "aria-selected": is_active,
            "aria-disabled": props.disabled,
            tabindex: tabindex_val,
            onclick: onclick_handler,
            onkeydown: onkeydown_handler,

            if let Some(icon) = props.icon {
                span { class: tab_icon_class, {icon} }
            }

            span { class: tab_label_class, "{props.tab}" }
        }
    };

    let tabpane_el = rsx! {
        div {
            class: tabpane_classes,
            role: "tabpanel",
            "data-key": item_key,
            "aria-hidden": aria_hidden_val,

            {if is_active { props.children } else { VNode::empty() }}
        }
    };

    VNode::Fragment(vec![tab_el, tabpane_el])
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::styled::StyledComponent;

    #[test]
    fn test_tab_position_default() {
        assert_eq!(TabPosition::default(), TabPosition::Top);
    }

    #[test]
    fn test_tab_position_distinct() {
        let positions = [
            TabPosition::Top,
            TabPosition::Right,
            TabPosition::Bottom,
            TabPosition::Left,
        ];
        for (i, a) in positions.iter().enumerate() {
            for (j, b) in positions.iter().enumerate() {
                if i != j {
                    assert_ne!(a, b);
                }
            }
        }
    }

    #[test]
    fn test_tabs_component_name() {
        assert_eq!(TabsComponent::name(), "tabs");
    }
}