feedback_modal.rs

  1use std::{ops::RangeInclusive, sync::Arc};
  2
  3use anyhow::{anyhow, bail};
  4use client::{Client, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
  5use db::kvp::KEY_VALUE_STORE;
  6use editor::{Editor, EditorEvent};
  7use futures::AsyncReadExt;
  8use gpui::{
  9    div, rems, serde_json, AppContext, DismissEvent, Div, EventEmitter, FocusHandle, FocusableView,
 10    Model, PromptLevel, Render, Task, View, ViewContext,
 11};
 12use isahc::Request;
 13use language::Buffer;
 14use project::Project;
 15use regex::Regex;
 16use serde_derive::Serialize;
 17use ui::{prelude::*, Button, ButtonStyle, IconPosition, Tooltip};
 18use util::ResultExt;
 19use workspace::{ModalView, Workspace};
 20
 21use crate::{system_specs::SystemSpecs, GiveFeedback, OpenZedCommunityRepo};
 22
 23// For UI testing purposes
 24const SEND_SUCCESS_IN_DEV_MODE: bool = true;
 25
 26// Temporary, until tests are in place
 27#[cfg(debug_assertions)]
 28const DEV_MODE: bool = true;
 29
 30#[cfg(not(debug_assertions))]
 31const DEV_MODE: bool = false;
 32
 33const DATABASE_KEY_NAME: &str = "email_address";
 34const EMAIL_REGEX: &str = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b";
 35const FEEDBACK_CHAR_LIMIT: RangeInclusive<i32> = 10..=5000;
 36const FEEDBACK_SUBMISSION_ERROR_TEXT: &str =
 37    "Feedback failed to submit, see error log for details.";
 38
 39#[derive(Serialize)]
 40struct FeedbackRequestBody<'a> {
 41    feedback_text: &'a str,
 42    email: Option<String>,
 43    metrics_id: Option<Arc<str>>,
 44    installation_id: Option<Arc<str>>,
 45    system_specs: SystemSpecs,
 46    is_staff: bool,
 47    token: &'a str,
 48}
 49
 50pub struct FeedbackModal {
 51    system_specs: SystemSpecs,
 52    feedback_editor: View<Editor>,
 53    email_address_editor: View<Editor>,
 54    awaiting_submission: bool,
 55    user_submitted: bool,
 56    character_count: i32,
 57}
 58
 59impl FocusableView for FeedbackModal {
 60    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
 61        self.feedback_editor.focus_handle(cx)
 62    }
 63}
 64impl EventEmitter<DismissEvent> for FeedbackModal {}
 65
 66impl ModalView for FeedbackModal {
 67    fn dismiss(&mut self, cx: &mut ViewContext<Self>) -> Task<bool> {
 68        if self.user_submitted {
 69            self.set_user_submitted(false, cx);
 70            return cx.spawn(|_, _| async { true });
 71        }
 72
 73        let has_feedback = self.feedback_editor.read(cx).text_option(cx).is_some();
 74
 75        if !has_feedback {
 76            return cx.spawn(|_, _| async { true });
 77        }
 78
 79        let answer = cx.prompt(PromptLevel::Info, "Discard feedback?", &["Yes", "No"]);
 80
 81        cx.spawn(|_, _| async { answer.await.ok() == Some(0) })
 82    }
 83}
 84
 85impl FeedbackModal {
 86    pub fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
 87        let _handle = cx.view().downgrade();
 88        workspace.register_action(move |workspace, _: &GiveFeedback, cx| {
 89            let markdown = workspace
 90                .app_state()
 91                .languages
 92                .language_for_name("Markdown");
 93
 94            let project = workspace.project().clone();
 95
 96            cx.spawn(|workspace, mut cx| async move {
 97                let markdown = markdown.await.log_err();
 98                let buffer = project
 99                    .update(&mut cx, |project, cx| {
100                        project.create_buffer("", markdown, cx)
101                    })?
102                    .expect("creating buffers on a local workspace always succeeds");
103
104                workspace.update(&mut cx, |workspace, cx| {
105                    let system_specs = SystemSpecs::new(cx);
106
107                    workspace.toggle_modal(cx, move |cx| {
108                        FeedbackModal::new(system_specs, project, buffer, cx)
109                    });
110                })?;
111
112                anyhow::Ok(())
113            })
114            .detach_and_log_err(cx);
115        });
116    }
117
118    pub fn new(
119        system_specs: SystemSpecs,
120        project: Model<Project>,
121        buffer: Model<Buffer>,
122        cx: &mut ViewContext<Self>,
123    ) -> Self {
124        let email_address_editor = cx.build_view(|cx| {
125            let mut editor = Editor::single_line(cx);
126            editor.set_placeholder_text("Email address (optional)", cx);
127
128            if let Ok(Some(email_address)) = KEY_VALUE_STORE.read_kvp(DATABASE_KEY_NAME) {
129                editor.set_text(email_address, cx)
130            }
131
132            editor
133        });
134
135        // Moved here because providing it inline breaks rustfmt
136        let placeholder_text =
137            "You can use markdown to organize your feedback with code and links.";
138
139        let feedback_editor = cx.build_view(|cx| {
140            let mut editor = Editor::for_buffer(buffer, Some(project.clone()), cx);
141            editor.set_placeholder_text(placeholder_text, cx);
142            // editor.set_show_gutter(false, cx);
143            editor.set_vertical_scroll_margin(5, cx);
144            editor
145        });
146
147        cx.subscribe(
148            &feedback_editor,
149            |this, editor, event: &EditorEvent, cx| match event {
150                EditorEvent::Edited => {
151                    this.character_count = editor
152                        .read(cx)
153                        .buffer()
154                        .read(cx)
155                        .as_singleton()
156                        .expect("Feedback editor is never a multi-buffer")
157                        .read(cx)
158                        .len() as i32;
159                    cx.notify();
160                }
161                _ => {}
162            },
163        )
164        .detach();
165
166        Self {
167            system_specs: system_specs.clone(),
168            feedback_editor,
169            email_address_editor,
170            awaiting_submission: false,
171            user_submitted: false,
172            character_count: 0,
173        }
174    }
175
176    pub fn submit(&mut self, cx: &mut ViewContext<Self>) -> Task<anyhow::Result<()>> {
177        let feedback_text = self.feedback_editor.read(cx).text(cx).trim().to_string();
178        let email = self.email_address_editor.read(cx).text_option(cx);
179
180        let answer = cx.prompt(
181            PromptLevel::Info,
182            "Ready to submit your feedback?",
183            &["Yes, Submit!", "No"],
184        );
185        let client = cx.global::<Arc<Client>>().clone();
186        let specs = self.system_specs.clone();
187        cx.spawn(|this, mut cx| async move {
188            let answer = answer.await.ok();
189            if answer == Some(0) {
190                match email.clone() {
191                    Some(email) => {
192                        let _ = KEY_VALUE_STORE
193                            .write_kvp(DATABASE_KEY_NAME.to_string(), email)
194                            .await;
195                    }
196                    None => {
197                        let _ = KEY_VALUE_STORE
198                            .delete_kvp(DATABASE_KEY_NAME.to_string())
199                            .await;
200                    }
201                };
202
203                this.update(&mut cx, |this, cx| {
204                    this.set_awaiting_submission(true, cx);
205                })
206                .log_err();
207
208                let res =
209                    FeedbackModal::submit_feedback(&feedback_text, email, client, specs).await;
210
211                match res {
212                    Ok(_) => {
213                        this.update(&mut cx, |this, cx| {
214                            this.set_user_submitted(true, cx);
215                            cx.emit(DismissEvent)
216                        })
217                        .ok();
218                    }
219                    Err(error) => {
220                        log::error!("{}", error);
221                        this.update(&mut cx, |this, cx| {
222                            let prompt = cx.prompt(
223                                PromptLevel::Critical,
224                                FEEDBACK_SUBMISSION_ERROR_TEXT,
225                                &["OK"],
226                            );
227                            cx.spawn(|_, _cx| async move {
228                                prompt.await.ok();
229                            })
230                            .detach();
231                            this.set_awaiting_submission(false, cx);
232                        })
233                        .log_err();
234                    }
235                }
236            }
237        })
238        .detach();
239
240        Task::ready(Ok(()))
241    }
242
243    fn set_awaiting_submission(&mut self, awaiting_submission: bool, cx: &mut ViewContext<Self>) {
244        self.awaiting_submission = awaiting_submission;
245        cx.notify();
246    }
247
248    fn set_user_submitted(&mut self, user_submitted: bool, cx: &mut ViewContext<Self>) {
249        self.user_submitted = user_submitted;
250        cx.notify();
251    }
252
253    async fn submit_feedback(
254        feedback_text: &str,
255        email: Option<String>,
256        zed_client: Arc<Client>,
257        system_specs: SystemSpecs,
258    ) -> anyhow::Result<()> {
259        if DEV_MODE {
260            if SEND_SUCCESS_IN_DEV_MODE {
261                return Ok(());
262            } else {
263                return Err(anyhow!("Error submitting feedback"));
264            }
265        }
266
267        let feedback_endpoint = format!("{}/api/feedback", *ZED_SERVER_URL);
268        let telemetry = zed_client.telemetry();
269        let metrics_id = telemetry.metrics_id();
270        let installation_id = telemetry.installation_id();
271        let is_staff = telemetry.is_staff();
272        let http_client = zed_client.http_client();
273        let request = FeedbackRequestBody {
274            feedback_text: &feedback_text,
275            email,
276            metrics_id,
277            installation_id,
278            system_specs,
279            is_staff: is_staff.unwrap_or(false),
280            token: ZED_SECRET_CLIENT_TOKEN,
281        };
282        let json_bytes = serde_json::to_vec(&request)?;
283        let request = Request::post(feedback_endpoint)
284            .header("content-type", "application/json")
285            .body(json_bytes.into())?;
286        let mut response = http_client.send(request).await?;
287        let mut body = String::new();
288        response.body_mut().read_to_string(&mut body).await?;
289        let response_status = response.status();
290        if !response_status.is_success() {
291            bail!("Feedback API failed with error: {}", response_status)
292        }
293        Ok(())
294    }
295
296    // TODO: Escape button calls dismiss
297    fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
298        cx.emit(DismissEvent)
299    }
300}
301
302impl Render for FeedbackModal {
303    type Element = Div;
304
305    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
306        let valid_email_address = match self.email_address_editor.read(cx).text_option(cx) {
307            Some(email_address) => Regex::new(EMAIL_REGEX).unwrap().is_match(&email_address),
308            None => true,
309        };
310
311        let valid_character_count = FEEDBACK_CHAR_LIMIT.contains(&self.character_count);
312
313        let allow_submission =
314            valid_character_count && valid_email_address && !self.awaiting_submission;
315
316        let submit_button_text = if self.awaiting_submission {
317            "Submitting..."
318        } else {
319            "Submit"
320        };
321
322        let open_community_repo =
323            cx.listener(|_, _, cx| cx.dispatch_action(Box::new(OpenZedCommunityRepo)));
324
325        // Moved this here because providing it inline breaks rustfmt
326        let provide_an_email_address =
327            "Provide an email address if you want us to be able to reply.";
328
329        v_stack()
330            .elevation_3(cx)
331            .key_context("GiveFeedback")
332            .on_action(cx.listener(Self::cancel))
333            .min_w(rems(40.))
334            .max_w(rems(96.))
335            .h(rems(32.))
336            .p_4()
337            .gap_4()
338            .child(v_stack().child(
339                // TODO: Add Headline component to `ui2`
340                div().text_xl().child("Share Feedback"),
341            ))
342            .child(
343                Label::new(if self.character_count < *FEEDBACK_CHAR_LIMIT.start() {
344                    format!(
345                        "Feedback must be at least {} characters.",
346                        FEEDBACK_CHAR_LIMIT.start()
347                    )
348                } else {
349                    format!(
350                        "Characters: {}",
351                        *FEEDBACK_CHAR_LIMIT.end() - self.character_count
352                    )
353                })
354                .color(if valid_character_count {
355                    Color::Success
356                } else {
357                    Color::Error
358                }),
359            )
360            .child(
361                div()
362                    .flex_1()
363                    .bg(cx.theme().colors().editor_background)
364                    .p_2()
365                    .border()
366                    .rounded_md()
367                    .border_color(cx.theme().colors().border)
368                    .child(self.feedback_editor.clone()),
369            )
370            .child(
371                div()
372                    .child(
373                        h_stack()
374                            .bg(cx.theme().colors().editor_background)
375                            .p_2()
376                            .border()
377                            .rounded_md()
378                            .border_color(cx.theme().colors().border)
379                            .child(self.email_address_editor.clone()),
380                    )
381                    .child(
382                        h_stack()
383                            .justify_between()
384                            .gap_1()
385                            .child(
386                                Button::new("community_repo", "Community Repo")
387                                    .style(ButtonStyle::Transparent)
388                                    .icon(Icon::ExternalLink)
389                                    .icon_position(IconPosition::End)
390                                    .icon_size(IconSize::Small)
391                                    .on_click(open_community_repo),
392                            )
393                            .child(
394                                h_stack()
395                                    .gap_1()
396                                    .child(
397                                        Button::new("cancel_feedback", "Cancel")
398                                            .style(ButtonStyle::Subtle)
399                                            .color(Color::Muted)
400                                            .on_click(cx.listener(move |_, _, cx| {
401                                                cx.spawn(|this, mut cx| async move {
402                                                    this.update(&mut cx, |_, cx| {
403                                                        cx.emit(DismissEvent)
404                                                    })
405                                                    .ok();
406                                                })
407                                                .detach();
408                                            })),
409                                    )
410                                    .child(
411                                        Button::new("send_feedback", submit_button_text)
412                                            .color(Color::Accent)
413                                            .style(ButtonStyle::Filled)
414                                            // TODO: Ensure that while submitting, "Sending..." is shown and disable the button
415                                            // TODO: If submit errors: show popup with error, don't close modal, set text back to "Submit", and re-enable button
416                                            .on_click(cx.listener(|this, _, cx| {
417                                                this.submit(cx).detach();
418                                            }))
419                                            .tooltip(move |cx| {
420                                                Tooltip::with_meta(
421                                                    "Submit feedback to the Zed team.",
422                                                    None,
423                                                    provide_an_email_address,
424                                                    cx,
425                                                )
426                                            })
427                                            .when(!allow_submission, |this| this.disabled(true)),
428                                    ),
429                            ),
430                    ),
431            )
432    }
433}
434
435// TODO: Maybe store email address whenever the modal is closed, versus just on submit, so users can remove it if they want without submitting
436// TODO: Testing of various button states, dismissal prompts, etc.