rok-ui 0.9.2

shadcn/ui-style component system for GPUI desktop apps, with a React-like developer experience.
Documentation
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Sidebar: an application side navigation that can collapse to icons.

use std::rc::Rc;

use gpui::{
    div, prelude::*, px, AnyElement, App, ElementId, SharedString, StyleRefinement, Window,
};

use super::{button::Button, direction::ActiveDirection, overlay::child_id, tooltip::Tooltip};
use crate::sx::SxStyled;
use crate::{
    hooks::{use_keyed_state, EventHandler},
    icon::{Icon, IconName},
    styles,
    styles::ApplyStyleOverrides,
    theme::ActiveTheme,
};

/// Which edge the sidebar sits on.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SidebarSide {
    /// Docked to the left edge.
    #[default]
    Left,
    /// Docked to the right edge.
    Right,
}

/// A navigation row. Rows with sub-items expand and collapse.
pub struct SidebarItem {
    label: SharedString,
    icon: Option<IconName>,
    badge: Option<SharedString>,
    active: bool,
    on_click: Option<EventHandler<()>>,
    sub_items: Vec<SidebarItem>,
    default_open: bool,
}

impl SidebarItem {
    /// Create it with its label.
    pub fn new(label: impl Into<SharedString>) -> Self {
        Self {
            label: label.into(),
            icon: None,
            badge: None,
            active: false,
            on_click: None,
            sub_items: Vec::new(),
            default_open: false,
        }
    }

    /// An icon shown with the label.
    #[must_use]
    pub fn icon(mut self, icon: IconName) -> Self {
        self.icon = Some(icon);
        self
    }

    /// A count or tag on the right, like unread messages.
    #[must_use]
    pub fn badge(mut self, badge: impl Into<SharedString>) -> Self {
        self.badge = Some(badge.into());
        self
    }

    /// Highlight as the current page.
    #[must_use]
    pub fn active(mut self, active: bool) -> Self {
        self.active = active;
        self
    }

    /// Called when clicked or activated with the keyboard.
    #[must_use]
    pub fn on_click(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
        self.on_click = Some(Rc::new(handler));
        self
    }

    /// A nested row, shown when this row is expanded.
    #[must_use]
    pub fn sub_item(mut self, item: SidebarItem) -> Self {
        self.sub_items.push(item);
        self
    }

    /// Start expanded (rows with sub-items only).
    #[must_use]
    pub fn default_open(mut self, open: bool) -> Self {
        self.default_open = open;
        self
    }
}

/// A labeled set of [`SidebarItem`]s.
pub struct SidebarGroup {
    label: Option<SharedString>,
    items: Vec<SidebarItem>,
}

impl SidebarGroup {
    /// An empty `SidebarGroup`; add content with the builder methods.
    #[must_use]
    pub fn new() -> Self {
        Self {
            label: None,
            items: Vec::new(),
        }
    }

    /// The group heading.
    #[must_use]
    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Add an item.
    #[must_use]
    pub fn item(mut self, item: SidebarItem) -> Self {
        self.items.push(item);
        self
    }
}

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

/// Controlled: pass `collapsed`; toggle it from a [`SidebarTrigger`]. Collapsed,
/// it shrinks to icons with tooltips.
///
/// ```no_run
/// # use rok_ui::prelude::*;
/// # fn example(window: &mut Window, cx: &mut App) {
/// # let collapsed = false;
/// # let team_switcher = div();
/// # let user_menu = div();
/// let shell = div()
///     .flex_dir()
///     .size_full()
///     .child(
///         Sidebar::new("app-sidebar")
///             .collapsed(collapsed)
///             .header(team_switcher)
///             .group(
///                 SidebarGroup::new()
///                     .label("Application")
///                     .item(SidebarItem::new("Home").icon(IconName::Home).active(true))
///                     .item(SidebarItem::new("Inbox").icon(IconName::Inbox).badge("24")),
///             )
///             .footer(user_menu),
///     )
///     .child(div().flex_1().child(SidebarTrigger::new("toggle").on_toggle(|_, _, _| {})));
/// # }
/// ```
#[derive(IntoElement)]
pub struct Sidebar {
    id: ElementId,
    collapsed: bool,
    side: SidebarSide,
    header: Vec<AnyElement>,
    footer: Vec<AnyElement>,
    groups: Vec<SidebarGroup>,
    children: Vec<AnyElement>,
    sx: crate::sx::Sx,
    style_overrides: StyleRefinement,
}

