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 ZedPredictModal {
178    fn render_data_collection_explanation(&self, cx: &Context<Self>) -> impl IntoElement {
179        fn label_item(label_text: impl Into<SharedString>) -> impl Element {
180            Label::new(label_text).color(Color::Muted).into_element()
181        }
182
183        fn info_item(label_text: impl Into<SharedString>) -> impl Element {
184            h_flex()
185                .items_start()
186                .gap_2()
187                .child(
188                    div()
189                        .mt_1p5()
190                        .child(Icon::new(IconName::Check).size(IconSize::XSmall)),
191                )
192                .child(div().w_full().child(label_item(label_text)))
193        }
194
195        fn multiline_info_item<E1: Into<SharedString>, E2: IntoElement>(
196            first_line: E1,
197            second_line: E2,
198        ) -> impl Element {
199            v_flex()
200                .child(info_item(first_line))
201                .child(div().pl_5().child(second_line))
202        }
203
204        v_flex()
205            .mt_2()
206            .p_2()
207            .rounded_sm()
208            .bg(cx.theme().colors().editor_background.opacity(0.5))
209            .border_1()
210            .border_color(cx.theme().colors().border_variant)
211            .child(
212                div().child(
213                    Label::new("To improve edit predictions, please consider contributing to our open dataset based on your interactions within open source repositories.")
214                        .mb_1()
215                )
216            )
217            .child(info_item(
218                "We collect data exclusively from open source projects.",
219            ))
220            .child(info_item(
221                "Zed automatically detects if your project is open source.",
222            ))
223            .child(info_item("Toggle participation at any time via the status bar menu."))
224            .child(multiline_info_item(
225                "If turned on, this setting applies for all open source repositories",
226                label_item("you open in Zed.")
227            ))
228            .child(multiline_info_item(
229                "Files with sensitive data, like `.env`, are excluded by default",
230                h_flex()
231                    .w_full()
232                    .flex_wrap()
233                    .child(label_item("via the"))
234                    .child(
235                        Button::new("doc-link", "disabled_globs").on_click(
236                            cx.listener(Self::inline_completions_doc),
237                        ),
238                    )
239                    .child(label_item("setting.")),
240            ))
241    }
242}
243
244impl Render for ZedPredictModal {
245    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
246        let window_height = window.viewport_size().height;
247        let max_height = window_height - px(200.);
248
249        let base = v_flex()
250            .id("edit-prediction-onboarding")
251            .key_context("ZedPredictModal")
252            .relative()
253            .w(px(550.))
254            .h_full()
255            .max_h(max_height)
256            .p_4()
257            .gap_2()
258            .when(self.data_collection_expanded, |element| {
259                element.overflow_y_scroll()
260            })
261            .when(!self.data_collection_expanded, |element| {
262                element.overflow_hidden()
263            })
264            .elevation_3(cx)
265            .track_focus(&self.focus_handle(cx))
266            .on_action(cx.listener(Self::cancel))
267            .on_action(cx.listener(|_, _: &menu::Cancel, _window, cx| {
268                onboarding_event!("Cancelled", trigger = "Action");
269                cx.emit(DismissEvent);
270            }))
271            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, _cx| {
272                this.focus_handle.focus(window);
273            }))
274            .child(
275                div()
276                    .p_1p5()
277                    .absolute()
278                    .top_1()
279                    .left_1()
280                    .right_0()
281                    .h(px(200.))
282                    .child(
283                        svg()
284                            .path("icons/zed_predict_bg.svg")
285                            .text_color(cx.theme().colors().icon_disabled)
286                            .w(px(530.))
287                            .h(px(128.))
288                            .overflow_hidden(),
289                    ),
290            )
291            .child(
292                h_flex()
293                    .w_full()
294                    .mb_2()
295                    .justify_between()
296                    .child(
297                        v_flex()
298                            .gap_1()
299                            .child(
300                                Label::new("Introducing Zed AI's")
301                                    .size(LabelSize::Small)
302                                    .color(Color::Muted),
303                            )
304                            .child(Headline::new("Edit Prediction").size(HeadlineSize::Large)),
305                    )
306                    .child({
307                        let tab = |n: usize| {
308                            let text_color = cx.theme().colors().text;
309                            let border_color = cx.theme().colors().text_accent.opacity(0.4);
310
311                            h_flex().child(
312                                h_flex()
313                                    .px_4()
314                                    .py_0p5()
315                                    .bg(cx.theme().colors().editor_background)
316                                    .border_1()
317                                    .border_color(border_color)
318                                    .rounded_sm()
319                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
320                                    .text_size(TextSize::XSmall.rems(cx))
321                                    .text_color(text_color)
322                                    .child("tab")
323                                    .with_animation(
324                                        n,
325                                        Animation::new(Duration::from_secs(2)).repeat(),
326                                        move |tab, delta| {
327                                            let delta = (delta - 0.15 * n as f32) / 0.7;
328                                            let delta = 1.0 - (0.5 - delta).abs() * 2.;
329                                            let delta = ease_in_out(delta.clamp(0., 1.));
330                                            let delta = 0.1 + 0.9 * delta;
331
332                                            tab.border_color(border_color.opacity(delta))
333                                                .text_color(text_color.opacity(delta))
334                                        },
335                                    ),
336                            )
337                        };
338
339                        v_flex()
340                            .gap_2()
341                            .items_center()
342                            .pr_2p5()
343                            .child(tab(0).ml_neg_20())
344                            .child(tab(1))
345                            .child(tab(2).ml_20())
346                    }),
347            )
348            .child(h_flex().absolute().top_2().right_2().child(
349                IconButton::new("cancel", IconName::X).on_click(cx.listener(
350                    |_, _: &ClickEvent, _window, cx| {
351                        onboarding_event!("Cancelled", trigger = "X click");
352                        cx.emit(DismissEvent);
353                    },
354                )),
355            ));
356
357        let blog_post_button = Button::new("view-blog", "Read the Blog Post")
358            .full_width()
359            .icon(IconName::ArrowUpRight)
360            .icon_size(IconSize::Indicator)
361            .icon_color(Color::Muted)
362            .on_click(cx.listener(Self::view_blog));
363
364        if self.user_store.read(cx).current_user().is_some() {
365            let copy = match self.sign_in_status {
366                SignInStatus::Idle => {
367                    "Zed can now predict your next edit on every keystroke. Powered by Zeta, our open-source, open-dataset language model."
368                }
369                SignInStatus::SignedIn => "Almost there! Ensure you:",
370                SignInStatus::Waiting => unreachable!(),
371            };
372
373            let accordion_icons = if self.data_collection_expanded {
374                (IconName::ChevronUp, IconName::ChevronDown)
375            } else {
376                (IconName::ChevronDown, IconName::ChevronUp)
377            };
378
379            base.child(Label::new(copy).color(Color::Muted))
380                .child(
381                    h_flex()
382                        .child(
383                            Checkbox::new("tos-checkbox", self.terms_of_service.into())
384                                .fill()
385                                .label("I have read and accept the")
386                                .on_click(cx.listener(move |this, state, _window, cx| {
387                                    this.terms_of_service = *state == ToggleState::Selected;
388                                    cx.notify();
389                                })),
390                        )
391                        .child(
392                            Button::new("view-tos", "Terms of Service")
393                                .icon(IconName::ArrowUpRight)
394                                .icon_size(IconSize::Indicator)
395                                .icon_color(Color::Muted)
396                                .on_click(cx.listener(Self::view_terms)),
397                        ),
398                )
399                .child(
400                    v_flex()
401                        .child(
402                            h_flex()
403                                .flex_wrap()
404                                .child(
405                                    Checkbox::new(
406                                        "training-data-checkbox",
407                                        self.data_collection_opted_in.into(),
408                                    )
409                                    .label(
410                                        "Contribute to the open dataset when editing open source.",
411                                    )
412                                    .fill()
413                                    .on_click(cx.listener(
414                                        move |this, state, _window, cx| {
415                                            this.data_collection_opted_in =
416                                                *state == ToggleState::Selected;
417                                            cx.notify()
418                                        },
419                                    )),
420                                )
421                                .child(
422                                    Button::new("learn-more", "Learn More")
423                                        .icon(accordion_icons.0)
424                                        .icon_size(IconSize::Indicator)
425                                        .icon_color(Color::Muted)
426                                        .on_click(cx.listener(|this, _, _, cx| {
427                                            this.data_collection_expanded =
428                                                !this.data_collection_expanded;
429                                            cx.notify();
430
431                                            if this.data_collection_expanded {
432                                                onboarding_event!(
433                                                    "Data Collection Learn More Clicked"
434                                                );
435                                            }
436                                        })),
437                                ),
438                        )
439                        .when(self.data_collection_expanded, |element| {
440                            element.child(self.render_data_collection_explanation(cx))
441                        }),
442                )
443                .child(
444                    v_flex()
445                        .mt_2()
446                        .gap_2()
447                        .w_full()
448                        .child(
449                            Button::new("accept-tos", "Enable Edit Prediction")
450                                .disabled(!self.terms_of_service)
451                                .style(ButtonStyle::Tinted(TintColor::Accent))
452                                .full_width()
453                                .on_click(cx.listener(Self::accept_and_enable)),
454                        )
455                        .child(blog_post_button),
456                )
457        } else {
458            base.child(
459                Label::new("To set Zed as your edit prediction provider, please sign in.")
460                    .color(Color::Muted),
461            )
462            .child(
463                v_flex()
464                    .mt_2()
465                    .gap_2()
466                    .w_full()
467                    .child(
468                        Button::new("accept-tos", "Sign in with GitHub")
469                            .disabled(self.sign_in_status == SignInStatus::Waiting)
470                            .style(ButtonStyle::Tinted(TintColor::Accent))
471                            .full_width()
472                            .on_click(cx.listener(Self::sign_in)),
473                    )
474                    .child(blog_post_button),
475            )
476        }
477    }
478}