1use std::rc::Rc;
2
3use gpui::{
4 AnyElement, App, ElementId, Entity, InteractiveElement, IntoElement, ParentElement, RenderOnce,
5 Role, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window, div,
6 prelude::FluentBuilder as _, svg,
7};
8use gpui_base::RadioGroup;
9use rust_i18n::t;
10
11use crate::{
12 ActiveTheme as _, IconName, Sizable, Size, StyledExt as _, ThemeStyled as _,
13 button::{Button, ButtonVariants as _},
14 icon::IconNamed as _,
15 input::Input,
16 kbd::Kbd,
17};
18
19use gpui_base::questionnaire::{
20 QuestionnaireChoiceControl, QuestionnaireChoiceState, QuestionnaireState,
21 QuestionnaireValidationError,
22};
23
24type ChoiceRenderer =
25 Rc<dyn Fn(&QuestionnaireChoiceState, &mut Window, &mut App) -> AnyElement + 'static>;
26
27#[derive(Default)]
37struct QuestionnaireSizes(std::collections::HashMap<gpui::EntityId, Size>);
38
39impl gpui::Global for QuestionnaireSizes {}
40
41const MAX_TRACKED_QUESTIONNAIRES: usize = 128;
45
46fn publish_size(state: &Entity<QuestionnaireState>, size: Size, cx: &mut App) {
47 let id = state.entity_id();
48 let sizes = cx.default_global::<QuestionnaireSizes>();
49 if sizes.0.len() >= MAX_TRACKED_QUESTIONNAIRES && !sizes.0.contains_key(&id) {
50 sizes.0.clear();
51 }
52 sizes.0.insert(id, size);
53}
54
55fn resolve_size(own: Option<Size>, state: &Entity<QuestionnaireState>, cx: &App) -> Size {
56 own.unwrap_or_else(|| {
57 cx.try_global::<QuestionnaireSizes>()
58 .and_then(|sizes| sizes.0.get(&state.entity_id()).copied())
59 .unwrap_or(Size::Medium)
60 })
61}
62
63#[derive(Clone, Copy)]
67struct QuestionnaireMetrics {
68 root_gap: gpui::Pixels,
69 item_gap: gpui::Pixels,
70 choices_gap: gpui::Pixels,
71 choice_gap: gpui::Pixels,
72 content_gap: gpui::Pixels,
73 choice_padding_x: gpui::Pixels,
74 choice_padding_y: gpui::Pixels,
75 choice_min_height: gpui::Pixels,
76 choice_radius: gpui::Pixels,
77 indicator_size: gpui::Pixels,
78 indicator_mark_size: gpui::Pixels,
79 indicator_check_size: gpui::Pixels,
80 shortcut_size: gpui::Pixels,
81 shortcut_text_size: gpui::Pixels,
82 shortcut_radius: gpui::Pixels,
83}
84
85impl QuestionnaireMetrics {
86 fn new(size: Size, cx: &App) -> Self {
87 let tokens = cx.theme().semantic_tokens();
88 let spacing = tokens.spacing;
89 let radius = tokens.radius;
90 match size {
91 Size::XSmall => Self {
92 root_gap: spacing.sm,
93 item_gap: spacing.sm,
94 choices_gap: spacing.xs,
95 choice_gap: spacing.xs + spacing.xxs,
96 content_gap: spacing.xxs,
97 choice_padding_x: spacing.sm,
98 choice_padding_y: spacing.xs,
99 choice_min_height: spacing.xl + spacing.xs,
100 choice_radius: radius.md,
101 indicator_size: spacing.md,
102 indicator_mark_size: spacing.xs + spacing.xxs * 0.5,
103 indicator_check_size: spacing.sm + spacing.xxs,
104 shortcut_size: spacing.lg,
105 shortcut_text_size: spacing.sm,
106 shortcut_radius: radius.sm,
107 },
108 Size::Small => Self {
109 root_gap: spacing.md,
110 item_gap: spacing.md,
111 choices_gap: spacing.xs + spacing.xxs,
112 choice_gap: spacing.sm,
113 content_gap: spacing.xxs,
114 choice_padding_x: spacing.sm + spacing.xxs,
115 choice_padding_y: spacing.sm,
116 choice_min_height: spacing.xxl + spacing.xs,
117 choice_radius: radius.lg,
118 indicator_size: spacing.md + spacing.xxs,
119 indicator_mark_size: spacing.xs + spacing.xxs,
120 indicator_check_size: spacing.md,
121 shortcut_size: spacing.lg + spacing.xxs,
122 shortcut_text_size: spacing.sm + spacing.xxs * 0.5,
123 shortcut_radius: radius.md,
124 },
125 Size::Large => Self {
126 root_gap: spacing.xl,
127 item_gap: spacing.xl,
128 choices_gap: spacing.sm + spacing.xxs,
129 choice_gap: spacing.md,
130 content_gap: spacing.xs,
131 choice_padding_x: spacing.lg,
132 choice_padding_y: spacing.md,
133 choice_min_height: spacing.xxl + spacing.lg,
134 choice_radius: radius.xl,
135 indicator_size: spacing.lg + spacing.xxs,
136 indicator_mark_size: spacing.sm + spacing.xxs,
137 indicator_check_size: spacing.lg,
138 shortcut_size: spacing.xl,
139 shortcut_text_size: spacing.md,
140 shortcut_radius: radius.lg,
141 },
142 Size::Size(value) => Self {
143 root_gap: value,
144 item_gap: value,
145 choices_gap: value * 0.5,
146 choice_gap: value * 0.625,
147 content_gap: value * 0.125,
148 choice_padding_x: value * 0.75,
149 choice_padding_y: value * 0.625,
150 choice_min_height: value * 2.75,
151 choice_radius: radius.lg,
152 indicator_size: value,
153 indicator_mark_size: value * 0.5,
154 indicator_check_size: value * 0.875,
155 shortcut_size: value * 1.25,
156 shortcut_text_size: value * 0.625,
157 shortcut_radius: radius.md,
158 },
159 Size::Medium => Self {
160 root_gap: spacing.lg,
161 item_gap: spacing.lg,
162 choices_gap: spacing.sm,
163 choice_gap: spacing.sm + spacing.xxs,
164 content_gap: spacing.xxs,
165 choice_padding_x: spacing.md,
166 choice_padding_y: spacing.sm + spacing.xxs,
167 choice_min_height: spacing.xxl + spacing.md,
168 choice_radius: radius.lg,
169 indicator_size: spacing.lg,
170 indicator_mark_size: spacing.sm,
171 indicator_check_size: spacing.md + spacing.xxs,
172 shortcut_size: spacing.lg + spacing.xs,
173 shortcut_text_size: spacing.sm + spacing.xxs,
174 shortcut_radius: radius.md,
175 },
176 }
177 }
178}
179
180fn text_style<T: Styled>(element: T, size: Size, cx: &App) -> T {
182 let typography = cx.theme().semantic_tokens().typography;
183 match size {
184 Size::XSmall => apply_text_token(element, typography.xs),
185 Size::Small => apply_text_token(element, typography.sm),
186 Size::Large => apply_text_token(element, typography.lg),
187 Size::Size(value) => element.text_size(value),
188 Size::Medium => apply_text_token(element, typography.md),
189 }
190}
191
192fn secondary_text_style<T: Styled>(element: T, size: Size, cx: &App) -> T {
194 let typography = cx.theme().semantic_tokens().typography;
195 match size {
196 Size::XSmall | Size::Small => apply_text_token(element, typography.xs),
197 Size::Large => apply_text_token(element, typography.md),
198 Size::Size(value) => element.text_size(value * 0.875),
199 Size::Medium => apply_text_token(element, typography.sm),
200 }
201}
202
203fn progress_text_style<T: Styled>(element: T, size: Size, cx: &App) -> T {
204 let typography = cx.theme().semantic_tokens().typography;
205 match size {
206 Size::Large => apply_text_token(element, typography.sm),
207 Size::Size(value) => element.text_size(value * 0.75),
208 _ => apply_text_token(element, typography.xs),
209 }
210 .font_weight(gpui::FontWeight::MEDIUM)
211}
212
213fn description_text_style<T: Styled>(element: T, size: Size, cx: &App) -> T {
214 secondary_text_style(element, size, cx)
215}
216
217fn title_text_style<T: Styled>(element: T, size: Size, cx: &App) -> T {
218 let typography = cx.theme().semantic_tokens().typography;
219 match size {
220 Size::XSmall => apply_text_token(element, typography.sm),
221 Size::Small => apply_text_token(element, typography.md),
222 Size::Large => apply_text_token(element, typography.xl),
223 Size::Size(value) => element.text_size(value * 1.125),
224 Size::Medium => apply_text_token(element, typography.lg),
225 }
226 .font_weight(gpui::FontWeight::MEDIUM)
227}
228
229fn answer_line_height(size: Size, cx: &App) -> gpui::Pixels {
233 let typography = cx.theme().semantic_tokens().typography;
234 match size {
235 Size::XSmall => typography.xs.line_height,
236 Size::Small => typography.sm.line_height,
237 Size::Large => typography.lg.line_height,
238 Size::Size(value) => value * 1.5,
239 Size::Medium => typography.md.line_height,
240 }
241}
242
243fn center_on_answer_line(height: gpui::Pixels, size: Size, cx: &App) -> gpui::Pixels {
245 ((answer_line_height(size, cx) - height) * 0.5).max(gpui::Pixels::ZERO)
246}
247
248fn apply_text_token<T: Styled>(element: T, token: gpui_base::TextStyleToken) -> T {
249 element
250 .text_size(token.size)
251 .line_height(token.line_height)
252 .font_weight(token.weight)
253}
254
255fn item_label(
256 definition: &gpui_base::questionnaire::QuestionnaireItemDefinition,
257) -> Option<SharedString> {
258 Some(definition.accessibility_label().clone())
259}
260
261fn item_description(
262 definition: &gpui_base::questionnaire::QuestionnaireItemDefinition,
263) -> Option<SharedString> {
264 definition.description().cloned()
265}
266
267#[cfg(debug_assertions)]
273#[track_caller]
274fn report_unknown_item(item: &SharedString) {
275 tracing::warn!("questionnaire has no item named `{item}`; the part renders nothing");
276}
277
278#[cfg(debug_assertions)]
280#[track_caller]
281fn report_unknown_choice(item: &SharedString, value: &SharedString) {
282 tracing::warn!(
283 "questionnaire item `{item}` has no choice named `{value}`; the part renders nothing"
284 );
285}
286
287#[cfg(not(debug_assertions))]
288fn report_unknown_item(_: &SharedString) {}
289
290#[cfg(not(debug_assertions))]
291fn report_unknown_choice(_: &SharedString, _: &SharedString) {}
292
293fn element_id(state: &Entity<QuestionnaireState>, suffix: impl std::fmt::Display) -> ElementId {
294 ElementId::Name(format!("questionnaire-{}-{suffix}", state.entity_id()).into())
295}
296
297#[derive(IntoElement)]
300pub struct Questionnaire {
301 state: Entity<QuestionnaireState>,
302 style: StyleRefinement,
303 size: Option<Size>,
304 children: Vec<AnyElement>,
305}
306
307impl Questionnaire {
308 pub fn new(state: &Entity<QuestionnaireState>) -> Self {
309 Self {
310 state: state.clone(),
311 style: StyleRefinement::default(),
312 size: None,
313 children: Vec::new(),
314 }
315 }
316}
317
318impl Sizable for Questionnaire {
319 fn with_size(mut self, size: impl Into<Size>) -> Self {
320 self.size = Some(size.into());
321 self
322 }
323}
324
325impl Styled for Questionnaire {
326 fn style(&mut self) -> &mut StyleRefinement {
327 &mut self.style
328 }
329}
330
331impl ParentElement for Questionnaire {
332 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
333 self.children.extend(elements);
334 }
335}
336
337impl RenderOnce for Questionnaire {
338 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
339 let size = self.size.unwrap_or(Size::Medium);
342 publish_size(&self.state, size, cx);
343 let metrics = QuestionnaireMetrics::new(size, cx);
344 let focus_handle = self.state.read(cx).focus_handle().clone();
345 let state = self.state.clone();
346 let debug_selector = format!("questionnaire-{}-root", self.state.entity_id());
347
348 div()
349 .id(element_id(&self.state, "root"))
350 .debug_selector(move || debug_selector)
351 .role(Role::Form)
352 .key_context("Questionnaire")
353 .track_focus(&focus_handle)
354 .capture_key_down(move |event, window, cx| {
355 gpui_base::questionnaire::handle_key_down(&state, event, window, cx)
356 })
357 .flex()
358 .flex_col()
359 .min_w_0()
360 .gap(metrics.root_gap)
361 .w_full()
362 .refine_style(&self.style)
363 .children(self.children)
364 }
365}
366
367#[derive(IntoElement)]
369pub struct QuestionnaireProgress {
370 state: Entity<QuestionnaireState>,
371 style: StyleRefinement,
372 size: Option<Size>,
373 children: Vec<AnyElement>,
374}
375
376impl QuestionnaireProgress {
377 pub fn new(state: &Entity<QuestionnaireState>) -> Self {
378 Self {
379 state: state.clone(),
380 style: StyleRefinement::default(),
381 size: None,
382 children: Vec::new(),
383 }
384 }
385}
386
387impl Sizable for QuestionnaireProgress {
388 fn with_size(mut self, size: impl Into<Size>) -> Self {
389 self.size = Some(size.into());
390 self
391 }
392}
393
394impl Styled for QuestionnaireProgress {
395 fn style(&mut self) -> &mut StyleRefinement {
396 &mut self.style
397 }
398}
399
400impl ParentElement for QuestionnaireProgress {
401 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
402 self.children.extend(elements);
403 }
404}
405
406impl RenderOnce for QuestionnaireProgress {
407 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
408 let progress = self.state.read(cx).progress();
409 let current = progress.current();
410 let total = progress.total();
411 let label: SharedString =
412 t!("Questionnaire.progress", current = current, total = total).into();
413 let colors = cx.theme().semantic_tokens().colors;
414 let has_children = !self.children.is_empty();
415
416 let size = resolve_size(self.size, &self.state, cx);
417 progress_text_style(
418 div()
419 .id(element_id(&self.state, "progress"))
420 .role(Role::ProgressIndicator)
421 .aria_label(label.clone())
422 .aria_min_numeric_value(0.)
423 .aria_max_numeric_value(total as f64)
424 .aria_numeric_value(current as f64)
425 .text_color(colors.muted_foreground),
426 size,
427 cx,
428 )
429 .refine_style(&self.style)
430 .when(!has_children, |this| this.child(label))
431 .children(self.children)
432 }
433}
434
435macro_rules! questionnaire_item_part {
436 ($name:ident, $fallback:ident, $style:ident, $color:ident, $closes_item_gap:expr) => {
437 #[derive(IntoElement)]
438 pub struct $name {
439 state: Entity<QuestionnaireState>,
440 item: SharedString,
441 style: StyleRefinement,
442 size: Option<Size>,
443 children: Vec<AnyElement>,
444 }
445
446 impl $name {
447 pub fn new(state: &Entity<QuestionnaireState>, item: impl Into<SharedString>) -> Self {
448 Self {
449 state: state.clone(),
450 item: item.into(),
451 style: StyleRefinement::default(),
452 size: None,
453 children: Vec::new(),
454 }
455 }
456 }
457
458 impl Sizable for $name {
459 fn with_size(mut self, size: impl Into<Size>) -> Self {
460 self.size = Some(size.into());
461 self
462 }
463 }
464
465 impl Styled for $name {
466 fn style(&mut self) -> &mut StyleRefinement {
467 &mut self.style
468 }
469 }
470
471 impl ParentElement for $name {
472 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
473 self.children.extend(elements);
474 }
475 }
476
477 impl RenderOnce for $name {
478 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
479 let Some(definition) = self.state.read(cx).item_definition(&self.item) else {
480 report_unknown_item(&self.item);
481 return gpui::Empty.into_any_element();
482 };
483 let fallback = $fallback(definition);
484 let has_children = !self.children.is_empty();
485 if !has_children && fallback.is_none() {
486 return gpui::Empty.into_any_element();
487 }
488 let colors = cx.theme().semantic_tokens().colors;
489 let closes_item_gap = $closes_item_gap && item_description(definition).is_none();
493 let size = resolve_size(self.size, &self.state, cx);
494 $style(div().w_full().text_color(colors.$color), size, cx)
495 .when(closes_item_gap, |this| {
496 this.mb(QuestionnaireMetrics::new(size, cx).item_gap)
497 })
498 .refine_style(&self.style)
499 .when(!has_children, |this| {
500 this.when_some(fallback, |this, fallback| this.child(fallback))
501 })
502 .children(self.children)
503 .into_any_element()
504 }
505 }
506 };
507}
508
509questionnaire_item_part!(
510 QuestionnaireTitle,
511 item_label,
512 title_text_style,
513 foreground,
514 true
515);
516questionnaire_item_part!(
517 QuestionnaireDescription,
518 item_description,
519 description_text_style,
520 muted_foreground,
521 false
522);
523
524#[derive(IntoElement)]
527pub struct QuestionnaireItem {
528 state: Entity<QuestionnaireState>,
529 item: SharedString,
530 style: StyleRefinement,
531 size: Option<Size>,
532 children: Vec<AnyElement>,
533}
534
535impl QuestionnaireItem {
536 pub fn new(state: &Entity<QuestionnaireState>, item: impl Into<SharedString>) -> Self {
537 Self {
538 state: state.clone(),
539 item: item.into(),
540 style: StyleRefinement::default(),
541 size: None,
542 children: Vec::new(),
543 }
544 }
545}
546
547impl Sizable for QuestionnaireItem {
548 fn with_size(mut self, size: impl Into<Size>) -> Self {
549 self.size = Some(size.into());
550 self
551 }
552}
553
554impl Styled for QuestionnaireItem {
555 fn style(&mut self) -> &mut StyleRefinement {
556 &mut self.style
557 }
558}
559
560impl ParentElement for QuestionnaireItem {
561 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
562 self.children.extend(elements);
563 }
564}
565
566impl RenderOnce for QuestionnaireItem {
567 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
568 let state = self.state.read(cx);
569 let active = state.current_item().is_some_and(|name| name == &self.item);
570 let Some(item_state) = state.item_state(&self.item) else {
571 report_unknown_item(&self.item);
572 return gpui::Empty.into_any_element();
573 };
574 if !active || item_state.is_disabled() {
575 return gpui::Empty.into_any_element();
576 }
577 let Some(definition) = state.item_definition(&self.item) else {
578 return gpui::Empty.into_any_element();
579 };
580 let focus_handle = state.item_focus_handle(&self.item).cloned();
581 let label = definition.accessibility_label().clone();
582 let description = definition.description().cloned();
583 let metrics = QuestionnaireMetrics::new(resolve_size(self.size, &self.state, cx), cx);
584
585 div()
586 .id(element_id(&self.state, format!("item-{}", self.item)))
587 .role(Role::Group)
588 .aria_label(label)
589 .when_some(description, |this, description| {
590 this.aria_description(description)
591 })
592 .when_some(focus_handle, |this, focus_handle| {
593 this.track_focus(&focus_handle.tab_index(-1).tab_stop(false))
594 })
595 .flex()
596 .flex_col()
597 .gap(metrics.item_gap)
598 .w_full()
599 .refine_style(&self.style)
600 .children(self.children)
601 .into_any_element()
602 }
603}
604
605#[derive(IntoElement)]
607pub struct QuestionnaireChoices {
608 state: Entity<QuestionnaireState>,
609 item: SharedString,
610 style: StyleRefinement,
611 size: Option<Size>,
612 children: Vec<AnyElement>,
613}
614
615impl QuestionnaireChoices {
616 pub fn new(state: &Entity<QuestionnaireState>, item: impl Into<SharedString>) -> Self {
617 Self {
618 state: state.clone(),
619 item: item.into(),
620 style: StyleRefinement::default(),
621 size: None,
622 children: Vec::new(),
623 }
624 }
625}
626
627impl Sizable for QuestionnaireChoices {
628 fn with_size(mut self, size: impl Into<Size>) -> Self {
629 self.size = Some(size.into());
630 self
631 }
632}
633
634impl Styled for QuestionnaireChoices {
635 fn style(&mut self) -> &mut StyleRefinement {
636 &mut self.style
637 }
638}
639
640impl ParentElement for QuestionnaireChoices {
641 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
642 self.children.extend(elements);
643 }
644}
645
646impl RenderOnce for QuestionnaireChoices {
647 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
648 let state = self.state.read(cx);
649 let active = state.current_item().is_some_and(|name| name == &self.item);
650 let Some(item) = state.item_state(&self.item) else {
651 report_unknown_item(&self.item);
652 return gpui::Empty.into_any_element();
653 };
654 if !active || item.is_disabled() {
655 return gpui::Empty.into_any_element();
656 }
657 let metrics = QuestionnaireMetrics::new(resolve_size(self.size, &self.state, cx), cx);
658
659 if item.is_multiple() {
660 div()
661 .id(element_id(&self.state, format!("choices-{}", self.item)))
662 .role(Role::Group)
663 .flex()
664 .flex_col()
665 .gap(metrics.choices_gap)
666 .w_full()
667 .refine_style(&self.style)
668 .children(self.children)
669 .into_any_element()
670 } else {
671 RadioGroup::new(element_id(&self.state, format!("choices-{}", self.item)))
672 .flex()
673 .flex_col()
674 .gap(metrics.choices_gap)
675 .w_full()
676 .refine_style(&self.style)
677 .children(self.children)
678 .into_any_element()
679 }
680 }
681}
682
683#[derive(IntoElement)]
685pub struct QuestionnaireChoice {
686 state: Entity<QuestionnaireState>,
687 item: SharedString,
688 value: SharedString,
689 style: StyleRefinement,
690 indicator_style: StyleRefinement,
691 content_style: StyleRefinement,
692 shortcut_style: StyleRefinement,
693 size: Option<Size>,
694 children: Vec<AnyElement>,
695 indicator_renderer: Option<ChoiceRenderer>,
696 shortcut_renderer: Option<ChoiceRenderer>,
697}
698
699impl QuestionnaireChoice {
700 pub fn new(
701 state: &Entity<QuestionnaireState>,
702 item: impl Into<SharedString>,
703 value: impl Into<SharedString>,
704 ) -> Self {
705 Self {
706 state: state.clone(),
707 item: item.into(),
708 value: value.into(),
709 style: StyleRefinement::default(),
710 indicator_style: StyleRefinement::default(),
711 content_style: StyleRefinement::default(),
712 shortcut_style: StyleRefinement::default(),
713 size: None,
714 children: Vec::new(),
715 indicator_renderer: None,
716 shortcut_renderer: None,
717 }
718 }
719
720 pub fn indicator_style(mut self, style: StyleRefinement) -> Self {
721 self.indicator_style = style;
722 self
723 }
724
725 pub fn content_style(mut self, style: StyleRefinement) -> Self {
726 self.content_style = style;
727 self
728 }
729
730 pub fn shortcut_style(mut self, style: StyleRefinement) -> Self {
731 self.shortcut_style = style;
732 self
733 }
734
735 pub fn render_indicator(
736 mut self,
737 renderer: impl Fn(&QuestionnaireChoiceState, &mut Window, &mut App) -> AnyElement + 'static,
738 ) -> Self {
739 self.indicator_renderer = Some(Rc::new(renderer));
740 self
741 }
742
743 pub fn render_shortcut(
744 mut self,
745 renderer: impl Fn(&QuestionnaireChoiceState, &mut Window, &mut App) -> AnyElement + 'static,
746 ) -> Self {
747 self.shortcut_renderer = Some(Rc::new(renderer));
748 self
749 }
750}
751
752impl Sizable for QuestionnaireChoice {
753 fn with_size(mut self, size: impl Into<Size>) -> Self {
754 self.size = Some(size.into());
755 self
756 }
757}
758
759impl Styled for QuestionnaireChoice {
760 fn style(&mut self) -> &mut StyleRefinement {
761 &mut self.style
762 }
763}
764
765impl ParentElement for QuestionnaireChoice {
766 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
767 self.children.extend(elements);
768 }
769}
770
771#[allow(clippy::too_many_arguments)]
772fn style_choice_card<T>(
773 base: T,
774 indicator: AnyElement,
775 content: AnyElement,
776 shortcut: AnyElement,
777 metrics: QuestionnaireMetrics,
778 selected: bool,
779 disabled: bool,
780 invalid: bool,
781 focused: bool,
782 instance_style: &StyleRefinement,
783 window: &Window,
784 cx: &App,
785) -> T
786where
787 T: Styled + ParentElement + StatefulInteractiveElement + gpui::prelude::FluentBuilder,
788{
789 let tokens = cx.theme().semantic_tokens();
790 base.flex()
791 .items_start()
792 .gap(metrics.choice_gap)
793 .w_full()
794 .min_h(metrics.choice_min_height)
795 .px(metrics.choice_padding_x)
796 .py(metrics.choice_padding_y)
797 .border_1()
798 .border_color(if invalid {
799 tokens.colors.destructive
800 } else if selected {
801 tokens.colors.primary.opacity(0.4)
802 } else {
803 tokens.colors.input
804 })
805 .bg(if selected {
806 tokens.colors.muted
807 } else if cx.theme().is_dark() {
808 tokens.colors.input.opacity(0.2)
809 } else {
810 tokens.colors.background.opacity(0.)
811 })
812 .rounded(metrics.choice_radius)
813 .when(!disabled, |this| {
814 this.hover(|style| style.bg(tokens.colors.muted.opacity(0.5)))
815 })
816 .when(focused, |this| this.focus_ring_style(window, cx))
817 .when(disabled, |this| this.opacity(0.5))
818 .refine_style(instance_style)
819 .child(indicator)
820 .child(content)
821 .child(shortcut)
822}
823
824impl RenderOnce for QuestionnaireChoice {
825 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
826 let state = self.state.read(cx);
827 let active = state.current_item().is_some_and(|name| name == &self.item);
828 let Some(choice_state) = state.choice_state(&self.item, &self.value) else {
829 if state.item_state(&self.item).is_none() {
830 report_unknown_item(&self.item);
831 } else {
832 report_unknown_choice(&self.item, &self.value);
833 }
834 return gpui::Empty.into_any_element();
835 };
836 if !active {
837 return gpui::Empty.into_any_element();
838 }
839 let Some(item) = state.item_state(&self.item) else {
840 report_unknown_item(&self.item);
841 return gpui::Empty.into_any_element();
842 };
843 let Some(definition) = state.choice_definition(&self.item, &self.value) else {
844 return gpui::Empty.into_any_element();
845 };
846 let multiple = item.is_multiple();
847 let label = definition.accessibility_label().clone();
848 let description = definition.description().cloned();
849 let selected = choice_state.is_selected();
850 let disabled = choice_state.is_disabled();
851 let invalid = choice_state.is_invalid();
852 let shortcut = choice_state.shortcut().cloned();
853 let focus_handle = state.choice_focus_handle(&self.item, &self.value).cloned();
854 let colors = cx.theme().semantic_tokens().colors;
855 let radius = cx.theme().semantic_tokens().radius;
856 let indicator_background = cx.theme().input_background();
857 let mono_font = cx.theme().semantic_tokens().typography.mono.clone();
858 let size = resolve_size(self.size, &self.state, cx);
859 let metrics = QuestionnaireMetrics::new(size, cx);
860 let indicator_offset = center_on_answer_line(metrics.indicator_size, size, cx);
861 let shortcut_offset = center_on_answer_line(metrics.shortcut_size, size, cx);
862 let focused = focus_handle
863 .as_ref()
864 .is_some_and(|focus_handle| focus_handle.is_focused(window));
865 let has_children = !self.children.is_empty();
866
867 let default_indicator = || {
868 div()
869 .relative()
870 .flex()
871 .items_center()
872 .justify_center()
873 .flex_shrink_0()
874 .size(metrics.indicator_size)
875 .border_1()
876 .border_color(if selected {
877 colors.primary
878 } else {
879 colors.input
880 })
881 .bg(if selected {
882 colors.primary
883 } else {
884 indicator_background
885 })
886 .when(multiple, |this| this.rounded(radius.sm))
887 .when(!multiple, |this| this.rounded(radius.full))
888 .refine_style(&self.indicator_style)
889 .when(selected && multiple, |this| {
890 this.child(
891 svg()
892 .size(metrics.indicator_check_size)
893 .path(IconName::Check.path())
894 .text_color(colors.primary_foreground),
895 )
896 })
897 .when(selected && !multiple, |this| {
898 this.child(
899 div()
900 .size(metrics.indicator_mark_size)
901 .rounded(radius.full)
902 .bg(colors.primary_foreground),
903 )
904 })
905 .into_any_element()
906 };
907
908 let indicator = div()
911 .flex_shrink_0()
912 .mt(indicator_offset)
913 .child(
914 self.indicator_renderer
915 .as_ref()
916 .map(|renderer| renderer(&choice_state, window, cx))
917 .unwrap_or_else(default_indicator),
918 )
919 .into_any_element();
920
921 let content = div()
922 .flex()
923 .flex_1()
924 .flex_col()
925 .gap(metrics.content_gap)
926 .refine_style(&self.content_style)
927 .when(!has_children, |this| {
928 this.child(text_style(
929 div().text_color(colors.foreground).child(label.clone()),
930 size,
931 cx,
932 ))
933 .when_some(description.clone(), |this, description| {
934 this.child(secondary_text_style(
935 div().text_color(colors.muted_foreground).child(description),
936 size,
937 cx,
938 ))
939 })
940 })
941 .children(self.children);
942
943 let os = cx.platform_info().os;
944 let default_shortcut = || {
945 let Some(shortcut) = shortcut.clone() else {
946 return gpui::Empty.into_any_element();
947 };
948 let Ok(keystroke) = gpui::Keystroke::parse_with_os(&shortcut.to_lowercase(), os) else {
949 return gpui::Empty.into_any_element();
950 };
951 Kbd::new(keystroke)
952 .outline()
953 .flex()
954 .items_center()
955 .justify_center()
956 .size(metrics.shortcut_size)
957 .p_0()
958 .bg(colors.background)
959 .border_color(colors.input)
960 .text_color(colors.muted_foreground)
961 .font_family(mono_font.clone())
962 .text_size(metrics.shortcut_text_size)
963 .font_weight(gpui::FontWeight::MEDIUM)
964 .rounded(metrics.shortcut_radius)
965 .refine_style(&self.shortcut_style)
966 .into_any_element()
967 };
968 let shortcut_element = div()
969 .flex_shrink_0()
970 .mt(shortcut_offset)
971 .child(
972 self.shortcut_renderer
973 .as_ref()
974 .map(|renderer| renderer(&choice_state, window, cx))
975 .unwrap_or_else(default_shortcut),
976 )
977 .into_any_element();
978
979 let id = element_id(&self.state, format!("choice-{}-{}", self.item, self.value));
980 let instance_style = self.style.clone();
981 let item_name = self.item.clone();
982 let choice_value = self.value.clone();
983
984 let Some(control) =
985 QuestionnaireChoiceControl::new(&self.state, item_name, choice_value, id, cx)
986 else {
987 return gpui::Empty.into_any_element();
988 };
989 match control {
990 QuestionnaireChoiceControl::Checkbox(base) => style_choice_card(
991 base,
992 indicator,
993 content.into_any_element(),
994 shortcut_element,
995 metrics,
996 selected,
997 disabled,
998 invalid,
999 focused,
1000 &instance_style,
1001 window,
1002 cx,
1003 )
1004 .into_any_element(),
1005 QuestionnaireChoiceControl::Radio(base) => style_choice_card(
1006 base,
1007 indicator,
1008 content.into_any_element(),
1009 shortcut_element,
1010 metrics,
1011 selected,
1012 disabled,
1013 invalid,
1014 focused,
1015 &instance_style,
1016 window,
1017 cx,
1018 )
1019 .into_any_element(),
1020 }
1021 }
1022}
1023
1024#[derive(IntoElement)]
1026pub struct QuestionnaireChoiceDescription {
1027 style: StyleRefinement,
1028 size: Option<Size>,
1029 children: Vec<AnyElement>,
1030}
1031
1032impl QuestionnaireChoiceDescription {
1033 pub fn new() -> Self {
1034 Self {
1035 style: StyleRefinement::default(),
1036 size: None,
1037 children: Vec::new(),
1038 }
1039 }
1040}
1041
1042impl Default for QuestionnaireChoiceDescription {
1043 fn default() -> Self {
1044 Self::new()
1045 }
1046}
1047
1048impl Sizable for QuestionnaireChoiceDescription {
1049 fn with_size(mut self, size: impl Into<Size>) -> Self {
1050 self.size = Some(size.into());
1051 self
1052 }
1053}
1054
1055impl Styled for QuestionnaireChoiceDescription {
1056 fn style(&mut self) -> &mut StyleRefinement {
1057 &mut self.style
1058 }
1059}
1060
1061impl ParentElement for QuestionnaireChoiceDescription {
1062 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1063 self.children.extend(elements);
1064 }
1065}
1066
1067impl RenderOnce for QuestionnaireChoiceDescription {
1068 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
1069 let colors = cx.theme().semantic_tokens().colors;
1070 secondary_text_style(
1071 div().text_color(colors.muted_foreground),
1072 self.size.unwrap_or(Size::Medium),
1073 cx,
1074 )
1075 .refine_style(&self.style)
1076 .children(self.children)
1077 }
1078}
1079
1080#[derive(IntoElement)]
1082pub struct QuestionnaireInput {
1083 state: Entity<QuestionnaireState>,
1084 item: SharedString,
1085 style: StyleRefinement,
1086 size: Option<Size>,
1087}
1088
1089impl QuestionnaireInput {
1090 pub fn new(state: &Entity<QuestionnaireState>, item: impl Into<SharedString>) -> Self {
1091 Self {
1092 state: state.clone(),
1093 item: item.into(),
1094 style: StyleRefinement::default(),
1095 size: None,
1096 }
1097 }
1098}
1099
1100impl Sizable for QuestionnaireInput {
1101 fn with_size(mut self, size: impl Into<Size>) -> Self {
1102 self.size = Some(size.into());
1103 self
1104 }
1105}
1106
1107impl Styled for QuestionnaireInput {
1108 fn style(&mut self) -> &mut StyleRefinement {
1109 &mut self.style
1110 }
1111}
1112
1113impl RenderOnce for QuestionnaireInput {
1114 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
1115 let state = self.state.read(cx);
1116 let active = state.current_item().is_some_and(|name| name == &self.item);
1117 let Some(item_state) = state.item_state(&self.item) else {
1118 report_unknown_item(&self.item);
1119 return gpui::Empty.into_any_element();
1120 };
1121 let Some(definition) = state.item_definition(&self.item) else {
1122 return gpui::Empty.into_any_element();
1123 };
1124 let Some(input_definition) = definition.input() else {
1125 return gpui::Empty.into_any_element();
1126 };
1127 if !active {
1128 return gpui::Empty.into_any_element();
1129 }
1130
1131 let size = resolve_size(self.size, &self.state, cx);
1132 let metrics = QuestionnaireMetrics::new(size, cx);
1133
1134 Input::new(input_definition.state())
1135 .aria_label(input_definition.accessibility_label().clone())
1136 .disabled(item_state.is_disabled() || input_definition.is_disabled())
1137 .with_size(size)
1138 .pl(metrics.choice_padding_x)
1141 .rounded(metrics.choice_radius)
1142 .when(item_state.is_invalid(), |this| {
1143 this.border_color(cx.theme().semantic_tokens().colors.destructive)
1144 })
1145 .refine_style(&self.style)
1146 .into_any_element()
1147 }
1148}
1149
1150#[derive(IntoElement)]
1152pub struct QuestionnaireError {
1153 state: Entity<QuestionnaireState>,
1154 item: SharedString,
1155 style: StyleRefinement,
1156 size: Option<Size>,
1157 children: Vec<AnyElement>,
1158}
1159
1160impl QuestionnaireError {
1161 pub fn new(state: &Entity<QuestionnaireState>, item: impl Into<SharedString>) -> Self {
1162 Self {
1163 state: state.clone(),
1164 item: item.into(),
1165 style: StyleRefinement::default(),
1166 size: None,
1167 children: Vec::new(),
1168 }
1169 }
1170}
1171
1172impl Sizable for QuestionnaireError {
1173 fn with_size(mut self, size: impl Into<Size>) -> Self {
1174 self.size = Some(size.into());
1175 self
1176 }
1177}
1178
1179impl Styled for QuestionnaireError {
1180 fn style(&mut self) -> &mut StyleRefinement {
1181 &mut self.style
1182 }
1183}
1184
1185impl ParentElement for QuestionnaireError {
1186 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1187 self.children.extend(elements);
1188 }
1189}
1190
1191fn questionnaire_error_root(id: ElementId) -> gpui::Stateful<gpui::Div> {
1192 div().id(id).role(Role::Alert)
1193}
1194
1195fn error_text(error: &QuestionnaireValidationError) -> SharedString {
1197 match error {
1198 QuestionnaireValidationError::Required => t!("Questionnaire.error.required").into(),
1199 QuestionnaireValidationError::Unanswered => t!("Questionnaire.error.optional").into(),
1200 QuestionnaireValidationError::Message(message) => message.clone(),
1201 _ => SharedString::default(),
1202 }
1203}
1204
1205impl RenderOnce for QuestionnaireError {
1206 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
1207 let state = self.state.read(cx);
1208 let Some(item) = state.item_state(&self.item) else {
1209 report_unknown_item(&self.item);
1210 return gpui::Empty.into_any_element();
1211 };
1212 let error = state.error(&self.item).cloned();
1213 if !item.is_invalid() || error.is_none() {
1214 return gpui::Empty.into_any_element();
1215 }
1216 let has_children = !self.children.is_empty();
1217 let colors = cx.theme().semantic_tokens().colors;
1218 let spacing = cx.theme().semantic_tokens().spacing;
1219 let size = resolve_size(self.size, &self.state, cx);
1220
1221 secondary_text_style(
1222 questionnaire_error_root(element_id(&self.state, format!("error-{}", self.item)))
1223 .mt(spacing.sm)
1224 .text_color(colors.destructive),
1225 size,
1226 cx,
1227 )
1228 .refine_style(&self.style)
1229 .when(!has_children, |this| {
1230 this.when_some(error, |this, error| this.child(error_text(&error)))
1231 })
1232 .children(self.children)
1233 .into_any_element()
1234 }
1235}
1236
1237#[derive(IntoElement)]
1239pub struct QuestionnaireActions {
1240 state: Entity<QuestionnaireState>,
1241 style: StyleRefinement,
1242 size: Option<Size>,
1243 children: Vec<AnyElement>,
1244}
1245
1246impl QuestionnaireActions {
1247 pub fn new(state: &Entity<QuestionnaireState>) -> Self {
1248 Self {
1249 state: state.clone(),
1250 style: StyleRefinement::default(),
1251 size: None,
1252 children: Vec::new(),
1253 }
1254 }
1255}
1256
1257impl Sizable for QuestionnaireActions {
1258 fn with_size(mut self, size: impl Into<Size>) -> Self {
1259 self.size = Some(size.into());
1260 self
1261 }
1262}
1263
1264impl Styled for QuestionnaireActions {
1265 fn style(&mut self) -> &mut StyleRefinement {
1266 &mut self.style
1267 }
1268}
1269
1270impl ParentElement for QuestionnaireActions {
1271 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1272 self.children.extend(elements);
1273 }
1274}
1275
1276impl RenderOnce for QuestionnaireActions {
1277 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
1278 let metrics = QuestionnaireMetrics::new(resolve_size(self.size, &self.state, cx), cx);
1279 let debug_selector = format!("questionnaire-{}-actions", self.state.entity_id());
1280 div()
1281 .id(element_id(&self.state, "actions"))
1282 .debug_selector(move || debug_selector)
1283 .flex()
1284 .min_w_0()
1285 .items_center()
1286 .justify_start()
1287 .gap(metrics.choices_gap)
1288 .w_full()
1289 .refine_style(&self.style)
1290 .children(self.children)
1291 }
1292}
1293
1294#[derive(Clone, Copy)]
1295enum QuestionnaireAction {
1296 Previous,
1297 Skip,
1298 Next,
1299 Submit,
1300}
1301
1302macro_rules! questionnaire_action_part {
1303 ($name:ident, $action:ident, $translation:literal, $outline:expr, $primary:expr) => {
1304 #[derive(IntoElement)]
1305 pub struct $name {
1306 state: Entity<QuestionnaireState>,
1307 style: StyleRefinement,
1308 size: Option<Size>,
1309 children: Vec<AnyElement>,
1310 }
1311
1312 impl $name {
1313 pub fn new(state: &Entity<QuestionnaireState>) -> Self {
1314 Self {
1315 state: state.clone(),
1316 style: StyleRefinement::default(),
1317 size: None,
1318 children: Vec::new(),
1319 }
1320 }
1321 }
1322
1323 impl Styled for $name {
1324 fn style(&mut self) -> &mut StyleRefinement {
1325 &mut self.style
1326 }
1327 }
1328
1329 impl Sizable for $name {
1330 fn with_size(mut self, size: impl Into<Size>) -> Self {
1331 self.size = Some(size.into());
1332 self
1333 }
1334 }
1335
1336 impl ParentElement for $name {
1337 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1338 self.children.extend(elements);
1339 }
1340 }
1341
1342 impl RenderOnce for $name {
1343 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
1344 let navigation = self.state.read(cx).navigation_state();
1345 let action = QuestionnaireAction::$action;
1346 let visible = match action {
1347 QuestionnaireAction::Previous => navigation.is_previous_visible(),
1348 QuestionnaireAction::Skip => navigation.is_skip_visible(),
1349 QuestionnaireAction::Next => navigation.is_next_visible(),
1350 QuestionnaireAction::Submit => navigation.is_submit_visible(),
1351 };
1352 if !visible {
1353 return gpui::Empty.into_any_element();
1354 }
1355
1356 let anchors_trailing_actions = match action {
1357 QuestionnaireAction::Skip => true,
1358 QuestionnaireAction::Next | QuestionnaireAction::Submit => {
1359 !navigation.is_skip_visible()
1360 }
1361 QuestionnaireAction::Previous => false,
1362 };
1363 let state = self.state.clone();
1364 let has_children = !self.children.is_empty();
1365 let debug_selector = format!(
1366 "questionnaire-{}-{}",
1367 self.state.entity_id(),
1368 stringify!($action)
1369 );
1370 Button::new(element_id(&self.state, stringify!($action)))
1371 .debug_selector(move || debug_selector)
1372 .with_size(resolve_size(self.size, &self.state, cx))
1373 .when($outline, |this| this.outline())
1374 .when($primary, |this| this.primary())
1375 .when(anchors_trailing_actions, |this| this.ml_auto())
1376 .on_click(move |_, window, cx| {
1377 state.update(cx, |state, cx| match action {
1378 QuestionnaireAction::Previous => state.go_previous(window, cx),
1379 QuestionnaireAction::Skip => state.skip_current(window, cx),
1380 QuestionnaireAction::Next => state.go_next(window, cx),
1381 QuestionnaireAction::Submit => state.submit(window, cx),
1382 });
1383 })
1384 .refine_style(&self.style)
1385 .when(!has_children, |this| this.label(t!($translation)))
1386 .children(self.children)
1387 .into_any_element()
1388 }
1389 }
1390 };
1391}
1392
1393questionnaire_action_part!(
1394 QuestionnairePrevious,
1395 Previous,
1396 "Questionnaire.previous",
1397 true,
1398 false
1399);
1400questionnaire_action_part!(QuestionnaireSkip, Skip, "Questionnaire.skip", true, false);
1401questionnaire_action_part!(QuestionnaireNext, Next, "Questionnaire.next", false, true);
1402questionnaire_action_part!(
1403 QuestionnaireSubmit,
1404 Submit,
1405 "Questionnaire.submit",
1406 false,
1407 true
1408);
1409
1410#[cfg(test)]
1411mod tests {
1412 use super::*;
1413 use gpui::{
1414 AppContext as _, Context, Element as _, Focusable as _, KeyDownEvent, Keystroke, Render,
1415 TestAppContext, VisualTestContext, accesskit, px,
1416 };
1417
1418 use gpui_base::questionnaire::{
1419 QuestionnaireChoiceDefinition, QuestionnaireEvent, QuestionnaireInputDefinition,
1420 QuestionnaireItemDefinition, QuestionnaireShortcutMode,
1421 };
1422
1423 #[test]
1424 fn compound_parts_support_builder_customization() {
1425 let _ = QuestionnaireChoiceDescription::new()
1426 .opacity(0.8)
1427 .child("Description");
1428 }
1429
1430 struct QuestionnaireHarness {
1431 state: Entity<QuestionnaireState>,
1432 override_skip_margin: bool,
1433 }
1434
1435 impl Render for QuestionnaireHarness {
1436 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1437 Questionnaire::new(&self.state)
1438 .size(px(480.))
1439 .child(
1440 QuestionnaireItem::new(&self.state, "choice")
1441 .child(
1442 QuestionnaireChoices::new(&self.state, "choice")
1443 .child(QuestionnaireChoice::new(&self.state, "choice", "alpha")),
1444 )
1445 .child(QuestionnaireInput::new(&self.state, "choice")),
1446 )
1447 .child(
1448 QuestionnaireItem::new(&self.state, "first")
1449 .child(
1450 QuestionnaireChoices::new(&self.state, "first")
1451 .child(QuestionnaireChoice::new(&self.state, "first", "alpha"))
1452 .child(QuestionnaireChoice::new(&self.state, "first", "beta")),
1453 )
1454 .child(QuestionnaireInput::new(&self.state, "first")),
1455 )
1456 .child(
1457 QuestionnaireItem::new(&self.state, "second")
1458 .child(QuestionnaireInput::new(&self.state, "second")),
1459 )
1460 .child(
1461 QuestionnaireActions::new(&self.state)
1462 .child(QuestionnairePrevious::new(&self.state))
1463 .child(
1464 QuestionnaireSkip::new(&self.state)
1465 .when(self.override_skip_margin, |this| this.ml(px(0.))),
1466 )
1467 .child(QuestionnaireNext::new(&self.state))
1468 .child(QuestionnaireSubmit::new(&self.state)),
1469 )
1470 }
1471 }
1472
1473 fn visual_harness(
1474 cx: &mut TestAppContext,
1475 items: Vec<QuestionnaireItemDefinition>,
1476 shortcuts: Option<QuestionnaireShortcutMode>,
1477 ) -> (&mut VisualTestContext, Entity<QuestionnaireState>) {
1478 cx.update(crate::init);
1479 let (view, cx) = cx.add_window_view(move |_, cx| {
1480 let state = cx.new(|cx| {
1481 let state = QuestionnaireState::new(items, cx).unwrap();
1482 match shortcuts {
1483 Some(shortcuts) => state.with_shortcuts(shortcuts),
1484 None => state,
1485 }
1486 });
1487 QuestionnaireHarness {
1488 state,
1489 override_skip_margin: false,
1490 }
1491 });
1492 cx.update(|window, cx| window.draw(cx).clear(cx));
1493 let state = cx.update(|_, cx| view.read(cx).state.clone());
1494 cx.update(|window, cx| {
1495 let focus_handle = state.read(cx).focus_handle().clone();
1496 focus_handle.focus(window, cx);
1497 });
1498 (cx, state)
1499 }
1500
1501 fn input_visual_harness(
1502 cx: &mut TestAppContext,
1503 multiple: bool,
1504 ) -> (&mut VisualTestContext, Entity<QuestionnaireState>) {
1505 cx.update(crate::init);
1506 let (view, cx) = cx.add_window_view(move |window, cx| {
1507 let input = cx.new(|cx| crate::input::InputState::new(window, cx));
1508 let state = cx.new(|cx| {
1509 QuestionnaireState::new(
1510 vec![
1511 QuestionnaireItemDefinition::new("first", "First")
1512 .with_required(true)
1513 .with_multiple(multiple)
1514 .with_choices([
1515 QuestionnaireChoiceDefinition::new("alpha", "Alpha"),
1516 QuestionnaireChoiceDefinition::new("beta", "Beta"),
1517 ])
1518 .with_input(QuestionnaireInputDefinition::new(input, "Other")),
1519 QuestionnaireItemDefinition::new("second", "Second"),
1520 ],
1521 cx,
1522 )
1523 .unwrap()
1524 });
1525 QuestionnaireHarness {
1526 state,
1527 override_skip_margin: false,
1528 }
1529 });
1530 cx.update(|window, cx| window.draw(cx).clear(cx));
1531 let state = cx.update(|_, cx| view.read(cx).state.clone());
1532 (cx, state)
1533 }
1534
1535 fn actions_visual_harness(
1536 cx: &mut TestAppContext,
1537 override_skip_margin: bool,
1538 ) -> (&mut VisualTestContext, Entity<QuestionnaireState>) {
1539 cx.update(crate::init);
1540 let (view, cx) = cx.add_window_view(|_, cx| {
1541 let state = cx.new(|cx| {
1542 QuestionnaireState::new(
1543 vec![
1544 QuestionnaireItemDefinition::new("first", "First").with_required(true),
1545 QuestionnaireItemDefinition::new("second", "Second"),
1546 QuestionnaireItemDefinition::new("third", "Third").with_required(true),
1547 ],
1548 cx,
1549 )
1550 .unwrap()
1551 .with_current_item("second")
1552 .unwrap()
1553 });
1554 QuestionnaireHarness {
1555 state,
1556 override_skip_margin,
1557 }
1558 });
1559 cx.update(|window, cx| window.draw(cx).clear(cx));
1560 let state = cx.update(|_, cx| view.read(cx).state.clone());
1561 (cx, state)
1562 }
1563
1564 fn focus_input(cx: &mut VisualTestContext, state: &Entity<QuestionnaireState>, item: &str) {
1565 cx.update(|window, cx| {
1566 let input = state.read(cx).input_state(item).unwrap();
1567 let focus_handle = input.read(cx).focus_handle(cx);
1568 focus_handle.focus(window, cx);
1569 });
1570 }
1571
1572 fn simulate_key(cx: &mut VisualTestContext, key: &str, is_held: bool, simulate_ime: bool) {
1573 let os = cx.update(|_, cx| cx.platform_info().os);
1574 let mut keystroke = Keystroke::parse_with_os(key, os).unwrap();
1575 if simulate_ime {
1576 keystroke = keystroke.with_simulated_ime();
1577 }
1578 cx.simulate_event(KeyDownEvent {
1579 keystroke,
1580 is_held,
1581 prefer_character_input: false,
1582 });
1583 }
1584
1585 #[gpui::test]
1586 fn progress_projects_numeric_accessibility(cx: &mut TestAppContext) {
1587 cx.update(crate::init);
1588 let window = cx.add_empty_window();
1589 window.update(|window, cx| {
1590 let state = cx.new(|cx| {
1591 QuestionnaireState::new(
1592 vec![
1593 QuestionnaireItemDefinition::new("first", "First"),
1594 QuestionnaireItemDefinition::new("second", "Second"),
1595 ],
1596 cx,
1597 )
1598 .unwrap()
1599 });
1600 let mut node = accesskit::Node::new(Role::ProgressIndicator);
1601 QuestionnaireProgress::new(&state)
1602 .render(window, cx)
1603 .into_element()
1604 .write_a11y_info(&mut node);
1605
1606 assert_eq!(node.numeric_value(), Some(1.));
1607 assert_eq!(node.min_numeric_value(), Some(0.));
1608 assert_eq!(node.max_numeric_value(), Some(2.));
1609
1610 let root = Questionnaire::new(&state).render(window, cx).into_element();
1611 assert_eq!(root.a11y_role(), Some(Role::Form));
1612 });
1613 }
1614
1615 #[gpui::test]
1616 fn actions_stay_inside_questionnaire_width(cx: &mut TestAppContext) {
1617 let (cx, state) = actions_visual_harness(cx, false);
1618 let entity_id = state.entity_id();
1619 let root_id = Box::leak(format!("questionnaire-{entity_id}-root").into_boxed_str());
1620 let actions_id = Box::leak(format!("questionnaire-{entity_id}-actions").into_boxed_str());
1621 let previous_id = Box::leak(format!("questionnaire-{entity_id}-Previous").into_boxed_str());
1622 let skip_id = Box::leak(format!("questionnaire-{entity_id}-Skip").into_boxed_str());
1623 let next_id = Box::leak(format!("questionnaire-{entity_id}-Next").into_boxed_str());
1624 let submit_id = Box::leak(format!("questionnaire-{entity_id}-Submit").into_boxed_str());
1625 let root = cx.debug_bounds(root_id).expect("questionnaire rendered");
1626 let actions = cx.debug_bounds(actions_id).expect("actions rendered");
1627 let previous = cx.debug_bounds(previous_id).expect("previous rendered");
1628 let skip = cx.debug_bounds(skip_id).expect("skip rendered");
1629 let next = cx.debug_bounds(next_id).expect("next rendered");
1630
1631 assert!(actions.left() >= root.left());
1632 assert!(actions.right() <= root.right());
1633 assert_eq!(previous.left(), actions.left());
1634 assert!(previous.right() <= skip.left());
1635 assert!(skip.right() <= next.left());
1636 assert_eq!(next.right(), actions.right());
1637
1638 cx.update(|window, cx| {
1639 state
1640 .update(cx, |state, cx| state.set_current_item("first", window, cx))
1641 .unwrap();
1642 window.draw(cx).clear(cx);
1643 });
1644 let first_actions = cx.debug_bounds(actions_id).expect("first actions rendered");
1645 let first_next = cx.debug_bounds(next_id).expect("first next rendered");
1646 assert!(first_next.left() >= first_actions.left());
1647 assert_eq!(first_next.right(), first_actions.right());
1648
1649 cx.update(|window, cx| {
1650 state
1651 .update(cx, |state, cx| state.set_current_item("third", window, cx))
1652 .unwrap();
1653 window.draw(cx).clear(cx);
1654 });
1655 let last_actions = cx.debug_bounds(actions_id).expect("last actions rendered");
1656 let last_previous = cx
1657 .debug_bounds(previous_id)
1658 .expect("last previous rendered");
1659 let submit = cx.debug_bounds(submit_id).expect("submit rendered");
1660 assert_eq!(last_previous.left(), last_actions.left());
1661 assert!(last_previous.right() <= submit.left());
1662 assert_eq!(submit.right(), last_actions.right());
1663 }
1664
1665 #[gpui::test]
1666 fn action_instance_style_overrides_default_trailing_anchor(cx: &mut TestAppContext) {
1667 let (cx, state) = actions_visual_harness(cx, true);
1668 let entity_id = state.entity_id();
1669 let actions_id = Box::leak(format!("questionnaire-{entity_id}-actions").into_boxed_str());
1670 let previous_id = Box::leak(format!("questionnaire-{entity_id}-Previous").into_boxed_str());
1671 let skip_id = Box::leak(format!("questionnaire-{entity_id}-Skip").into_boxed_str());
1672 let next_id = Box::leak(format!("questionnaire-{entity_id}-Next").into_boxed_str());
1673 let actions = cx.debug_bounds(actions_id).expect("actions rendered");
1674 let previous = cx.debug_bounds(previous_id).expect("previous rendered");
1675 let skip = cx.debug_bounds(skip_id).expect("skip rendered");
1676 let next = cx.debug_bounds(next_id).expect("next rendered");
1677
1678 assert_eq!(previous.left(), actions.left());
1679 assert!(previous.right() <= skip.left());
1680 assert!(skip.right() <= next.left());
1681 assert!(next.right() < actions.right());
1682 }
1683
1684 struct ScaleHarness {
1685 state: Entity<QuestionnaireState>,
1686 root_size: Size,
1687 part_size: Option<Size>,
1688 }
1689
1690 impl Render for ScaleHarness {
1691 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1692 let part_size = self.part_size;
1693 Questionnaire::new(&self.state)
1694 .with_size(self.root_size)
1695 .size(px(480.))
1696 .child(
1697 QuestionnaireItem::new(&self.state, "scale")
1698 .when_some(part_size, |this, size| this.with_size(size))
1699 .child(
1700 QuestionnaireChoices::new(&self.state, "scale")
1701 .when_some(part_size, |this, size| this.with_size(size))
1702 .child(
1703 div()
1704 .id("scale-choice")
1705 .debug_selector(|| "scale-choice".to_string())
1706 .child(
1707 QuestionnaireChoice::new(&self.state, "scale", "alpha")
1708 .when_some(part_size, |this, size| {
1709 this.with_size(size)
1710 }),
1711 ),
1712 ),
1713 ),
1714 )
1715 }
1716 }
1717
1718 fn scale_harness(
1719 cx: &mut TestAppContext,
1720 root_size: Size,
1721 part_size: Option<Size>,
1722 ) -> gpui::Bounds<gpui::Pixels> {
1723 cx.update(crate::init);
1724 let (_view, cx) = cx.add_window_view(move |_, cx| {
1725 let state = cx.new(|cx| {
1726 QuestionnaireState::new(
1727 vec![
1728 QuestionnaireItemDefinition::new("scale", "Scale")
1729 .with_choice(QuestionnaireChoiceDefinition::new("alpha", "Alpha")),
1730 ],
1731 cx,
1732 )
1733 .unwrap()
1734 });
1735 ScaleHarness {
1736 state,
1737 root_size,
1738 part_size,
1739 }
1740 });
1741 cx.update(|window, cx| window.draw(cx).clear(cx));
1742 cx.debug_bounds("scale-choice").expect("choice rendered")
1743 }
1744
1745 #[gpui::test]
1746 fn parts_take_their_scale_from_the_root_and_a_part_may_override_it(cx: &mut TestAppContext) {
1747 let inherited = scale_harness(cx, Size::Small, None);
1750 let explicit = scale_harness(cx, Size::Small, Some(Size::Small));
1751 assert_eq!(inherited.size, explicit.size);
1752
1753 let large_root = scale_harness(cx, Size::Large, None);
1755 assert!(large_root.size.height > inherited.size.height);
1756
1757 let overridden = scale_harness(cx, Size::Large, Some(Size::Small));
1759 assert_eq!(overridden.size, inherited.size);
1760 }
1761
1762 #[gpui::test]
1763 fn shortcut_guards_held_keys_before_activation(cx: &mut TestAppContext) {
1764 let (cx, state) = visual_harness(
1765 cx,
1766 vec![
1767 QuestionnaireItemDefinition::new("choice", "Choice")
1768 .with_choice(QuestionnaireChoiceDefinition::new("alpha", "Alpha")),
1769 QuestionnaireItemDefinition::new("second", "Second"),
1770 ],
1771 Some(QuestionnaireShortcutMode::Letters),
1772 );
1773
1774 simulate_key(cx, "a", true, true);
1775 simulate_key(cx, "a", false, false);
1776 simulate_key(cx, "shift-a", false, true);
1777 cx.update(|_, cx| assert!(state.read(cx).answer("choice").unwrap().is_empty()));
1778
1779 simulate_key(cx, "a", false, true);
1780 cx.update(|window, cx| {
1781 assert_eq!(
1782 state.read(cx).answer("choice").unwrap().choices(),
1783 &[SharedString::from("alpha")]
1784 );
1785 assert_eq!(
1786 state
1787 .read(cx)
1788 .focused_current_choice(window)
1789 .map(SharedString::as_ref),
1790 Some("alpha")
1791 );
1792 });
1793 simulate_key(cx, "enter", false, false);
1794 cx.update(|_, cx| {
1795 assert_eq!(state.read(cx).current_item().unwrap().as_ref(), "second");
1796 });
1797 }
1798
1799 #[gpui::test]
1800 fn root_keyboard_preserves_navigation_and_radio_semantics(cx: &mut TestAppContext) {
1801 let (cx, state) = visual_harness(
1802 cx,
1803 vec![
1804 QuestionnaireItemDefinition::new("first", "First")
1805 .with_required(true)
1806 .with_choices([
1807 QuestionnaireChoiceDefinition::new("alpha", "Alpha"),
1808 QuestionnaireChoiceDefinition::new("beta", "Beta"),
1809 ]),
1810 QuestionnaireItemDefinition::new("second", "Second"),
1811 ],
1812 None,
1813 );
1814
1815 simulate_key(cx, "right", false, false);
1816 cx.update(|_, cx| {
1817 assert_eq!(state.read(cx).current_item().unwrap().as_ref(), "first");
1818 assert!(state.read(cx).answer("first").unwrap().is_empty());
1819 });
1820
1821 cx.update(|window, cx| {
1822 let focus_handle = state
1823 .read(cx)
1824 .choice_focus_handle("first", "alpha")
1825 .unwrap()
1826 .clone();
1827 focus_handle.focus(window, cx);
1828 });
1829 simulate_key(cx, "enter", false, false);
1830 cx.update(|_, cx| {
1831 assert_eq!(state.read(cx).current_item().unwrap().as_ref(), "first");
1832 assert!(state.read(cx).answer("first").unwrap().is_empty());
1833 });
1834
1835 simulate_key(cx, "right", false, false);
1836 cx.update(|window, cx| window.draw(cx).clear(cx));
1837 cx.update(|_, cx| {
1838 assert_eq!(
1839 state.read(cx).answer("first").unwrap().choices(),
1840 &[SharedString::from("beta")]
1841 );
1842 assert_eq!(state.read(cx).current_item().unwrap().as_ref(), "first");
1843 });
1844
1845 simulate_key(cx, "enter", false, false);
1846 cx.update(|_, cx| {
1847 assert_eq!(state.read(cx).current_item().unwrap().as_ref(), "second");
1848 });
1849 }
1850
1851 #[gpui::test]
1852 fn empty_input_enter_stays_put_and_arrows_move_to_answers(cx: &mut TestAppContext) {
1853 let (cx, state) = input_visual_harness(cx, false);
1854 focus_input(cx, &state, "first");
1855
1856 simulate_key(cx, "enter", false, false);
1857 cx.update(|_, cx| {
1858 assert_eq!(state.read(cx).current_item().unwrap().as_ref(), "first");
1859 assert!(state.read(cx).answer("first").unwrap().is_empty());
1860 assert!(state.read(cx).error("first").is_none());
1861 });
1862
1863 simulate_key(cx, "secondary-enter", false, false);
1864 cx.update(|_, cx| {
1865 assert_eq!(state.read(cx).current_item().unwrap().as_ref(), "first");
1866 assert!(state.read(cx).error("first").is_some());
1867 });
1868
1869 focus_input(cx, &state, "first");
1870 simulate_key(cx, "up", false, false);
1871 cx.update(|window, cx| {
1872 assert_eq!(
1873 state
1874 .read(cx)
1875 .focused_current_choice(window)
1876 .map(SharedString::as_ref),
1877 Some("beta")
1878 );
1879 });
1880
1881 simulate_key(cx, "down", false, false);
1882 cx.update(|window, cx| {
1883 assert!(state.read(cx).is_current_input_focused(window));
1884 assert_eq!(
1885 state.read(cx).answer("first").unwrap().choices(),
1886 &[SharedString::from("beta")]
1887 );
1888 });
1889
1890 simulate_key(cx, "down", false, false);
1891 cx.update(|window, cx| {
1892 assert_eq!(
1893 state
1894 .read(cx)
1895 .focused_current_choice(window)
1896 .map(SharedString::as_ref),
1897 Some("alpha")
1898 );
1899 assert_eq!(
1900 state.read(cx).answer("first").unwrap().choices(),
1901 &[SharedString::from("alpha")]
1902 );
1903 });
1904
1905 simulate_key(cx, "down", false, false);
1906 cx.update(|window, cx| {
1907 assert_eq!(
1908 state
1909 .read(cx)
1910 .focused_current_choice(window)
1911 .map(SharedString::as_ref),
1912 Some("beta")
1913 );
1914 assert_eq!(
1915 state.read(cx).answer("first").unwrap().choices(),
1916 &[SharedString::from("beta")]
1917 );
1918 });
1919
1920 cx.update(|window, cx| {
1921 state.update(cx, |state, cx| {
1922 state
1923 .set_input_value("first", "Preserved draft", window, cx)
1924 .unwrap();
1925 state.activate_choice("first", "alpha", cx).unwrap();
1926 });
1927 });
1928 focus_input(cx, &state, "first");
1929 simulate_key(cx, "enter", false, false);
1930 cx.update(|_, cx| {
1931 let answer = state.read(cx).answer("first").unwrap();
1932 assert_eq!(state.read(cx).current_item().unwrap().as_ref(), "first");
1933 assert_eq!(answer.choices(), &[SharedString::from("alpha")]);
1934 assert!(answer.freeform().is_none());
1935 });
1936 }
1937
1938 #[gpui::test]
1939 fn filled_group_input_keeps_text_editing_directions(cx: &mut TestAppContext) {
1940 let (cx, state) = input_visual_harness(cx, true);
1941 cx.update(|window, cx| {
1942 state
1943 .update(cx, |state, cx| {
1944 state.set_input_value("first", "Freeform answer", window, cx)
1945 })
1946 .unwrap();
1947 });
1948 focus_input(cx, &state, "first");
1949
1950 simulate_key(cx, "down", false, false);
1951 cx.update(|window, cx| {
1952 let state = state.read(cx);
1953 assert!(state.is_current_input_focused(window));
1954 assert_eq!(
1955 state
1956 .answer("first")
1957 .unwrap()
1958 .freeform()
1959 .map(SharedString::as_ref),
1960 Some("Freeform answer")
1961 );
1962 assert!(state.answer("first").unwrap().choices().is_empty());
1963 });
1964
1965 simulate_key(cx, "up", false, false);
1966 cx.update(|window, cx| {
1967 let state = state.read(cx);
1968 assert!(state.is_current_input_focused(window));
1969 assert_eq!(
1970 state
1971 .answer("first")
1972 .unwrap()
1973 .freeform()
1974 .map(SharedString::as_ref),
1975 Some("Freeform answer")
1976 );
1977 assert!(state.answer("first").unwrap().choices().is_empty());
1978 });
1979 }
1980
1981 struct ChooseHarness {
1985 state: Entity<QuestionnaireState>,
1986 submits: usize,
1987 _subscription: gpui::Subscription,
1988 }
1989
1990 impl Render for ChooseHarness {
1991 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1992 let state = &self.state;
1993 let choice = |item: &'static str, value: &'static str| {
1994 div()
1995 .id(SharedString::from(format!("choice-{item}-{value}")))
1996 .debug_selector(move || format!("choice-{item}-{value}"))
1997 .child(QuestionnaireChoice::new(state, item, value))
1998 };
1999 Questionnaire::new(state)
2000 .size(px(480.))
2001 .child(
2002 QuestionnaireItem::new(state, "first").child(
2003 QuestionnaireChoices::new(state, "first")
2004 .child(choice("first", "alpha"))
2005 .child(choice("first", "beta")),
2006 ),
2007 )
2008 .child(
2009 QuestionnaireItem::new(state, "second").child(
2010 QuestionnaireChoices::new(state, "second")
2011 .child(choice("second", "x"))
2012 .child(choice("second", "y")),
2013 ),
2014 )
2015 .child(
2016 QuestionnaireItem::new(state, "third")
2017 .child(
2018 QuestionnaireChoices::new(state, "third")
2019 .child(choice("third", "omega")),
2020 )
2021 .child(QuestionnaireInput::new(state, "third")),
2022 )
2023 }
2024 }
2025
2026 fn choose_harness(
2027 cx: &mut TestAppContext,
2028 ) -> (
2029 &mut VisualTestContext,
2030 Entity<ChooseHarness>,
2031 Entity<QuestionnaireState>,
2032 ) {
2033 cx.update(crate::init);
2034 let (view, cx) = cx.add_window_view(|window, cx| {
2035 let input = cx.new(|cx| crate::input::InputState::new(window, cx));
2036 let state = cx.new(|cx| {
2037 QuestionnaireState::new(
2038 vec![
2039 QuestionnaireItemDefinition::new("first", "First").with_choices([
2040 QuestionnaireChoiceDefinition::new("alpha", "Alpha"),
2041 QuestionnaireChoiceDefinition::new("beta", "Beta"),
2042 ]),
2043 QuestionnaireItemDefinition::new("second", "Second")
2044 .with_multiple(true)
2045 .with_choices([
2046 QuestionnaireChoiceDefinition::new("x", "X"),
2047 QuestionnaireChoiceDefinition::new("y", "Y"),
2048 ]),
2049 QuestionnaireItemDefinition::new("third", "Third")
2050 .with_choice(QuestionnaireChoiceDefinition::new("omega", "Omega"))
2051 .with_input(QuestionnaireInputDefinition::new(input, "Other")),
2052 ],
2053 cx,
2054 )
2055 .unwrap()
2056 .with_shortcuts(QuestionnaireShortcutMode::Numbers)
2057 });
2058 let subscription = cx.subscribe(&state, |this: &mut ChooseHarness, _, event, _| {
2059 if matches!(event, QuestionnaireEvent::Submit(_)) {
2060 this.submits += 1;
2061 }
2062 });
2063 ChooseHarness {
2064 state,
2065 submits: 0,
2066 _subscription: subscription,
2067 }
2068 });
2069 cx.update(|window, cx| window.draw(cx).clear(cx));
2070 let state = cx.update(|_, cx| view.read(cx).state.clone());
2071 cx.update(|window, cx| {
2072 let focus_handle = state.read(cx).focus_handle().clone();
2073 focus_handle.focus(window, cx);
2074 });
2075 (cx, view, state)
2076 }
2077
2078 fn wait_out_hold(cx: &mut VisualTestContext) {
2080 cx.executor()
2081 .advance_clock(std::time::Duration::from_millis(200));
2082 cx.run_until_parked();
2083 cx.update(|window, cx| window.draw(cx).clear(cx));
2084 }
2085
2086 fn click_choice(cx: &mut VisualTestContext, item: &str, value: &str) {
2087 cx.update(|window, cx| window.draw(cx).clear(cx));
2088 let selector = Box::leak(format!("choice-{item}-{value}").into_boxed_str());
2089 let bounds = cx.debug_bounds(selector).expect("choice rendered");
2090 cx.simulate_click(bounds.center(), gpui::Modifiers::default());
2091 }
2092
2093 fn press(cx: &mut VisualTestContext, key: &str) {
2094 let os = cx.update(|_, cx| cx.platform_info().os);
2095 let keystroke = Keystroke::parse_with_os(key, os).unwrap();
2096 cx.simulate_event(KeyDownEvent {
2097 keystroke: keystroke.clone(),
2098 is_held: false,
2099 prefer_character_input: false,
2100 });
2101 cx.simulate_event(gpui::KeyUpEvent { keystroke });
2102 }
2103
2104 fn focus_choice(
2105 cx: &mut VisualTestContext,
2106 state: &Entity<QuestionnaireState>,
2107 item: &str,
2108 value: &str,
2109 ) {
2110 cx.update(|window, cx| {
2111 let focus_handle = state
2112 .read(cx)
2113 .choice_focus_handle(item, value)
2114 .unwrap()
2115 .clone();
2116 focus_handle.focus(window, cx);
2117 });
2118 }
2119
2120 fn current(cx: &mut VisualTestContext, state: &Entity<QuestionnaireState>) -> SharedString {
2121 cx.update(|_, cx| state.read(cx).current_item().unwrap().clone())
2122 }
2123
2124 fn choices(
2125 cx: &mut VisualTestContext,
2126 state: &Entity<QuestionnaireState>,
2127 item: &str,
2128 ) -> Vec<SharedString> {
2129 cx.update(|_, cx| state.read(cx).answer(item).unwrap().choices().to_vec())
2130 }
2131
2132 #[gpui::test]
2133 fn clicking_a_single_choice_shows_it_then_advances(cx: &mut TestAppContext) {
2134 let (cx, view, state) = choose_harness(cx);
2135
2136 click_choice(cx, "first", "alpha");
2137 cx.run_until_parked();
2138 assert_eq!(
2139 choices(cx, &state, "first"),
2140 vec![SharedString::from("alpha")]
2141 );
2142 assert_eq!(current(cx, &state), "first", "the selection paints first");
2143 wait_out_hold(cx);
2144 assert_eq!(current(cx, &state), "second");
2145
2146 click_choice(cx, "second", "x");
2147 wait_out_hold(cx);
2148 assert_eq!(current(cx, &state), "second", "a checkbox only toggles");
2149 assert_eq!(choices(cx, &state, "second"), vec![SharedString::from("x")]);
2150
2151 cx.update(|window, cx| state.update(cx, |state, cx| state.go_next(window, cx)));
2152 focus_input(cx, &state, "third");
2153 cx.simulate_input("draft");
2154 wait_out_hold(cx);
2155 assert_eq!(current(cx, &state), "third", "typing never advances");
2156
2157 click_choice(cx, "third", "omega");
2158 click_choice(cx, "third", "omega");
2159 wait_out_hold(cx);
2160 assert_eq!(
2161 cx.update(|_, cx| view.read(cx).submits),
2162 1,
2163 "a double click on the last item submits once"
2164 );
2165
2166 cx.update(|window, cx| {
2168 state
2169 .update(cx, |state, cx| state.set_current_item("first", window, cx))
2170 .unwrap();
2171 });
2172 click_choice(cx, "first", "alpha");
2173 assert_eq!(current(cx, &state), "second");
2174 }
2175
2176 #[gpui::test]
2177 fn shortcuts_and_space_advance_while_arrows_only_move(cx: &mut TestAppContext) {
2178 let (cx, _, state) = choose_harness(cx);
2179
2180 focus_choice(cx, &state, "first", "alpha");
2181 press(cx, "down");
2182 wait_out_hold(cx);
2183 assert_eq!(
2184 choices(cx, &state, "first"),
2185 vec![SharedString::from("beta")]
2186 );
2187 assert_eq!(
2188 current(cx, &state),
2189 "first",
2190 "an arrow moves the selection only"
2191 );
2192
2193 simulate_key(cx, "1", false, true);
2194 cx.run_until_parked();
2195 assert_eq!(
2196 choices(cx, &state, "first"),
2197 vec![SharedString::from("alpha")]
2198 );
2199 assert_eq!(current(cx, &state), "first");
2200 wait_out_hold(cx);
2201 assert_eq!(current(cx, &state), "second");
2202
2203 simulate_key(cx, "2", false, true);
2204 wait_out_hold(cx);
2205 assert_eq!(
2206 current(cx, &state),
2207 "second",
2208 "a multiple-answer shortcut toggles"
2209 );
2210 assert_eq!(choices(cx, &state, "second"), vec![SharedString::from("y")]);
2211
2212 cx.update(|window, cx| state.update(cx, |state, cx| state.go_previous(window, cx)));
2213 focus_choice(cx, &state, "first", "beta");
2214 press(cx, "space");
2215 wait_out_hold(cx);
2216 assert_eq!(
2217 choices(cx, &state, "first"),
2218 vec![SharedString::from("beta")]
2219 );
2220 assert_eq!(current(cx, &state), "second", "Space chooses and advances");
2221 }
2222
2223 #[test]
2224 fn invalid_error_projects_alert_role() {
2225 let error = questionnaire_error_root("questionnaire-error-test".into()).into_element();
2226 assert_eq!(error.a11y_role(), Some(Role::Alert));
2227 }
2228}