u0ui 0.3.10

Carbon UI: IBM Carbon v11 visuals with a shadcn-style API for GPUI Kit
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! Questionnaire: a step-by-step form of single-choice, multiple-choice and
//! free-text questions (`.cu-quiz*` in `custom.css`, `Questionnaire` in
//! `index.jsx`), composed of u0ui's [`Progress`] (small), [`RadioGroup`],
//! [`Checkbox`], [`Textarea`] and [`Button`].
//!
//! - **Behavior** (the reference's): one question at a time; Next refuses to
//!   advance past an unanswered required question and shows the error row;
//!   Skip appears on optional questions but the last; Previous is disabled on
//!   the first; the last step's primary button submits every answer. Answers
//!   persist when moving back and forth. Kit's `questionnaire` is a different
//!   survey widget (its own layout, controls and copy), so it is not used.
//! - **Layout**: `.cu-quiz { flex column; gap: spacing-05; max-width: 32rem;
//!   padding: spacing-05; background: layer-01 }`; a 12px `text-secondary`
//!   kicker (the title); the small progress bar labelled by
//!   [`QuestionnaireTexts::progress`]; the question in `heading-03` (20/28,
//!   `margin-top: spacing-03`) and an optional `body-01` description in
//!   `text-secondary`; the control; the error row (`margin-top: spacing-03`,
//!   4px gap, 16px `ErrorFilled` in `support-error`, 12px `text-error`);
//!   actions at the end, 1px apart: ghost `md` Previous / Skip, primary `md`
//!   Next / Submit. `.cu-quiz` paints `layer-01` but is not a Carbon
//!   `<Layer>`, so contextual tokens keep their root values: the progress
//!   track is `border-subtle-00` and the textarea `field-01`
//!   ([`CONTROL_LAYER`]).
//! - **Copy**: every string comes from the caller ([`QuestionnaireTexts`]).
use super::button::{Button, ButtonSize, ButtonVariant};
use super::checkbox::Checkbox;
use super::form::rem;
use super::progress::{Progress, ProgressSize};
use super::radio_group::{RadioGroup, RadioGroupItem, RadioOrientation};
use super::textarea::{Textarea, TextareaState};
use crate::{
    icons::{CarbonIcon, Icon, IconSize},
    theme::{LayerLevel, color},
    tokens::{ColorRole, SPACING_02, SPACING_03, SPACING_05, TypeStyle},
    typography::TypeStyled as _,
};
use gpui_kit::{
    AnyElement, App, AppContext as _, ElementId, Entity, IntoElement, ParentElement, RenderOnce,
    SharedString, Styled, Subscription, Window, component::input::InputEvent, div,
    prelude::FluentBuilder as _, px,
};
use std::{collections::HashMap, rc::Rc};

/// `QuestionnaireItem.type`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum QuestionKind {
    /// One choice (radio group).
    Single,
    /// Any number of choices (checkboxes).
    Multiple,
    /// Free text (a 3-row textarea).
    Text,
}

/// One question (`QuestionnaireItem`).
#[derive(Clone, Debug)]
pub struct QuestionnaireItem {
    /// The answer key.
    pub name: SharedString,
    /// The question.
    pub title: SharedString,
    /// Extra text under the question.
    pub description: Option<SharedString>,
    /// Its kind.
    pub kind: QuestionKind,
    /// The choices (single / multiple).
    pub choices: Vec<SharedString>,
    /// Must be answered to continue.
    pub required: bool,
}

impl QuestionnaireItem {
    /// A question of `kind` keyed `name`.
    pub fn new(
        name: impl Into<SharedString>,
        title: impl Into<SharedString>,
        kind: QuestionKind,
    ) -> Self {
        Self {
            name: name.into(),
            title: title.into(),
            description: None,
            kind,
            choices: Vec::new(),
            required: false,
        }
    }

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

    /// The choices.
    pub fn choices<S: Into<SharedString>>(mut self, choices: impl IntoIterator<Item = S>) -> Self {
        self.choices = choices.into_iter().map(Into::into).collect();
        self
    }

    /// Mark it required.
    pub fn required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }
}

/// An answer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Answer {
    /// The chosen value.
    Single(SharedString),
    /// The checked values, in the order checked.
    Multiple(Vec<SharedString>),
    /// The text.
    Text(SharedString),
}

