update
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run
Rust / build (macos-latest, stable) (pull_request) Waiting to run
Rust / build (ubuntu-latest, stable) (pull_request) Waiting to run
Rust / build (windows-latest, stable) (pull_request) Waiting to run

This commit is contained in:
2026-11-19 10:37:22 +07:00
parent c7c1d0c741
commit 2a9d42a612
29 changed files with 532 additions and 425 deletions
+14 -10
View File
@@ -21,8 +21,8 @@ use ui::toast::{Toast, Toasts};
use crate::app::placeholder::PlaceholderView; use crate::app::placeholder::PlaceholderView;
use crate::app::sign_in::SignedOutView; use crate::app::sign_in::SignedOutView;
use crate::explore::ExploreView; use crate::explore::ExploreView;
use crate::identity; use crate::identity::passphrase::PassphraseDialog;
use crate::shared::dialogs::DialogHost; use crate::shared::log_dropped;
use crate::titlebar::{ use crate::titlebar::{
CreateRepository, REPOSITORY_KEY_CONTEXT, SwitchRepository, TitlebarView, CreateRepository, REPOSITORY_KEY_CONTEXT, SwitchRepository, TitlebarView,
bind_repository_shortcuts, bind_repository_shortcuts,
@@ -35,7 +35,7 @@ pub struct AppRoot {
toasts: Entity<Toasts>, toasts: Entity<Toasts>,
sign_in: Entity<SignedOutView>, sign_in: Entity<SignedOutView>,
empty: Entity<PlaceholderView>, empty: Entity<PlaceholderView>,
dialogs: Entity<DialogHost>, passphrase: Option<Entity<PassphraseDialog>>,
_subscriptions: Vec<Subscription>, _subscriptions: Vec<Subscription>,
} }
@@ -50,9 +50,6 @@ impl AppRoot {
let sign_in = cx.new(|_| SignedOutView::new()); let sign_in = cx.new(|_| SignedOutView::new());
let empty = cx.new(|_| PlaceholderView::new("Select a repository")); let empty = cx.new(|_| PlaceholderView::new("Select a repository"));
let dialogs = cx.new(DialogHost::new);
DialogHost::set_global(dialogs.clone(), cx);
let backend = Backend::global(cx); let backend = Backend::global(cx);
let settings = SettingsStore::global(cx); let settings = SettingsStore::global(cx);
let mut subscriptions = Vec::new(); let mut subscriptions = Vec::new();
@@ -62,7 +59,7 @@ impl AppRoot {
window, window,
|this, backend, event, window, cx| match event { |this, backend, event, window, cx| match event {
BackendEvent::PassphraseRequired => { BackendEvent::PassphraseRequired => {
identity::helpers::open_passphrase(cx); this.open_passphrase(cx);
} }
BackendEvent::Error(message) => { BackendEvent::Error(message) => {
this.toasts.update(cx, |toasts, cx| { this.toasts.update(cx, |toasts, cx| {
@@ -86,9 +83,10 @@ impl AppRoot {
apply_appearance(&settings, cx); apply_appearance(&settings, cx);
})); }));
let app = cx.entity().downgrade();
window.defer(cx, move |_window, cx| { window.defer(cx, move |_window, cx| {
if backend.read(cx).passphrase_required() { if backend.read(cx).passphrase_required() {
identity::helpers::open_passphrase(cx); log_dropped(app.update(cx, |this, cx| this.open_passphrase(cx)));
} }
}); });
@@ -98,10 +96,15 @@ impl AppRoot {
toasts, toasts,
sign_in, sign_in,
empty, empty,
dialogs, passphrase: None,
_subscriptions: subscriptions, _subscriptions: subscriptions,
} }
} }
fn open_passphrase(&mut self, cx: &mut Context<Self>) {
self.passphrase = Some(PassphraseDialog::new(cx));
cx.notify();
}
} }
impl Render for AppRoot { impl Render for AppRoot {
@@ -167,7 +170,8 @@ impl Render for AppRoot {
) )
.toasts(self.toasts.clone()), .toasts(self.toasts.clone()),
) )
.child(self.dialogs.clone())
.child(titlebar_view.palette()) .child(titlebar_view.palette())
.children(titlebar_view.dialogs())
.when_some(self.passphrase.clone(), |el, view| el.child(view))
} }
} }
+28 -12
View File
@@ -1,18 +1,36 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
App, Context, FontWeight, IntoElement, ParentElement as _, Render, SharedString, Styled as _, App, Context, Entity, FontWeight, IntoElement, ParentElement as _, Render, SharedString,
Window, div, Styled as _, Window, div,
}; };
use ui::button::{Button, ButtonVariant}; use ui::button::{Button, ButtonVariant};
use ui::common::v_flex; use ui::common::v_flex;
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use crate::identity; use crate::identity::import::ImportDialog;
use crate::identity::onboarding::OnboardingDialog;
pub struct SignedOutView; pub struct SignedOutView {
onboarding: Option<Entity<OnboardingDialog>>,
import: Option<Entity<ImportDialog>>,
}
impl SignedOutView { impl SignedOutView {
pub fn new() -> Self { pub fn new() -> Self {
Self Self {
onboarding: None,
import: None,
}
}
fn open_onboarding(&mut self, cx: &mut Context<Self>) {
self.onboarding = Some(OnboardingDialog::new(cx));
cx.notify();
}
fn open_import(&mut self, cx: &mut Context<Self>) {
self.import = Some(ImportDialog::new(cx));
cx.notify();
} }
} }
@@ -23,7 +41,7 @@ impl Panel for SignedOutView {
} }
impl Render for SignedOutView { impl Render for SignedOutView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex() v_flex()
.size_full() .size_full()
.items_center() .items_center()
@@ -42,18 +60,16 @@ impl Render for SignedOutView {
.child( .child(
Button::new("onboarding") Button::new("onboarding")
.label("Join now") .label("Join now")
.on_click(|_, _, cx| { .on_click(cx.listener(|this, _, _, cx| this.open_onboarding(cx))),
identity::helpers::open_onboarding(cx);
}),
) )
.child( .child(
Button::new("import") Button::new("import")
.label("Import identity") .label("Import identity")
.variant(ButtonVariant::Secondary) .variant(ButtonVariant::Secondary)
.on_click(|_, _, cx| { .on_click(cx.listener(|this, _, _, cx| this.open_import(cx))),
identity::helpers::open_import(cx);
}),
), ),
) )
.when_some(self.onboarding.clone(), |el, view| el.child(view))
.when_some(self.import.clone(), |el, view| el.child(view))
} }
} }
+24 -14
View File
@@ -1,25 +1,32 @@
use gpui::{ use gpui::{
AnyElement, Context, IntoElement, ParentElement as _, Render, Styled as _, Window, div, AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div,
}; };
use signed_state::Backend; use signed_state::Backend;
use ui::button::{Button, ButtonVariant}; use ui::button::{Button, ButtonVariant};
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::Dialog; use ui::dialog::{Dialog, DialogHandle};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::dialogs::close_global; pub struct ExitDialog {
handle: DialogHandle,
}
pub struct ExitDialog; impl ExitDialog {
pub fn new(cx: &mut App) -> Entity<Self> {
cx.new(|_| Self {
handle: DialogHandle::new(true),
})
}
}
impl Render for ExitDialog { impl Render for ExitDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let cancel_close = self.handle.clone();
let confirm_close = self.handle.clone();
Dialog::new("exit-dialog") Dialog::new("exit-dialog")
.open(true) .handle(self.handle.clone())
.on_change(|open, _, cx| {
if !open {
close_global(cx);
}
})
.title("Exit Signed?") .title("Exit Signed?")
.content(|_, cx| { .content(|_, cx| {
v_flex() v_flex()
@@ -33,20 +40,23 @@ impl Render for ExitDialog {
) )
.into_any_element() .into_any_element()
}) })
.actions(|_, _| { .actions(move |_, _| {
let cancel_close = cancel_close.clone();
let confirm_close = confirm_close.clone();
let cancel: AnyElement = Button::new("cancel-exit") let cancel: AnyElement = Button::new("cancel-exit")
.label("Cancel") .label("Cancel")
.variant(ButtonVariant::Secondary) .variant(ButtonVariant::Secondary)
.on_click(|_, _, cx| close_global(cx)) .on_click(move |_, _, cx| cancel_close.close(cx))
.into_any_element(); .into_any_element();
let exit: AnyElement = Button::new("confirm-exit") let exit: AnyElement = Button::new("confirm-exit")
.label("Exit") .label("Exit")
.variant(ButtonVariant::Destructive) .variant(ButtonVariant::Destructive)
.on_click(|_, _, cx| { .on_click(move |_, _, cx| {
let backend = Backend::global(cx); let backend = Backend::global(cx);
backend.update(cx, |backend, cx| backend.sign_out(cx)); backend.update(cx, |backend, cx| backend.sign_out(cx));
close_global(cx); confirm_close.close(cx);
}) })
.into_any_element(); .into_any_element();
-23
View File
@@ -1,23 +0,0 @@
use gpui::{App, AppContext as _};
use super::exit::ExitDialog;
use super::import::ImportDialog;
use super::onboarding::OnboardingDialog;
use super::passphrase::PassphraseDialog;
use crate::shared::dialogs::open_global;
pub fn open_passphrase(cx: &mut App) {
open_global(PassphraseDialog::new(cx), cx);
}
pub fn open_onboarding(cx: &mut App) {
open_global(OnboardingDialog::new(cx), cx);
}
pub fn open_import(cx: &mut App) {
open_global(ImportDialog::new(cx), cx);
}
pub fn open_exit(cx: &mut App) {
open_global(cx.new(|_| ExitDialog), cx);
}
+40 -19
View File
@@ -6,12 +6,11 @@ use gpui::{
use signed_state::Backend; use signed_state::Backend;
use ui::button::Button; use ui::button::Button;
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::Dialog; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::input::{Input, InputState, InputStateEvent}; use ui::input::{Input, InputState, InputStateEvent};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::dialogs::close_global;
use crate::shared::progress::{DialogProgress, error_row}; use crate::shared::progress::{DialogProgress, error_row};
#[derive(Clone, Copy, Default, PartialEq, Eq)] #[derive(Clone, Copy, Default, PartialEq, Eq)]
@@ -56,6 +55,7 @@ pub struct ImportState {
} }
pub struct ImportDialog { pub struct ImportDialog {
handle: DialogHandle,
secret_input: Entity<InputState>, secret_input: Entity<InputState>,
pass_input: Entity<InputState>, pass_input: Entity<InputState>,
repass_input: Entity<InputState>, repass_input: Entity<InputState>,
@@ -65,6 +65,7 @@ pub struct ImportDialog {
impl ImportDialog { impl ImportDialog {
pub fn new(cx: &mut App) -> Entity<Self> { pub fn new(cx: &mut App) -> Entity<Self> {
let handle = DialogHandle::new(true);
let state = cx.new(|_| ImportState::default()); let state = cx.new(|_| ImportState::default());
let secret_input = InputState::new(cx); let secret_input = InputState::new(cx);
let pass_input = InputState::builder().password().build(cx); let pass_input = InputState::builder().password().build(cx);
@@ -78,15 +79,24 @@ impl ImportDialog {
let pass_input = pass_input.clone(); let pass_input = pass_input.clone();
let repass_input = repass_input.clone(); let repass_input = repass_input.clone();
let state = state.clone(); let state = state.clone();
let handle = handle.clone();
subscriptions.push(cx.subscribe(input, move |_this, _input, event, cx| { subscriptions.push(cx.subscribe(input, move |_this, _input, event, cx| {
if matches!(event, InputStateEvent::Submitted) { if matches!(event, InputStateEvent::Submitted) {
submit(&secret_input, &pass_input, &repass_input, &state, cx); submit(
&secret_input,
&pass_input,
&repass_input,
&state,
&handle,
cx,
);
} }
})); }));
} }
Self { Self {
handle,
secret_input, secret_input,
pass_input, pass_input,
repass_input, repass_input,
@@ -110,15 +120,11 @@ impl Render for ImportDialog {
let action_pass = pass_input.clone(); let action_pass = pass_input.clone();
let action_repass = repass_input.clone(); let action_repass = repass_input.clone();
let action_close = self.handle.clone();
Dialog::new("import-dialog") Dialog::new("import-dialog")
.open(true) .handle(self.handle.clone())
.min_width(px(520.)) .min_width(px(520.))
.on_change(|open, _, cx| {
if !open {
close_global(cx);
}
})
.title("Import identity") .title("Import identity")
.content(move |_window, cx| { .content(move |_window, cx| {
let state = state.read(cx); let state = state.read(cx);
@@ -181,13 +187,14 @@ impl Render for ImportDialog {
let pass = action_pass.clone(); let pass = action_pass.clone();
let repass = action_repass.clone(); let repass = action_repass.clone();
let state = action_state.clone(); let state = action_state.clone();
let handle = action_close.clone();
let import: AnyElement = Button::new("import-identity") let import: AnyElement = Button::new("import-identity")
.label(label) .label(label)
.loading(busy) .loading(busy)
.disabled(busy) .disabled(busy)
.on_click(move |_, _, cx| { .on_click(move |_, _, cx| {
submit(&secret, &pass, &repass, &state, cx); submit(&secret, &pass, &repass, &state, &handle, cx);
}) })
.into_any_element(); .into_any_element();
@@ -201,6 +208,7 @@ fn submit(
pass_input: &Entity<InputState>, pass_input: &Entity<InputState>,
repass_input: &Entity<InputState>, repass_input: &Entity<InputState>,
state: &Entity<ImportState>, state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App, cx: &mut App,
) { ) {
if state.read(cx).progress.busy { if state.read(cx).progress.busy {
@@ -208,14 +216,19 @@ fn submit(
} }
match state.read(cx).stage { match state.read(cx).stage {
Stage::Credential => start_import(secret_input, state, cx), Stage::Credential => start_import(secret_input, state, handle, cx),
Stage::Encrypt => import_nsec(pass_input, repass_input, state, cx), Stage::Encrypt => import_nsec(pass_input, repass_input, state, handle, cx),
Stage::Decrypt => import_ncryptsec(pass_input, state, cx), Stage::Decrypt => import_ncryptsec(pass_input, state, handle, cx),
} }
} }
/// Parses the entered credential and either moves to the passphrase step or connects to a bunker. /// Parses the entered credential and either moves to the passphrase step or connects to a bunker.
fn start_import(secret_input: &Entity<InputState>, state: &Entity<ImportState>, cx: &mut App) { fn start_import(
secret_input: &Entity<InputState>,
state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App,
) {
let credential = match Credential::parse(secret_input.read(cx).value()) { let credential = match Credential::parse(secret_input.read(cx).value()) {
Some(credential) => credential, Some(credential) => credential,
None => { None => {
@@ -254,7 +267,7 @@ fn start_import(secret_input: &Entity<InputState>, state: &Entity<ImportState>,
let backend = Backend::global(cx); let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| backend.import_bunker(&uri, cx)); let task = backend.update(cx, |backend, cx| backend.import_bunker(&uri, cx));
finish_import(task, state, cx); finish_import(task, state, handle, cx);
} }
} }
} }
@@ -264,6 +277,7 @@ fn import_nsec(
pass_input: &Entity<InputState>, pass_input: &Entity<InputState>,
repass_input: &Entity<InputState>, repass_input: &Entity<InputState>,
state: &Entity<ImportState>, state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App, cx: &mut App,
) { ) {
let backend = Backend::global(cx); let backend = Backend::global(cx);
@@ -293,11 +307,16 @@ fn import_nsec(
}); });
let task = backend.update(cx, |backend, cx| backend.import_nsec(&nsec, &pass, cx)); let task = backend.update(cx, |backend, cx| backend.import_nsec(&nsec, &pass, cx));
finish_import(task, state, cx); finish_import(task, state, handle, cx);
} }
/// Decrypts the entered `ncryptsec` with the passphrase and signs in with it. /// Decrypts the entered `ncryptsec` with the passphrase and signs in with it.
fn import_ncryptsec(pass_input: &Entity<InputState>, state: &Entity<ImportState>, cx: &mut App) { fn import_ncryptsec(
pass_input: &Entity<InputState>,
state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App,
) {
let backend = Backend::global(cx); let backend = Backend::global(cx);
let ncryptsec = state.read(cx).credential.clone(); let ncryptsec = state.read(cx).credential.clone();
let pass = pass_input.read(cx).value().to_string(); let pass = pass_input.read(cx).value().to_string();
@@ -318,19 +337,21 @@ fn import_ncryptsec(pass_input: &Entity<InputState>, state: &Entity<ImportState>
let task = backend.update(cx, |backend, cx| { let task = backend.update(cx, |backend, cx| {
backend.import_ncryptsec(&ncryptsec, &pass, cx) backend.import_ncryptsec(&ncryptsec, &pass, cx)
}); });
finish_import(task, state, cx); finish_import(task, state, handle, cx);
} }
/// Runs the import task to completion, closing the dialog on success. /// Runs the import task to completion, closing the dialog on success.
fn finish_import<T: 'static>( fn finish_import<T: 'static>(
task: Task<Result<T, anyhow::Error>>, task: Task<Result<T, anyhow::Error>>,
state: &Entity<ImportState>, state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App, cx: &mut App,
) { ) {
let state = state.clone(); let state = state.clone();
let handle = handle.clone();
cx.spawn(async move |cx| match task.await { cx.spawn(async move |cx| match task.await {
Ok(_) => cx.update(close_global), Ok(_) => cx.update(|cx| handle.close(cx)),
Err(error) => { Err(error) => {
state.update(cx, |state, cx| { state.update(cx, |state, cx| {
state.progress.fail(error.to_string()); state.progress.fail(error.to_string());
-1
View File
@@ -1,5 +1,4 @@
pub mod exit; pub mod exit;
pub mod helpers;
pub mod import; pub mod import;
pub mod onboarding; pub mod onboarding;
pub mod passphrase; pub mod passphrase;
+6 -9
View File
@@ -6,15 +6,15 @@ use gpui::{
use signed_state::Backend; use signed_state::Backend;
use ui::button::Button; use ui::button::Button;
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::Dialog; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::dialogs::close_global;
use crate::shared::progress::{DialogProgress, error_row}; use crate::shared::progress::{DialogProgress, error_row};
pub struct OnboardingDialog { pub struct OnboardingDialog {
handle: DialogHandle,
name_input: Entity<InputState>, name_input: Entity<InputState>,
pass_input: Entity<InputState>, pass_input: Entity<InputState>,
repass_input: Entity<InputState>, repass_input: Entity<InputState>,
@@ -29,6 +29,7 @@ impl OnboardingDialog {
let repass_input = InputState::builder().password().build(cx); let repass_input = InputState::builder().password().build(cx);
cx.new(|_| Self { cx.new(|_| Self {
handle: DialogHandle::new(true),
name_input, name_input,
pass_input, pass_input,
repass_input, repass_input,
@@ -61,9 +62,10 @@ impl OnboardingDialog {
let backend = Backend::global(cx); let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| backend.create_identity(&name, &pass, cx)); let task = backend.update(cx, |backend, cx| backend.create_identity(&name, &pass, cx));
let state = self.state.clone(); let state = self.state.clone();
let handle = self.handle.clone();
cx.spawn(async move |_this, cx| match task.await { cx.spawn(async move |_this, cx| match task.await {
Ok(_) => cx.update(close_global), Ok(_) => cx.update(|cx| handle.close(cx)),
Err(error) => { Err(error) => {
state.update(cx, |state, cx| { state.update(cx, |state, cx| {
state.fail(error.to_string()); state.fail(error.to_string());
@@ -85,13 +87,8 @@ impl Render for OnboardingDialog {
let this = cx.entity().downgrade(); let this = cx.entity().downgrade();
Dialog::new("onboarding-dialog") Dialog::new("onboarding-dialog")
.open(true) .handle(self.handle.clone())
.min_width(px(520.)) .min_width(px(520.))
.on_change(|open, _, cx| {
if !open {
close_global(cx);
}
})
.title("Create identity") .title("Create identity")
.content(move |_window, cx| { .content(move |_window, cx| {
let progress = state.read(cx); let progress = state.read(cx);
+8 -7
View File
@@ -6,15 +6,15 @@ use gpui::{
use signed_state::Backend; use signed_state::Backend;
use ui::button::Button; use ui::button::Button;
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::Dialog; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent}; use ui::input::{Input, InputState, InputStateEvent};
use crate::shared::dialogs::close_global;
use crate::shared::progress::{DialogProgress, error_row, push_steps_row}; use crate::shared::progress::{DialogProgress, error_row, push_steps_row};
pub struct PassphraseDialog { pub struct PassphraseDialog {
handle: DialogHandle,
pass_input: Entity<InputState>, pass_input: Entity<InputState>,
state: Entity<DialogProgress>, state: Entity<DialogProgress>,
_enter_subscription: Subscription, _enter_subscription: Subscription,
@@ -34,6 +34,7 @@ impl PassphraseDialog {
}); });
Self { Self {
handle: DialogHandle::new(true),
pass_input, pass_input,
state, state,
_enter_subscription: enter_subscription, _enter_subscription: enter_subscription,
@@ -64,11 +65,10 @@ impl PassphraseDialog {
let backend = Backend::global(cx); let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| backend.restore_with_passphrase(&pass, cx)); let task = backend.update(cx, |backend, cx| backend.restore_with_passphrase(&pass, cx));
let state = self.state.clone(); let state = self.state.clone();
let handle = self.handle.clone();
cx.spawn(async move |_this, cx| match task.await { cx.spawn(async move |_this, cx| match task.await {
Ok(_) => { Ok(_) => cx.update(|cx| handle.close(cx)),
cx.update(close_global);
}
Err(error) => { Err(error) => {
state.update(cx, |state, cx| { state.update(cx, |state, cx| {
state.fail(error.to_string()); state.fail(error.to_string());
@@ -88,8 +88,9 @@ impl Render for PassphraseDialog {
let this = cx.entity().downgrade(); let this = cx.entity().downgrade();
Dialog::new("passphrase-dialog") Dialog::new("passphrase-dialog")
.open(true) .handle(self.handle.clone())
.on_change(|_open, _, _| {}) .close_on_escape(false)
.close_on_backdrop(false)
.min_width(px(420.)) .min_width(px(420.))
.title("Unlock your identity") .title("Unlock your identity")
.content(move |_window, cx| { .content(move |_window, cx| {
+10 -2
View File
@@ -34,6 +34,7 @@ const ISSUE_ROW_HEIGHT: f32 = 73.;
pub struct IssuesView { pub struct IssuesView {
workspace: WeakEntity<Workspace>, workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>, store: Entity<RepoStore>,
new_issue: Option<Entity<new_issue::NewIssueDialog>>,
filter: IssueFilter, filter: IssueFilter,
visible_issues: Vec<usize>, visible_issues: Vec<usize>,
counts: StatusCounts, counts: StatusCounts,
@@ -61,7 +62,8 @@ impl IssuesView {
Self { Self {
workspace, workspace,
store, store: store.clone(),
new_issue: None,
filter: IssueFilter::Open, filter: IssueFilter::Open,
visible_issues: Vec::new(), visible_issues: Vec::new(),
counts: StatusCounts::default(), counts: StatusCounts::default(),
@@ -72,6 +74,11 @@ impl IssuesView {
} }
} }
fn open_new_issue(&mut self, cx: &mut Context<Self>) {
self.new_issue = Some(new_issue::NewIssueDialog::new(self.store.clone(), cx));
cx.notify();
}
/// Total number of issues across all statuses, for the sidebar label. /// Total number of issues across all statuses, for the sidebar label.
pub fn total_count(&self) -> usize { pub fn total_count(&self) -> usize {
self.counts.total self.counts.total
@@ -159,7 +166,7 @@ impl IssuesView {
.label("New issue") .label("New issue")
.icon(Icon::named(IconRole::CirclePlus)) .icon(Icon::named(IconRole::CirclePlus))
.on_click(cx.listener(|this, _, _, cx| { .on_click(cx.listener(|this, _, _, cx| {
new_issue::open(this.store.clone(), cx); this.open_new_issue(cx);
})), })),
) )
.into_any_element() .into_any_element()
@@ -184,6 +191,7 @@ impl Render for IssuesView {
v_flex() v_flex()
.size_full() .size_full()
.child(self.render_header(cx)) .child(self.render_header(cx))
.when_some(self.new_issue.clone(), |el, view| el.child(view))
.child( .child(
v_flex() v_flex()
.relative() .relative()
+5 -15
View File
@@ -5,14 +5,13 @@ use gpui::{
use signed_state::RepoStore; use signed_state::RepoStore;
use ui::button::Button; use ui::button::Button;
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::Dialog; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::dialogs::{close_global, open_global};
pub struct NewIssueDialog { pub struct NewIssueDialog {
handle: DialogHandle,
store: Entity<RepoStore>, store: Entity<RepoStore>,
subject: Entity<InputState>, subject: Entity<InputState>,
content: Entity<InputState>, content: Entity<InputState>,
@@ -24,6 +23,7 @@ impl NewIssueDialog {
let content = InputState::builder().multiline().build(cx); let content = InputState::builder().multiline().build(cx);
cx.new(|_| Self { cx.new(|_| Self {
handle: DialogHandle::new(true),
store, store,
subject, subject,
content, content,
@@ -39,7 +39,7 @@ impl NewIssueDialog {
store.open_issue(subject, content, cx); store.open_issue(subject, content, cx);
}); });
close_global(cx); self.handle.close(cx);
} }
} }
@@ -50,13 +50,8 @@ impl Render for NewIssueDialog {
let this = cx.entity().downgrade(); let this = cx.entity().downgrade();
Dialog::new("new-issue-dialog") Dialog::new("new-issue-dialog")
.open(true) .handle(self.handle.clone())
.min_width(gpui::px(520.)) .min_width(gpui::px(520.))
.on_change(|open, _, cx| {
if !open {
close_global(cx);
}
})
.title("New issue") .title("New issue")
.content(move |_, cx| { .content(move |_, cx| {
v_flex() v_flex()
@@ -90,8 +85,3 @@ impl Render for NewIssueDialog {
}) })
} }
} }
/// Opens the new-issue form for `store`.
pub fn open(store: Entity<RepoStore>, cx: &mut App) {
open_global(NewIssueDialog::new(store, cx), cx);
}
+10 -1
View File
@@ -49,6 +49,7 @@ pub struct PullRequestDetailView {
workspace: WeakEntity<Workspace>, workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>, store: Entity<RepoStore>,
pr_id: EventId, pr_id: EventId,
update_dialog: Option<Entity<dialogs::update::UpdatePrDialog>>,
comment_input: Entity<InputState>, comment_input: Entity<InputState>,
worktree: Option<PathBuf>, worktree: Option<PathBuf>,
description: SharedString, description: SharedString,
@@ -90,6 +91,7 @@ impl PullRequestDetailView {
workspace, workspace,
store, store,
pr_id, pr_id,
update_dialog: None,
comment_input, comment_input,
worktree: None, worktree: None,
description: SharedString::default(), description: SharedString::default(),
@@ -555,7 +557,13 @@ impl PullRequestDetailView {
}) })
.cloned(); .cloned();
if let Some(root) = root { if let Some(root) = root {
dialogs::update::open(this.store.clone(), root, cx); this.update_dialog =
Some(dialogs::update::UpdatePrDialog::new(
this.store.clone(),
root,
cx,
));
cx.notify();
} }
})); }));
}, },
@@ -596,6 +604,7 @@ impl Render for PullRequestDetailView {
.size_full() .size_full()
.min_h_0() .min_h_0()
.child(self.render_header(cx)) .child(self.render_header(cx))
.when_some(self.update_dialog.clone(), |el, view| el.child(view))
.child(self.render_tabs(cx)) .child(self.render_tabs(cx))
.map(|this| match self.active_tab { .map(|this| match self.active_tab {
0 => this.child(self.render_discussion(cx)), 0 => this.child(self.render_discussion(cx)),
@@ -6,14 +6,13 @@ use nostr::prelude::Event;
use signed_state::RepoStore; use signed_state::RepoStore;
use ui::button::Button; use ui::button::Button;
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::Dialog; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::dialogs::{close_global, open_global};
pub struct UpdatePrDialog { pub struct UpdatePrDialog {
handle: DialogHandle,
store: Entity<RepoStore>, store: Entity<RepoStore>,
root: Event, root: Event,
patch: Entity<InputState>, patch: Entity<InputState>,
@@ -22,7 +21,12 @@ pub struct UpdatePrDialog {
impl UpdatePrDialog { impl UpdatePrDialog {
pub fn new(store: Entity<RepoStore>, root: Event, cx: &mut App) -> Entity<Self> { pub fn new(store: Entity<RepoStore>, root: Event, cx: &mut App) -> Entity<Self> {
let patch = InputState::builder().multiline().build(cx); let patch = InputState::builder().multiline().build(cx);
cx.new(|_| Self { store, root, patch }) cx.new(|_| Self {
handle: DialogHandle::new(true),
store,
root,
patch,
})
} }
fn submit(&mut self, cx: &mut Context<Self>) { fn submit(&mut self, cx: &mut Context<Self>) {
@@ -33,7 +37,7 @@ impl UpdatePrDialog {
self.store.update(cx, |store, cx| { self.store.update(cx, |store, cx| {
store.update_pull_request(&self.root, patch, cx); store.update_pull_request(&self.root, patch, cx);
}); });
close_global(cx); self.handle.close(cx);
} }
} }
@@ -43,13 +47,8 @@ impl Render for UpdatePrDialog {
let this = cx.entity().downgrade(); let this = cx.entity().downgrade();
Dialog::new("update-pr-dialog") Dialog::new("update-pr-dialog")
.open(true) .handle(self.handle.clone())
.min_width(gpui::px(520.)) .min_width(gpui::px(520.))
.on_change(|open, _, cx| {
if !open {
close_global(cx);
}
})
.title("Update pull request") .title("Update pull request")
.content(move |_, cx| { .content(move |_, cx| {
v_flex() v_flex()
@@ -79,7 +78,3 @@ impl Render for UpdatePrDialog {
}) })
} }
} }
pub fn open(store: Entity<RepoStore>, root: Event, cx: &mut App) {
open_global(UpdatePrDialog::new(store, root, cx), cx);
}
+4 -14
View File
@@ -8,13 +8,12 @@ use signed_core::Announcement;
use ui::avatar::Avatar; use ui::avatar::Avatar;
use ui::clipboard::ClipboardButton; use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, h_flex, v_flex}; use ui::common::{Sizable as _, h_flex, v_flex};
use ui::dialog::Dialog; use ui::dialog::{Dialog, DialogHandle};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::middle_truncate; use utils::middle_truncate;
use crate::shared::dialogs::{close_global, open_global};
pub struct AboutDialog { pub struct AboutDialog {
handle: DialogHandle,
announcement: Announcement, announcement: Announcement,
directory: Entity<ProfileDirectory>, directory: Entity<ProfileDirectory>,
} }
@@ -26,6 +25,7 @@ impl AboutDialog {
cx: &mut App, cx: &mut App,
) -> Entity<Self> { ) -> Entity<Self> {
cx.new(|_| Self { cx.new(|_| Self {
handle: DialogHandle::new(true),
announcement, announcement,
directory, directory,
}) })
@@ -38,13 +38,8 @@ impl Render for AboutDialog {
let directory = self.directory.clone(); let directory = self.directory.clone();
Dialog::new("about-dialog") Dialog::new("about-dialog")
.open(true) .handle(self.handle.clone())
.min_width(px(500.)) .min_width(px(500.))
.on_change(|open, _, cx| {
if !open {
close_global(cx);
}
})
.title("About") .title("About")
.content(move |_, cx| announcement_rows(&announcement, &directory, cx)) .content(move |_, cx| announcement_rows(&announcement, &directory, cx))
.into_any_element() .into_any_element()
@@ -259,8 +254,3 @@ fn list(id: &'static str, items: impl IntoIterator<Item = String>, cx: &App) ->
})) }))
.into_any_element() .into_any_element()
} }
/// Opens the read-only repository metadata dialog.
pub fn open(announcement: Announcement, directory: Entity<ProfileDirectory>, cx: &mut App) {
open_global(AboutDialog::new(announcement, directory, cx), cx);
}
+34 -39
View File
@@ -3,34 +3,35 @@ use std::path::PathBuf;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _,
PathPromptOptions, Render, Styled as _, WeakEntity, Window, div, px, PathPromptOptions, Render, Styled as _, Task, WeakEntity, Window, div, px,
}; };
use settings::SettingsStore; use settings::SettingsStore;
use signed_state::{Backend, CheckoutsStore}; use signed_state::{Backend, CheckoutsStore};
use ui::button::{Button, ButtonVariant}; use ui::button::{Button, ButtonVariant};
use ui::common::{h_flex, v_flex}; use ui::common::{h_flex, v_flex};
use ui::dialog::Dialog; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tooltip::Tooltip; use ui::tooltip::Tooltip;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::repo::actions::open_repo_panel; use crate::repo::actions::open_repo_panel;
use crate::shared::dialogs::{close_global, open_global};
use crate::shared::progress::{DialogProgress, error_row, push_steps_row}; use crate::shared::progress::{DialogProgress, error_row, push_steps_row};
use crate::workspace::Workspace; use crate::workspace::Workspace;
/// Progress of the create-repository flow, so async results can be rendered. /// Progress of the create-repository flow, so async results can be rendered.
pub struct CreateRepoDialog { pub struct CreateRepoDialog {
workspace: WeakEntity<Workspace>,
handle: DialogHandle,
name_input: Entity<InputState>, name_input: Entity<InputState>,
desc_input: Entity<InputState>, desc_input: Entity<InputState>,
folder_input: Entity<InputState>, folder_input: Entity<InputState>,
relay_input: Entity<InputState>, relay_input: Entity<InputState>,
state: Entity<DialogProgress>, state: Entity<DialogProgress>,
grasp_state: Entity<GraspServersState>, grasp_state: Entity<GraspServersState>,
workspace: WeakEntity<Workspace>, /// Held so the grasp-server load is cancelled when the dialog drops.
task: Option<Task<()>>,
} }
impl CreateRepoDialog { impl CreateRepoDialog {
@@ -40,6 +41,11 @@ impl CreateRepoDialog {
cx: &mut App, cx: &mut App,
) -> Entity<Self> { ) -> Entity<Self> {
let settings = SettingsStore::global(cx); let settings = SettingsStore::global(cx);
let grasp_settings = settings.read(cx).settings().grasp_servers.clone();
let name_input = InputState::new(cx);
let desc_input = InputState::builder().multiline().build(cx);
let default_folder = settings let default_folder = settings
.read(cx) .read(cx)
.settings() .settings()
@@ -47,29 +53,33 @@ impl CreateRepoDialog {
.default_folder .default_folder
.clone() .clone()
.unwrap_or_else(paths::desktop_dir); .unwrap_or_else(paths::desktop_dir);
let grasp_settings = settings.read(cx).settings().grasp_servers.clone();
let name_input = InputState::new(cx);
let desc_input = InputState::builder().multiline().build(cx);
let folder_input = InputState::builder() let folder_input = InputState::builder()
.text(default_folder.to_string_lossy()) .text(default_folder.to_string_lossy())
.read_only()
.build(cx); .build(cx);
folder_input.update(cx, |state, cx| state.set_read_only(true, cx));
let relay_input = InputState::new(cx); let relay_input = InputState::new(cx);
let state = cx.new(|_| DialogProgress::default()); let state = cx.new(|_| DialogProgress::default());
let grasp_state = cx.new(|_| GraspServersState::new_default(&grasp_settings)); let grasp_state = cx.new(|_| GraspServersState::new_default(&grasp_settings));
load_user_grasp_servers(grasp_state.clone(), window, cx); cx.new(|cx| {
cx.defer_in(window, move |this: &mut Self, window, cx| {
let task = load_user_grasp_servers(this.grasp_state.clone(), window, cx);
this.task = Some(task);
});
cx.new(|_| Self { Self {
name_input, workspace,
desc_input, handle: DialogHandle::new(true),
folder_input, name_input,
relay_input, desc_input,
state, folder_input,
grasp_state, relay_input,
workspace, state,
grasp_state,
task: None,
}
}) })
} }
@@ -110,6 +120,7 @@ impl CreateRepoDialog {
}); });
let state = self.state.clone(); let state = self.state.clone();
let workspace = self.workspace.clone(); let workspace = self.workspace.clone();
let close = self.handle.clone();
let handle = window.window_handle(); let handle = window.window_handle();
cx.spawn(async move |_this, cx| match task.await { cx.spawn(async move |_this, cx| match task.await {
@@ -127,7 +138,7 @@ impl CreateRepoDialog {
window, window,
cx, cx,
); );
close_global(cx); close.close(cx);
}) })
.ok(); .ok();
} }
@@ -161,27 +172,16 @@ impl Render for CreateRepoDialog {
let this = cx.entity().downgrade(); let this = cx.entity().downgrade();
Dialog::new("create-repo-dialog") Dialog::new("create-repo-dialog")
.open(true) .handle(self.handle.clone())
.min_width(px(520.)) .min_width(px(520.))
.on_change(|open, _, cx| { .title("Create Repository")
if !open {
close_global(cx);
}
})
.title("Create repository")
.content(move |_window, cx| { .content(move |_window, cx| {
let progress = state.read(cx); let progress = state.read(cx);
v_flex() v_flex()
.gap_3() .gap_3()
.child( .child(
div() Field::new("repo-name", "Repository Name")
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child("Publish a new repository to your grasp servers."),
)
.child(
Field::new("repo-name", "Repository name")
.description("Max 100 characters") .description("Max 100 characters")
.child(Input::new("repo-name-input", name_input.clone())), .child(Input::new("repo-name-input", name_input.clone())),
) )
@@ -196,7 +196,7 @@ impl Render for CreateRepoDialog {
.child( .child(
h_flex() h_flex()
.gap_1() .gap_1()
.items_center() .w_full()
.child(div().flex_1().child(Input::new( .child(div().flex_1().child(Input::new(
"repo-folder-input", "repo-folder-input",
folder_input.clone(), folder_input.clone(),
@@ -275,8 +275,3 @@ fn choose_folder(folder_input: &Entity<InputState>, window: &mut Window, cx: &mu
}) })
.detach(); .detach();
} }
/// Opens the create-repository form.
pub fn open(workspace: WeakEntity<Workspace>, window: &mut Window, cx: &mut App) {
open_global(CreateRepoDialog::new(workspace, window, cx), cx);
}
@@ -1,7 +1,7 @@
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, SharedString, AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, SharedString,
Styled as _, Window, div, Styled as _, Task, Window, div,
}; };
use nostr::prelude::RelayUrl; use nostr::prelude::RelayUrl;
use settings::{DEFAULT_GRASP_SERVERS, GraspServersSettings}; use settings::{DEFAULT_GRASP_SERVERS, GraspServersSettings};
@@ -214,7 +214,7 @@ pub fn load_user_grasp_servers(
state: Entity<GraspServersState>, state: Entity<GraspServersState>,
window: &mut Window, window: &mut Window,
cx: &mut App, cx: &mut App,
) { ) -> Task<()> {
let backend = Backend::global(cx); let backend = Backend::global(cx);
let (user, client) = { let (user, client) = {
let backend = backend.read(cx); let backend = backend.read(cx);
@@ -223,7 +223,7 @@ pub fn load_user_grasp_servers(
let Some(user) = user else { let Some(user) = user else {
state.update(cx, |state, _| state.loading_servers = false); state.update(cx, |state, _| state.loading_servers = false);
return; return Task::ready(());
}; };
let task = let task =
@@ -249,7 +249,6 @@ pub fn load_user_grasp_servers(
log::warn!("failed to apply grasp servers: {error}"); log::warn!("failed to apply grasp servers: {error}");
} }
}) })
.detach();
} }
/// Normalize a user-typed grasp server, adding a `wss://` scheme when none is given. /// Normalize a user-typed grasp server, adding a `wss://` scheme when none is given.
+26 -31
View File
@@ -3,7 +3,7 @@ use std::path::PathBuf;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, WeakEntity, Window, div, px, SharedString, Styled as _, Task, WeakEntity, Window, div, px,
}; };
use settings::SettingsStore; use settings::SettingsStore;
use signed_core::RepoAddr; use signed_core::RepoAddr;
@@ -11,7 +11,7 @@ use signed_git::Repo;
use signed_state::Backend; use signed_state::Backend;
use ui::button::Button; use ui::button::Button;
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::Dialog; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
@@ -20,10 +20,10 @@ use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::repo::RepoDetailView; use crate::repo::RepoDetailView;
use crate::shared::dialogs::{close_global, open_global};
use crate::shared::progress::{DialogProgress, error_row, push_steps_row}; use crate::shared::progress::{DialogProgress, error_row, push_steps_row};
pub struct InitRepoDialog { pub struct InitRepoDialog {
handle: DialogHandle,
local_path: PathBuf, local_path: PathBuf,
name_input: Entity<InputState>, name_input: Entity<InputState>,
desc_input: Entity<InputState>, desc_input: Entity<InputState>,
@@ -33,6 +33,8 @@ pub struct InitRepoDialog {
branches: Vec<SharedString>, branches: Vec<SharedString>,
selected_branch: Option<SharedString>, selected_branch: Option<SharedString>,
view: WeakEntity<RepoDetailView>, view: WeakEntity<RepoDetailView>,
/// Held so the grasp-server load is cancelled when the dialog drops.
task: Option<Task<()>>,
} }
impl InitRepoDialog { impl InitRepoDialog {
@@ -63,18 +65,25 @@ impl InitRepoDialog {
let desc_input = InputState::builder().multiline().build(cx); let desc_input = InputState::builder().multiline().build(cx);
let relay_input = InputState::new(cx); let relay_input = InputState::new(cx);
load_user_grasp_servers(grasp_state.clone(), window, cx); let dialog = cx.new(|cx| {
cx.defer_in(window, move |this: &mut Self, window, cx| {
let task = load_user_grasp_servers(this.grasp_state.clone(), window, cx);
this.task = Some(task);
});
let dialog = cx.new(|_| Self { Self {
local_path, handle: DialogHandle::new(true),
name_input, local_path,
desc_input, name_input,
relay_input, desc_input,
state, relay_input,
grasp_state, state,
branches: Vec::new(), grasp_state,
selected_branch: None, branches: Vec::new(),
view, selected_branch: None,
view,
task: None,
}
}); });
load_branches(dialog.clone(), cx); load_branches(dialog.clone(), cx);
@@ -122,12 +131,13 @@ impl InitRepoDialog {
}); });
let state = self.state.clone(); let state = self.state.clone();
let view = self.view.clone(); let view = self.view.clone();
let close = self.handle.clone();
let handle = window.window_handle(); let handle = window.window_handle();
cx.spawn(async move |_this, cx| match task.await { cx.spawn(async move |_this, cx| match task.await {
Ok(announcement) => { Ok(announcement) => {
cx.update_window(handle, |_, _window, cx| { cx.update_window(handle, |_, _window, cx| {
close_global(cx); close.close(cx);
if let Some(view) = view.upgrade() { if let Some(view) = view.upgrade() {
view.update(cx, |this, cx| this.apply_announcement(announcement, cx)); view.update(cx, |this, cx| this.apply_announcement(announcement, cx));
} }
@@ -166,13 +176,8 @@ impl Render for InitRepoDialog {
let selected_branch = self.selected_branch.clone(); let selected_branch = self.selected_branch.clone();
Dialog::new("init-repo-dialog") Dialog::new("init-repo-dialog")
.open(true) .handle(self.handle.clone())
.min_width(px(520.)) .min_width(px(520.))
.on_change(|open, _, cx| {
if !open {
close_global(cx);
}
})
.title("Initialize repository") .title("Initialize repository")
.content(move |_, cx| { .content(move |_, cx| {
let progress = state.read(cx); let progress = state.read(cx);
@@ -279,13 +284,3 @@ fn load_branches(dialog: Entity<InitRepoDialog>, cx: &mut App) {
}) })
.detach(); .detach();
} }
/// Opens the initialize form for `local_path`.
pub fn open(
local_path: PathBuf,
view: WeakEntity<RepoDetailView>,
window: &mut Window,
cx: &mut App,
) {
open_global(InitRepoDialog::new(local_path, view, window, cx), cx);
}
+15 -17
View File
@@ -5,19 +5,22 @@ use gpui::{
use signed_state::RepoStore; use signed_state::RepoStore;
use ui::button::{Button, ButtonVariant}; use ui::button::{Button, ButtonVariant};
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::Dialog; use ui::dialog::{Dialog, DialogHandle};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::dialogs::{close_global, open_global};
pub struct ResetRemoteDialog { pub struct ResetRemoteDialog {
handle: DialogHandle,
store: Entity<RepoStore>, store: Entity<RepoStore>,
deleted: Vec<String>, deleted: Vec<String>,
} }
impl ResetRemoteDialog { impl ResetRemoteDialog {
pub fn new(store: Entity<RepoStore>, deleted: Vec<String>, cx: &mut App) -> Entity<Self> { pub fn new(store: Entity<RepoStore>, deleted: Vec<String>, cx: &mut App) -> Entity<Self> {
cx.new(|_| Self { store, deleted }) cx.new(|_| Self {
handle: DialogHandle::new(true),
store,
deleted,
})
} }
} }
@@ -25,15 +28,12 @@ impl Render for ResetRemoteDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let deleted = self.deleted.clone(); let deleted = self.deleted.clone();
let store = self.store.clone(); let store = self.store.clone();
let cancel_close = self.handle.clone();
let confirm_close = self.handle.clone();
Dialog::new("reset-remote-dialog") Dialog::new("reset-remote-dialog")
.open(true) .handle(self.handle.clone())
.min_width(px(480.)) .min_width(px(480.))
.on_change(|open, _, cx| {
if !open {
close_global(cx);
}
})
.title("Reset remote to local") .title("Reset remote to local")
.content(move |_, cx| { .content(move |_, cx| {
v_flex() v_flex()
@@ -67,10 +67,13 @@ impl Render for ResetRemoteDialog {
}) })
.actions(move |_, _| { .actions(move |_, _| {
let store = store.clone(); let store = store.clone();
let cancel_close = cancel_close.clone();
let confirm_close = confirm_close.clone();
let cancel: AnyElement = Button::new("cancel-reset-remote") let cancel: AnyElement = Button::new("cancel-reset-remote")
.label("Cancel") .label("Cancel")
.variant(ButtonVariant::Secondary) .variant(ButtonVariant::Secondary)
.on_click(|_, _, cx| close_global(cx)) .on_click(move |_, _, cx| cancel_close.close(cx))
.into_any_element(); .into_any_element();
let confirm: AnyElement = Button::new("confirm-reset-remote") let confirm: AnyElement = Button::new("confirm-reset-remote")
@@ -84,7 +87,7 @@ impl Render for ResetRemoteDialog {
} }
}) })
.detach(); .detach();
close_global(cx); confirm_close.close(cx);
}) })
.into_any_element(); .into_any_element();
@@ -92,8 +95,3 @@ impl Render for ResetRemoteDialog {
}) })
} }
} }
/// Opens the reset confirmation listing the refs the reset deletes.
pub fn open(store: Entity<RepoStore>, deleted: Vec<String>, cx: &mut App) {
open_global(ResetRemoteDialog::new(store, deleted, cx), cx);
}
+10 -3
View File
@@ -39,7 +39,13 @@ impl RepoDetailView {
let Some(local_path) = self.store.read(cx).path.clone() else { let Some(local_path) = self.store.read(cx).path.clone() else {
return; return;
}; };
dialogs::init::open(local_path, cx.entity().downgrade(), window, cx); self.init = Some(dialogs::init::InitRepoDialog::new(
local_path,
cx.entity().downgrade(),
window,
cx,
));
cx.notify();
} }
pub(super) fn render_about(&mut self, cx: &mut Context<Self>) -> AnyElement { pub(super) fn render_about(&mut self, cx: &mut Context<Self>) -> AnyElement {
@@ -225,11 +231,12 @@ impl RepoDetailView {
let announcement = announcement_for_menu.clone(); let announcement = announcement_for_menu.clone();
move |_, cx| { move |_, cx| {
if let Err(error) = weak.update(cx, |this, cx| { if let Err(error) = weak.update(cx, |this, cx| {
dialogs::about::open( this.about = Some(dialogs::about::AboutDialog::new(
announcement.clone(), announcement.clone(),
this.directory.clone(), this.directory.clone(),
cx, cx,
); ));
cx.notify();
}) { }) {
log::warn!("failed to open about: {error}"); log::warn!("failed to open about: {error}");
} }
+13 -1
View File
@@ -63,6 +63,9 @@ pub enum RefKind {
pub struct RepoDetailView { pub struct RepoDetailView {
pub(super) workspace: WeakEntity<Workspace>, pub(super) workspace: WeakEntity<Workspace>,
pub(super) store: Entity<RepoStore>, pub(super) store: Entity<RepoStore>,
about: Option<Entity<dialogs::about::AboutDialog>>,
init: Option<Entity<dialogs::init::InitRepoDialog>>,
reset: Option<Entity<dialogs::reset::ResetRemoteDialog>>,
/// A repository opened by address alone starts without an announcement. /// A repository opened by address alone starts without an announcement.
repo_started: bool, repo_started: bool,
/// The file explorer and preview. /// The file explorer and preview.
@@ -171,6 +174,9 @@ impl RepoDetailView {
Self { Self {
workspace, workspace,
store: store.clone(), store: store.clone(),
about: None,
init: None,
reset: None,
repo_started: false, repo_started: false,
files, files,
history, history,
@@ -808,7 +814,10 @@ impl RepoDetailView {
let deleted = probe.await; let deleted = probe.await;
this.update_in(cx, |this, _window, cx| match deleted { this.update_in(cx, |this, _window, cx| match deleted {
Ok(deleted) => dialogs::reset::open(store, deleted, cx), Ok(deleted) => {
this.reset = Some(dialogs::reset::ResetRemoteDialog::new(store, deleted, cx));
cx.notify();
}
Err(error) => { Err(error) => {
this.error = Some(error.to_string().into()); this.error = Some(error.to_string().into());
cx.notify(); cx.notify();
@@ -1030,5 +1039,8 @@ impl Render for RepoDetailView {
.child(self.render_pane(cx)), .child(self.render_pane(cx)),
), ),
) )
.when_some(self.about.clone(), |el, view| el.child(view))
.when_some(self.init.clone(), |el, view| el.child(view))
.when_some(self.reset.clone(), |el, view| el.child(view))
} }
} }
+16 -15
View File
@@ -107,7 +107,8 @@ pub fn event_fetching_select(cx: &App) -> Select<EventFetchingStrategy> {
} }
pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement { pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement {
let servers = SettingsStore::global(cx) let store = SettingsStore::global(cx);
let servers = store
.read(cx) .read(cx)
.settings() .settings()
.grasp_servers .grasp_servers
@@ -117,17 +118,16 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
v_flex() v_flex()
.gap_2() .gap_2()
.children(servers.iter().enumerate().map(|(ix, server)| { .children(servers.iter().enumerate().map(|(ix, server)| {
let store = SettingsStore::global(cx);
h_flex() h_flex()
.gap_1() .gap_1()
.child( .child(
div() h_flex()
.flex_1() .flex_1()
.h_8() .h_8()
.px_2() .px_2()
.bg(cx.theme().colors.muted) .bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground) .text_color(cx.theme().colors.muted_foreground)
.typeset(TextRole::Body, cx) .typeset(TextRole::Caption, cx)
.rounded(cx.theme().radius.control) .rounded(cx.theme().radius.control)
.child(display_server(server)), .child(display_server(server)),
) )
@@ -167,7 +167,9 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
.tooltip(Tooltip::text("Add grasp server")) .tooltip(Tooltip::text("Add grasp server"))
.on_click({ .on_click({
let input = input.clone(); let input = input.clone();
move |_, window, cx| add_server(&input, window, cx) move |_, window, cx| {
add_server(&input, window, cx);
}
}), }),
), ),
) )
@@ -182,14 +184,18 @@ fn display_server(server: &str) -> SharedString {
} }
fn add_server(input: &Entity<InputState>, window: &mut Window, cx: &mut App) { fn add_server(input: &Entity<InputState>, window: &mut Window, cx: &mut App) {
let settings = SettingsStore::global(cx);
let value = input.read(cx).value().trim().to_owned(); let value = input.read(cx).value().trim().to_owned();
if value.is_empty() { if value.is_empty() {
return; return;
} }
let Some((normalized, _)) = normalize_server(&value) else { let Some((normalized, _)) = normalize_server(&value) else {
return; return;
}; };
SettingsStore::global(cx).update(cx, |store, cx| {
settings.update(cx, |store, cx| {
store.edit( store.edit(
|settings| { |settings| {
if !settings.grasp_servers.default_servers.contains(&normalized) { if !settings.grasp_servers.default_servers.contains(&normalized) {
@@ -206,28 +212,22 @@ fn add_server(input: &Entity<InputState>, window: &mut Window, cx: &mut App) {
} }
pub fn scan_paths_editor(cx: &App) -> AnyElement { pub fn scan_paths_editor(cx: &App) -> AnyElement {
let scan_paths = SettingsStore::global(cx)
.read(cx)
.settings()
.local_repos
.scan_paths
.clone();
let store = SettingsStore::global(cx); let store = SettingsStore::global(cx);
let scan_paths = store.read(cx).settings().local_repos.scan_paths.clone();
v_flex() v_flex()
.gap_2() .gap_2()
.children(scan_paths.iter().enumerate().map(|(ix, path)| { .children(scan_paths.iter().enumerate().map(|(ix, path)| {
let store = store.clone();
h_flex() h_flex()
.gap_1() .gap_1()
.child( .child(
div() h_flex()
.flex_1() .flex_1()
.h_8() .h_8()
.px_2() .px_2()
.bg(cx.theme().colors.muted) .bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground) .text_color(cx.theme().colors.muted_foreground)
.typeset(TextRole::Body, cx) .typeset(TextRole::Caption, cx)
.rounded(cx.theme().radius.control) .rounded(cx.theme().radius.control)
.child(path.display().to_string()), .child(path.display().to_string()),
) )
@@ -237,6 +237,7 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement {
.variant(ui::button::ButtonVariant::Ghost) .variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove")) .tooltip(Tooltip::text("Remove"))
.on_click(move |_, _, cx| { .on_click(move |_, _, cx| {
let store = SettingsStore::global(cx);
store.update(cx, |store, cx| { store.update(cx, |store, cx| {
store.edit( store.edit(
|settings| { |settings| {
+46 -49
View File
@@ -10,13 +10,12 @@ use helpers::{
}; };
use settings::SettingsStore; use settings::SettingsStore;
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::Dialog; use ui::dialog::{Dialog, DialogHandle};
use ui::input::InputState; use ui::input::InputState;
use ui::separator::Separator; use ui::separator::Separator;
use crate::shared::dialogs::open_global;
pub struct SettingsDialog { pub struct SettingsDialog {
handle: DialogHandle,
grasp_input: Entity<InputState>, grasp_input: Entity<InputState>,
default_folder: Entity<InputState>, default_folder: Entity<InputState>,
} }
@@ -39,6 +38,7 @@ impl SettingsDialog {
.build(cx); .build(cx);
cx.new(|_| Self { cx.new(|_| Self {
handle: DialogHandle::new(true),
grasp_input, grasp_input,
default_folder, default_folder,
}) })
@@ -47,61 +47,58 @@ impl SettingsDialog {
impl Render for SettingsDialog { impl Render for SettingsDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
const APPEARANCE_DESC: &str =
"Choose whether the app follows the system theme or uses a light/dark theme.";
const FETCH_DESC: &str = "Curated fetches events from relays in the repository's announcement. Uncensored also fetches from every maintainer's relays.";
const GRASP_DESC: &str =
"Servers used to host your git repositories via the Grasp protocol";
const SCAN_DESC: &str = "Directories scanned for local git repositories.";
const FOLDER_DESC: &str = "The folder for newly created repositories.";
let grasp_input = self.grasp_input.clone(); let grasp_input = self.grasp_input.clone();
let default_folder = self.default_folder.clone(); let default_folder = self.default_folder.clone();
Dialog::new("settings-dialog") Dialog::new("settings-dialog")
.open(true) .handle(self.handle.clone())
.min_width(px(650.))
.height(px(560.)) .height(px(560.))
.on_change(|open, _, cx| {
if !open {
crate::shared::dialogs::close_global(cx);
}
})
.title("Settings") .title("Settings")
.content(move |_, cx| { .content(move |_, cx| {
v_flex() v_flex()
.gap_4() .gap_4()
.child(setting_row( .child(setting_row(
cx, cx,
"Appearance", "Appearance",
"Choose whether the app follows the system theme or uses a light/dark theme.", APPEARANCE_DESC,
appearance_select(cx), appearance_select(cx),
)) ))
.child(Separator::horizontal()) .child(Separator::horizontal())
.child(setting_row( .child(setting_row(
cx, cx,
"Event Fetching Strategy", "Event Fetching Strategy",
"Curated fetches events from relays in the repository's announcement. Uncensored also fetches from every maintainer's relays.", FETCH_DESC,
event_fetching_select(cx), event_fetching_select(cx),
)) ))
.child(Separator::horizontal()) .child(Separator::horizontal())
.child(setting_block( .child(setting_block(
cx, cx,
"Grasp Servers", "Grasp Servers",
"Servers used to host your git repositories via the Grasp protocol", GRASP_DESC,
grasp_servers_editor(&grasp_input, cx), grasp_servers_editor(&grasp_input, cx),
)) ))
.child(Separator::horizontal()) .child(Separator::horizontal())
.child(setting_block( .child(setting_block(
cx, cx,
"Scan Directories", "Scan Directories",
"Directories scanned for local git repositories.", SCAN_DESC,
scan_paths_editor(cx), scan_paths_editor(cx),
)) ))
.child(setting_block( .child(setting_block(
cx, cx,
"Default Folder", "Default Folder",
"The folder for newly created repositories.", FOLDER_DESC,
default_folder_selector(&default_folder), default_folder_selector(&default_folder),
)) ))
.into_any_element() .into_any_element()
}) })
} }
} }
/// Opens the settings dialog.
pub fn open(cx: &mut App) {
open_global(SettingsDialog::new(cx), cx);
}
-59
View File
@@ -1,59 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyView, App, Context, Entity, Global, IntoElement, ParentElement as _, Render, Styled as _,
Window, div,
};
struct GlobalDialogHost(Entity<DialogHost>);
impl Global for GlobalDialogHost {}
/// Owns the modal currently mounted at the window root.
pub struct DialogHost {
open: Option<AnyView>,
}
impl DialogHost {
pub fn new(_cx: &mut Context<Self>) -> Self {
Self { open: None }
}
pub fn set_global(entity: Entity<Self>, cx: &mut App) {
cx.set_global(GlobalDialogHost(entity));
}
pub fn global(cx: &App) -> Entity<Self> {
cx.global::<GlobalDialogHost>().0.clone()
}
pub fn open(&mut self, view: AnyView, cx: &mut Context<Self>) {
self.open = Some(view);
cx.notify();
}
pub fn close(&mut self, cx: &mut Context<Self>) {
self.open = None;
cx.notify();
}
}
impl Render for DialogHost {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.absolute()
.inset_0()
.when_some(self.open.clone(), |host, view| host.child(view))
}
}
/// Replaces the mounted modal with `view`.
pub fn open_global(view: impl Into<AnyView>, cx: &mut App) {
let host = DialogHost::global(cx);
host.update(cx, |host, cx| host.open(view.into(), cx));
}
/// Unmounts the current modal, if any.
pub fn close_global(cx: &mut App) {
let host = DialogHost::global(cx);
host.update(cx, |host, cx| host.close(cx));
}
-1
View File
@@ -1,4 +1,3 @@
pub mod dialogs;
pub mod panels; pub mod panels;
pub mod progress; pub mod progress;
pub mod tree; pub mod tree;
+73 -21
View File
@@ -2,7 +2,7 @@ use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, KeyBinding, AnyElement, AnyView, App, AppContext as _, Context, Entity, IntoElement, KeyBinding,
KeyBindingContextPredicate, ParentElement as _, SharedString, Subscription, WeakEntity, Window, KeyBindingContextPredicate, ParentElement as _, SharedString, Subscription, WeakEntity, Window,
}; };
use metadata::{Profile, ProfileDirectory}; use metadata::{Profile, ProfileDirectory};
@@ -21,10 +21,11 @@ use ui::tabs::{Tab, Tabs, TabsVariant};
use ui::tooltip::Tooltip; use ui::tooltip::Tooltip;
use crate::explore::ExploreView; use crate::explore::ExploreView;
use crate::identity::exit::ExitDialog;
use crate::repo::{RepoDetailView, actions, dialogs}; use crate::repo::{RepoDetailView, actions, dialogs};
use crate::settings::SettingsDialog;
use crate::shared::{log_dropped, panels}; use crate::shared::{log_dropped, panels};
use crate::workspace::Workspace; use crate::workspace::Workspace;
use crate::{identity, settings};
mod repository_switcher; mod repository_switcher;
@@ -110,6 +111,9 @@ pub struct TitlebarView {
/// The command palette opened from the titlebar. /// The command palette opened from the titlebar.
palette: Entity<CommandPaletteState>, palette: Entity<CommandPaletteState>,
repository_switcher: Entity<RepositorySwitcher>, repository_switcher: Entity<RepositorySwitcher>,
settings: Option<Entity<SettingsDialog>>,
exit: Option<Entity<ExitDialog>>,
create: Option<Entity<dialogs::create::CreateRepoDialog>>,
user_menu_open: bool, user_menu_open: bool,
_subscriptions: Vec<Subscription>, _subscriptions: Vec<Subscription>,
} }
@@ -124,11 +128,11 @@ impl TitlebarView {
let repos = RepoListStore::global(cx); let repos = RepoListStore::global(cx);
let local = LocalReposStore::global(cx); let local = LocalReposStore::global(cx);
let palette = Self::new_palette(workspace.clone(), window, cx); let weak = cx.entity().downgrade();
let palette = Self::new_palette(weak.clone(), window, cx);
let directory = ProfileDirectory::new(cx); let directory = ProfileDirectory::new(cx);
let entity = cx.entity(); let entity = cx.entity();
let weak = entity.downgrade();
let mut subscriptions = Vec::new(); let mut subscriptions = Vec::new();
let repository_switcher = cx.new(|cx| { let repository_switcher = cx.new(|cx| {
@@ -197,13 +201,16 @@ impl TitlebarView {
directory, directory,
palette, palette,
repository_switcher, repository_switcher,
settings: None,
exit: None,
create: None,
user_menu_open: false, user_menu_open: false,
_subscriptions: subscriptions, _subscriptions: subscriptions,
} }
} }
fn new_palette( fn new_palette(
workspace: WeakEntity<Workspace>, weak: WeakEntity<Self>,
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Entity<CommandPaletteState> { ) -> Entity<CommandPaletteState> {
@@ -220,13 +227,19 @@ impl TitlebarView {
CommandPaletteState::new( CommandPaletteState::new(
CommandPalette::new("command-palette", Self::palette_commands(), matcher) CommandPalette::new("command-palette", Self::palette_commands(), matcher)
.on_execute(move |command, window, cx| match command.id.as_ref() { .on_execute(move |command, window, cx| match command.id.as_ref() {
"create-repo" => dialogs::create::open(workspace.clone(), window, cx), "create-repo" => {
log_dropped(weak.update(cx, |this, cx| this.open_create(window, cx)));
}
"rescan-repos" => { "rescan-repos" => {
let local_repos = LocalReposStore::global(cx); let local_repos = LocalReposStore::global(cx);
local_repos.update(cx, |store, cx| store.rescan(cx)); local_repos.update(cx, |store, cx| store.rescan(cx));
} }
"open-settings" => settings::open(cx), "open-settings" => {
"exit" => identity::helpers::open_exit(cx), log_dropped(weak.update(cx, |this, cx| this.open_settings(cx)));
}
"exit" => {
log_dropped(weak.update(cx, |this, cx| this.open_exit(cx)));
}
_ => {} _ => {}
}), }),
window, window,
@@ -403,7 +416,35 @@ impl TitlebarView {
pub(crate) fn create_repository(&mut self, window: &mut Window, cx: &mut Context<Self>) { pub(crate) fn create_repository(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.repository_switcher self.repository_switcher
.update(cx, |switcher, cx| switcher.close(cx)); .update(cx, |switcher, cx| switcher.close(cx));
dialogs::create::open(self.workspace.clone(), window, cx); self.open_create(window, cx);
}
fn open_settings(&mut self, cx: &mut Context<Self>) {
self.settings = Some(SettingsDialog::new(cx));
cx.notify();
}
fn open_exit(&mut self, cx: &mut Context<Self>) {
self.exit = Some(ExitDialog::new(cx));
cx.notify();
}
fn open_create(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let view = dialogs::create::CreateRepoDialog::new(self.workspace.clone(), window, cx);
self.create = Some(view);
cx.notify();
}
/// The dialogs this titlebar opens, rendered at the window root.
pub fn dialogs(&self) -> Vec<AnyView> {
[
self.settings.clone().map(Into::into),
self.exit.clone().map(Into::into),
self.create.clone().map(Into::into),
]
.into_iter()
.flatten()
.collect()
} }
fn activate(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) { fn activate(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
@@ -507,7 +548,7 @@ impl TitlebarView {
} }
pub fn render_new_repository(&self) -> AnyElement { pub fn render_new_repository(&self) -> AnyElement {
let workspace = self.workspace.clone(); let weak = self.weak.clone();
Button::new("add-repo") Button::new("add-repo")
.icon(IconRole::Plus) .icon(IconRole::Plus)
@@ -515,7 +556,7 @@ impl TitlebarView {
.fully_rounded(true) .fully_rounded(true)
.tooltip(Tooltip::text("Create repository")) .tooltip(Tooltip::text("Create repository"))
.on_click(move |_, window, cx| { .on_click(move |_, window, cx| {
dialogs::create::open(workspace.clone(), window, cx); log_dropped(weak.update(cx, |this, cx| this.open_create(window, cx)));
}) })
.into_any_element() .into_any_element()
} }
@@ -528,11 +569,14 @@ impl TitlebarView {
Menu::new("user-menu") Menu::new("user-menu")
.open(self.user_menu_open) .open(self.user_menu_open)
.on_change(move |open, _, cx| { .on_change({
log_dropped(weak.update(cx, |this, cx| { let weak = weak.clone();
this.user_menu_open = open; move |open, _, cx| {
cx.notify(); log_dropped(weak.update(cx, |this, cx| {
})); this.user_menu_open = open;
cx.notify();
}));
}
}) })
.trigger({ .trigger({
let name = name.clone(); let name = name.clone();
@@ -552,13 +596,21 @@ impl TitlebarView {
.into_any_element() .into_any_element()
} }
}) })
.items(|_, _| { .items(move |_, _| {
vec![ vec![
MenuItem::new("Settings").handler(|_, cx| settings::open(cx)), MenuItem::new("Settings").handler({
let weak = weak.clone();
move |_, cx| {
log_dropped(weak.update(cx, |this, cx| this.open_settings(cx)));
}
}),
MenuItem::separator(), MenuItem::separator(),
MenuItem::new("Exit") MenuItem::new("Exit").destructive(true).handler({
.destructive(true) let weak = weak.clone();
.handler(|_, cx| identity::helpers::open_exit(cx)), move |_, cx| {
log_dropped(weak.update(cx, |this, cx| this.open_exit(cx)));
}
}),
] ]
}) })
} }
+2 -1
View File
@@ -25,6 +25,7 @@ use crate::components::common::{
}; };
use crate::components::spinner::Spinner; use crate::components::spinner::Spinner;
use crate::icons::Icon; use crate::icons::Icon;
use crate::spinner::SpinnerVariant;
use crate::theme::{ActiveTheme as _, ControlMetrics, DISABLED_OPACITY, Size}; use crate::theme::{ActiveTheme as _, ControlMetrics, DISABLED_OPACITY, Size};
/// The single activation handler, shared by pointer, Enter, and Space. /// The single activation handler, shared by pointer, Enter, and Space.
@@ -362,7 +363,7 @@ impl RenderOnce for Button {
h_flex().absolute().inset_0().justify_center().child( h_flex().absolute().inset_0().justify_center().child(
Spinner::new((self.id.clone(), "spinner")) Spinner::new((self.id.clone(), "spinner"))
.with_size(self.size) .with_size(self.size)
.variant(crate::components::spinner::SpinnerVariant::Icon) .variant(SpinnerVariant::Icon)
.color(foreground), .color(foreground),
), ),
) )
+110 -16
View File
@@ -1,5 +1,9 @@
//! Renders a centred panel over a dim scrim: the platform's modal. //! Renders a centred panel over a dim scrim: the platform's modal.
//! //!
//! Give the dialog a [`DialogHandle`] to share its open state: dismissal
//! through escape, the scrim, or the close button updates every holder of a
//! clone, and they can open or close it in turn.
//!
//! # Examples //! # Examples
//! //!
//! ```no_run //! ```no_run
@@ -17,6 +21,7 @@
//! .on_change(|open, _window, _cx| println!("dialog open: {open}")); //! .on_change(|open, _window, _cx| println!("dialog open: {open}"));
//! ``` //! ```
use std::cell::Cell;
use std::rc::Rc; use std::rc::Rc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
@@ -32,6 +37,7 @@ use crate::components::common::{DIALOG_LAYER, Sizable, StyledExt as _, v_flex};
use crate::components::grain::grain; use crate::components::grain::grain;
use crate::components::scroll_area::ScrollArea; use crate::components::scroll_area::ScrollArea;
use crate::icons::IconRole; use crate::icons::IconRole;
use crate::layout::h_flex;
use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH, TextRole, Typeset as _}; use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH, TextRole, Typeset as _};
/// Requests the dialog's close: `false` closes. /// Requests the dialog's close: `false` closes.
@@ -39,6 +45,42 @@ pub type ChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type ContentFn = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>; type ContentFn = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>;
type ActionsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<AnyElement>>; type ActionsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<AnyElement>>;
/// The shared open state of a dialog; clone it to open or close from anywhere.
#[derive(Clone, Default)]
pub struct DialogHandle {
open: Rc<Cell<bool>>,
}
impl DialogHandle {
/// Creates a handle with the given open state.
pub fn new(open: bool) -> Self {
Self {
open: Rc::new(Cell::new(open)),
}
}
/// Whether the dialog is open.
pub fn is_open(&self) -> bool {
self.open.get()
}
/// Opens the dialog.
pub fn open(&self, cx: &mut App) {
self.set_open(true, cx);
}
/// Closes the dialog.
pub fn close(&self, cx: &mut App) {
self.set_open(false, cx);
}
fn set_open(&self, open: bool, cx: &mut App) {
if self.open.replace(open) != open {
cx.refresh_windows();
}
}
}
/// A centred panel over a dim scrim: the platform's modal. /// A centred panel over a dim scrim: the platform's modal.
#[derive(IntoElement)] #[derive(IntoElement)]
#[must_use] #[must_use]
@@ -49,7 +91,10 @@ pub struct Dialog {
grain: bool, grain: bool,
title: Option<SharedString>, title: Option<SharedString>,
a11y_label: Option<SharedString>, a11y_label: Option<SharedString>,
handle: Option<DialogHandle>,
on_change: Option<ChangeHandler>, on_change: Option<ChangeHandler>,
close_on_escape: bool,
close_on_backdrop: bool,
content: Option<ContentFn>, content: Option<ContentFn>,
actions: Option<ActionsFn>, actions: Option<ActionsFn>,
min_width: Option<DefiniteLength>, min_width: Option<DefiniteLength>,
@@ -70,7 +115,10 @@ impl Dialog {
grain: false, grain: false,
title: None, title: None,
a11y_label: None, a11y_label: None,
handle: None,
on_change: None, on_change: None,
close_on_escape: true,
close_on_backdrop: true,
content: None, content: None,
actions: None, actions: None,
min_width: None, min_width: None,
@@ -79,7 +127,7 @@ impl Dialog {
} }
} }
/// Sets the current open state. /// Sets the initial open state; a handle overrides it.
pub fn open(mut self, open: bool) -> Self { pub fn open(mut self, open: bool) -> Self {
self.open = open; self.open = open;
self self
@@ -97,6 +145,24 @@ impl Dialog {
self self
} }
/// Shares the dialog's open state.
pub fn handle(mut self, handle: DialogHandle) -> Self {
self.handle = Some(handle);
self
}
/// Sets whether escape dismisses the dialog.
pub fn close_on_escape(mut self, close: bool) -> Self {
self.close_on_escape = close;
self
}
/// Sets whether clicking the scrim dismisses the dialog.
pub fn close_on_backdrop(mut self, close: bool) -> Self {
self.close_on_backdrop = close;
self
}
/// Requests close through `on_change` on escape, scrim clicks, and the close button. /// Requests close through `on_change` on escape, scrim clicks, and the close button.
pub fn on_change<F>(mut self, handler: F) -> Self pub fn on_change<F>(mut self, handler: F) -> Self
where where
@@ -171,10 +237,24 @@ impl RenderOnce for Dialog {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let root = div().absolute().inset_0(); let root = div().absolute().inset_0();
if !self.open { let open = self
.handle
.as_ref()
.map_or(self.open, DialogHandle::is_open);
if !open {
return root.into_any_element(); return root.into_any_element();
} }
// A handle routes dismissal through the shared state
let on_change = self.on_change.clone().or_else(|| {
self.handle.clone().map(|handle| {
Rc::new(move |open: bool, _window: &mut Window, cx: &mut App| {
handle.set_open(open, cx);
}) as ChangeHandler
})
});
let (scrim_color, border, foreground, surface, radius, shadows, enter_duration) = { let (scrim_color, border, foreground, surface, radius, shadows, enter_duration) = {
let theme = cx.theme(); let theme = cx.theme();
( (
@@ -200,9 +280,10 @@ impl RenderOnce for Dialog {
.or_else(|| self.title.clone()) .or_else(|| self.title.clone())
.unwrap_or_else(|| SharedString::from(self.id.to_string())); .unwrap_or_else(|| SharedString::from(self.id.to_string()));
let on_change = self.on_change.clone();
let alert = self.alert; let alert = self.alert;
let show_close = !alert && on_change.is_some(); let close_on_escape = self.close_on_escape;
let close_on_backdrop = self.close_on_backdrop;
let show_close = !alert && on_change.is_some() && (close_on_escape || close_on_backdrop);
// Keyboard focus rides the panel across frames. // Keyboard focus rides the panel across frames.
let focus = crate::components::common::focus_handle(&self.id, window, cx); let focus = crate::components::common::focus_handle(&self.id, window, cx);
@@ -227,8 +308,6 @@ impl RenderOnce for Dialog {
}) })
.max_w(relative(0.9)) .max_w(relative(0.9))
.when_some(height, |panel, height| panel.h(height)) .when_some(height, |panel, height| panel.h(height))
.p_4()
.gap_4()
.bg(surface) .bg(surface)
.text_color(foreground) .text_color(foreground)
.rounded(radius) .rounded(radius)
@@ -242,6 +321,7 @@ impl RenderOnce for Dialog {
move |event: &KeyDownEvent, window, cx| { move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "escape" if event.keystroke.key == "escape"
&& !alert && !alert
&& close_on_escape
&& let Some(on_change) = &on_change && let Some(on_change) = &on_change
{ {
on_change(false, window, cx); on_change(false, window, cx);
@@ -251,20 +331,27 @@ impl RenderOnce for Dialog {
}) })
.when(self.title.is_some() || show_close, |panel| { .when(self.title.is_some() || show_close, |panel| {
panel.child( panel.child(
div() h_flex()
.flex() .h_12()
.items_center() .px_2()
.justify_end()
.gap_2() .gap_2()
.justify_between()
.child(div().size_5())
.when_some(self.title.clone(), |row, title| { .when_some(self.title.clone(), |row, title| {
row.child(div().flex_1().typeset(TextRole::Title3, cx).child(title)) row.child(
div()
.flex_1()
.text_center()
.typeset(TextRole::Headline, cx)
.child(title),
)
}) })
.when(show_close, |row| { .when(show_close, |row| {
row.child( row.child(
Button::new("dialog-close") Button::new("dialog-close")
.icon(IconRole::Close) .icon(IconRole::Close)
.variant(ButtonVariant::Ghost) .variant(ButtonVariant::Ghost)
.xsmall() .small()
.debug_selector(|| "dialog-close".to_string()) .debug_selector(|| "dialog-close".to_string())
.accessibility_label("Close") .accessibility_label("Close")
.on_click({ .on_click({
@@ -287,15 +374,22 @@ impl RenderOnce for Dialog {
.handle(scroll) .handle(scroll)
.flex_1() .flex_1()
.min_h_0() .min_h_0()
.child(content), .child(div().p_2().child(content)),
) )
} else { } else {
this.child(content) this.child(div().p_2().child(content))
} }
}) })
}) })
.when_some(actions, |panel, actions| { .when_some(actions, |panel, actions| {
panel.child(div().flex().justify_end().gap_3().children(actions)) panel.child(
h_flex()
.px_2()
.h_12()
.justify_end()
.gap_2()
.children(actions),
)
}) })
.child( .child(
canvas(|_, _, _| {}, { canvas(|_, _, _| {}, {
@@ -315,7 +409,7 @@ impl RenderOnce for Dialog {
.bg(scrim_color) .bg(scrim_color)
.occlude() .occlude()
.when(self.grain, |scrim| scrim.child(grain())) .when(self.grain, |scrim| scrim.child(grain()))
.when(!alert, |scrim| { .when(!alert && close_on_backdrop, |scrim| {
scrim.on_mouse_down(MouseButton::Left, { scrim.on_mouse_down(MouseButton::Left, {
let on_change = on_change.clone(); let on_change = on_change.clone();
move |_, _window, cx| { move |_, _window, cx| {
+1
View File
@@ -110,6 +110,7 @@ impl RenderOnce for ScrollArea {
let pane = div() let pane = div()
.id(self.id.clone()) .id(self.id.clone())
.h_full()
.overflow_hidden() .overflow_hidden()
.when(self.axes != ScrollAxes::Horizontal, |area| { .when(self.axes != ScrollAxes::Horizontal, |area| {
area.overflow_y_scroll() area.overflow_y_scroll()
+23 -25
View File
@@ -105,30 +105,28 @@ impl RenderOnce for Shell {
theme.colors.muted theme.colors.muted
}; };
let layout = v_flex() frame(
.w_full() v_flex()
.h_full() .w_full()
.overflow_hidden() .h_full()
.bg(background) .overflow_hidden()
.refine_style(&self.style) .bg(background)
.when(self.transparent && self.grain, |layout| { .refine_style(&self.style)
layout.child(grain_overlay()) .when(self.transparent && self.grain, |layout| {
}); layout.child(grain_overlay())
})
let layout = layout .when_some(self.titlebar, |layout, titlebar| {
.when_some(self.titlebar, |layout, titlebar| { layout.child(titlebar.transparent(self.transparent))
layout.child(titlebar.transparent(self.transparent)) })
}) .child(self.panel.unwrap_or_else(|| div().into_any_element())),
.child(self.panel.unwrap_or_else(|| div().into_any_element())); window,
cx,
let frame = frame(layout, window, cx); )
.when_some(self.toasts, |frame, toasts| {
frame frame.child(ToastsView::new((id.clone(), "toasts"), toasts))
.when_some(self.toasts, |frame, toasts| { })
frame.child(ToastsView::new((id.clone(), "toasts"), toasts)) .when_some(self.alerts, |frame, alerts| {
}) frame.child(AlertsView::new((id, "alerts"), alerts))
.when_some(self.alerts, |frame, alerts| { })
frame.child(AlertsView::new((id, "alerts"), alerts))
})
} }
} }
+1 -1
View File
@@ -34,7 +34,7 @@ pub enum TextRole {
Title2, Title2,
/// Sub-section and dialog headings. /// Sub-section and dialog headings.
Title3, Title3,
/// Body-sized emphasis — list row titles, group labels. /// Body-sized emphasis, list row titles, group labels.
Headline, Headline,
/// Control labels and reading text. /// Control labels and reading text.
Body, Body,