feedback_editor.rs

  1use std::{
  2    any::TypeId,
  3    borrow::Cow,
  4    ops::{Range, RangeInclusive},
  5    sync::Arc,
  6};
  7
  8use anyhow::bail;
  9use client::{Client, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
 10use editor::{Anchor, Editor};
 11use futures::AsyncReadExt;
 12use gpui::{
 13    actions,
 14    elements::{ChildView, Flex, Label, ParentElement, Svg},
 15    platform::PromptLevel,
 16    serde_json, AnyElement, AnyViewHandle, AppContext, Element, Entity, ModelHandle, Task, View,
 17    ViewContext, ViewHandle,
 18};
 19use isahc::Request;
 20use language::Buffer;
 21use postage::prelude::Stream;
 22
 23use project::Project;
 24use serde::Serialize;
 25use util::ResultExt;
 26use workspace::{
 27    item::{Item, ItemHandle},
 28    searchable::{SearchableItem, SearchableItemHandle},
 29    AppState, Workspace,
 30};
 31
 32use crate::{submit_feedback_button::SubmitFeedbackButton, system_specs::SystemSpecs};
 33
 34const FEEDBACK_CHAR_LIMIT: RangeInclusive<usize> = 10..=5000;
 35const FEEDBACK_SUBMISSION_ERROR_TEXT: &str =
 36    "Feedback failed to submit, see error log for details.";
 37
 38actions!(feedback, [GiveFeedback, SubmitFeedback]);
 39
 40pub fn init(system_specs: SystemSpecs, app_state: Arc<AppState>, cx: &mut AppContext) {
 41    cx.add_action({
 42        move |workspace: &mut Workspace, _: &GiveFeedback, cx: &mut ViewContext<Workspace>| {
 43            FeedbackEditor::deploy(system_specs.clone(), workspace, app_state.clone(), cx);
 44        }
 45    });
 46
 47    cx.add_async_action(
 48        |submit_feedback_button: &mut SubmitFeedbackButton, _: &SubmitFeedback, cx| {
 49            if let Some(active_item) = submit_feedback_button.active_item.as_ref() {
 50                Some(active_item.update(cx, |feedback_editor, cx| feedback_editor.handle_save(cx)))
 51            } else {
 52                None
 53            }
 54        },
 55    );
 56}
 57
 58#[derive(Serialize)]
 59struct FeedbackRequestBody<'a> {
 60    feedback_text: &'a str,
 61    metrics_id: Option<Arc<str>>,
 62    system_specs: SystemSpecs,
 63    is_staff: bool,
 64    token: &'a str,
 65}
 66
 67#[derive(Clone)]
 68pub(crate) struct FeedbackEditor {
 69    system_specs: SystemSpecs,
 70    editor: ViewHandle<Editor>,
 71    project: ModelHandle<Project>,
 72}
 73
 74impl FeedbackEditor {
 75    fn new(
 76        system_specs: SystemSpecs,
 77        project: ModelHandle<Project>,
 78        buffer: ModelHandle<Buffer>,
 79        cx: &mut ViewContext<Self>,
 80    ) -> Self {
 81        let editor = cx.add_view(|cx| {
 82            let mut editor = Editor::for_buffer(buffer, Some(project.clone()), cx);
 83            editor.set_vertical_scroll_margin(5, cx);
 84            editor
 85        });
 86
 87        cx.subscribe(&editor, |_, _, e, cx| cx.emit(e.clone()))
 88            .detach();
 89
 90        Self {
 91            system_specs: system_specs.clone(),
 92            editor,
 93            project,
 94        }
 95    }
 96
 97    fn handle_save(&mut self, cx: &mut ViewContext<Self>) -> Task<anyhow::Result<()>> {
 98        let feedback_text = self.editor.read(cx).text(cx);
 99        let feedback_char_count = feedback_text.chars().count();
100        let feedback_text = feedback_text.trim().to_string();
101
102        let error = if feedback_char_count < *FEEDBACK_CHAR_LIMIT.start() {
103            Some(format!(
104                "Feedback can't be shorter than {} characters.",
105                FEEDBACK_CHAR_LIMIT.start()
106            ))
107        } else if feedback_char_count > *FEEDBACK_CHAR_LIMIT.end() {
108            Some(format!(
109                "Feedback can't be longer than {} characters.",
110                FEEDBACK_CHAR_LIMIT.end()
111            ))
112        } else {
113            None
114        };
115
116        if let Some(error) = error {
117            cx.prompt(PromptLevel::Critical, &error, &["OK"]);
118            return Task::ready(Ok(()));
119        }
120
121        let mut answer = cx.prompt(
122            PromptLevel::Info,
123            "Ready to submit your feedback?",
124            &["Yes, Submit!", "No"],
125        );
126
127        let client = cx.global::<Arc<Client>>().clone();
128        let specs = self.system_specs.clone();
129
130        cx.spawn(|this, mut cx| async move {
131            let answer = answer.recv().await;
132
133            if answer == Some(0) {
134                match FeedbackEditor::submit_feedback(&feedback_text, client, specs).await {
135                    Ok(_) => {
136                        this.update(&mut cx, |_, cx| {
137                            cx.dispatch_action(workspace::CloseActiveItem);
138                        })
139                        .log_err();
140                    }
141                    Err(error) => {
142                        log::error!("{}", error);
143                        this.update(&mut cx, |_, cx| {
144                            cx.prompt(
145                                PromptLevel::Critical,
146                                FEEDBACK_SUBMISSION_ERROR_TEXT,
147                                &["OK"],
148                            );
149                        })
150                        .log_err();
151                    }
152                }
153            }
154        })
155        .detach();
156
157        Task::ready(Ok(()))
158    }
159
160    async fn submit_feedback(
161        feedback_text: &str,
162        zed_client: Arc<Client>,
163        system_specs: SystemSpecs,
164    ) -> anyhow::Result<()> {
165        let feedback_endpoint = format!("{}/api/feedback", *ZED_SERVER_URL);
166
167        let metrics_id = zed_client.metrics_id();
168        let is_staff = zed_client.is_staff();
169        let http_client = zed_client.http_client();
170
171        let request = FeedbackRequestBody {
172            feedback_text: &feedback_text,
173            metrics_id,
174            system_specs,
175            is_staff: is_staff.unwrap_or(false),
176            token: ZED_SECRET_CLIENT_TOKEN,
177        };
178
179        let json_bytes = serde_json::to_vec(&request)?;
180
181        let request = Request::post(feedback_endpoint)
182            .header("content-type", "application/json")
183            .body(json_bytes.into())?;
184
185        let mut response = http_client.send(request).await?;
186        let mut body = String::new();
187        response.body_mut().read_to_string(&mut body).await?;
188
189        let response_status = response.status();
190
191        if !response_status.is_success() {
192            bail!("Feedback API failed with error: {}", response_status)
193        }
194
195        Ok(())
196    }
197}
198
199impl FeedbackEditor {
200    pub fn deploy(
201        system_specs: SystemSpecs,
202        _: &mut Workspace,
203        app_state: Arc<AppState>,
204        cx: &mut ViewContext<Workspace>,
205    ) {
206        let markdown = app_state.languages.language_for_name("Markdown");
207        cx.spawn(|workspace, mut cx| async move {
208            let markdown = markdown.await.log_err();
209            workspace
210                .update(&mut cx, |workspace, cx| {
211                    workspace.with_local_workspace(&app_state, cx, |workspace, cx| {
212                        let project = workspace.project().clone();
213                        let buffer = project
214                            .update(cx, |project, cx| project.create_buffer("", markdown, cx))
215                            .expect("creating buffers on a local workspace always succeeds");
216                        let feedback_editor = cx
217                            .add_view(|cx| FeedbackEditor::new(system_specs, project, buffer, cx));
218                        workspace.add_item(Box::new(feedback_editor), cx);
219                    })
220                })?
221                .await
222        })
223        .detach_and_log_err(cx);
224    }
225}
226
227impl View for FeedbackEditor {
228    fn ui_name() -> &'static str {
229        "FeedbackEditor"
230    }
231
232    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
233        ChildView::new(&self.editor, cx).into_any()
234    }
235
236    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
237        if cx.is_self_focused() {
238            cx.focus(&self.editor);
239        }
240    }
241}
242
243impl Entity for FeedbackEditor {
244    type Event = editor::Event;
245}
246
247impl Item for FeedbackEditor {
248    fn tab_tooltip_text(&self, _: &AppContext) -> Option<Cow<str>> {
249        Some("Send Feedback".into())
250    }
251
252    fn tab_content<T: View>(
253        &self,
254        _: Option<usize>,
255        style: &theme::Tab,
256        _: &AppContext,
257    ) -> AnyElement<T> {
258        Flex::row()
259            .with_child(
260                Svg::new("icons/feedback_16.svg")
261                    .with_color(style.label.text.color)
262                    .constrained()
263                    .with_width(style.type_icon_width)
264                    .aligned()
265                    .contained()
266                    .with_margin_right(style.spacing),
267            )
268            .with_child(
269                Label::new("Send Feedback", style.label.clone())
270                    .aligned()
271                    .contained(),
272            )
273            .into_any()
274    }
275
276    fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
277        self.editor.for_each_project_item(cx, f)
278    }
279
280    fn is_singleton(&self, _: &AppContext) -> bool {
281        true
282    }
283
284    fn can_save(&self, _: &AppContext) -> bool {
285        true
286    }
287
288    fn save(
289        &mut self,
290        _: ModelHandle<Project>,
291        cx: &mut ViewContext<Self>,
292    ) -> Task<anyhow::Result<()>> {
293        self.handle_save(cx)
294    }
295
296    fn save_as(
297        &mut self,
298        _: ModelHandle<Project>,
299        _: std::path::PathBuf,
300        cx: &mut ViewContext<Self>,
301    ) -> Task<anyhow::Result<()>> {
302        self.handle_save(cx)
303    }
304
305    fn reload(
306        &mut self,
307        _: ModelHandle<Project>,
308        _: &mut ViewContext<Self>,
309    ) -> Task<anyhow::Result<()>> {
310        Task::Ready(Some(Ok(())))
311    }
312
313    fn clone_on_split(
314        &self,
315        _workspace_id: workspace::WorkspaceId,
316        cx: &mut ViewContext<Self>,
317    ) -> Option<Self>
318    where
319        Self: Sized,
320    {
321        let buffer = self
322            .editor
323            .read(cx)
324            .buffer()
325            .read(cx)
326            .as_singleton()
327            .expect("Feedback buffer is only ever singleton");
328
329        Some(Self::new(
330            self.system_specs.clone(),
331            self.project.clone(),
332            buffer.clone(),
333            cx,
334        ))
335    }
336
337    fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
338        Some(Box::new(handle.clone()))
339    }
340
341    fn act_as_type<'a>(
342        &'a self,
343        type_id: TypeId,
344        self_handle: &'a ViewHandle<Self>,
345        _: &'a AppContext,
346    ) -> Option<&'a AnyViewHandle> {
347        if type_id == TypeId::of::<Self>() {
348            Some(self_handle)
349        } else if type_id == TypeId::of::<Editor>() {
350            Some(&self.editor)
351        } else {
352            None
353        }
354    }
355}
356
357impl SearchableItem for FeedbackEditor {
358    type Match = Range<Anchor>;
359
360    fn to_search_event(event: &Self::Event) -> Option<workspace::searchable::SearchEvent> {
361        Editor::to_search_event(event)
362    }
363
364    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
365        self.editor
366            .update(cx, |editor, cx| editor.clear_matches(cx))
367    }
368
369    fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
370        self.editor
371            .update(cx, |editor, cx| editor.update_matches(matches, cx))
372    }
373
374    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
375        self.editor
376            .update(cx, |editor, cx| editor.query_suggestion(cx))
377    }
378
379    fn activate_match(
380        &mut self,
381        index: usize,
382        matches: Vec<Self::Match>,
383        cx: &mut ViewContext<Self>,
384    ) {
385        self.editor
386            .update(cx, |editor, cx| editor.activate_match(index, matches, cx))
387    }
388
389    fn find_matches(
390        &mut self,
391        query: project::search::SearchQuery,
392        cx: &mut ViewContext<Self>,
393    ) -> Task<Vec<Self::Match>> {
394        self.editor
395            .update(cx, |editor, cx| editor.find_matches(query, cx))
396    }
397
398    fn active_match_index(
399        &mut self,
400        matches: Vec<Self::Match>,
401        cx: &mut ViewContext<Self>,
402    ) -> Option<usize> {
403        self.editor
404            .update(cx, |editor, cx| editor.active_match_index(matches, cx))
405    }
406}