Skip to main content

gpui_deck/
questionnaire.rs

1//! Linear question, review, and completion state with application-owned answers.
2
3use gpui::{
4    AnyElement, App, Div, ElementId, InteractiveElement as _, IntoElement, ParentElement,
5    RenderOnce, Role, SharedString, Stateful, StatefulInteractiveElement as _, StyleRefinement,
6    Styled, Window, div,
7};
8
9use crate::{ObservedElement, TestSupportExt as _};
10
11/// The current part of a linear questionnaire.
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub enum QuestionnaireStage {
14    Question(usize),
15    Review,
16    Complete,
17}
18
19/// A small, presentation-independent questionnaire controller.
20///
21/// `A` is the application's answer type, which may be an enum for different
22/// kinds of question. Editors, prompts, validation, and persistence belong to the
23/// application. There is no schema interpreter or form field registry. Retain
24/// this value in the application's view, and notify that view after navigation.
25/// Answer values survive Back, review, completion, and editing a previous step.
26pub struct QuestionnaireState<A> {
27    answers: Vec<Option<A>>,
28    stage: QuestionnaireStage,
29    error: Option<SharedString>,
30}
31
32impl<A> QuestionnaireState<A> {
33    /// Creates a fixed linear flow. An empty flow starts at Review.
34    pub fn new(question_count: usize) -> Self {
35        Self {
36            answers: (0..question_count).map(|_| None).collect(),
37            stage: if question_count == 0 {
38                QuestionnaireStage::Review
39            } else {
40                QuestionnaireStage::Question(0)
41            },
42            error: None,
43        }
44    }
45
46    pub fn stage(&self) -> QuestionnaireStage {
47        self.stage
48    }
49    pub fn question_count(&self) -> usize {
50        self.answers.len()
51    }
52    pub fn answer(&self, index: usize) -> Option<&A> {
53        self.answers.get(index).and_then(Option::as_ref)
54    }
55    pub fn answers(&self) -> &[Option<A>] {
56        &self.answers
57    }
58    pub fn error(&self) -> Option<&SharedString> {
59        self.error.as_ref()
60    }
61
62    /// Retains the submitted answer, including when validation rejects it.
63    /// Advances only on the application's successful validation result.
64    /// An error stays on its question; submit again to replace it.
65    pub fn submit_answer(&mut self, answer: A, validation: Result<(), SharedString>) -> bool {
66        let QuestionnaireStage::Question(index) = self.stage else {
67            return false;
68        };
69        self.answers[index] = Some(answer);
70        if let Err(error) = validation {
71            self.error = Some(error);
72            return false;
73        }
74        self.error = None;
75        self.stage = if index + 1 < self.answers.len() {
76            QuestionnaireStage::Question(index + 1)
77        } else {
78            QuestionnaireStage::Review
79        };
80        true
81    }
82
83    pub fn can_go_back(&self) -> bool {
84        match self.stage {
85            QuestionnaireStage::Question(index) => index > 0,
86            QuestionnaireStage::Review => !self.answers.is_empty(),
87            QuestionnaireStage::Complete => true,
88        }
89    }
90
91    /// Moves to the previous question, from Review to the last question, or
92    /// from Complete to Review. It never clears answers.
93    pub fn back(&mut self) -> bool {
94        self.stage = match self.stage {
95            QuestionnaireStage::Question(index) if index > 0 => {
96                QuestionnaireStage::Question(index - 1)
97            }
98            QuestionnaireStage::Review if !self.answers.is_empty() => {
99                QuestionnaireStage::Question(self.answers.len() - 1)
100            }
101            QuestionnaireStage::Complete => QuestionnaireStage::Review,
102            _ => return false,
103        };
104        self.error = None;
105        true
106    }
107
108    /// Commits the reviewed answers. Completion is local state, not a network
109    /// submission; applications perform their own side effects after success.
110    pub fn complete(&mut self) -> bool {
111        if self.stage != QuestionnaireStage::Review {
112            return false;
113        }
114        self.stage = QuestionnaireStage::Complete;
115        true
116    }
117}
118
119/// An unstyled semantic group for the active question, review, or result.
120///
121/// Supply a name describing the current stage, an existing Input or other
122/// control, and app-owned navigation Buttons. Move focus to the next editor
123/// after changing questions, or to a retained review/result control when that
124/// editor unmounts. This group adds no automatic focus stop or keyboard binding.
125#[derive(IntoElement)]
126pub struct Questionnaire {
127    base: ObservedElement<Stateful<Div>>,
128}
129
130impl Questionnaire {
131    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
132        Self {
133            base: div()
134                .id(id)
135                .test_support()
136                .role(Role::Group)
137                .aria_label(label),
138        }
139    }
140}
141
142impl Styled for Questionnaire {
143    fn style(&mut self) -> &mut StyleRefinement {
144        self.base.style()
145    }
146}
147
148impl ParentElement for Questionnaire {
149    fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
150        self.base.extend(children);
151    }
152}
153
154impl RenderOnce for Questionnaire {
155    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
156        self.base
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn validated_answers_survive_back_review_and_completion() {
166        let mut flow = QuestionnaireState::new(2);
167        assert!(!flow.complete());
168        assert!(!flow.back());
169        assert!(!flow.submit_answer(String::new(), Err("A name is required".into())));
170        assert_eq!(flow.stage(), QuestionnaireStage::Question(0));
171        assert_eq!(flow.answer(0).map(String::as_str), Some(""));
172        assert_eq!(
173            flow.error().map(|error| error.as_ref()),
174            Some("A name is required")
175        );
176        assert!(flow.submit_answer("First answer".to_string(), Ok(())));
177        assert!(flow.back());
178        assert_eq!(flow.answer(0).map(String::as_str), Some("First answer"));
179        assert!(flow.submit_answer("Edited answer".to_string(), Ok(())));
180        assert!(flow.submit_answer("Second answer".to_string(), Ok(())));
181        assert_eq!(flow.stage(), QuestionnaireStage::Review);
182        assert!(flow.back());
183        assert_eq!(flow.answer(1).map(String::as_str), Some("Second answer"));
184        assert!(flow.submit_answer("Final answer".to_string(), Ok(())));
185        assert!(flow.complete());
186        assert_eq!(flow.stage(), QuestionnaireStage::Complete);
187        assert!(!flow.submit_answer("Ignored".to_string(), Ok(())));
188        assert!(flow.back());
189        assert_eq!(flow.stage(), QuestionnaireStage::Review);
190        assert_eq!(flow.answer(0).map(String::as_str), Some("Edited answer"));
191        assert_eq!(flow.answer(1).map(String::as_str), Some("Final answer"));
192    }
193}