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