impl Answer {
    /// Whether it counts as answered (`v == null || v === '' || !v.length`).
    pub fn is_answered(answer: Option<&Answer>) -> bool {
        match answer {
            None => false,
            Some(Answer::Single(v)) | Some(Answer::Text(v)) => !v.is_empty(),
            Some(Answer::Multiple(v)) => !v.is_empty(),
        }
    }
}

/// Every user-facing string (the reference hard-codes English ones).
#[derive(Clone)]
pub struct QuestionnaireTexts {
    /// The progress label for question `i` (1-based) of `n`, e.g. "Question 1 of 3".
    pub progress: Rc<dyn Fn(usize, usize) -> SharedString>,
    /// "Previous".
    pub previous: SharedString,
    /// "Skip".
    pub skip: SharedString,
    /// "Next".
    pub next: SharedString,
    /// "Submit".
    pub submit: SharedString,
    /// "Answer this question to continue."
    pub required: SharedString,
}

/// What a step does on the primary button.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Advance {
    /// Show the required error.
    Refuse,
    /// Go to the next question.
    Next,
    /// Submit.
    Submit,
}

/// The primary button's effect on question `index` of `count`.
pub fn advance(index: usize, count: usize, required: bool, answered: bool) -> Advance {
    if required && !answered {
        Advance::Refuse
    } else if index + 1 >= count {
        Advance::Submit
    } else {
        Advance::Next
    }
}

/// The progress value (`((i + 1) / items.length) * 100`).
pub fn progress_value(index: usize, count: usize) -> f32 {
    (index + 1) as f32 / count.max(1) as f32 * 100.
}

/// Whether Skip shows (`!it.required && !last`).
pub fn shows_skip(index: usize, count: usize, required: bool) -> bool {
    !required && index + 1 < count
}

/// The level the progress bar and the textarea are drawn at: root (One), since
/// `.cu-quiz` creates no Carbon layer (`--border-subtle` stays
/// `border-subtle-00`, `--field` stays `field-01`).
pub const CONTROL_LAYER: LayerLevel = LayerLevel::One;

#[derive(Default)]
struct QuizState {
    index: usize,
    answers: HashMap<SharedString, Answer>,
    error: bool,
    texts: HashMap<SharedString, Entity<TextareaState>>,
    _text_changes: Vec<Subscription>,
}

impl QuizState {
    /// Any answer change clears the error, as the reference's `set()` calls
    /// `setErr('')` (free text included: every keystroke).
    fn answer_changed(&mut self) {
        self.error = false;
    }
}

type SubmitHandler = Rc<dyn Fn(&HashMap<SharedString, Answer>, &mut Window, &mut App)>;

/// The questionnaire. See the module docs.
#[derive(IntoElement)]
pub struct Questionnaire {
    id: ElementId,
    title: Option<SharedString>,
    items: Vec<QuestionnaireItem>,
    texts: QuestionnaireTexts,
    on_submit: Option<SubmitHandler>,
}

impl Questionnaire {
    /// A questionnaire over `items`, with the caller's copy.
    pub fn new(
        id: impl Into<ElementId>,
        items: Vec<QuestionnaireItem>,
        texts: QuestionnaireTexts,
    ) -> Self {
        Self {
            id: id.into(),
            title: None,
            items,
            texts,
            on_submit: None,
        }
    }

    /// The kicker above the progress bar.
    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Called with every answer on submit.
    pub fn on_submit(
        mut self,
        f: impl Fn(&HashMap<SharedString, Answer>, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_submit = Some(Rc::new(f));
        self
    }
}

/// The answers with free-text fields read from their editors.
fn collect(state: &Entity<QuizState>, cx: &App) -> HashMap<SharedString, Answer> {
    let s = state.read(cx);
    let mut answers = s.answers.clone();
    for (name, editor) in &s.texts {
        let text = editor.read(cx).value();
        answers.insert(name.clone(), Answer::Text(text));
    }
    answers
}

impl RenderOnce for Questionnaire {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let count = self.items.len();
        let state = window.use_keyed_state((id.clone(), "quiz"), cx, |_, _| QuizState::default());
        let index = state.read(cx).index.min(count.saturating_sub(1));
        let Some(item) = self.items.get(index).cloned() else {
            return div().into_any_element();
        };
        let name = item.name.clone();

