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