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
//! Toggle and `ToggleGroup`: buttons that stay pressed.

use std::rc::Rc;

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

use crate::sx::SxStyled;
use crate::{
    hooks::EventHandler,
    icon::{Icon, IconName},
    styles,
    styles::{ApplyStyleOverrides, ComponentSize},
    theme::ActiveTheme,
};

/// Visual style of a toggle.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ToggleVariant {
    /// Transparent until pressed or hovered.
    #[default]
    Default,
    /// Bordered.
    Outline,
}

/// A two-state button. Controlled: pass `pressed`, update it in `on_change`.
///
/// ```no_run
/// # use rok_ui::prelude::*;
/// # fn example(window: &mut Window, cx: &mut App) {
/// # let bold = false;
/// # fn set_bold(_: bool, _: &mut App) {}
/// let toggle = Toggle::new("bold")
///     .icon(IconName::Bold)
///     .tooltip("Bold")
///     .pressed(bold)
///     .on_change(move |pressed, _, cx| set_bold(*pressed, cx));
/// # }
/// ```
#[derive(IntoElement)]
pub struct Toggle {
    id: ElementId,
    pressed: bool,
    icon: Option<IconName>,
    label: Option<SharedString>,
    variant: ToggleVariant,
    size: ComponentSize,
    disabled: bool,
    tooltip_text: Option<SharedString>,
    on_change: Option<EventHandler<bool>>,
    sx: crate::sx::Sx,
    style_overrides: StyleRefinement,
}

crate::implement_style_overrides!(Toggle);

impl Toggle {
    /// 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(),
            pressed: false,
            icon: None,
            label: None,
            variant: ToggleVariant::Default,
            size: ComponentSize::Medium,
            disabled: false,
            tooltip_text: None,
            on_change: None,
            sx: crate::sx::Sx::new(),
            style_overrides: StyleRefinement::default(),
        }
    }

    /// Whether the toggle is on.
    #[must_use]
    pub fn pressed(mut self, pressed: bool) -> Self {
        self.pressed = pressed;
        self
    }

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

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

    /// Plain or outlined.
    #[must_use]
    pub fn variant(mut self, variant: ToggleVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Shorthand for `.variant(ToggleVariant::Outline)`.
    #[must_use]
    pub fn outline(self) -> Self {
        self.variant(ToggleVariant::Outline)
    }

    /// The size.
    #[must_use]
    pub fn size(mut self, size: ComponentSize) -> Self {
        self.size = size;
        self
    }

    /// Disable it: it ignores input and renders muted.
    #[must_use]
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// A tooltip shown on hover.
    #[must_use]
    pub fn tooltip(mut self, text: impl Into<SharedString>) -> Self {
        self.tooltip_text = Some(text.into());
        self
    }

    /// Receives the new pressed value.
    #[must_use]
    pub fn on_change(mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
        self.on_change = Some(Rc::new(handler));
        self
    }
}

styles! {
    TOGGLE = {
        base: {
            display: flex,
            flex: none,
            align: center,
            justify: center,
            gap: 2,
            padding_x: 2.5,
            radius: md,
            border: 1,
            border_color: transparent,
            color: foreground,
            text: sm,
            font: medium,
            whitespace: nowrap,
        },
        icon_only: { padding_x: 0 },
        size(ComponentSize): {
            Small: { height: 8, min_width: 8 },
            Medium: { height: 9, min_width: 9 },
            Large: { height: 10, min_width: 10 },
        },
        variant(ToggleVariant): {
            Default: {},
            Outline: { border_color: input, shadow: xs },
        },
        pressed: { background: accent, color: accent_foreground },
        interactive: {
            cursor: pointer,
            hover: { background: muted, color: muted_foreground },
            focus: { border_color: ring },
        },
        inert: { opacity: 0.5 },
    }
}

impl RenderOnce for Toggle {
    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
        let colors = &cx.theme().colors;
        let pressed = self.pressed;
        // Icons do not inherit text color in GPUI.
        let icon_color = if pressed {
            colors.accent_foreground
        } else {
            colors.foreground
        };

        div()
            .id(self.id)
            // The caller's `sx` is merged into the same call: GPUI allows a single
            // hover / focus style per element.
            .sx((
                &TOGGLE.base,
                self.label.is_none().then_some(&TOGGLE.icon_only),
                TOGGLE.size(self.size),
                TOGGLE.variant(self.variant),
                pressed.then_some(&TOGGLE.pressed),
                if self.disabled {
                    &TOGGLE.inert
                } else {
                    &TOGGLE.interactive
                },
                &self.sx,
            ))
            .when(!self.disabled, |toggle| {
                toggle
                    .tab_index(0)
                    .when_some(self.on_change, |toggle, handler| {
                        toggle.on_click(move |_, window, cx| handler(&!pressed, window, cx))
                    })
            })
            .when_some(self.tooltip_text, |toggle, text| {
                toggle.tooltip(super::Tooltip::text(text))
            })
            .when_some(self.icon, |toggle, icon| {
                toggle.child(Icon::new(icon).size(px(16.)).color(icon_color))
            })
            .when_some(self.label, |toggle, label| {
                toggle.child(crate::components::bidi_text::text(label))
            })
            .apply_style_overrides(&self.style_overrides)
    }
}

struct ToggleGroupItem {
    value: SharedString,
    icon: Option<IconName>,
    label: Option<SharedString>,
    tooltip: Option<SharedString>,
    disabled: bool,
}

