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, AnyViewHandle, AppContext, Element, ElementBox, Entity, ModelHandle, RenderContext,
 17    Task, View, 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 this = cx.handle();
128        let client = cx.global::<Arc<Client>>().clone();
129        let specs = self.system_specs.clone();
130
131        cx.spawn(|_, mut cx| async move {
132            let answer = answer.recv().await;
133
134            if answer == Some(0) {
135                match FeedbackEditor::submit_feedback(&feedback_text, client, specs).await {
136                    Ok(_) => {
137                        cx.update(|cx| {
138                            this.update(cx, |_, cx| {
139                                cx.dispatch_action(workspace::CloseActiveItem);
140                            })
141                        });
142                    }
143                    Err(error) => {
144                        log::error!("{}", error);
145
146                        cx.update(|cx| {
147                            this.update(cx, |_, cx| {
148                                cx.prompt(
149                                    PromptLevel::Critical,
150                                    FEEDBACK_SUBMISSION_ERROR_TEXT,
151                                    &["OK"],
152                                );
153                            })
154                        });
155                    }
156                }
157            }
158        })
159        .detach();
160
161        Task::ready(Ok(()))
162    }
163
164    async fn submit_feedback(
165        feedback_text: &str,
166        zed_client: Arc<Client>,
167        system_specs: SystemSpecs,
168    ) -> anyhow::Result<()> {
169        let feedback_endpoint = format!("{}/api/feedback", *ZED_SERVER_URL);
170
171        let metrics_id = zed_client.metrics_id();
172        let is_staff = zed_client.is_staff();
173        let http_client = zed_client.http_client();
174
175        let request = FeedbackRequestBody {
176            feedback_text: &feedback_text,
177            metrics_id,
178            system_specs,
179            is_staff: is_staff.unwrap_or(false),
180            token: ZED_SECRET_CLIENT_TOKEN,
181        };
182
183        let json_bytes = serde_json::to_vec(&request)?;
184
185        let request = Request::post(feedback_endpoint)
186            .header("content-type", "application/json")
187            .body(json_bytes.into())?;
188
189        let mut response = http_client.send(request).await?;
190        let mut body = String::new();
191        response.body_mut().read_to_string(&mut body).await?;
192
193        let response_status = response.status();
194
195        if !response_status.is_success() {
196            bail!("Feedback API failed with error: {}", response_status)
197        }
198
199        Ok(())
200    }
201}
202
203impl FeedbackEditor {
204    pub fn deploy(
205        system_specs: SystemSpecs,
206        _: &mut Workspace,
207        app_state: Arc<AppState>,
208        cx: &mut ViewContext<Workspace>,
209    ) {
210        let markdown = app_state.languages.language_for_name("Markdown");
211        cx.spawn(|workspace, mut cx| async move {
212            let markdown = markdown.await.log_err();
213            workspace
214                .update(&mut cx, |workspace, cx| {
215                    workspace.with_local_workspace(&app_state, cx, |workspace, cx| {
216                        let project = workspace.project().clone();
217                        let buffer = project
218                            .update(cx, |project, cx| project.create_buffer("", markdown, cx))
219                            .expect("creating buffers on a local workspace always succeeds");
220                        let feedback_editor = cx
221                            .add_view(|cx| FeedbackEditor::new(system_specs, project, buffer, cx));
222                        workspace.add_item(Box::new(feedback_editor), cx);
223                    })
224                })
225                .await;
226        })
227        .detach();
228    }
229}
230
231impl View for FeedbackEditor {
232    fn ui_name() -> &'static str {
233        "FeedbackEditor"
234    }
235
236    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
237        ChildView::new(&self.editor, cx).boxed()
238    }
239
240    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
241        if cx.is_self_focused() {
242            cx.focus(&self.editor);
243        }
244    }
245}
246
247impl Entity for FeedbackEditor {
248    type Event = editor::Event;
249}
250
251impl Item for FeedbackEditor {
252    fn tab_tooltip_text(&self, _: &AppContext) -> Option<Cow<str>> {
253        Some("Send Feedback".into())
254    }
255
256    fn tab_content(&self, _: Option<usize>, style: &theme::Tab, _: &AppContext) -> ElementBox {
257        Flex::row()
258            .with_child(
259                Svg::new("icons/feedback_16.svg")
260                    .with_color(style.label.text.color)
261                    .constrained()
262                    .with_width(style.type_icon_width)
263                    .aligned()
264                    .contained()
265                    .with_margin_right(style.spacing)
266                    .boxed(),
267            )
268            .with_child(
269                Label::new("Send Feedback", style.label.clone())
270                    .aligned()
271                    .contained()
272                    .boxed(),
273            )
274            .boxed()
275    }
276
277    fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
278        self.editor.for_each_project_item(cx, f)
279    }
280
281    fn is_singleton(&self, _: &AppContext) -> bool {
282        true
283    }
284
285    fn can_save(&self, _: &AppContext) -> bool {
286        true
287    }
288
289    fn save(
290        &mut self,
291        _: ModelHandle<Project>,
292        cx: &mut ViewContext<Self>,
293    ) -> Task<anyhow::Result<()>> {
294        self.handle_save(cx)
295    }
296
297    fn save_as(
298        &mut self,
299        _: ModelHandle<Project>,
300        _: std::path::PathBuf,
301        cx: &mut ViewContext<Self>,
302    ) -> Task<anyhow::Result<()>> {
303        self.handle_save(cx)
304    }
305
306    fn reload(
307        &mut self,
308        _: ModelHandle<Project>,
309        _: &mut ViewContext<Self>,
310    ) -> Task<anyhow::Result<()>> {
311        Task::Ready(Some(Ok(())))
312    }
313
314    fn clone_on_split(
315        &self,
316        _workspace_id: workspace::WorkspaceId,
317        cx: &mut ViewContext<Self>,
318    ) -> Option<Self>
319    where
320        Self: Sized,
321    {
322        let buffer = self
323            .editor
324            .read(cx)
325            .buffer()
326            .read(cx)
327            .as_singleton()
328            .expect("Feedback buffer is only ever singleton");
329
330        Some(Self::new(
331            self.system_specs.clone(),
332            self.project.clone(),
333            buffer.clone(),
334            cx,
335        ))
336    }
337
338    fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
339        Some(Box::new(handle.clone()))
340    }
341
342    fn act_as_type<'a>(
343        &'a self,
344        type_id: TypeId,
345        self_handle: &'a ViewHandle<Self>,
346        _: &'a AppContext,
347    ) -> Option<&'a AnyViewHandle> {
348        if type_id == TypeId::of::<Self>() {
349            Some(self_handle)
350        } else if type_id == TypeId::of::<Editor>() {
351            Some(&self.editor)
352        } else {
353            None
354        }
355    }
356}
357
358impl SearchableItem for FeedbackEditor {
359    type Match = Range<Anchor>;
360
361    fn to_search_event(event: &Self::Event) -> Option<workspace::searchable::SearchEvent> {
362        Editor::to_search_event(event)
363    }
364
365    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
366        self.editor
367            .update(cx, |editor, cx| editor.clear_matches(cx))
368    }
369
370    fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
371        self.editor
372            .update(cx, |editor, cx| editor.update_matches(matches, cx))
373    }
374
375    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
376        self.editor
377            .update(cx, |editor, cx| editor.query_suggestion(cx))
378    }
379
380    fn activate_match(
381        &mut self,
382        index: usize,
383        matches: Vec<Self::Match>,
384        cx: &mut ViewContext<Self>,
385    ) {
386        self.editor
387            .update(cx, |editor, cx| editor.activate_match(index, matches, cx))
388    }
389
390    fn find_matches(
391        &mut self,
392        query: project::search::SearchQuery,
393        cx: &mut ViewContext<Self>,
394    ) -> Task<Vec<Self::Match>> {
395        self.editor
396            .update(cx, |editor, cx| editor.find_matches(query, cx))
397    }
398
399    fn active_match_index(
400        &mut self,
401        matches: Vec<Self::Match>,
402        cx: &mut ViewContext<Self>,
403    ) -> Option<usize> {
404        self.editor
405            .update(cx, |editor, cx| editor.active_match_index(matches, cx))
406    }
407}