feedback_editor.rs

  1use std::{
  2    any::TypeId,
  3    ops::{Range, RangeInclusive},
  4    sync::Arc,
  5};
  6
  7use anyhow::bail;
  8use client::{Client, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
  9use editor::{Anchor, Editor};
 10use futures::AsyncReadExt;
 11use gpui::{
 12    actions,
 13    elements::{ChildView, Flex, Label, MouseEventHandler, ParentElement, Stack, Text},
 14    serde_json, AnyViewHandle, AppContext, CursorStyle, Element, ElementBox, Entity, ModelHandle,
 15    MouseButton, MutableAppContext, PromptLevel, RenderContext, Task, View, ViewContext,
 16    ViewHandle, WeakViewHandle,
 17};
 18use isahc::Request;
 19use language::Buffer;
 20use postage::prelude::Stream;
 21
 22use project::Project;
 23use serde::Serialize;
 24use settings::Settings;
 25use workspace::{
 26    item::{Item, ItemHandle},
 27    searchable::{SearchableItem, SearchableItemHandle},
 28    AppState, StatusItemView, ToolbarItemLocation, ToolbarItemView, Workspace,
 29};
 30
 31use crate::system_specs::SystemSpecs;
 32
 33const FEEDBACK_CHAR_LIMIT: RangeInclusive<usize> = 10..=5000;
 34const FEEDBACK_PLACEHOLDER_TEXT: &str = "Save to submit feedback as Markdown.";
 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 MutableAppContext) {
 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
 58pub struct DeployFeedbackButton;
 59
 60impl Entity for DeployFeedbackButton {
 61    type Event = ();
 62}
 63
 64impl View for DeployFeedbackButton {
 65    fn ui_name() -> &'static str {
 66        "DeployFeedbackButton"
 67    }
 68
 69    fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox {
 70        Stack::new()
 71            .with_child(
 72                MouseEventHandler::<Self>::new(0, cx, |state, cx| {
 73                    let theme = &cx.global::<Settings>().theme;
 74                    let theme = &theme.workspace.status_bar.feedback;
 75
 76                    Text::new(
 77                        "Give Feedback".to_string(),
 78                        theme.style_for(state, true).clone(),
 79                    )
 80                    .boxed()
 81                })
 82                .with_cursor_style(CursorStyle::PointingHand)
 83                .on_click(MouseButton::Left, |_, cx| cx.dispatch_action(GiveFeedback))
 84                .boxed(),
 85            )
 86            .boxed()
 87    }
 88}
 89
 90impl StatusItemView for DeployFeedbackButton {
 91    fn set_active_pane_item(&mut self, _: Option<&dyn ItemHandle>, _: &mut ViewContext<Self>) {}
 92}
 93
 94#[derive(Serialize)]
 95struct FeedbackRequestBody<'a> {
 96    feedback_text: &'a str,
 97    metrics_id: Option<Arc<str>>,
 98    system_specs: SystemSpecs,
 99    is_staff: bool,