/// A row of [`Toggle`]s. With `.multiple(true)` any number can be pressed;
/// otherwise pressing one releases the others (pressing it again clears it).
///
/// ```no_run
/// # use rok_ui::prelude::*;
/// # fn example(window: &mut Window, cx: &mut App) {
/// # let pressed_values: Vec<SharedString> = Vec::new();
/// # fn set_pressed_values(_: Vec<SharedString>, _: &mut App) {}
/// let formatting = ToggleGroup::new("formatting")
///     .multiple(true)
///     .outline()
///     .icon_item("bold", IconName::Bold, "Bold")
///     .icon_item("italic", IconName::Italic, "Italic")
///     .value(pressed_values.clone())
///     .on_change(move |values, _, cx| set_pressed_values(values.clone(), cx));
/// # }
/// ```
#[derive(IntoElement)]
pub struct ToggleGroup {
    id: ElementId,
    items: Vec<ToggleGroupItem>,
    value: Vec<SharedString>,
    multiple: bool,
    variant: ToggleVariant,
    size: ComponentSize,
    disabled: bool,
    on_change: Option<EventHandler<Vec<SharedString>>>,
    sx: crate::sx::Sx,
    style_overrides: StyleRefinement,
}

crate::implement_style_overrides!(ToggleGroup);

impl ToggleGroup {
    /// 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(),
            items: Vec::new(),
            value: Vec::new(),
            multiple: false,
            variant: ToggleVariant::Default,
            size: ComponentSize::Medium,
            disabled: false,
            on_change: None,
            sx: crate::sx::Sx::new(),
            style_overrides: StyleRefinement::default(),
        }
    }

    /// A text item.
    #[must_use]
    pub fn item(mut self, value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        self.items.push(ToggleGroupItem {
            value: value.into(),
            icon: None,
            label: Some(label.into()),
            tooltip: None,
            disabled: false,
        });
        self
    }

    /// An icon-only item; `tooltip` doubles as its name.
    #[must_use]
    pub fn icon_item(
        mut self,
        value: impl Into<SharedString>,
        icon: IconName,
        tooltip: impl Into<SharedString>,
    ) -> Self {
        self.items.push(ToggleGroupItem {
            value: value.into(),
            icon: Some(icon),
            label: None,
            tooltip: Some(tooltip.into()),
            disabled: false,
        });
        self
    }

    /// Disable the item added last.
    #[must_use]
    pub fn disable_last(mut self) -> Self {
        if let Some(item) = self.items.last_mut() {
            item.disabled = true;
        }
        self
    }

    /// The pressed items' values.
    #[must_use]
    pub fn value(mut self, value: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
        self.value = value.into_iter().map(Into::into).collect();
        self
    }

    /// Allow more than one pressed item.
    #[must_use]
    pub fn multiple(mut self, multiple: bool) -> Self {
        self.multiple = multiple;
        self
    }

    /// Bordered items.
    #[must_use]
    pub fn outline(mut self) -> Self {
        self.variant = ToggleVariant::Outline;
        self
    }

    /// The size.
    #[must_use]
    pub fn size(mut self, size: ComponentSize) -> Self {
        self.size = size;
        self
    }

    /// Disable it: it ignores input and renders muted.
    #[must_use]
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Receives the pressed values after a change.
    #[must_use]
    pub fn on_change(
        mut self,
        handler: impl Fn(&Vec<SharedString>, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_change = Some(Rc::new(handler));
        self
    }
}

styles! {
    TOGGLE_GROUP = {
        group: { display: flex, align: center },
        plain: { gap: 1 },
        outline: { radius: md, shadow: xs },
        // Outlined groups join into one bordered strip.
        joined: { shadow: none },
        first: { radius_end: none },
        middle: { radius: none, margin_start: -0.25 },
        last: { radius_start: none, margin_start: -0.25 },
    }
}

impl RenderOnce for ToggleGroup {
    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
        let is_outline = self.variant == ToggleVariant::Outline;
        let count = self.items.len();
        let value = self.value;
        let multiple = self.multiple;

        let toggles: Vec<AnyElement> = self
            .items
            .into_iter()
            .enumerate()
            .map(|(index, item)| {
                let is_pressed = value.contains(&item.value);
                let on_change = self.on_change.clone();
                let current = value.clone();
                let item_value = item.value.clone();
                let joined = (is_outline && count > 1).then(|| {
                    let position = if index == 0 {
                        &TOGGLE_GROUP.first
                    } else if index + 1 == count {
                        &TOGGLE_GROUP.last
                    } else {
                        &TOGGLE_GROUP.middle
                    };
                    (&TOGGLE_GROUP.joined, position)
                });
                Toggle::new(index)
                    .pressed(is_pressed)
                    .variant(self.variant)
                    .size(self.size)
                    .disabled(self.disabled || item.disabled)
                    .when_some(item.icon, Toggle::icon)
                    .when_some(item.label, Toggle::label)
                    .when_some(item.tooltip, Toggle::tooltip)
                    .sx(joined)
                    .on_change(move |pressed, window, cx| {
                        let next: Vec<SharedString> = match (multiple, *pressed) {
                            (true, true) => current
                                .iter()
                                .cloned()
                                .chain(std::iter::once(item_value.clone()))
                                .collect(),
                            (true, false) => current
                                .iter()
                                .filter(|value| **value != item_value)
                                .cloned()
                                .collect(),
                            (false, true) => vec![item_value.clone()],
                            (false, false) => Vec::new(),
                        };
                        if let Some(handler) = on_change.as_ref() {
                            handler(&next, window, cx);
                        }
                    })
                    .into_any_element()
            })
            .collect();

        div()
            .id(self.id)
            .sx((
                &TOGGLE_GROUP.group,
                if is_outline {
                    &TOGGLE_GROUP.outline
                } else {
                    &TOGGLE_GROUP.plain
                },
                &self.sx,
            ))
            .children(toggles)
            .apply_style_overrides(&self.style_overrides)
    }
}