        // Free text lives in an editor kept per question.
        if item.kind == QuestionKind::Text && !state.read(cx).texts.contains_key(&name) {
            let editor = cx.new(|cx| TextareaState::new(window, cx));
            state.update(cx, |s, cx| {
                let changes = cx.subscribe(&editor, |s: &mut QuizState, _, event, cx| {
                    if matches!(event, InputEvent::Change) {
                        s.answer_changed();
                        cx.notify();
                    }
                });
                s._text_changes.push(changes);
                s.texts.insert(name.clone(), editor);
            });
        }
        let answers = collect(&state, cx);
        let current = answers.get(&name).cloned();
        // Every answer change clears the error (`set` clears `err`).
        let show_error = state.read(cx).error;

        let set_answer = {
            let state = state.clone();
            let name = name.clone();
            move |answer: Answer, cx: &mut App| {
                state.update(cx, |s, cx| {
                    s.answer_changed();
                    s.answers.insert(name.clone(), answer);
                    cx.notify();
                })
            }
        };

        let control: AnyElement = match item.kind {
            QuestionKind::Single => {
                let set_answer = set_answer.clone();
                let mut group = RadioGroup::new((id.clone(), format!("radio-{name}")))
                    .orientation(RadioOrientation::Vertical)
                    .on_value_change(move |v, _, cx| set_answer(Answer::Single(v.clone()), cx));
                if let Some(Answer::Single(v)) = &current {
                    group = group.value(v.clone());
                }
                for choice in &item.choices {
                    group = group.item(RadioGroupItem::new(choice.clone()).label(choice.clone()));
                }
                group.into_any_element()
            }
            QuestionKind::Multiple => {
                let checked = match &current {
                    Some(Answer::Multiple(v)) => v.clone(),
                    _ => Vec::new(),
                };
                // Each checkbox brings `.cds--checkbox-wrapper`'s 6px bottom
                // margin, the last 3px.
                let last = item.choices.len().saturating_sub(1);
                div()
                    .flex()
                    .flex_col()
                    .children(item.choices.iter().enumerate().map(|(k, choice)| {
                        let on = checked.contains(choice);
                        let checked = checked.clone();
                        let choice_value = choice.clone();
                        let set_answer = set_answer.clone();
                        Checkbox::new((id.clone(), format!("check-{name}-{k}")))
                            .label(choice.clone())
                            .checked(on)
                            .last_of_type(k == last)
                            .on_checked_change(move |now, _, cx| {
                                let mut next: Vec<SharedString> = checked
                                    .iter()
                                    .filter(|c| **c != choice_value)
                                    .cloned()
                                    .collect();
                                if now {
                                    next.push(choice_value.clone());
                                }
                                set_answer(Answer::Multiple(next), cx)
                            })
                    }))
                    .into_any_element()
            }
            QuestionKind::Text => {
                let editor = state.read(cx).texts.get(&name).cloned();
                match editor {
                    Some(editor) => Textarea::new((id.clone(), format!("text-{name}")), &editor)
                        .label(item.title.clone())
                        .hide_label(true)
                        .rows(3)
                        .layer(CONTROL_LAYER)
                        .into_any_element(),
                    None => div().into_any_element(),
                }
            }
        };

        let texts = self.texts.clone();
        let on_submit = self.on_submit.clone();
        let primary = {
            let state = state.clone();
            let required = item.required;
            move |_: &gpui_kit::ClickEvent, window: &mut Window, cx: &mut App| {
                let answers = collect(&state, cx);
                let answered = Answer::is_answered(answers.get(&name));
                match advance(index, count, required, answered) {
                    Advance::Refuse => state.update(cx, |s, cx| {
                        s.error = true;
                        cx.notify();
                    }),
                    Advance::Next => state.update(cx, |s, cx| {
                        s.error = false;
                        s.index = index + 1;
                        cx.notify();
                    }),
                    Advance::Submit => {
                        if let Some(f) = on_submit.as_ref() {
                            f(&answers, window, cx);
                        }
                    }
                }
            }
        };
        let go = |to: usize| {
            let state = state.clone();
            move |_: &gpui_kit::ClickEvent, _: &mut Window, cx: &mut App| {
                state.update(cx, |s, cx| {
                    s.error = false;
                    s.index = to;
                    cx.notify();
                })
            }
        };
        let last = index + 1 >= count;