100    token: &'a str,
101}
102
103#[derive(Clone)]
104struct FeedbackEditor {
105    system_specs: SystemSpecs,
106    editor: ViewHandle<Editor>,
107    project: ModelHandle<Project>,
108}
109
110impl FeedbackEditor {
111    fn new(
112        system_specs: SystemSpecs,
113        project: ModelHandle<Project>,
114        buffer: ModelHandle<Buffer>,
115        cx: &mut ViewContext<Self>,
116    ) -> Self {
117        let editor = cx.add_view(|cx| {
118            let mut editor = Editor::for_buffer(buffer, Some(project.clone()), cx);
119            editor.set_vertical_scroll_margin(5, cx);
120            editor.set_placeholder_text(FEEDBACK_PLACEHOLDER_TEXT, cx);
121            editor
122        });
123
124        cx.subscribe(&editor, |_, _, e, cx| cx.emit(e.clone()))
125            .detach();
126
127        Self {
128            system_specs: system_specs.clone(),
129            editor,
130            project,
131        }
132    }
133
134    fn handle_save(&mut self, cx: &mut ViewContext<Self>) -> Task<anyhow::Result<()>> {
135        let feedback_text = self.editor.read(cx).text(cx);
136        let feedback_char_count = feedback_text.chars().count();
137        let feedback_text = feedback_text.trim().to_string();
138
139        let error = if feedback_char_count < *FEEDBACK_CHAR_LIMIT.start() {
140            Some(format!(
141                "Feedback can't be shorter than {} characters.",
142                FEEDBACK_CHAR_LIMIT.start()
143            ))
144        } else if feedback_char_count > *FEEDBACK_CHAR_LIMIT.end() {
145            Some(format!(
146                "Feedback can't be longer than {} characters.",
147                FEEDBACK_CHAR_LIMIT.end()
148            ))
149        } else {
150            None
151        };
152
153        if let Some(error) = error {
154            cx.prompt(PromptLevel::Critical, &error, &["OK"]);
155            return Task::ready(Ok(()));
156        }
157
158        let mut answer = cx.prompt(
159            PromptLevel::Info,
160            "Ready to submit your feedback?",
161            &["Yes, Submit!", "No"],
162        );
163
164        let this = cx.handle();
165        let client = cx.global::<Arc<Client>>().clone();
166        let specs = self.system_specs.clone();
167
168        cx.spawn(|_, mut cx| async move {
169            let answer = answer.recv().await;
170
171            if answer == Some(0) {
172                match FeedbackEditor::submit_feedback(&feedback_text, client, specs).await {
173                    Ok(_) => {
174                        cx.update(|cx| {
175                            this.update(cx, |_, cx| {
176                                cx.dispatch_action(workspace::CloseActiveItem);
177                            })
178                        });
179                    }
180                    Err(error) => {
181                        log::error!("{}", error);
182
183                        cx.update(|cx| {
184                            this.update(cx, |_, cx| {
185                                cx.prompt(
186                                    PromptLevel::Critical,
187                                    FEEDBACK_SUBMISSION_ERROR_TEXT,
188                                    &["OK"],
189                                );
190                            })
191                        });
192                    }
193                }
194            }
195        })
196        .detach();
197
198        Task::ready(Ok(()))
199    }
200
201    async fn submit_feedback(
202        feedback_text: &str,
203        zed_client: Arc<Client>,
204        system_specs: SystemSpecs,
205    ) -> anyhow::Result<()> {
206        let feedback_endpoint = format!("{}/api/feedback", *ZED_SERVER_URL);
207
208        let metrics_id = zed_client.metrics_id();
209        let is_staff = zed_client.is_staff();
210        let http_client = zed_client.http_client();
211
212        let request = FeedbackRequestBody {
213            feedback_text: &feedback_text,
214            metrics_id,
215            system_specs,
216            is_staff: is_staff.unwrap_or(false),
217            token: ZED_SECRET_CLIENT_TOKEN,
218        };
219
220        let json_bytes = serde_json::to_vec(&request)?;
221
222        let request = Request::post(feedback_endpoint)
223            .header("content-type", "application/json")
224            .body(json_bytes.into())?;
225
226        let mut response = http_client.send(request).await?;
227        let mut body = String::new();
228        response.body_mut().read_to_string(&mut body).await?;
229
230        let response_status = response.status();
231
232        if !response_status.is_success() {
233            bail!("Feedback API failed with error: {}", response_status)
234        }
235
236        Ok(())
237    }
238}
239
240impl FeedbackEditor {
241    pub fn deploy(
242        system_specs: SystemSpecs,
243        workspace: &mut Workspace,
244        app_state: Arc<AppState>,
245        cx: &mut ViewContext<Workspace>,
246    ) {
247        workspace
248            .with_local_workspace(&app_state, cx, |workspace, cx| {
249                let project = workspace.project().clone();
250                let markdown_language = project.read(cx).languages().language_for_name("Markdown");
251                let buffer = project
252                    .update(cx, |project, cx| {
253                        project.create_buffer("", markdown_language, cx)
254                    })
255                    .expect("creating buffers on a local workspace always succeeds");
256                let feedback_editor =
257                    cx.add_view(|cx| FeedbackEditor::new(system_specs, project, buffer, cx));
258                workspace.add_item(Box::new(feedback_editor), cx);
259            })
260            .detach();
261    }
262}
263
264impl View for FeedbackEditor {
265    fn ui_name() -> &'static str {
266        "FeedbackEditor"
267    }
268
269    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
270        ChildView::new(&self.editor, cx).boxed()
271    }
272
273    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
274        if cx.is_self_focused() {
275            cx.focus(&self.editor);
276        }
277    }
278}
279
280impl Entity for FeedbackEditor {
281    type Event = editor::Event;
282}
283
284impl Item for FeedbackEditor {
285    fn tab_content(&self, _: Option<usize>, style: &theme::Tab, _: &AppContext) -> ElementBox {
286        Flex::row()
287            .with_child(
288                Label::new("Feedback".to_string(), style.label.clone())
289                    .aligned()
290                    .contained()
291                    .boxed(),
292            )
293            .boxed()
294    }
295
296    fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
297        self.editor.for_each_project_item(cx, f)
298    }
299
300    fn to_item_events(_: &Self::Event) -> Vec<workspace::item::ItemEvent> {
301        Vec::new()
302    }
303
304    fn is_singleton(&self, _: &AppContext) -> bool {
305        true
306    }
307
308    fn set_nav_history(&mut self, _: workspace::ItemNavHistory, _: &mut ViewContext<Self>) {}
309
310    fn can_save(&self, _: &AppContext) -> bool {
311        true
312    }
313
314    fn save(
315        &mut self,
316        _: ModelHandle<Project>,
317        cx: &mut ViewContext<Self>,
318    ) -> Task<anyhow::Result<()>> {
319        self.handle_save(cx)
320    }
321
322    fn save_as(
323        &mut self,
324        _: ModelHandle<Project>,
325        _: std::path::PathBuf,
326        cx: &mut ViewContext<Self>,
327    ) -> Task<anyhow::Result<()>> {
328        self.handle_save(cx)
329    }
330
331    fn reload(
332        &mut self,
333        _: ModelHandle<Project>,
334        _: &mut ViewContext<Self>,
335    ) -> Task<anyhow::Result<()>> {
336        unreachable!("reload should not have been called")
337    }
338
339    fn clone_on_split(
340        &self,
341        _workspace_id: workspace::WorkspaceId,
342        cx: &mut ViewContext<Self>,
343    ) -> Option<Self>
344    where
345        Self: Sized,
346    {
347        let buffer = self
348            .editor
349            .read(cx)
350            .buffer()
351            .read(cx)
352            .as_singleton()
353            .expect("Feedback buffer is only ever singleton");
354
355        Some(Self::new(
356            self.system_specs.clone(),
357            self.project.clone(),
358            buffer.clone(),
359            cx,
360        ))
361    }
362
363    fn serialized_item_kind() -> Option<&'static str> {
364        None
365    }
366
367    fn deserialize(
368        _: ModelHandle<Project>,
369        _: WeakViewHandle<Workspace>,
370        _: workspace::WorkspaceId,
371        _: workspace::ItemId,
372        _: &mut ViewContext<workspace::Pane>,
373    ) -> Task<anyhow::Result<ViewHandle<Self>>> {
374        unreachable!()
375    }
376
377    fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
378        Some(Box::new(handle.clone()))
379    }
380
381    fn act_as_type(
382        &self,
383        type_id: TypeId,
384        self_handle: &ViewHandle<Self>,
385        _: &AppContext,
386    ) -> Option<AnyViewHandle> {
387        if type_id == TypeId::of::<Self>() {
388            Some(self_handle.into())
389        } else if type_id == TypeId::of::<Editor>() {
390            Some((&self.editor).into())
391        } else {
392            None
393        }
394    }
395}
396
397impl SearchableItem for FeedbackEditor {
398    type Match = Range<Anchor>;
399
400    fn to_search_event(event: &Self::Event) -> Option<workspace::searchable::SearchEvent> {
401        Editor::to_search_event(event)
402    }
403
404    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
405        self.editor
406            .update(cx, |editor, cx| editor.clear_matches(cx))
407    }
408
409    fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
410        self.editor
411            .update(cx, |editor, cx| editor.update_matches(matches, cx))
412    }
413
414    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
415        self.editor
416            .update(cx, |editor, cx| editor.query_suggestion(cx))
417    }
418
419    fn activate_match(
420        &mut self,
421        index: usize,
422        matches: Vec<Self::Match>,
423        cx: &mut ViewContext<Self>,
424    ) {
425        self.editor
426            .update(cx, |editor, cx| editor.activate_match(index, matches, cx))
427    }
428
429    fn find_matches(
430        &mut self,
431        query: project::search::SearchQuery,
432        cx: &mut ViewContext<Self>,
433    ) -> Task<Vec<Self::Match>> {
434        self.editor
435            .update(cx, |editor, cx| editor.find_matches(query, cx))
436    }
437
438    fn active_match_index(
439        &mut self,
440        matches: Vec<Self::Match>,
441        cx: &mut ViewContext<Self>,
442    ) -> Option<usize> {
443        self.editor
444            .update(cx, |editor, cx| editor.active_match_index(matches, cx))
445    }
446}
447
448pub struct SubmitFeedbackButton {
449    active_item: Option<ViewHandle<FeedbackEditor>>,
450}
451
452impl SubmitFeedbackButton {
453    pub fn new() -> Self {
454        Self {
455            active_item: Default::default(),
456        }
457    }
458}
459
460impl Entity for SubmitFeedbackButton {
461    type Event = ();
462}
463
464impl View for SubmitFeedbackButton {
465    fn ui_name() -> &'static str {
466        "SubmitFeedbackButton"
467    }
468
469    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
470        let theme = cx.global::<Settings>().theme.clone();
471        enum SubmitFeedbackButton {}
472        MouseEventHandler::<SubmitFeedbackButton>::new(0, cx, |state, _| {
473            let style = theme.feedback.submit_button.style_for(state, false);
474            Label::new("Submit as Markdown".into(), style.text.clone())
475                .contained()
476                .with_style(style.container)
477                .boxed()
478        })
479        .with_cursor_style(CursorStyle::PointingHand)
480        .on_click(MouseButton::Left, |_, cx| {
481            cx.dispatch_action(SubmitFeedback)
482        })
483        .aligned()
484        .contained()
485        .with_margin_left(theme.feedback.button_margin)
486        .boxed()
487    }
488}
489
490impl ToolbarItemView for SubmitFeedbackButton {
491    fn set_active_pane_item(
492        &mut self,
493        active_pane_item: Option<&dyn ItemHandle>,
494        cx: &mut ViewContext<Self>,
495    ) -> workspace::ToolbarItemLocation {
496        cx.notify();
497        if let Some(feedback_editor) = active_pane_item.and_then(|i| i.downcast::<FeedbackEditor>())
498        {
499            self.active_item = Some(feedback_editor);
500            ToolbarItemLocation::PrimaryRight { flex: None }
501        } else {
502            self.active_item = None;
503            ToolbarItemLocation::Hidden
504        }
505    }
506}