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