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