Remove 2 suffix for picker, feedback

Co-authored-by: Mikayla <mikayla@zed.dev>
This commit is contained in:
Max Brunsfeld
2024-01-03 10:55:34 -08:00
co-authored by Mikayla
parent 0ac8aae17b
commit bcad3a5847
32 changed files with 405 additions and 1728 deletions
+28 -70
View File
@@ -1,91 +1,49 @@
use gpui::{
elements::*,
platform::{CursorStyle, MouseButton},
Entity, View, ViewContext, WeakViewHandle,
};
use gpui::{Render, ViewContext, WeakView};
use ui::{prelude::*, ButtonCommon, Icon, IconButton, Tooltip};
use workspace::{item::ItemHandle, StatusItemView, Workspace};
use crate::feedback_editor::{FeedbackEditor, GiveFeedback};
use crate::{feedback_modal::FeedbackModal, GiveFeedback};
pub struct DeployFeedbackButton {
active: bool,
workspace: WeakViewHandle<Workspace>,
}
impl Entity for DeployFeedbackButton {
type Event = ();
workspace: WeakView<Workspace>,
}
impl DeployFeedbackButton {
pub fn new(workspace: &Workspace) -> Self {
DeployFeedbackButton {
active: false,
workspace: workspace.weak_handle(),
}
}
}
impl View for DeployFeedbackButton {
fn ui_name() -> &'static str {
"DeployFeedbackButton"
}
fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
let active = self.active;
let theme = theme::current(cx).clone();
Stack::new()
.with_child(
MouseEventHandler::new::<Self, _>(0, cx, |state, _| {
let style = &theme
.workspace
.status_bar
.panel_buttons
.button
.in_state(active)
.style_for(state);
Svg::new("icons/feedback.svg")
.with_color(style.icon_color)
.constrained()
.with_width(style.icon_size)
.aligned()
.constrained()
.with_width(style.icon_size)
.with_height(style.icon_size)
.contained()
.with_style(style.container)
impl Render for DeployFeedbackButton {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
let is_open = self
.workspace
.upgrade()
.and_then(|workspace| {
workspace.update(cx, |workspace, cx| {
workspace.active_modal::<FeedbackModal>(cx)
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, this, cx| {
if !active {
if let Some(workspace) = this.workspace.upgrade(cx) {
workspace
.update(cx, |workspace, cx| FeedbackEditor::deploy(workspace, cx))
}
}
})
.with_tooltip::<Self>(
0,
"Send Feedback",
Some(Box::new(GiveFeedback)),
theme.tooltip.clone(),
cx,
),
)
.into_any()
})
.is_some();
IconButton::new("give-feedback", Icon::Envelope)
.style(ui::ButtonStyle::Subtle)
.icon_size(IconSize::Small)
.selected(is_open)
.tooltip(|cx| Tooltip::text("Share Feedback", cx))
.on_click(|_, cx| {
cx.dispatch_action(Box::new(GiveFeedback));
})
.into_any_element()
}
}
impl StatusItemView for DeployFeedbackButton {
fn set_active_pane_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
if let Some(item) = item {
if let Some(_) = item.downcast::<FeedbackEditor>() {
self.active = true;
cx.notify();
return;
}
}
self.active = false;
cx.notify();
fn set_active_pane_item(
&mut self,
_item: Option<&dyn ItemHandle>,
_cx: &mut ViewContext<Self>,
) {
}
}
+44 -45
View File
@@ -1,13 +1,14 @@
pub mod deploy_feedback_button;
pub mod feedback_editor;
pub mod feedback_info_text;
pub mod submit_feedback_button;
mod system_specs;
use gpui::{actions, platform::PromptLevel, AppContext, ClipboardItem, ViewContext};
use gpui::{actions, AppContext, ClipboardItem, PromptLevel};
use system_specs::SystemSpecs;
use workspace::Workspace;
pub mod deploy_feedback_button;
pub mod feedback_modal;
actions!(feedback, [GiveFeedback, SubmitFeedback]);
mod system_specs;
actions!(
zed,
[
@@ -19,44 +20,42 @@ actions!(
);
pub fn init(cx: &mut AppContext) {
feedback_editor::init(cx);
// TODO: a way to combine these two into one?
cx.observe_new_views(feedback_modal::FeedbackModal::register)
.detach();
cx.add_action(
move |_: &mut Workspace,
_: &CopySystemSpecsIntoClipboard,
cx: &mut ViewContext<Workspace>| {
let specs = SystemSpecs::new(&cx).to_string();
cx.prompt(
PromptLevel::Info,
&format!("Copied into clipboard:\n\n{specs}"),
&["OK"],
);
let item = ClipboardItem::new(specs.clone());
cx.write_to_clipboard(item);
},
);
cx.observe_new_views(|workspace: &mut Workspace, _| {
workspace
.register_action(|_, _: &CopySystemSpecsIntoClipboard, cx| {
let specs = SystemSpecs::new(&cx).to_string();
cx.add_action(
|_: &mut Workspace, _: &RequestFeature, cx: &mut ViewContext<Workspace>| {
let url = "https://github.com/zed-industries/community/issues/new?assignees=&labels=enhancement%2Ctriage&template=0_feature_request.yml";
cx.platform().open_url(url);
},
);
cx.add_action(
move |_: &mut Workspace, _: &FileBugReport, cx: &mut ViewContext<Workspace>| {
let url = format!(
"https://github.com/zed-industries/community/issues/new?assignees=&labels=defect%2Ctriage&template=2_bug_report.yml&environment={}",
urlencoding::encode(&SystemSpecs::new(&cx).to_string())
);
cx.platform().open_url(&url);
},
);
cx.add_global_action(open_zed_community_repo);
}
pub fn open_zed_community_repo(_: &OpenZedCommunityRepo, cx: &mut AppContext) {
let url = "https://github.com/zed-industries/community";
cx.platform().open_url(&url);
let prompt = cx.prompt(
PromptLevel::Info,
&format!("Copied into clipboard:\n\n{specs}"),
&["OK"],
);
cx.spawn(|_, _cx| async move {
prompt.await.ok();
})
.detach();
let item = ClipboardItem::new(specs.clone());
cx.write_to_clipboard(item);
})
.register_action(|_, _: &RequestFeature, cx| {
let url = "https://github.com/zed-industries/community/issues/new?assignees=&labels=enhancement%2Ctriage&template=0_feature_request.yml";
cx.open_url(url);
})
.register_action(move |_, _: &FileBugReport, cx| {
let url = format!(
"https://github.com/zed-industries/community/issues/new?assignees=&labels=defect%2Ctriage&template=2_bug_report.yml&environment={}",
urlencoding::encode(&SystemSpecs::new(&cx).to_string())
);
cx.open_url(&url);
})
.register_action(move |_, _: &OpenZedCommunityRepo, cx| {
let url = "https://github.com/zed-industries/community";
cx.open_url(&url);
});
})
.detach();
}
-442
View File
@@ -1,442 +0,0 @@
use crate::system_specs::SystemSpecs;
use anyhow::bail;
use client::{Client, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
use editor::{Anchor, Editor};
use futures::AsyncReadExt;
use gpui::{
actions,
elements::{ChildView, Flex, Label, ParentElement, Svg},
platform::PromptLevel,
serde_json, AnyElement, AnyViewHandle, AppContext, Element, Entity, ModelHandle, Task, View,
ViewContext, ViewHandle,
};
use isahc::Request;
use language::Buffer;
use postage::prelude::Stream;
use project::{search::SearchQuery, Project};
use regex::Regex;
use serde::Serialize;
use smallvec::SmallVec;
use std::{
any::TypeId,
borrow::Cow,
ops::{Range, RangeInclusive},
sync::Arc,
};
use util::ResultExt;
use workspace::{
item::{Item, ItemEvent, ItemHandle},
searchable::{SearchableItem, SearchableItemHandle},
Workspace,
};
const FEEDBACK_CHAR_LIMIT: RangeInclusive<usize> = 10..=5000;
const FEEDBACK_SUBMISSION_ERROR_TEXT: &str =
"Feedback failed to submit, see error log for details.";
actions!(feedback, [GiveFeedback, SubmitFeedback]);
pub fn init(cx: &mut AppContext) {
cx.add_action({
move |workspace: &mut Workspace, _: &GiveFeedback, cx: &mut ViewContext<Workspace>| {
FeedbackEditor::deploy(workspace, cx);
}
});
}
#[derive(Serialize)]
struct FeedbackRequestBody<'a> {
feedback_text: &'a str,
email: Option<String>,
metrics_id: Option<Arc<str>>,
installation_id: Option<Arc<str>>,
system_specs: SystemSpecs,
is_staff: bool,
token: &'a str,
}
#[derive(Clone)]
pub(crate) struct FeedbackEditor {
system_specs: SystemSpecs,
editor: ViewHandle<Editor>,
project: ModelHandle<Project>,
pub allow_submission: bool,
}
impl FeedbackEditor {
fn new(
system_specs: SystemSpecs,
project: ModelHandle<Project>,
buffer: ModelHandle<Buffer>,
cx: &mut ViewContext<Self>,
) -> Self {
let editor = cx.add_view(|cx| {
let mut editor = Editor::for_buffer(buffer, Some(project.clone()), cx);
editor.set_vertical_scroll_margin(5, cx);
editor
});
cx.subscribe(&editor, |_, _, e, cx| cx.emit(e.clone()))
.detach();
Self {
system_specs: system_specs.clone(),
editor,
project,
allow_submission: true,
}
}
pub fn submit(&mut self, cx: &mut ViewContext<Self>) -> Task<anyhow::Result<()>> {
if !self.allow_submission {
return Task::ready(Ok(()));
}
let feedback_text = self.editor.read(cx).text(cx);
let feedback_char_count = feedback_text.chars().count();
let feedback_text = feedback_text.trim().to_string();
let error = if feedback_char_count < *FEEDBACK_CHAR_LIMIT.start() {
Some(format!(
"Feedback can't be shorter than {} characters.",
FEEDBACK_CHAR_LIMIT.start()
))
} else if feedback_char_count > *FEEDBACK_CHAR_LIMIT.end() {
Some(format!(
"Feedback can't be longer than {} characters.",
FEEDBACK_CHAR_LIMIT.end()
))
} else {
None
};
if let Some(error) = error {
cx.prompt(PromptLevel::Critical, &error, &["OK"]);
return Task::ready(Ok(()));
}
let mut answer = cx.prompt(
PromptLevel::Info,
"Ready to submit your feedback?",
&["Yes, Submit!", "No"],
);
let client = cx.global::<Arc<Client>>().clone();
let specs = self.system_specs.clone();
cx.spawn(|this, mut cx| async move {
let answer = answer.recv().await;
if answer == Some(0) {
this.update(&mut cx, |feedback_editor, cx| {
feedback_editor.set_allow_submission(false, cx);
})
.log_err();
match FeedbackEditor::submit_feedback(&feedback_text, client, specs).await {
Ok(_) => {
this.update(&mut cx, |_, cx| cx.emit(editor::Event::Closed))
.log_err();
}
Err(error) => {
log::error!("{}", error);
this.update(&mut cx, |feedback_editor, cx| {
cx.prompt(
PromptLevel::Critical,
FEEDBACK_SUBMISSION_ERROR_TEXT,
&["OK"],
);
feedback_editor.set_allow_submission(true, cx);
})
.log_err();
}
}
}
})
.detach();
Task::ready(Ok(()))
}
fn set_allow_submission(&mut self, allow_submission: bool, cx: &mut ViewContext<Self>) {
self.allow_submission = allow_submission;
cx.notify();
}
async fn submit_feedback(
feedback_text: &str,
zed_client: Arc<Client>,
system_specs: SystemSpecs,
) -> anyhow::Result<()> {
let feedback_endpoint = format!("{}/api/feedback", *ZED_SERVER_URL);
let telemetry = zed_client.telemetry();
let metrics_id = telemetry.metrics_id();
let installation_id = telemetry.installation_id();
let is_staff = telemetry.is_staff();
let http_client = zed_client.http_client();
let re = Regex::new(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b").unwrap();
let emails: Vec<&str> = re
.captures_iter(feedback_text)
.map(|capture| capture.get(0).unwrap().as_str())
.collect();
let email = emails.first().map(|e| e.to_string());
let request = FeedbackRequestBody {
feedback_text: &feedback_text,
email,
metrics_id,
installation_id,
system_specs,
is_staff: is_staff.unwrap_or(false),
token: ZED_SECRET_CLIENT_TOKEN,
};
let json_bytes = serde_json::to_vec(&request)?;
let request = Request::post(feedback_endpoint)
.header("content-type", "application/json")
.body(json_bytes.into())?;
let mut response = http_client.send(request).await?;
let mut body = String::new();
response.body_mut().read_to_string(&mut body).await?;
let response_status = response.status();
if !response_status.is_success() {
bail!("Feedback API failed with error: {}", response_status)
}
Ok(())
}
}
impl FeedbackEditor {
pub fn deploy(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
let markdown = workspace
.app_state()
.languages
.language_for_name("Markdown");
cx.spawn(|workspace, mut cx| async move {
let markdown = markdown.await.log_err();
workspace
.update(&mut cx, |workspace, cx| {
workspace.with_local_workspace(cx, |workspace, cx| {
let project = workspace.project().clone();
let buffer = project
.update(cx, |project, cx| project.create_buffer("", markdown, cx))
.expect("creating buffers on a local workspace always succeeds");
let system_specs = SystemSpecs::new(cx);
let feedback_editor = cx
.add_view(|cx| FeedbackEditor::new(system_specs, project, buffer, cx));
workspace.add_item(Box::new(feedback_editor), cx);
})
})?
.await
})
.detach_and_log_err(cx);
}
}
impl View for FeedbackEditor {
fn ui_name() -> &'static str {
"FeedbackEditor"
}
fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
ChildView::new(&self.editor, cx).into_any()
}
fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
if cx.is_self_focused() {
cx.focus(&self.editor);
}
}
}
impl Entity for FeedbackEditor {
type Event = editor::Event;
}
impl Item for FeedbackEditor {
fn tab_tooltip_text(&self, _: &AppContext) -> Option<Cow<str>> {
Some("Send Feedback".into())
}
fn tab_content<T: 'static>(
&self,
_: Option<usize>,
style: &theme::Tab,
_: &AppContext,
) -> AnyElement<T> {
Flex::row()
.with_child(
Svg::new("icons/feedback.svg")
.with_color(style.label.text.color)
.constrained()
.with_width(style.type_icon_width)
.aligned()
.contained()
.with_margin_right(style.spacing),
)
.with_child(
Label::new("Send Feedback", style.label.clone())
.aligned()
.contained(),
)
.into_any()
}
fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
self.editor.for_each_project_item(cx, f)
}
fn is_singleton(&self, _: &AppContext) -> bool {
true
}
fn can_save(&self, _: &AppContext) -> bool {
true
}
fn save(
&mut self,
_: ModelHandle<Project>,
cx: &mut ViewContext<Self>,
) -> Task<anyhow::Result<()>> {
self.submit(cx)
}
fn save_as(
&mut self,
_: ModelHandle<Project>,
_: std::path::PathBuf,
cx: &mut ViewContext<Self>,
) -> Task<anyhow::Result<()>> {
self.submit(cx)
}
fn reload(
&mut self,
_: ModelHandle<Project>,
_: &mut ViewContext<Self>,
) -> Task<anyhow::Result<()>> {
Task::Ready(Some(Ok(())))
}
fn clone_on_split(
&self,
_workspace_id: workspace::WorkspaceId,
cx: &mut ViewContext<Self>,
) -> Option<Self>
where
Self: Sized,
{
let buffer = self
.editor
.read(cx)
.buffer()
.read(cx)
.as_singleton()
.expect("Feedback buffer is only ever singleton");
Some(Self::new(
self.system_specs.clone(),
self.project.clone(),
buffer.clone(),
cx,
))
}
fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
Some(Box::new(handle.clone()))
}
fn act_as_type<'a>(
&'a self,
type_id: TypeId,
self_handle: &'a ViewHandle<Self>,
_: &'a AppContext,
) -> Option<&'a AnyViewHandle> {
if type_id == TypeId::of::<Self>() {
Some(self_handle)
} else if type_id == TypeId::of::<Editor>() {
Some(&self.editor)
} else {
None
}
}
fn to_item_events(event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
Editor::to_item_events(event)
}
}
impl SearchableItem for FeedbackEditor {
type Match = Range<Anchor>;
fn to_search_event(
&mut self,
event: &Self::Event,
cx: &mut ViewContext<Self>,
) -> Option<workspace::searchable::SearchEvent> {
self.editor
.update(cx, |editor, cx| editor.to_search_event(event, cx))
}
fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
self.editor
.update(cx, |editor, cx| editor.clear_matches(cx))
}
fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
self.editor
.update(cx, |editor, cx| editor.update_matches(matches, cx))
}
fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
self.editor
.update(cx, |editor, cx| editor.query_suggestion(cx))
}
fn activate_match(
&mut self,
index: usize,
matches: Vec<Self::Match>,
cx: &mut ViewContext<Self>,
) {
self.editor
.update(cx, |editor, cx| editor.activate_match(index, matches, cx))
}
fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
self.editor
.update(cx, |e, cx| e.select_matches(matches, cx))
}
fn replace(&mut self, matches: &Self::Match, query: &SearchQuery, cx: &mut ViewContext<Self>) {
self.editor
.update(cx, |e, cx| e.replace(matches, query, cx));
}
fn find_matches(
&mut self,
query: Arc<project::search::SearchQuery>,
cx: &mut ViewContext<Self>,
) -> Task<Vec<Self::Match>> {
self.editor
.update(cx, |editor, cx| editor.find_matches(query, cx))
}
fn active_match_index(
&mut self,
matches: Vec<Self::Match>,
cx: &mut ViewContext<Self>,
) -> Option<usize> {
self.editor
.update(cx, |editor, cx| editor.active_match_index(matches, cx))
}
}
-94
View File
@@ -1,94 +0,0 @@
use gpui::{
elements::{Flex, Label, MouseEventHandler, ParentElement, Text},
platform::{CursorStyle, MouseButton},
AnyElement, Element, Entity, View, ViewContext, ViewHandle,
};
use workspace::{item::ItemHandle, ToolbarItemLocation, ToolbarItemView};
use crate::{feedback_editor::FeedbackEditor, open_zed_community_repo, OpenZedCommunityRepo};
pub struct FeedbackInfoText {
active_item: Option<ViewHandle<FeedbackEditor>>,
}
impl FeedbackInfoText {
pub fn new() -> Self {
Self {
active_item: Default::default(),
}
}
}
impl Entity for FeedbackInfoText {
type Event = ();
}
impl View for FeedbackInfoText {
fn ui_name() -> &'static str {
"FeedbackInfoText"
}
fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
let theme = theme::current(cx).clone();
Flex::row()
.with_child(
Text::new(
"Share your feedback. Include your email for replies. For issues and discussions, visit the ",
theme.feedback.info_text_default.text.clone(),
)
.with_soft_wrap(false)
.aligned(),
)
.with_child(
MouseEventHandler::new::<OpenZedCommunityRepo, _>(0, cx, |state, _| {
let style = if state.hovered() {
&theme.feedback.link_text_hover
} else {
&theme.feedback.link_text_default
};
Label::new("community repo", style.text.clone())
.contained()
.with_style(style.container)
.aligned()
.left()
.clipped()
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, |_, _, cx| {
open_zed_community_repo(&Default::default(), cx)
}),
)
.with_child(
Text::new(".", theme.feedback.info_text_default.text.clone())
.with_soft_wrap(false)
.aligned(),
)
.contained()
.with_style(theme.feedback.info_text_default.container)
.aligned()
.left()
.clipped()
.into_any()
}
}
impl ToolbarItemView for FeedbackInfoText {
fn set_active_pane_item(
&mut self,
active_pane_item: Option<&dyn ItemHandle>,
cx: &mut ViewContext<Self>,
) -> workspace::ToolbarItemLocation {
cx.notify();
if let Some(feedback_editor) = active_pane_item.and_then(|i| i.downcast::<FeedbackEditor>())
{
self.active_item = Some(feedback_editor);
ToolbarItemLocation::PrimaryLeft {
flex: Some((1., false)),
}
} else {
self.active_item = None;
ToolbarItemLocation::Hidden
}
}
}
+557
View File
@@ -0,0 +1,557 @@
use std::{ops::RangeInclusive, sync::Arc, time::Duration};
use anyhow::{anyhow, bail};
use bitflags::bitflags;
use client::{Client, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
use db::kvp::KEY_VALUE_STORE;
use editor::{Editor, EditorEvent};
use futures::AsyncReadExt;
use gpui::{
div, red, rems, serde_json, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
Model, PromptLevel, Render, Task, View, ViewContext,
};
use isahc::Request;
use language::Buffer;
use project::Project;
use regex::Regex;
use serde_derive::Serialize;
use ui::{prelude::*, Button, ButtonStyle, IconPosition, Tooltip};
use util::ResultExt;
use workspace::{ModalView, Workspace};
use crate::{system_specs::SystemSpecs, GiveFeedback, OpenZedCommunityRepo};
// For UI testing purposes
const SEND_SUCCESS_IN_DEV_MODE: bool = true;
const SEND_TIME_IN_DEV_MODE: Duration = Duration::from_secs(2);
// Temporary, until tests are in place
#[cfg(debug_assertions)]
const DEV_MODE: bool = true;
#[cfg(not(debug_assertions))]
const DEV_MODE: bool = false;
const DATABASE_KEY_NAME: &str = "email_address";
const EMAIL_REGEX: &str = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b";
const FEEDBACK_CHAR_LIMIT: RangeInclusive<i32> = 10..=5000;
const FEEDBACK_SUBMISSION_ERROR_TEXT: &str =
"Feedback failed to submit, see error log for details.";
#[derive(Serialize)]
struct FeedbackRequestBody<'a> {
feedback_text: &'a str,
email: Option<String>,
metrics_id: Option<Arc<str>>,
installation_id: Option<Arc<str>>,
system_specs: SystemSpecs,
is_staff: bool,
token: &'a str,
}
bitflags! {
#[derive(Debug, Clone, PartialEq)]
struct InvalidStateFlags: u8 {
const EmailAddress = 0b00000001;
const CharacterCount = 0b00000010;
}
}
#[derive(Debug, Clone, PartialEq)]
enum CannotSubmitReason {
InvalidState { flags: InvalidStateFlags },
AwaitingSubmission,
}
#[derive(Debug, Clone, PartialEq)]
enum SubmissionState {
CanSubmit,
CannotSubmit { reason: CannotSubmitReason },
}
pub struct FeedbackModal {
system_specs: SystemSpecs,
feedback_editor: View<Editor>,
email_address_editor: View<Editor>,
submission_state: Option<SubmissionState>,
dismiss_modal: bool,
character_count: i32,
}
impl FocusableView for FeedbackModal {
fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
self.feedback_editor.focus_handle(cx)
}
}
impl EventEmitter<DismissEvent> for FeedbackModal {}
impl ModalView for FeedbackModal {
fn on_before_dismiss(&mut self, cx: &mut ViewContext<Self>) -> bool {
self.update_email_in_store(cx);
if self.dismiss_modal {
return true;
}
let has_feedback = self.feedback_editor.read(cx).text_option(cx).is_some();
if !has_feedback {
return true;
}
let answer = cx.prompt(PromptLevel::Info, "Discard feedback?", &["Yes", "No"]);
cx.spawn(move |this, mut cx| async move {
if answer.await.ok() == Some(0) {
this.update(&mut cx, |this, cx| {
this.dismiss_modal = true;
cx.emit(DismissEvent)
})
.log_err();
}
})
.detach();
false
}
}
impl FeedbackModal {
pub fn register(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
let _handle = cx.view().downgrade();
workspace.register_action(move |workspace, _: &GiveFeedback, cx| {
let markdown = workspace
.app_state()
.languages
.language_for_name("Markdown");
let project = workspace.project().clone();
cx.spawn(|workspace, mut cx| async move {
let markdown = markdown.await.log_err();
let buffer = project
.update(&mut cx, |project, cx| {
project.create_buffer("", markdown, cx)
})?
.expect("creating buffers on a local workspace always succeeds");
workspace.update(&mut cx, |workspace, cx| {
let system_specs = SystemSpecs::new(cx);
workspace.toggle_modal(cx, move |cx| {
FeedbackModal::new(system_specs, project, buffer, cx)
});
})?;
anyhow::Ok(())
})
.detach_and_log_err(cx);
});
}
pub fn new(
system_specs: SystemSpecs,
project: Model<Project>,
buffer: Model<Buffer>,
cx: &mut ViewContext<Self>,
) -> Self {
let email_address_editor = cx.new_view(|cx| {
let mut editor = Editor::single_line(cx);
editor.set_placeholder_text("Email address (optional)", cx);
if let Ok(Some(email_address)) = KEY_VALUE_STORE.read_kvp(DATABASE_KEY_NAME) {
editor.set_text(email_address, cx)
}
editor
});
// Moved here because providing it inline breaks rustfmt
let placeholder_text =
"You can use markdown to organize your feedback with code and links.";
let feedback_editor = cx.new_view(|cx| {
let mut editor = Editor::for_buffer(buffer, Some(project.clone()), cx);
editor.set_placeholder_text(placeholder_text, cx);
// editor.set_show_gutter(false, cx);
editor.set_vertical_scroll_margin(5, cx);
editor
});
cx.subscribe(&feedback_editor, |this, editor, event: &EditorEvent, cx| {
if *event == EditorEvent::Edited {
this.character_count = editor
.read(cx)
.buffer()
.read(cx)
.as_singleton()
.expect("Feedback editor is never a multi-buffer")
.read(cx)
.len() as i32;
cx.notify();
}
})
.detach();
Self {
system_specs: system_specs.clone(),
feedback_editor,
email_address_editor,
submission_state: None,
dismiss_modal: false,
character_count: 0,
}
}
pub fn submit(&mut self, cx: &mut ViewContext<Self>) -> Task<anyhow::Result<()>> {
let feedback_text = self.feedback_editor.read(cx).text(cx).trim().to_string();
let email = self.email_address_editor.read(cx).text_option(cx);
let answer = cx.prompt(
PromptLevel::Info,
"Ready to submit your feedback?",
&["Yes, Submit!", "No"],
);
let client = cx.global::<Arc<Client>>().clone();
let specs = self.system_specs.clone();
cx.spawn(|this, mut cx| async move {
let answer = answer.await.ok();
if answer == Some(0) {
this.update(&mut cx, |this, cx| {
this.submission_state = Some(SubmissionState::CannotSubmit {
reason: CannotSubmitReason::AwaitingSubmission,
});
cx.notify();
})
.log_err();
let res =
FeedbackModal::submit_feedback(&feedback_text, email, client, specs).await;
match res {
Ok(_) => {
this.update(&mut cx, |this, cx| {
this.dismiss_modal = true;
cx.notify();
cx.emit(DismissEvent)
})
.ok();
}
Err(error) => {
log::error!("{}", error);
this.update(&mut cx, |this, cx| {
let prompt = cx.prompt(
PromptLevel::Critical,
FEEDBACK_SUBMISSION_ERROR_TEXT,
&["OK"],
);
cx.spawn(|_, _cx| async move {
prompt.await.ok();
})
.detach();
this.submission_state = Some(SubmissionState::CanSubmit);
cx.notify();
})
.log_err();
}
}
}
})
.detach();
Task::ready(Ok(()))
}
async fn submit_feedback(
feedback_text: &str,
email: Option<String>,
zed_client: Arc<Client>,
system_specs: SystemSpecs,
) -> anyhow::Result<()> {
if DEV_MODE {
smol::Timer::after(SEND_TIME_IN_DEV_MODE).await;
if SEND_SUCCESS_IN_DEV_MODE {
return Ok(());
} else {
return Err(anyhow!("Error submitting feedback"));
}
}
let feedback_endpoint = format!("{}/api/feedback", *ZED_SERVER_URL);
let telemetry = zed_client.telemetry();
let metrics_id = telemetry.metrics_id();
let installation_id = telemetry.installation_id();
let is_staff = telemetry.is_staff();
let http_client = zed_client.http_client();
let request = FeedbackRequestBody {
feedback_text: &feedback_text,
email,
metrics_id,
installation_id,
system_specs,
is_staff: is_staff.unwrap_or(false),
token: ZED_SECRET_CLIENT_TOKEN,
};
let json_bytes = serde_json::to_vec(&request)?;
let request = Request::post(feedback_endpoint)
.header("content-type", "application/json")
.body(json_bytes.into())?;
let mut response = http_client.send(request).await?;
let mut body = String::new();
response.body_mut().read_to_string(&mut body).await?;
let response_status = response.status();
if !response_status.is_success() {
bail!("Feedback API failed with error: {}", response_status)
}
Ok(())
}
fn update_submission_state(&mut self, cx: &mut ViewContext<Self>) {
if self.awaiting_submission() {
return;
}
let mut invalid_state_flags = InvalidStateFlags::empty();
let valid_email_address = match self.email_address_editor.read(cx).text_option(cx) {
Some(email_address) => Regex::new(EMAIL_REGEX).unwrap().is_match(&email_address),
None => true,
};
if !valid_email_address {
invalid_state_flags |= InvalidStateFlags::EmailAddress;
}
if !FEEDBACK_CHAR_LIMIT.contains(&self.character_count) {
invalid_state_flags |= InvalidStateFlags::CharacterCount;
}
if invalid_state_flags.is_empty() {
self.submission_state = Some(SubmissionState::CanSubmit);
} else {
self.submission_state = Some(SubmissionState::CannotSubmit {
reason: CannotSubmitReason::InvalidState {
flags: invalid_state_flags,
},
});
}
}
fn update_email_in_store(&self, cx: &mut ViewContext<Self>) {
let email = self.email_address_editor.read(cx).text_option(cx);
cx.spawn(|_, _| async move {
match email {
Some(email) => {
KEY_VALUE_STORE
.write_kvp(DATABASE_KEY_NAME.to_string(), email)
.await
.ok();
}
None => {
KEY_VALUE_STORE
.delete_kvp(DATABASE_KEY_NAME.to_string())
.await
.ok();
}
}
})
.detach();
}
fn valid_email_address(&self) -> bool {
!self.in_invalid_state(InvalidStateFlags::EmailAddress)
}
fn valid_character_count(&self) -> bool {
!self.in_invalid_state(InvalidStateFlags::CharacterCount)
}
fn in_invalid_state(&self, flag: InvalidStateFlags) -> bool {
match self.submission_state {
Some(SubmissionState::CannotSubmit {
reason: CannotSubmitReason::InvalidState { ref flags },
}) => flags.contains(flag),
_ => false,
}
}
fn awaiting_submission(&self) -> bool {
matches!(
self.submission_state,
Some(SubmissionState::CannotSubmit {
reason: CannotSubmitReason::AwaitingSubmission
})
)
}
fn can_submit(&self) -> bool {
matches!(self.submission_state, Some(SubmissionState::CanSubmit))
}
fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
cx.emit(DismissEvent)
}
}
impl Render for FeedbackModal {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
self.update_submission_state(cx);
let submit_button_text = if self.awaiting_submission() {
"Submitting..."
} else {
"Submit"
};
let open_community_repo =
cx.listener(|_, _, cx| cx.dispatch_action(Box::new(OpenZedCommunityRepo)));
// Moved this here because providing it inline breaks rustfmt
let provide_an_email_address =
"Provide an email address if you want us to be able to reply.";
v_stack()
.elevation_3(cx)
.key_context("GiveFeedback")
.on_action(cx.listener(Self::cancel))
.min_w(rems(40.))
.max_w(rems(96.))
.h(rems(32.))
.p_4()
.gap_4()
.child(v_stack().child(
// TODO: Add Headline component to `ui2`
div().text_xl().child("Share Feedback"),
))
.child(
Label::new(if self.character_count < *FEEDBACK_CHAR_LIMIT.start() {
format!(
"Feedback must be at least {} characters.",
FEEDBACK_CHAR_LIMIT.start()
)
} else {
format!(
"Characters: {}",
*FEEDBACK_CHAR_LIMIT.end() - self.character_count
)
})
.color(if self.valid_character_count() {
Color::Success
} else {
Color::Error
}),
)
.child(
div()
.flex_1()
.bg(cx.theme().colors().editor_background)
.p_2()
.border()
.rounded_md()
.border_color(cx.theme().colors().border)
.child(self.feedback_editor.clone()),
)
.child(
h_stack()
.bg(cx.theme().colors().editor_background)
.p_2()
.border()
.rounded_md()
.border_color(if self.valid_email_address() {
cx.theme().colors().border
} else {
red()
})
.child(self.email_address_editor.clone()),
)
.child(
h_stack()
.justify_between()
.gap_1()
.child(
Button::new("community_repository", "Community Repository")
.style(ButtonStyle::Transparent)
.icon(Icon::ExternalLink)
.icon_position(IconPosition::End)
.icon_size(IconSize::Small)
.on_click(open_community_repo),
)
.child(
h_stack()
.gap_1()
.child(
Button::new("cancel_feedback", "Cancel")
.style(ButtonStyle::Subtle)
.color(Color::Muted)
.on_click(cx.listener(move |_, _, cx| {
cx.spawn(|this, mut cx| async move {
this.update(&mut cx, |_, cx| cx.emit(DismissEvent))
.ok();
})
.detach();
})),
)
.child(
Button::new("submit_feedback", submit_button_text)
.color(Color::Accent)
.style(ButtonStyle::Filled)
.on_click(cx.listener(|this, _, cx| {
this.submit(cx).detach();
}))
.tooltip(move |cx| {
Tooltip::with_meta(
"Submit feedback to the Zed team.",
None,
provide_an_email_address,
cx,
)
})
.when(!self.can_submit(), |this| this.disabled(true)),
),
),
)
}
}
// TODO: Testing of various button states, dismissal prompts, etc.
// #[cfg(test)]
// mod test {
// use super::*;
// #[test]
// fn test_invalid_email_addresses() {
// let markdown = markdown.await.log_err();
// let buffer = project.update(&mut cx, |project, cx| {
// project.create_buffer("", markdown, cx)
// })??;
// workspace.update(&mut cx, |workspace, cx| {
// let system_specs = SystemSpecs::new(cx);
// workspace.toggle_modal(cx, move |cx| {
// let feedback_modal = FeedbackModal::new(system_specs, project, buffer, cx);
// assert!(!feedback_modal.can_submit());
// assert!(!feedback_modal.valid_email_address(cx));
// assert!(!feedback_modal.valid_character_count());
// feedback_modal
// .email_address_editor
// .update(cx, |this, cx| this.set_text("a", cx));
// feedback_modal.set_submission_state(cx);
// assert!(!feedback_modal.valid_email_address(cx));
// feedback_modal
// .email_address_editor
// .update(cx, |this, cx| this.set_text("a&b.com", cx));
// feedback_modal.set_submission_state(cx);
// assert!(feedback_modal.valid_email_address(cx));
// });
// })?;
// }
// }
@@ -1,108 +0,0 @@
use crate::feedback_editor::{FeedbackEditor, SubmitFeedback};
use anyhow::Result;
use gpui::{
elements::{Label, MouseEventHandler},
platform::{CursorStyle, MouseButton},
AnyElement, AppContext, Element, Entity, Task, View, ViewContext, ViewHandle,
};
use workspace::{item::ItemHandle, ToolbarItemLocation, ToolbarItemView};
pub fn init(cx: &mut AppContext) {
cx.add_async_action(SubmitFeedbackButton::submit);
}
pub struct SubmitFeedbackButton {
pub(crate) active_item: Option<ViewHandle<FeedbackEditor>>,
}
impl SubmitFeedbackButton {
pub fn new() -> Self {
Self {
active_item: Default::default(),
}
}
pub fn submit(
&mut self,
_: &SubmitFeedback,
cx: &mut ViewContext<Self>,
) -> Option<Task<Result<()>>> {
if let Some(active_item) = self.active_item.as_ref() {
Some(active_item.update(cx, |feedback_editor, cx| feedback_editor.submit(cx)))
} else {
None
}
}
}
impl Entity for SubmitFeedbackButton {
type Event = ();
}
impl View for SubmitFeedbackButton {
fn ui_name() -> &'static str {
"SubmitFeedbackButton"
}
fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
let theme = theme::current(cx).clone();
let allow_submission = self
.active_item
.as_ref()
.map_or(true, |i| i.read(cx).allow_submission);
enum SubmitFeedbackButton {}
MouseEventHandler::new::<SubmitFeedbackButton, _>(0, cx, |state, _| {
let text;
let style = if allow_submission {
text = "Submit as Markdown";
theme.feedback.submit_button.style_for(state)
} else {
text = "Submitting...";
theme
.feedback
.submit_button
.disabled
.as_ref()
.unwrap_or(&theme.feedback.submit_button.default)
};
Label::new(text, style.text.clone())
.contained()
.with_style(style.container)
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, |_, this, cx| {
this.submit(&Default::default(), cx);
})
.aligned()
.contained()
.with_margin_left(theme.feedback.button_margin)
.with_tooltip::<Self>(
0,
"cmd-s",
Some(Box::new(SubmitFeedback)),
theme.tooltip.clone(),
cx,
)
.into_any()
}
}
impl ToolbarItemView for SubmitFeedbackButton {
fn set_active_pane_item(
&mut self,
active_pane_item: Option<&dyn ItemHandle>,
cx: &mut ViewContext<Self>,
) -> workspace::ToolbarItemLocation {
cx.notify();
if let Some(feedback_editor) = active_pane_item.and_then(|i| i.downcast::<FeedbackEditor>())
{
self.active_item = Some(feedback_editor);
ToolbarItemLocation::PrimaryRight { flex: None }
} else {
self.active_item = None;
ToolbarItemLocation::Hidden
}
}
}
+9 -18
View File
@@ -1,17 +1,14 @@
use client::ZED_APP_VERSION;
use gpui::{platform::AppVersion, AppContext};
use gpui::AppContext;
use human_bytes::human_bytes;
use serde::Serialize;
use std::{env, fmt::Display};
use sysinfo::{System, SystemExt};
use util::channel::ReleaseChannel;
// TODO: Move this file out of feedback and into a more general place
#[derive(Clone, Debug, Serialize)]
pub struct SystemSpecs {
#[serde(serialize_with = "serialize_app_version")]
app_version: Option<AppVersion>,
app_version: Option<String>,
release_channel: &'static str,
os_name: &'static str,
os_version: Option<String>,
@@ -21,16 +18,17 @@ pub struct SystemSpecs {
impl SystemSpecs {
pub fn new(cx: &AppContext) -> Self {
let platform = cx.platform();
let app_version = ZED_APP_VERSION.or_else(|| platform.app_version().ok());
let app_version = ZED_APP_VERSION
.or_else(|| cx.app_metadata().app_version)
.map(|v| v.to_string());
let release_channel = cx.global::<ReleaseChannel>().display_name();
let os_name = platform.os_name();
let os_name = cx.app_metadata().os_name;
let system = System::new_all();
let memory = system.total_memory();
let architecture = env::consts::ARCH;
let os_version = platform
.os_version()
.ok()
let os_version = cx
.app_metadata()
.os_version
.map(|os_version| os_version.to_string());
SystemSpecs {
@@ -68,10 +66,3 @@ impl Display for SystemSpecs {
write!(f, "{system_specs}")
}
}
fn serialize_app_version<S>(version: &Option<AppVersion>, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
version.map(|v| v.to_string()).serialize(serializer)
}