crate::implement_style_overrides!(Sidebar);

impl Sidebar {
    /// Create the component. `id` must be unique among its siblings; it keys the component's state.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            collapsed: false,
            side: SidebarSide::Left,
            header: Vec::new(),
            footer: Vec::new(),
            groups: Vec::new(),
            children: Vec::new(),
            sx: crate::sx::Sx::new(),
            style_overrides: StyleRefinement::default(),
        }
    }

    /// Show icons only.
    #[must_use]
    pub fn collapsed(mut self, collapsed: bool) -> Self {
        self.collapsed = collapsed;
        self
    }

    /// Which window edge the sidebar docks to.
    #[must_use]
    pub fn side(mut self, side: SidebarSide) -> Self {
        self.side = side;
        self
    }

    /// Pinned to the top (an app or team switcher).
    #[must_use]
    pub fn header(mut self, element: impl IntoElement) -> Self {
        self.header.push(element.into_any_element());
        self
    }

    /// Pinned to the bottom (the user menu).
    #[must_use]
    pub fn footer(mut self, element: impl IntoElement) -> Self {
        self.footer.push(element.into_any_element());
        self
    }

    /// Add a group of items.
    #[must_use]
    pub fn group(mut self, group: SidebarGroup) -> Self {
        self.groups.push(group);
        self
    }
}

impl ParentElement for Sidebar {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

styles! {
    SIDEBAR = {
        root: {
            display: flex,
            direction: column,
            flex: none,
            height: full,
            width: 64,
            background: muted/40,
            border_color: border,
        },
        collapsed: { width: 12 },
        // Physical sides: `Left` and `Right` are already swapped for RTL.
        side(SidebarSide): {
            Left: { border_right: 1 },
            Right: { border_left: 1 },
        },
        section: { display: flex, direction: column, gap: 2, padding: 2 },
        content: { display: flex, direction: column, flex: 1 },
        group: { display: flex, direction: column, gap: 0.5, padding: 2 },
        group_label: {
            height: 8,
            padding_x: 2,
            display: flex,
            align: center,
            text: xs,
            font: medium,
            color: muted_foreground,
        },
        item: {
            display: flex,
            align: center,
            gap: 2,
            height: 8,
            padding_x: 2,
            radius: md,
            text: sm,
            cursor: pointer,
            border: 1,
            border_color: transparent,
            hover: { background: accent, color: accent_foreground },
            focus: { border_color: ring },
        },
        nested_item: { height: 7 },
        active: { background: accent, color: accent_foreground, font: medium },
        collapsed_item: { width: 8, justify: center, padding_x: 0 },
        item_label: { flex: 1, truncate: true },
        badge: { text: xs, font: medium },
        item_with_children: { display: flex, direction: column, gap: 0.5 },
        children: {
            display: flex,
            direction: column,
            gap: 0.5,
            margin_start: 3.5,
            padding_start: 2.5,
            border_start: 1,
            border_color: border,
        },
        trigger: { width: 7, height: 7 },
    }
}

fn render_item(
    item: SidebarItem,
    item_id: ElementId,
    collapsed: bool,
    depth: usize,
    window: &mut Window,
    cx: &mut App,
) -> AnyElement {
    let has_sub_items = !item.sub_items.is_empty();
    let default_open = item.default_open;
    let open_state = use_keyed_state(child_id(&item_id, "open"), window, cx, || default_open);
    let is_open = has_sub_items && open_state.get(cx);
    let colors = &cx.theme().colors;
    let (foreground, muted_foreground) = (colors.foreground, colors.muted_foreground);
    let on_click = item.on_click.clone();
    let label = item.label.clone();

    let row = div()
        .id(item_id.clone())
        .tab_index(0)
        .sx((
            &SIDEBAR.item,
            (depth > 0).then_some(&SIDEBAR.nested_item),
            item.active.then_some(&SIDEBAR.active),
            collapsed.then_some(&SIDEBAR.collapsed_item),
        ))
        .when(collapsed, |row| row.tooltip(Tooltip::text(label.clone())))
        .on_click(move |_, window, cx| {
            if has_sub_items {
                open_state.update(cx, |open| *open = !*open);
            }
            if let Some(handler) = on_click.as_ref() {
                handler(&(), window, cx);
            }
        })
        .when_some(item.icon, |row, icon| {
            row.child(Icon::new(icon).size(px(16.)).color(foreground))
        })
        .when(!collapsed, |row| {
            row.child(
                div()
                    .sx(&SIDEBAR.item_label)
                    .child(crate::components::bidi_text::text(item.label)),
            )
            .when_some(item.badge, |row, badge| {
                row.child(
                    div()
                        .sx(&SIDEBAR.badge)
                        .child(crate::components::bidi_text::text(badge)),
                )
            })
            .when(has_sub_items, |row| {
                row.child(
                    Icon::new(if is_open {
                        IconName::ChevronDown
                    } else {
                        IconName::ChevronRight.for_direction()
                    })
                    .size(px(14.))
                    .color(muted_foreground),
                )
            })
        });

    if !is_open || collapsed {
        return row.into_any_element();
    }
    let sub_rows: Vec<AnyElement> = item
        .sub_items
        .into_iter()
        .enumerate()
        .map(|(index, sub_item)| {
            let sub_id = ElementId::NamedChild(Box::new(item_id.clone()), index.to_string().into());
            render_item(sub_item, sub_id, collapsed, depth + 1, window, cx)
        })
        .collect();
    div()
        .sx(&SIDEBAR.item_with_children)
        .child(row)
        .child(div().sx(&SIDEBAR.children).children(sub_rows))
        .into_any_element()
}

impl RenderOnce for Sidebar {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let collapsed = self.collapsed;
        let side = match (self.side, cx.direction().is_rtl()) {
            (SidebarSide::Left, true) => SidebarSide::Right,
            (SidebarSide::Right, true) => SidebarSide::Left,
            (side, false) => side,
        };
        let groups: Vec<AnyElement> = self
            .groups
            .into_iter()
            .enumerate()
            .map(|(group_index, group)| {
                let rows: Vec<AnyElement> = group
                    .items
                    .into_iter()
                    .enumerate()
                    .map(|(item_index, item)| {
                        let item_id = ElementId::NamedChild(
                            Box::new(child_id(&self.id, "item")),
                            format!("{group_index}-{item_index}").into(),
                        );
                        render_item(item, item_id, collapsed, 0, window, cx)
                    })
                    .collect();
                div()
                    .sx(&SIDEBAR.group)
                    .when_some(group.label.filter(|_| !collapsed), |group, label| {
                        group.child(
                            div()
                                .sx(&SIDEBAR.group_label)
                                .child(crate::components::bidi_text::text(label)),
                        )
                    })
                    .children(rows)
                    .into_any_element()
            })
            .collect();

