onboarding_modal.rs

  1use std::{sync::Arc, time::Duration};
  2
  3use crate::{ZED_PREDICT_DATA_COLLECTION_CHOICE, onboarding_event};
  4use anyhow::Context as _;
  5use client::{Client, UserStore};
  6use db::kvp::KEY_VALUE_STORE;
  7use fs::Fs;
  8use gpui::{
  9    Animation, AnimationExt as _, ClickEvent, DismissEvent, Entity, EventEmitter, FocusHandle,
 10    Focusable, MouseDownEvent, Render, ease_in_out, svg,
 11};
 12use language::language_settings::{AllLanguageSettings, EditPredictionProvider};
 13use settings::{Settings, update_settings_file};
 14use ui::{Checkbox, TintColor, prelude::*};
 15use util::ResultExt;
 16use workspace::{ModalView, Workspace, notifications::NotifyTaskExt};
 17
 18/// Introduces user to Zed's Edit Prediction feature and terms of service
 19pub struct ZedPredictModal {
 20    user_store: Entity<UserStore>,
 21    client: Arc<Client>,
 22    fs: Arc<dyn Fs>,
 23    focus_handle: FocusHandle,
 24    sign_in_status: SignInStatus,
 25    terms_of_service: bool,
 26    data_collection_expanded: bool,
 27    data_collection_opted_in: bool,
 28}
 29
 30#[derive(PartialEq, Eq)]
 31enum SignInStatus {
 32    /// Signed out or signed in but not from this modal
 33    Idle,
 34    /// Authentication triggered from this modal
 35    Waiting,
 36    /// Signed in after authentication from this modal
 37    SignedIn,
 38}
 39
 40impl ZedPredictModal {
 41    pub fn toggle(
 42        workspace: &mut Workspace,
 43        user_store: Entity<UserStore>,
 44        client: Arc<Client>,
 45        fs: Arc<dyn Fs>,
 46        window: &mut Window,
 47        cx: &mut Context<Workspace>,
 48    ) {
 49        workspace.toggle_modal(window, cx, |_window, cx| Self {
 50            user_store,
 51            client,
 52            fs,
 53            focus_handle: cx.focus_handle(),
 54            sign_in_status: SignInStatus::Idle,
 55            terms_of_service: false,
 56            data_collection_expanded: false,
 57            data_collection_opted_in: false,
 58        });
 59    }
 60
 61    fn view_terms(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context<Self>) {
 62        cx.open_url("https://zed.dev/terms-of-service");
 63        cx.notify();
 64
 65        onboarding_event!("ToS Link Clicked");
 66    }
 67
 68    fn view_blog(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context<Self>) {
 69        cx.open_url("https://zed.dev/blog/edit-prediction");
 70        cx.notify();
 71
 72        onboarding_event!("Blog Link clicked");
 73    }
 74
 75    fn inline_completions_doc(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context<Self>) {
 76        cx.open_url("https://zed.dev/docs/configuring-zed#disabled-globs");
 77        cx.notify();
 78
 79        onboarding_event!("Docs Link Clicked");
 80    }
 81
 82    fn accept_and_enable(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
 83        let task = self
 84            .user_store
 85            .update(cx, |this, cx| this.accept_terms_of_service(cx));
 86        let fs = self.fs.clone();
 87
 88        cx.spawn(async move |this, cx| {
 89            task.await?;
 90
 91            let mut data_collection_opted_in = false;
 92            this.update(cx, |this, _cx| {
 93                data_collection_opted_in = this.data_collection_opted_in;
 94            })
 95            .ok();
 96
 97            KEY_VALUE_STORE
 98                .write_kvp(
 99                    ZED_PREDICT_DATA_COLLECTION_CHOICE.into(),
100                    data_collection_opted_in.to_string(),
101                )
102                .await
103                .log_err();
104
105            // Make sure edit prediction provider setting is using the new key
106            let settings_path = paths::settings_file().as_path();
107            let settings_path = fs.canonicalize(settings_path).await.with_context(|| {
108                format!("Failed to canonicalize settings path {:?}", settings_path)
109            })?;
110
111            if let Some(settings) = fs.load(&settings_path).await.log_err() {
112                if let Some(new_settings) =
113                    migrator::migrate_edit_prediction_provider_settings(&settings)?
114                {
115                    fs.atomic_write(settings_path, new_settings).await?;
116                }
117            }
118
119            this.update(cx, |this, cx| {
120                update_settings_file::<AllLanguageSettings>(this.fs.clone(), cx, move |file, _| {
121                    file.features
122                        .get_or_insert(Default::default())
123                        .edit_prediction_provider = Some(EditPredictionProvider::Zed);
124                });
125
126                cx.emit(DismissEvent);
127            })
128        })
129        .detach_and_notify_err(window, cx);
130
131        onboarding_event!(
132            "Enable Clicked",
133            data_collection_opted_in = self.data_collection_opted_in,
134        );
135    }
136
137    fn sign_in(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
138        let client = self.client.clone();
139        self.sign_in_status = SignInStatus::Waiting;
140
141        cx.spawn(async move |this, cx| {
142            let result = client.authenticate_and_connect(true, &cx).await;
143
144            let status = match result {
145                Ok(_) => SignInStatus::SignedIn,
146                Err(_) => SignInStatus::Idle,
147            };
148
149            this.update(cx, |this, cx| {
150                this.sign_in_status = status;
151                onboarding_event!("Signed In");
152                cx.notify()
153            })?;
154
155            result
156        })
157        .detach_and_notify_err(window, cx);
158
159        onboarding_event!("Sign In Clicked");
160    }
161
162    fn cancel(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
163        cx.emit(DismissEvent);
164    }
165}
166
167impl EventEmitter<DismissEvent> for ZedPredictModal {}
168
169impl Focusable for ZedPredictModal {
170    fn focus_handle(&self, _cx: &App) -> FocusHandle {
171        self.focus_handle.clone()
172    }
173}
174
175impl ModalView for ZedPredictModal {}
176
177impl Render for ZedPredictModal {
178    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
179        let window_height = window.viewport_size().height;
180        let max_height = window_height - px(200.);
181
182        let base = v_flex()
183            .id("edit-prediction-onboarding")
184            .key_context("ZedPredictModal")
185            .relative()
186            .w(px(550.))
187            .h_full()
188            .max_h(max_height)
189            .p_4()
190            .gap_2()
191            .when(self.data_collection_expanded, |element| {
192                element.overflow_y_scroll()
193            })
194            .when(!self.data_collection_expanded, |element| {
195                element.overflow_hidden()
196            })
197            .elevation_3(cx)
198            .track_focus(&self.focus_handle(cx))
199            .on_action(cx.listener(Self::cancel))
200            .on_action(cx.listener(|_, _: &menu::Cancel, _window, cx| {
201                onboarding_event!("Cancelled", trigger = "Action");
202                cx.emit(DismissEvent);
203            }))
204            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, _cx| {
205                this.focus_handle.focus(window);
206            }))
207            .child(
208                div()
209                    .p_1p5()
210                    .absolute()
211                    .top_1()
212                    .left_1()
213                    .right_0()
214                    .h(px(200.))
215                    .child(
216                        svg()
217                            .path("icons/zed_predict_bg.svg")
218                            .text_color(cx.theme().colors().icon_disabled)
219                            .w(px(530.))
220                            .h(px(128.))
221                            .overflow_hidden(),
222                    ),
223            )
224            .child(
225                h_flex()
226                    .w_full()
227                    .mb_2()
228                    .justify_between()
229                    .child(
230                        v_flex()
231                            .gap_1()
232                            .child(
233                                Label::new("Introducing Zed AI's")
234                                    .size(LabelSize::Small)
235                                    .color(Color::Muted),
236                            )
237                            .child(Headline::new("Edit Prediction").size(HeadlineSize::Large)),
238                    )
239                    .child({
240                        let tab = |n: usize| {
241                            let text_color = cx.theme().colors().text;
242                            let border_color = cx.theme().colors().text_accent.opacity(0.4);
243
244                            h_flex().child(
245                                h_flex()
246                                    .px_4()
247                                    .py_0p5()
248                                    .bg(cx.theme().colors().editor_background)
249                                    .border_1()
250                                    .border_color(border_color)
251                                    .rounded_sm()
252                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
253                                    .text_size(TextSize::XSmall.rems(cx))
254                                    .text_color(text_color)
255                                    .child("tab")
256                                    .with_animation(
257                                        n,
258                                        Animation::new(Duration::from_secs(2)).repeat(),
259                                        move |tab, delta| {
260                                            let delta = (delta - 0.15 * n as f32) / 0.7;
261                                            let delta = 1.0 - (0.5 - delta).abs() * 2.;
262                                            let delta = ease_in_out(delta.clamp(0., 1.));
263                                            let delta = 0.1 + 0.9 * delta;
264
265                                            tab.border_color(border_color.opacity(delta))
266                                                .text_color(text_color.opacity(delta))
267                                        },
268                                    ),
269                            )
270                        };
271
272                        v_flex()
273                            .gap_2()
274                            .items_center()
275                            .pr_2p5()
276                            .child(tab(0).ml_neg_20())
277                            .child(tab(1))
278                            .child(tab(2).ml_20())
279                    }),
280            )
281            .child(h_flex().absolute().top_2().right_2().child(
282                IconButton::new("cancel", IconName::X).on_click(cx.listener(
283                    |_, _: &ClickEvent, _window, cx| {
284                        onboarding_event!("Cancelled", trigger = "X click");
285                        cx.emit(DismissEvent);
286                    },
287                )),
288            ));
289
290        let blog_post_button = Button::new("view-blog", "Read the Blog Post")
291            .full_width()
292            .icon(IconName::ArrowUpRight)
293            .icon_size(IconSize::Indicator)
294            .icon_color(Color::Muted)
295            .on_click(cx.listener(Self::view_blog));
296
297        if self.user_store.read(cx).current_user().is_some() {
298            let copy = match self.sign_in_status {
299                SignInStatus::Idle => {
300                    "Zed can now predict your next edit on every keystroke. Powered by Zeta, our open-source, open-dataset language model."
301                }
302                SignInStatus::SignedIn => "Almost there! Ensure you:",
303                SignInStatus::Waiting => unreachable!(),
304            };
305
306            let accordion_icons = if self.data_collection_expanded {
307                (IconName::ChevronUp, IconName::ChevronDown)
308            } else {
309                (IconName::ChevronDown, IconName::ChevronUp)
310            };
311
312            fn label_item(label_text: impl Into<SharedString>) -> impl Element {
313                Label::new(label_text).color(Color::Muted).into_element()
314            }
315
316            fn info_item(label_text: impl Into<SharedString>) -> impl Element {
317                h_flex()
318                    .items_start()
319                    .gap_2()
320                    .child(
321                        div()
322                            .mt_1p5()
323                            .child(Icon::new(IconName::Check).size(IconSize::XSmall)),
324                    )
325                    .child(div().w_full().child(label_item(label_text)))
326            }
327
328            fn multiline_info_item<E1: Into<SharedString>, E2: IntoElement>(
329                first_line: E1,
330                second_line: E2,
331            ) -> impl Element {
332                v_flex()
333                    .child(info_item(first_line))
334                    .child(div().pl_5().child(second_line))
335            }
336
337            base.child(Label::new(copy).color(Color::Muted))
338                .child(
339                    h_flex()
340                        .child(
341                            Checkbox::new("tos-checkbox", self.terms_of_service.into())
342                                .fill()
343                                .label("I have read and accept the")
344                                .on_click(cx.listener(move |this, state, _window, cx| {
345                                    this.terms_of_service = *state == ToggleState::Selected;
346                                    cx.notify();
347                                })),
348                        )
349                        .child(
350                            Button::new("view-tos", "Terms of Service")
351                                .icon(IconName::ArrowUpRight)
352                                .icon_size(IconSize::Indicator)
353                                .icon_color(Color::Muted)
354                                .on_click(cx.listener(Self::view_terms)),
355                        ),
356                )
357                .child(
358                    v_flex()
359                        .child(
360                            h_flex()
361                                .flex_wrap()
362                                .child(
363                                    Checkbox::new(
364                                        "training-data-checkbox",
365                                        self.data_collection_opted_in.into(),
366                                    )
367                                    .label("Contribute to the open dataset when editing open source.")
368                                    .fill()
369                                    .on_click(cx.listener(
370                                        move |this, state, _window, cx| {
371                                            this.data_collection_opted_in =
372                                                *state == ToggleState::Selected;
373                                            cx.notify()
374                                        },
375                                    )),
376                                )
377                                .child(
378                                    Button::new("learn-more", "Learn More")
379                                        .icon(accordion_icons.0)
380                                        .icon_size(IconSize::Indicator)
381                                        .icon_color(Color::Muted)
382                                        .on_click(cx.listener(|this, _, _, cx| {
383                                            this.data_collection_expanded =
384                                                !this.data_collection_expanded;
385                                            cx.notify();
386
387                                            if this.data_collection_expanded {
388                                                onboarding_event!("Data Collection Learn More Clicked");
389                                            }
390                                        })),
391                                ),
392                        )
393                        .when(self.data_collection_expanded, |element| {
394                            element.child(
395                                v_flex()
396                                    .mt_2()
397                                    .p_2()
398                                    .rounded_sm()
399                                    .bg(cx.theme().colors().editor_background.opacity(0.5))
400                                    .border_1()
401                                    .border_color(cx.theme().colors().border_variant)
402                                    .child(
403                                        div().child(
404                                            Label::new("To improve edit predictions, please consider contributing to our open dataset based on your interactions within open source repositories.")
405                                                .mb_1()
406                                        )
407                                    )
408                                    .child(info_item(
409                                        "We collect data exclusively from open source projects.",
410                                    ))
411                                    .child(info_item(
412                                        "Zed automatically detects if your project is open source.",
413                                    ))
414                                    .child(info_item("Toggle participation at any time via the status bar menu."))
415                                    .child(multiline_info_item(
416                                        "If turned on, this setting applies for all open source repositories",
417                                        label_item("you open in Zed.")
418                                    ))
419                                    .child(multiline_info_item(
420                                        "Files with sensitive data, like `.env`, are excluded by default",
421                                        h_flex()
422                                            .w_full()
423                                            .flex_wrap()
424                                            .child(label_item("via the"))
425                                            .child(
426                                                Button::new("doc-link", "disabled_globs").on_click(
427                                                    cx.listener(Self::inline_completions_doc),
428                                                ),
429                                            )
430                                            .child(label_item("setting.")),
431                                    )),
432                            )
433                        }),
434                )
435                .child(
436                    v_flex()
437                        .mt_2()
438                        .gap_2()
439                        .w_full()
440                        .child(
441                            Button::new("accept-tos", "Enable Edit Prediction")
442                                .disabled(!self.terms_of_service)
443                                .style(ButtonStyle::Tinted(TintColor::Accent))
444                                .full_width()
445                                .on_click(cx.listener(Self::accept_and_enable)),
446                        )
447                        .child(blog_post_button),
448                )
449        } else {
450            base.child(
451                Label::new("To set Zed as your edit prediction provider, please sign in.")
452                    .color(Color::Muted),
453            )
454            .child(
455                v_flex()
456                    .mt_2()
457                    .gap_2()
458                    .w_full()
459                    .child(
460                        Button::new("accept-tos", "Sign in with GitHub")
461                            .disabled(self.sign_in_status == SignInStatus::Waiting)
462                            .style(ButtonStyle::Tinted(TintColor::Accent))
463                            .full_width()
464                            .on_click(cx.listener(Self::sign_in)),
465                    )
466                    .child(blog_post_button),
467            )
468        }
469    }
470}