A multi-step form with single-choice, multiple-choice, freeform and skippable questions.
use gpui::{div, prelude::*, px, Context, Entity, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::input::TextInput;
use crate::ui::questionnaire::{
Questionnaire, QuestionnaireChoice, QuestionnaireQuestion, QuestionnaireState,
};
#[derive(Default)]
pub struct QuestionnaireDemo {
state: QuestionnaireState,
notes: Option<Entity<TextInput>>,
submitted: bool,
}
impl Render for QuestionnaireDemo {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let notes = self
.notes
.get_or_insert_with(|| cx.new(|cx| TextInput::new(cx).placeholder("Tell us more")))
.clone();
let theme = cx.theme();
if self.submitted {
let platforms = self.state.answer(1).join(", ");
return div()
.w(px(420.0))
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_base()
.font_weight(FontWeight::MEDIUM)
.child("Thanks, you're all set."),
)
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child(format!("We'll set up a starter for {platforms}.")),
)
.child(
div().child(
Button::new("restart", "Start over")
.variant(ButtonVariant::Outline)
.on_click(cx.listener(|this, _, window, cx| {
this.state = QuestionnaireState::default();
this.submitted = false;
if let Some(notes) = this.notes.clone() {
notes.update(cx, |input, cx| input.set_text("", window, cx));
}
cx.notify();
})),
),
)
.into_any_element();
}
let questions = vec![
QuestionnaireQuestion::new("What are you building?")
.description("We'll tailor the starter project to it.")
.choice(
QuestionnaireChoice::new("app", "An app")
.description("Something people install and run."),
)
.choice(
QuestionnaireChoice::new("library", "A library")
.description("Code other developers depend on."),
),
QuestionnaireQuestion::new("Which platforms do you target?")
.description("Pick all that apply.")
.multiple(true)
.choice(QuestionnaireChoice::new("macOS", "macOS"))
.choice(QuestionnaireChoice::new("Windows", "Windows"))
.choice(QuestionnaireChoice::new("Linux", "Linux")),
QuestionnaireQuestion::new("Anything else we should know?")
.description("Optional. Mention deadlines or constraints.")
.required(false)
.choice(QuestionnaireChoice::new("none", "Nothing else"))
.input(notes),
];
div()
.w(px(460.0))
.child(
Questionnaire::new("onboarding", questions, &self.state)
.shortcuts(true)
.on_change(cx.listener(|this, state: &QuestionnaireState, _, cx| {
this.state = state.clone();
cx.notify();
}))
.on_submit(cx.listener(|this, state: &QuestionnaireState, _, cx| {
this.state = state.clone();
this.submitted = true;
cx.notify();
})),
)
.into_any_element()
}
}Installation
Copies src/ui/questionnaire.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/questionnaire.rs.src/ui/questionnaire.rs //! A multi-step form: one question at a time, with single-choice, multiple-choice, freeform and //! skippable questions, and Previous / Skip / Next / Submit navigation. //! //! The parent view owns a `QuestionnaireState` (which question is showing, the answers and //! whether to show the "answer required" error) and stores the new state from `on_change`. use std::rc::Rc; use gpui::{ div, prelude::*, px, svg, App, ElementId, Entity, FontWeight, KeyDownEvent, SharedString, Window, }; use crate::theme::ActiveTheme; use crate::ui::button::{Button, ButtonVariant}; use crate::ui::input::TextInput; use crate::ui::kbd::Kbd; /// Lucide's `check` with a heavier 3px stroke, to read at the small size it's drawn here. const CHECK: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>"#; const SHORTCUT_KEYS: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; /// A fixed answer: a bold label and an optional muted description. #[derive(Clone)] pub struct QuestionnaireChoice { value: SharedString, label: SharedString, description: Option<SharedString>, } impl QuestionnaireChoice { pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self { Self { value: value.into(), label: label.into(), description: None, } } pub fn description(mut self, description: impl Into<SharedString>) -> Self { self.description = Some(description.into()); self } } /// One step of the questionnaire. #[derive(Clone)] pub struct QuestionnaireQuestion { title: SharedString, description: Option<SharedString>, choices: Vec<QuestionnaireChoice>, multiple: bool, required: bool, input: Option<Entity<TextInput>>, } impl QuestionnaireQuestion { /// A required single-choice question. Add answers with `choice`. pub fn new(title: impl Into<SharedString>) -> Self { Self { title: title.into(), description: None, choices: Vec::new(), multiple: false, required: true, input: None, } } /// Helper text under the title. pub fn description(mut self, description: impl Into<SharedString>) -> Self { self.description = Some(description.into()); self } pub fn choice(mut self, choice: QuestionnaireChoice) -> Self { self.choices.push(choice); self } /// Lets the reader pick any number of choices (checkboxes instead of radios). pub fn multiple(mut self, multiple: bool) -> Self { self.multiple = multiple; self } /// An optional question shows a Skip button and can be left empty. pub fn required(mut self, required: bool) -> Self { self.required = required; self } /// A freeform answer under the choices, e.g. "Something else". Create the field once in /// your view with `cx.new(|cx| TextInput::new(cx).placeholder(...))` and keep it. pub fn input(mut self, input: Entity<TextInput>) -> Self { self.input = Some(input); self } } /// Where the reader is and what they've answered. Owned by the parent view. #[derive(Clone, Default, PartialEq)] pub struct QuestionnaireState { /// Index of the question being shown. pub active: usize, /// Selected choice values, per question. pub answers: Vec<Vec<SharedString>>, /// Set when the reader tried to move on from an unanswered required question. pub invalid: bool, } impl QuestionnaireState { /// The values chosen for question `ix`, empty if none. pub fn answer(&self, ix: usize) -> &[SharedString] { self.answers.get(ix).map(Vec::as_slice).unwrap_or(&[]) } fn select(&mut self, ix: usize, value: SharedString, multiple: bool) { if self.answers.len() <= ix { self.answers.resize(ix + 1, Vec::new()); } let answer = &mut self.answers[ix]; if !multiple { *answer = vec![value]; } else if let Some(pos) = answer.iter().position(|chosen| *chosen == value) { answer.remove(pos); } else { answer.push(value); } self.invalid = false; } } type ChangeHandler = Rc<dyn Fn(&QuestionnaireState, &mut Window, &mut App) + 'static>; #[derive(IntoElement)] pub struct Questionnaire { id: ElementId, questions: Vec<QuestionnaireQuestion>, state: QuestionnaireState, shortcuts: bool, error: SharedString, on_change: Option<ChangeHandler>, on_submit: Option<ChangeHandler>, } impl Questionnaire { pub fn new( id: impl Into<ElementId>, questions: Vec<QuestionnaireQuestion>, state: &QuestionnaireState, ) -> Self { Self { id: id.into(), questions, state: state.clone(), shortcuts: false, error: "Choose an answer to continue.".into(), on_change: None, on_submit: None, } } /// Letter keys (A, B, C...) pick choices once the questionnaire has focus, and each choice /// shows its letter. pub fn shortcuts(mut self, shortcuts: bool) -> Self { self.shortcuts = shortcuts; self } /// The message shown when a required question is left empty. pub fn error_message(mut self, message: impl Into<SharedString>) -> Self { self.error = message.into(); self } /// Receives the next state after a choice, Previous, Skip or Next. pub fn on_change( mut self, handler: impl Fn(&QuestionnaireState, &mut Window, &mut App) + 'static, ) -> Self { self.on_change = Some(Rc::new(handler)); self } /// Called with the final state when Submit is pressed on the last question and it is /// answered (or optional). Freeform answers are read from the `TextInput`s you passed. pub fn on_submit( mut self, handler: impl Fn(&QuestionnaireState, &mut Window, &mut App) + 'static, ) -> Self { self.on_submit = Some(Rc::new(handler)); self } } impl RenderOnce for Questionnaire { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { // Focus is what routes the letter shortcuts here; the app has no reason to own it. let focus = window .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle()) .read(cx) .clone(); let theme = cx.theme().clone(); let total = self.questions.len(); let active = self.state.active.min(total.saturating_sub(1)); let Some(question) = self.questions.get(active).cloned() else { return div().id(self.id).into_any_element(); }; let state = self.state; let on_change = self.on_change; let on_submit = self.on_submit; let last = active + 1 == total; let answered = !state.answer(active).is_empty() || question .input .as_ref() .is_some_and(|input| !input.read(cx).text().trim().is_empty()); let emit = { let on_change = on_change.clone(); move |next: QuestionnaireState, window: &mut Window, cx: &mut App| { if let Some(handler) = &on_change { handler(&next, window, cx); } } }; let select = { let emit = emit.clone(); let state = state.clone(); let multiple = question.multiple; move |value: SharedString, window: &mut Window, cx: &mut App| { let mut next = state.clone(); next.select(active, value, multiple); emit(next, window, cx); } }; let choices: Vec<_> = question .choices .iter() .enumerate() .map(|(ix, choice)| { let checked = state.answer(active).contains(&choice.value); let value = choice.value.clone(); let select = select.clone(); let focus = focus.clone(); let indicator = div() .flex() .flex_none() .items_center() .justify_center() .mt(px(2.0)) .size(px(16.0)) .border_1() .map(|this| { if question.multiple { this.rounded(px(4.0)) } else { this.rounded_full() } }) .map(|this| { if checked { this.border_color(theme.primary).bg(theme.primary) } else { this.border_color(theme.input) } }) .when(checked && !question.multiple, |this| { this.child( div() .size(px(8.0)) .rounded_full() .bg(theme.primary_foreground), ) }) .when(checked && question.multiple, |this| { this.child( svg() .data(CHECK) .size(px(12.0)) .text_color(theme.primary_foreground), ) }); let shortcut = SHORTCUT_KEYS .get(ix..ix + 1) .filter(|_| self.shortcuts) .map(|key| div().flex_none().child(Kbd::new(key))); div() .id(("choice", ix)) .flex() .items_start() .gap(px(10.0)) .min_h(px(44.0)) .px_3() .py(px(10.0)) .rounded(theme.radius) .border_1() .text_sm() .cursor_pointer() .map(|this| { if checked { this.border_color(theme.primary.opacity(0.4)) .bg(theme.muted) } else { this.border_color(if state.invalid { theme.destructive } else { theme.input }) .hover(|style| style.bg(theme.muted.opacity(0.5))) } }) .on_click(move |_, window, cx| { focus.focus(window, cx); select(value.clone(), window, cx); }) .child(indicator) .child( div() .flex() .flex_col() .flex_1() .min_w_0() .gap(px(2.0)) .child( div() .font_weight(FontWeight::MEDIUM) .child(choice.label.clone()), ) .children(choice.description.clone().map(|description| { div().text_color(theme.muted_foreground).child(description) })), ) .children(shortcut) }) .collect(); let previous = { let emit = emit.clone(); let state = state.clone(); Button::new("previous", "Previous") .variant(ButtonVariant::Outline) .disabled(active == 0) .on_click(move |_, window, cx| { let mut next = state.clone(); next.active = active.saturating_sub(1); next.invalid = false; emit(next, window, cx); }) }; let skip = (!question.required).then(|| { let emit = emit.clone(); let state = state.clone(); let on_submit = on_submit.clone(); Button::new("skip", "Skip") .variant(ButtonVariant::Outline) .on_click(move |_, window, cx| { let mut next = state.clone(); if let Some(answer) = next.answers.get_mut(active) { answer.clear(); } next.invalid = false; if last { if let Some(handler) = &on_submit { handler(&next, window, cx); } } else { next.active = active + 1; emit(next, window, cx); } }) }); let forward = { let state = state.clone(); let required = question.required; Button::new( if last { "submit" } else { "next" }, if last { "Submit" } else { "Next" }, ) .on_click(move |_, window, cx| { let mut next = state.clone(); if required && !answered { next.invalid = true; emit(next, window, cx); } else if last { if let Some(handler) = &on_submit { handler(&next, window, cx); } } else { next.active = active + 1; next.invalid = false; emit(next, window, cx); } }) }; let shortcut_choices: Vec<SharedString> = question .choices .iter() .map(|choice| choice.value.clone()) .collect(); let shortcuts = self.shortcuts; div() .id(self.id) .track_focus(&focus) .flex() .flex_col() .gap_4() .w_full() .min_w_0() .when(shortcuts, |this| { this.on_key_down(move |event: &KeyDownEvent, window, cx| { // Keys typed into the freeform field belong to the field. if !focus.is_focused(window) || event.keystroke.modifiers.modified() { return; } let key = event.keystroke.key.to_ascii_uppercase(); let picked = SHORTCUT_KEYS .find(key.as_str()) .filter(|_| key.len() == 1) .and_then(|ix| shortcut_choices.get(ix).cloned()); if let Some(value) = picked { select(value, window, cx); cx.stop_propagation(); } }) }) .child( div() .text_xs() .font_weight(FontWeight::MEDIUM) .text_color(theme.muted_foreground) .child(format!("Question {} of {}", active + 1, total)), ) .child( div() .flex() .flex_col() .gap_1p5() .child( div() .text_base() .font_weight(FontWeight::MEDIUM) .text_color(theme.foreground) .child(question.title.clone()), ) .children(question.description.clone().map(|description| { div() .text_sm() .text_color(theme.muted_foreground) .child(description) })), ) .child( div() .flex() .flex_col() .gap_2() .children(choices) .children( question .input .clone() .map(|input| div().w_full().child(input)), ) .when(state.invalid, |this| { this.child( div() .mt_1() .text_sm() .text_color(theme.destructive) .child(self.error), ) }), ) .child( div() .flex() .items_center() .gap_2() .child(div().flex().flex_1().child(previous)) .children(skip) .child(forward), ) .into_any_element() } }Register the module
// src/ui/mod.rs pub mod questionnaire;
Usage
use crate::ui::questionnaire::*;API Reference
QuestionnaireChoice
A fixed answer: a bold label and an optional muted description.
QuestionnaireChoice::new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self.description(description: impl Into<SharedString>)QuestionnaireQuestion
One step of the questionnaire.
QuestionnaireQuestion::new(title: impl Into<SharedString>) -> SelfA required single-choice question. Add answers with choice.
.description(description: impl Into<SharedString>)Helper text under the title.
.choice(choice: QuestionnaireChoice).multiple(multiple: bool)Lets the reader pick any number of choices (checkboxes instead of radios).
.required(required: bool)An optional question shows a Skip button and can be left empty.
.input(input: Entity<TextInput>)A freeform answer under the choices, e.g. "Something else". Create the field once in your view with cx.new(|cx| TextInput::new(cx).placeholder(...)) and keep it.
QuestionnaireState
Where the reader is and what they've answered. Owned by the parent view.
.answer(ix: usize) -> &[SharedString]The values chosen for question ix, empty if none.
Questionnaire
Questionnaire::new(id: impl Into<ElementId>, questions: Vec<QuestionnaireQuestion>, state: &QuestionnaireState) -> Self.shortcuts(shortcuts: bool)Letter keys (A, B, C...) pick choices once the questionnaire has focus, and each choice shows its letter.
.error_message(message: impl Into<SharedString>)The message shown when a required question is left empty.
.on_change(handler: impl Fn(&QuestionnaireState, &mut Window, &mut App) + 'static)Receives the next state after a choice, Previous, Skip or Next.
.on_submit(handler: impl Fn(&QuestionnaireState, &mut Window, &mut App) + 'static)Called with the final state when Submit is pressed on the last question and it is answered (or optional). Freeform answers are read from the TextInputs you passed.