feedback_modal.rs

  1use std::{ops::RangeInclusive, sync::Arc, time::Duration};
  2
  3use anyhow::{anyhow, bail};
  4use bitflags::bitflags;
  5use client::Client;
  6use db::kvp::KEY_VALUE_STORE;
  7use editor::{Editor, EditorEvent};
  8use futures::AsyncReadExt;
  9use gpui::{
 10    div, rems, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView, Model,
 11    PromptLevel, Render, Task, View, ViewContext,
 12};
 13use http_client::HttpClient;
 14use isahc::Request;
 15use language::Buffer;
 16use project::Project;
 17use regex::Regex;
 18use serde_derive::Serialize;
 19use ui::{prelude::*, Button, ButtonStyle, IconPosition, Tooltip};
 20use util::ResultExt;
 21use workspace::notifications::NotificationId;
 22use workspace::{DismissDecision, ModalView, Toast, Workspace};
 23
 24use crate::{system_specs::SystemSpecs, GiveFeedback, OpenZedRepo};
 25
 26// For UI testing purposes
 27const SEND_SUCCESS_IN_DEV_MODE: bool = true;
 28const SEND_TIME_IN_DEV_MODE: Duration = Duration::from_secs(2);
 29
 30// Temporary, until tests are in place
 31#[cfg(debug_assertions)]
 32const DEV_MODE: bool = true;
 33
 34#[cfg(not(debug_assertions))]
 35const DEV_MODE: bool = false;
 36
 37const DATABASE_KEY_NAME: &str = "email_address";
 38const EMAIL_REGEX: &str = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b";
 39const FEEDBACK_CHAR_LIMIT: RangeInclusive<i32> = 10..=5000;
 40const FEEDBACK_SUBMISSION_ERROR_TEXT: &str =
 41    "Feedback failed to submit, see error log for details.";
 42
 43#[derive(Serialize)]
 44struct FeedbackRequestBody<'a> {
 45    feedback_text: &'a str,
 46    email: Option<String>,
 47    metrics_id: Option<Arc<str>>,
 48    installation_id: Option<Arc<str>>,
 49    system_specs: SystemSpecs,
 50    is_staff: bool,
 51}
 52
 53bitflags! {
 54    #[derive(Debug, Clone, PartialEq)]
 55    struct InvalidStateFlags: u8 {
 56        const EmailAddress = 0b00000001;
 57        const CharacterCount = 0b00000010;
 58    }
 59}
 60
 61#[derive(Debug, Clone, PartialEq)]
 62enum CannotSubmitReason {
 63    InvalidState { flags: InvalidStateFlags },
 64    AwaitingSubmission,
 65}
 66
 67#[derive(Debug, Clone, PartialEq)]
 68enum SubmissionState {
 69    CanSubmit,
 70    CannotSubmit { reason: CannotSubmitReason },
 71}
 72
 73pub struct FeedbackModal {
 74    system_specs: SystemSpecs,
 75    feedback_editor: View<Editor>,
 76    email_address_editor: View<Editor>,
 77    submission_state: Option<SubmissionState>,
 78    dismiss_modal: bool,
 79    character_count: i32,
 80}
 81
 82impl FocusableView for FeedbackModal {
 83    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
 84        self.feedback_editor.focus_handle(cx)
 85    }
 86}
 87impl EventEmitter<DismissEvent> for FeedbackModal {}
 88
 89impl ModalView for FeedbackModal {
 90    fn on_before_dismiss(&mut self, cx: &mut ViewContext<Self>) -> DismissDecision {
 91        self.update_email_in_store(cx);
 92
 93        if self.dismiss_modal {
 94            return DismissDecision::Dismiss(true);
 95        }
 96
 97        let has_feedback = self.feedback_editor.read(cx).text_option(cx).is_some();
 98        if !has_feedback {
 99            return DismissDecision::Dismiss(true);
100        }
101
102        let answer = cx.prompt(PromptLevel::Info, "Discard feedback?", None, &["Yes", "No"]);
103
104        cx.spawn(move |this, mut cx| async move {
105            if answer.await.ok() == Some(0) {
106                this.update(&mut cx, |this, cx| {
107                    this.dismiss_modal = true;
108                    cx.emit(DismissEvent)
109                })
110                .log_err();
111            }
112        })
113        .detach();
114
115        DismissDecision::Pending
116    }
117}
118
119impl FeedbackModal {
120    pub fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
121        let _handle = cx.view().downgrade();
122        workspace.register_action(move |workspace, _: &GiveFeedback, cx| {
123            let markdown = workspace
124                .app_state()
125                .languages
126                .language_for_name("Markdown");
127
128            let project = workspace.project().clone();
129            let is_local_project = project.read(cx).is_local_or_ssh();
130
131            if !is_local_project {
132                struct FeedbackInRemoteProject;
133
134                workspace.show_toast(
135                    Toast::new(
136                        NotificationId::unique::<FeedbackInRemoteProject>(),
137                        "You can only submit feedback in your own project.",
138                    ),
139                    cx,
140                );
141                return;
142            }
143
144            let system_specs = SystemSpecs::new(cx);
145            cx.spawn(|workspace, mut cx| async move {
146                let markdown = markdown.await.log_err();
147                let buffer = project.update(&mut cx, |project, cx| {
148                    project.create_local_buffer("", markdown, cx)
149                })?;
150                let system_specs = system_specs.await;
151
152                workspace.update(&mut cx, |workspace, cx| {
153                    workspace.toggle_modal(cx, move |cx| {
154                        FeedbackModal::new(system_specs, project, buffer, cx)
155                    });
156                })?;
157
158                anyhow::Ok(())
159            })
160            .detach_and_log_err(cx);
161        });
162    }
163
164    pub fn new(
165        system_specs: SystemSpecs,
166        project: Model<Project>,
167        buffer: Model<Buffer>,
168        cx: &mut ViewContext<Self>,
169    ) -> Self {
170        let email_address_editor = cx.new_view(|cx| {
171            let mut editor = Editor::single_line(cx);
172            editor.set_placeholder_text("Email address (optional)", cx);
173
174            if let Ok(Some(email_address)) = KEY_VALUE_STORE.read_kvp(DATABASE_KEY_NAME) {
175                editor.set_text(email_address, cx)
176            }
177
178            editor
179        });
180
181        let feedback_editor = cx.new_view(|cx| {
182            let mut editor = Editor::for_buffer(buffer, Some(project.clone()), cx);
183            editor.set_placeholder_text(
184                "You can use markdown to organize your feedback with code and links.",
185                cx,
186            );
187            editor.set_show_gutter(false, cx);
188            editor.set_show_indent_guides(false, cx);
189            editor.set_show_inline_completions(Some(false), cx);
190            editor.set_vertical_scroll_margin(5, cx);
191            editor.set_use_modal_editing(false);
192            editor
193        });
194
195        cx.subscribe(&feedback_editor, |this, editor, event: &EditorEvent, cx| {
196            if matches!(event, EditorEvent::Edited { .. }) {
197                this.character_count = editor
198                    .read(cx)
199                    .buffer()
200                    .read(cx)
201                    .as_singleton()
202                    .expect("Feedback editor is never a multi-buffer")
203                    .read(cx)
204                    .len() as i32;
205                cx.notify();
206            }
207        })
208        .detach();
209
210        Self {
211            system_specs: system_specs.clone(),
212            feedback_editor,
213            email_address_editor,
214            submission_state: None,
215            dismiss_modal: false,
216            character_count: 0,
217        }
218    }
219
220    pub fn submit(&mut self, cx: &mut ViewContext<Self>) -> Task<anyhow::Result<()>> {
221        let feedback_text = self.feedback_editor.read(cx).text(cx).trim().to_string();
222        let email = self.email_address_editor.read(cx).text_option(cx);
223
224        let answer = cx.prompt(
225            PromptLevel::Info,
226            "Ready to submit your feedback?",
227            None,
228            &["Yes, Submit!", "No"],
229        );
230        let client = Client::global(cx).clone();
231        let specs = self.system_specs.clone();
232        cx.spawn(|this, mut cx| async move {
233            let answer = answer.await.ok();
234            if answer == Some(0) {
235                this.update(&mut cx, |this, cx| {
236                    this.submission_state = Some(SubmissionState::CannotSubmit {
237                        reason: CannotSubmitReason::AwaitingSubmission,
238                    });
239                    cx.notify();
240                })
241                .log_err();
242
243                let res =
244                    FeedbackModal::submit_feedback(&feedback_text, email, client, specs).await;
245
246                match res {
247                    Ok(_) => {
248                        this.update(&mut cx, |this, cx| {
249                            this.dismiss_modal = true;
250                            cx.notify();
251                            cx.emit(DismissEvent)
252                        })
253                        .ok();
254                    }
255                    Err(error) => {
256                        log::error!("{}", error);
257                        this.update(&mut cx, |this, cx| {
258                            let prompt = cx.prompt(
259                                PromptLevel::Critical,
260                                FEEDBACK_SUBMISSION_ERROR_TEXT,
261                                None,
262                                &["OK"],
263                            );
264                            cx.spawn(|_, _cx| async move {
265                                prompt.await.ok();
266                            })
267                            .detach();
268
269                            this.submission_state = Some(SubmissionState::CanSubmit);
270                            cx.notify();
271                        })
272                        .log_err();
273                    }
274                }
275            }
276        })
277        .detach();
278
279        Task::ready(Ok(()))
280    }
281
282    async fn submit_feedback(
283        feedback_text: &str,
284        email: Option<String>,
285        zed_client: Arc<Client>,
286        system_specs: SystemSpecs,
287    ) -> anyhow::Result<()> {
288        if DEV_MODE {
289            smol::Timer::after(SEND_TIME_IN_DEV_MODE).await;
290
291            if SEND_SUCCESS_IN_DEV_MODE {
292                return Ok(());
293            } else {
294                return Err(anyhow!("Error submitting feedback"));
295            }
296        }
297
298        let telemetry = zed_client.telemetry();
299        let metrics_id = telemetry.metrics_id();
300        let installation_id = telemetry.installation_id();
301        let is_staff = telemetry.is_staff();
302        let http_client = zed_client.http_client();
303        let feedback_endpoint = http_client.build_url("/api/feedback");
304        let request = FeedbackRequestBody {
305            feedback_text,
306            email,
307            metrics_id,
308            installation_id,
309            system_specs,
310            is_staff: is_staff.unwrap_or(false),
311        };
312        let json_bytes = serde_json::to_vec(&request)?;
313        let request = Request::post(feedback_endpoint)
314            .header("content-type", "application/json")
315            .body(json_bytes.into())?;
316        let mut response = http_client.send(request).await?;
317        let mut body = String::new();
318        response.body_mut().read_to_string(&mut body).await?;
319        let response_status = response.status();
320        if !response_status.is_success() {
321            bail!("Feedback API failed with error: {}", response_status)
322        }
323        Ok(())
324    }
325
326    fn update_submission_state(&mut self, cx: &mut ViewContext<Self>) {
327        if self.awaiting_submission() {
328            return;
329        }
330
331        let mut invalid_state_flags = InvalidStateFlags::empty();
332
333        let valid_email_address = match self.email_address_editor.read(cx).text_option(cx) {
334            Some(email_address) => Regex::new(EMAIL_REGEX).unwrap().is_match(&email_address),
335            None => true,
336        };
337
338        if !valid_email_address {
339            invalid_state_flags |= InvalidStateFlags::EmailAddress;
340        }
341
342        if !FEEDBACK_CHAR_LIMIT.contains(&self.character_count) {
343            invalid_state_flags |= InvalidStateFlags::CharacterCount;
344        }
345
346        if invalid_state_flags.is_empty() {
347            self.submission_state = Some(SubmissionState::CanSubmit);
348        } else {
349            self.submission_state = Some(SubmissionState::CannotSubmit {
350                reason: CannotSubmitReason::InvalidState {
351                    flags: invalid_state_flags,
352                },
353            });
354        }
355    }
356
357    fn update_email_in_store(&self, cx: &mut ViewContext<Self>) {
358        let email = self.email_address_editor.read(cx).text_option(cx);
359
360        cx.spawn(|_, _| async move {
361            match email {
362                Some(email) => {
363                    KEY_VALUE_STORE
364                        .write_kvp(DATABASE_KEY_NAME.to_string(), email)
365                        .await
366                        .ok();
367                }
368                None => {
369                    KEY_VALUE_STORE
370                        .delete_kvp(DATABASE_KEY_NAME.to_string())
371                        .await
372                        .ok();
373                }
374            }
375        })
376        .detach();
377    }
378
379    fn valid_email_address(&self) -> bool {
380        !self.in_invalid_state(InvalidStateFlags::EmailAddress)
381    }
382
383    fn valid_character_count(&self) -> bool {
384        !self.in_invalid_state(InvalidStateFlags::CharacterCount)
385    }
386
387    fn in_invalid_state(&self, flag: InvalidStateFlags) -> bool {
388        match self.submission_state {
389            Some(SubmissionState::CannotSubmit {
390                reason: CannotSubmitReason::InvalidState { ref flags },
391            }) => flags.contains(flag),
392            _ => false,
393        }
394    }
395
396    fn awaiting_submission(&self) -> bool {
397        matches!(
398            self.submission_state,
399            Some(SubmissionState::CannotSubmit {
400                reason: CannotSubmitReason::AwaitingSubmission
401            })
402        )
403    }
404
405    fn can_submit(&self) -> bool {
406        matches!(self.submission_state, Some(SubmissionState::CanSubmit))
407    }
408
409    fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
410        cx.emit(DismissEvent)
411    }
412}
413
414impl Render for FeedbackModal {
415    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
416        self.update_submission_state(cx);
417
418        let submit_button_text = if self.awaiting_submission() {
419            "Submitting..."
420        } else {
421            "Submit"
422        };
423
424        let open_zed_repo = cx.listener(|_, _, cx| cx.dispatch_action(Box::new(OpenZedRepo)));
425
426        v_flex()
427            .elevation_3(cx)
428            .key_context("GiveFeedback")
429            .on_action(cx.listener(Self::cancel))
430            .min_w(rems(40.))
431            .max_w(rems(96.))
432            .h(rems(32.))
433            .p_4()
434            .gap_2()
435            .child(Headline::new("Give Feedback"))
436            .child(
437                Label::new(if self.character_count < *FEEDBACK_CHAR_LIMIT.start() {
438                    format!(
439                        "Feedback must be at least {} characters.",
440                        FEEDBACK_CHAR_LIMIT.start()
441                    )
442                } else {
443                    format!(
444                        "Characters: {}",
445                        *FEEDBACK_CHAR_LIMIT.end() - self.character_count
446                    )
447                })
448                .color(if self.valid_character_count() {
449                    Color::Success
450                } else {
451                    Color::Error
452                }),
453            )
454            .child(
455                div()
456                    .flex_1()
457                    .bg(cx.theme().colors().editor_background)
458                    .p_2()
459                    .border_1()
460                    .rounded_md()
461                    .border_color(cx.theme().colors().border)
462                    .child(self.feedback_editor.clone()),
463            )
464            .child(
465                v_flex()
466                    .gap_1()
467                    .child(
468                        h_flex()
469                            .bg(cx.theme().colors().editor_background)
470                            .p_2()
471                            .border_1()
472                            .rounded_md()
473                            .border_color(if self.valid_email_address() {
474                                cx.theme().colors().border
475                            } else {
476                                cx.theme().status().error_border
477                            })
478                            .child(self.email_address_editor.clone()),
479                    )
480                    .child(
481                        Label::new("Provide an email address if you want us to be able to reply.")
482                            .size(LabelSize::Small)
483                            .color(Color::Muted),
484                    ),
485            )
486            .child(
487                h_flex()
488                    .justify_between()
489                    .gap_1()
490                    .child(
491                        Button::new("zed_repository", "Zed Repository")
492                            .style(ButtonStyle::Transparent)
493                            .icon(IconName::ExternalLink)
494                            .icon_position(IconPosition::End)
495                            .icon_size(IconSize::Small)
496                            .on_click(open_zed_repo),
497                    )
498                    .child(
499                        h_flex()
500                            .gap_1()
501                            .child(
502                                Button::new("cancel_feedback", "Cancel")
503                                    .style(ButtonStyle::Subtle)
504                                    .color(Color::Muted)
505                                    .on_click(cx.listener(move |_, _, cx| {
506                                        cx.spawn(|this, mut cx| async move {
507                                            this.update(&mut cx, |_, cx| cx.emit(DismissEvent))
508                                                .ok();
509                                        })
510                                        .detach();
511                                    })),
512                            )
513                            .child(
514                                Button::new("submit_feedback", submit_button_text)
515                                    .color(Color::Accent)
516                                    .style(ButtonStyle::Filled)
517                                    .on_click(cx.listener(|this, _, cx| {
518                                        this.submit(cx).detach();
519                                    }))
520                                    .tooltip(move |cx| {
521                                        Tooltip::text("Submit feedback to the Zed team.", cx)
522                                    })
523                                    .when(!self.can_submit(), |this| this.disabled(true)),
524                            ),
525                    ),
526            )
527    }
528}
529
530// TODO: Testing of various button states, dismissal prompts, etc. :)