        div()
            .flex()
            .flex_col()
            .gap(SPACING_05)
            .max_w(rem(512.))
            .p(SPACING_05)
            .bg(color(ColorRole::Layer01))
            .when_some(self.title, |this, title| {
                this.child(
                    div()
                        .type_style(TypeStyle::Label01)
                        .text_color(color(ColorRole::TextSecondary))
                        .child(title),
                )
            })
            .child(
                Progress::new((id.clone(), "progress"))
                    .label((texts.progress)(index + 1, count))
                    .value(progress_value(index, count))
                    .size(ProgressSize::Small)
                    .layer(CONTROL_LAYER),
            )
            .child(
                div()
                    .flex()
                    .flex_col()
                    .child(
                        div()
                            .mt(SPACING_03)
                            .type_style(TypeStyle::Heading03)
                            .text_color(color(ColorRole::TextPrimary))
                            .child(item.title.clone()),
                    )
                    .when_some(item.description.clone(), |this, d| {
                        this.child(
                            div()
                                .type_style(TypeStyle::Body01)
                                .text_color(color(ColorRole::TextSecondary))
                                .child(d),
                        )
                    }),
            )
            .child(
                div()
                    .flex()
                    .flex_col()
                    .child(control)
                    .when(show_error, |this| {
                        this.child(
                            div()
                                .flex()
                                .flex_row()
                                .items_center()
                                .gap(SPACING_02)
                                .mt(SPACING_03)
                                .text_size(rem(12.))
                                .text_color(color(ColorRole::TextError))
                                .child(
                                    Icon::carbon(CarbonIcon::ErrorFilled)
                                        .size(IconSize::S16)
                                        .color(color(ColorRole::SupportError)),
                                )
                                .child(texts.required.clone()),
                        )
                    }),
            )
            .child(
                div()
                    .flex()
                    .flex_row()
                    .justify_end()
                    .gap(px(1.))
                    .child(
                        Button::new((id.clone(), "previous"), texts.previous.clone())
                            .variant(ButtonVariant::Ghost)
                            .size(ButtonSize::Md)
                            .disabled(index == 0)
                            .on_click(go(index.saturating_sub(1))),
                    )
                    .when(shows_skip(index, count, item.required), |this| {
                        this.child(
                            Button::new((id.clone(), "skip"), texts.skip.clone())
                                .variant(ButtonVariant::Ghost)
                                .size(ButtonSize::Md)
                                .on_click(go(index + 1)),
                        )
                    })
                    .child(
                        Button::new(
                            (id.clone(), "primary"),
                            if last {
                                texts.submit.clone()
                            } else {
                                texts.next.clone()
                            },
                        )
                        .variant(ButtonVariant::Primary)
                        .size(ButtonSize::Md)
                        .on_click(primary),
                    ),
            )
            .into_any_element()
    }
}

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

    #[test]
    fn steps_follow_the_reference_logic() {
        assert_eq!(advance(0, 3, true, false), Advance::Refuse);
        assert_eq!(advance(0, 3, true, true), Advance::Next);
        assert_eq!(advance(1, 3, false, false), Advance::Next);
        assert_eq!(advance(2, 3, false, false), Advance::Submit);
        assert!(shows_skip(1, 3, false));
        assert!(!shows_skip(0, 3, true));
        assert!(!shows_skip(2, 3, false));
        assert!((progress_value(0, 3) - 100. / 3.).abs() < 1e-4);
        assert_eq!(progress_value(2, 3), 100.);
    }

    #[test]
    fn controls_use_root_tokens_and_changes_clear_the_error() {
        crate::theme::tests_set(crate::tokens::CarbonTheme::White);
        // `.cds--progress-bar__track { background: var(--border-subtle) }` at root.
        assert_eq!(
            crate::components::separator::line_color(CONTROL_LAYER),
            color(ColorRole::BorderSubtle00)
        );
        let mut s = QuizState {
            error: true,
            ..Default::default()
        };
        s.answer_changed();
        assert!(!s.error);
    }

    #[test]
    fn empty_answers_do_not_count() {
        assert!(!Answer::is_answered(None));
        assert!(!Answer::is_answered(Some(&Answer::Text("".into()))));
        assert!(!Answer::is_answered(Some(&Answer::Multiple(vec![]))));
        assert!(Answer::is_answered(Some(&Answer::Single("2–10".into()))));
    }
}