        div()
            .id(self.id)
            .sx((
                &SIDEBAR.root,
                collapsed.then_some(&SIDEBAR.collapsed),
                SIDEBAR.side(side),
                &self.sx,
            ))
            .when(!self.header.is_empty(), |sidebar| {
                sidebar.child(div().sx(&SIDEBAR.section).children(self.header))
            })
            .child(
                div()
                    .sx(&SIDEBAR.content)
                    .id("sidebar-content")
                    .overflow_y_scroll()
                    .children(groups)
                    .children(self.children),
            )
            .when(!self.footer.is_empty(), |sidebar| {
                sidebar.child(div().sx(&SIDEBAR.section).children(self.footer))
            })
            .apply_style_overrides(&self.style_overrides)
    }
}

/// The ghost button that collapses and expands a [`Sidebar`].
#[derive(IntoElement)]
pub struct SidebarTrigger {
    id: ElementId,
    on_toggle: Option<EventHandler<()>>,
}

impl SidebarTrigger {
    /// Create the component. `id` must be unique among its siblings; it keys the component's state.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            on_toggle: None,
        }
    }

    /// Called when clicked; toggle your sidebar state here.
    #[must_use]
    pub fn on_toggle(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
        self.on_toggle = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for SidebarTrigger {
    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
        let on_toggle = self.on_toggle;
        Button::new(self.id)
            .ghost()
            .icon_only(IconName::PanelLeft)
            .sx(&SIDEBAR.trigger)
            .tooltip("Toggle sidebar")
            .on_click(move |_, window, cx| {
                if let Some(handler) = on_toggle.as_ref() {
                    handler(&(), window, cx);
                }
            })
    }
}