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