feedback_modal.rs

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