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