feat: rework window layout around panel stack (#36)
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

Reviewed-on: #36
This commit was merged in pull request #36.
This commit is contained in:
2026-11-24 03:42:54 +00:00
parent 81a46abbe5
commit a2abfb2f27
99 changed files with 6145 additions and 8891 deletions
+1 -6
View File
@@ -1,12 +1,7 @@
use gpui::App;
use settings::{AppearanceMode, Settings};
use settings::AppearanceMode;
use ui::theme::{ThemeVariant, follow_system, set_mode_override};
/// Applies the persisted light/dark/system preference to the kit theme.
pub fn apply_appearance(settings: &Settings, cx: &mut App) {
apply_appearance_mode(settings.appearance, cx);
}
/// Applies one appearance mode to the kit theme.
pub fn apply_appearance_mode(mode: AppearanceMode, cx: &mut App) {
match mode {
+59 -83
View File
@@ -1,25 +1,22 @@
pub mod helpers;
mod placeholder;
mod sign_in;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
Render, Styled as _, Subscription, Window, div, px,
App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, Styled as _, Subscription, WeakEntity, Window, div,
};
use helpers::apply_appearance;
use helpers::apply_appearance_mode;
use settings::SettingsStore;
use signed_state::{Backend, BackendEvent};
use ui::common::h_flex;
use ui::common::{h_flex, v_flex};
use ui::icons::IconRole;
use ui::layout::panel::PanelRow;
use ui::layout::shell::Shell;
use ui::layout::panel::PanelStack;
use ui::layout::root::RootContext as _;
use ui::layout::titlebar::Titlebar;
use ui::theme::ActiveTheme as _;
use ui::toast::{Toast, Toasts};
use ui::toast::Toast;
use crate::app::placeholder::PlaceholderView;
use crate::app::sign_in::SignedOutView;
use crate::explore::ExploreView;
use crate::identity::passphrase::PassphraseDialog;
use crate::shared::log_dropped;
@@ -27,15 +24,10 @@ use crate::titlebar::{
CreateRepository, REPOSITORY_KEY_CONTEXT, SwitchRepository, TitlebarView,
bind_repository_shortcuts,
};
use crate::workspace::Workspace;
pub struct AppRoot {
workspace: Entity<Workspace>,
panels: Entity<PanelStack>,
titlebar: Entity<TitlebarView>,
toasts: Entity<Toasts>,
sign_in: Entity<SignedOutView>,
explore: Entity<ExploreView>,
empty: Entity<PlaceholderView>,
passphrase: Option<Entity<PassphraseDialog>>,
_subscriptions: Vec<Subscription>,
}
@@ -44,13 +36,11 @@ impl AppRoot {
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
bind_repository_shortcuts(cx);
let workspace = cx.new(|_| Workspace::new());
let titlebar = cx.new(|cx| TitlebarView::new(workspace.downgrade(), window, cx));
let toasts = cx.new(|_| Toasts::default());
let sign_in = cx.new(|_| SignedOutView::new());
let explore = cx.new(|cx| ExploreView::new(workspace.downgrade(), cx));
let app = cx.entity().downgrade();
let panels = cx.new(|cx| PanelStack::new("signed-panel", cx));
let titlebar = cx.new(|cx| TitlebarView::new(app.clone(), window, cx));
let empty = cx.new(|_| PlaceholderView::new("Select a repository"));
panels.update(cx, |panels, cx| panels.set_empty(empty, None, cx));
let backend = Backend::global(cx);
let settings = SettingsStore::global(cx);
@@ -59,22 +49,18 @@ impl AppRoot {
subscriptions.push(cx.subscribe_in(
&backend,
window,
|this, backend, event, window, cx| match event {
|this, _backend, event, window, cx| match event {
BackendEvent::PassphraseRequired => {
this.open_passphrase(cx);
}
BackendEvent::Error(message) => {
this.toasts.update(cx, |toasts, cx| {
toasts.push(Toast::new(message.clone()).icon(IconRole::Warning), cx);
});
cx.toast(Toast::new(message.clone()).icon(IconRole::Warning));
}
BackendEvent::SignerChanged => {
this.workspace.update(cx, |workspace, cx| {
workspace.clear(cx);
let app = cx.entity().downgrade();
window.defer(cx, move |window, cx| {
Self::reset_to_explore(&app, window, cx)
});
if backend.read(cx).current_user().is_some() {
ExploreView::open(&this.workspace.downgrade(), window, cx);
}
}
_ => {}
},
@@ -82,60 +68,56 @@ impl AppRoot {
subscriptions.push(cx.observe(&settings, |_this, store, cx| {
let settings = store.read(cx).settings().clone();
apply_appearance(&settings, cx);
apply_appearance_mode(settings.appearance, cx);
}));
let app = cx.entity().downgrade();
window.defer(cx, move |_window, cx| {
window.defer(cx, move |window, cx| {
if backend.read(cx).passphrase_required() {
log_dropped(app.update(cx, |this, cx| this.open_passphrase(cx)));
}
Self::reset_to_explore(&app, window, cx);
});
Self {
workspace,
panels,
titlebar,
toasts,
sign_in,
explore,
empty,
passphrase: None,
_subscriptions: subscriptions,
}
}
fn open_passphrase(&mut self, cx: &mut Context<Self>) {
self.passphrase = Some(PassphraseDialog::new(cx));
cx.notify();
if self.passphrase.is_some() {
return;
}
let dialog = PassphraseDialog::new(cx);
self.passphrase = Some(dialog.clone());
cx.open_dialog(dialog);
}
/// The panel stack: the main stack, the split stack, and the divider between them.
pub fn panels(&self) -> &Entity<PanelStack> {
&self.panels
}
/// Empties the stack and opens it on the explore panel, where every session starts.
fn reset_to_explore(app: &WeakEntity<Self>, window: &mut Window, cx: &mut App) {
let result = app.update(cx, |this, cx| {
this.panels.update(cx, |panels, cx| panels.clear(cx))
});
log_dropped(result);
ExploreView::open(app, window, cx);
}
}
impl Render for AppRoot {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let backend = Backend::global(cx);
let signed_in = backend.read(cx).current_user().is_some();
let repo_tabs = PanelStack::main_tabs(self.panels.clone(), cx);
let titlebar_view = self.titlebar.read(cx);
let workspace = self.workspace.read(cx);
let main = workspace.active_main();
let prefix = h_flex()
.gap_1()
.child(titlebar_view.render_new_repository())
.child(titlebar_view.render_explore())
.child(titlebar_view.repository_switcher());
let tab_bar = h_flex()
.gap_1()
.when_some(titlebar_view.render_repo_tabs(workspace), |bar, tabs| {
bar.child(tabs)
});
div()
.relative()
.size_full()
.font_family(cx.theme().ui_font())
.text_color(cx.theme().colors.foreground)
.key_context(REPOSITORY_KEY_CONTEXT)
.on_action(cx.listener(|this, action: &SwitchRepository, window, cx| {
this.titlebar.update(cx, |titlebar, cx| {
@@ -148,34 +130,28 @@ impl Render for AppRoot {
});
}))
.child(
Shell::new("signed-shell")
.titlebar(
v_flex()
.size_full()
.overflow_hidden()
.child(
Titlebar::new("signed-titlebar")
.prefix(prefix)
.tab_bar(tab_bar)
.prefix(
h_flex()
.gap_1()
.child(titlebar_view.render_new_repository())
.child(titlebar_view.render_explore())
.child(titlebar_view.repository_switcher()),
)
.tab_bar(
h_flex()
.gap_1()
.when_some(repo_tabs, |bar, tabs| bar.child(tabs)),
)
.when_some(titlebar_view.render_user_menu(cx), |titlebar, menu| {
titlebar.suffix(menu)
}),
)
.panel(
PanelRow::new("signed-panel")
.when_some(main.as_ref(), |row, main| {
row.main(main.clone()).when(workspace.has_details(), |row| {
row.split(self.workspace.clone())
})
})
.when(!main.is_some() && signed_in, |row| {
row.main(self.empty.clone())
})
.when(!main.is_some() && !signed_in, |row| {
row.main(self.sign_in.clone())
.split_at(self.explore.clone(), px(300.))
}),
)
.toasts(self.toasts.clone()),
.child(self.panels.clone()),
)
.child(titlebar_view.palette())
.children(titlebar_view.dialogs())
.when_some(self.passphrase.clone(), |el, view| el.child(view))
}
}
+1 -8
View File
@@ -1,8 +1,7 @@
use gpui::{
App, Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div,
Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div,
};
use ui::empty_state::EmptyState;
use ui::layout::panel::Panel;
/// A tab that stands in for a screen that is not ported yet.
pub struct PlaceholderView {
@@ -17,12 +16,6 @@ impl PlaceholderView {
}
}
impl Panel for PlaceholderView {
fn title(&self, _cx: &App) -> SharedString {
self.title.clone()
}
}
impl Render for PlaceholderView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(EmptyState::new(self.title.clone()))
-112
View File
@@ -1,112 +0,0 @@
use std::time::{SystemTime, UNIX_EPOCH};
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Context, Entity, IntoElement, ObjectFit, ParentElement as _, Render, SharedString,
Styled as _, StyledImage as _, Window, div, img,
};
use ui::button::{Button, ButtonVariant};
use ui::common::v_flex;
use ui::layout::panel::Panel;
use ui::theme::ActiveTheme as _;
use crate::identity::import::ImportDialog;
use crate::identity::onboarding::OnboardingDialog;
pub struct SignedOutView {
banner: SharedString,
onboarding: Option<Entity<OnboardingDialog>>,
import: Option<Entity<ImportDialog>>,
}
impl SignedOutView {
pub fn new() -> Self {
Self {
banner: pick_banner(),
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();
}
}
impl Panel for SignedOutView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Signed")
}
}
/// One of the three banner photos, picked per process launch.
fn pick_banner() -> SharedString {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|now| now.subsec_nanos())
.unwrap_or(0);
format!("backgrounds/banner{}.jpg", nanos % 3 + 1).into()
}
impl Render for SignedOutView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
v_flex()
.size_full()
.child(
v_flex()
.size_full()
.relative()
.bg(colors.background)
.rounded(theme.radius.overlay)
.overflow_hidden()
.child(
div().absolute().inset_0().child(
img(self.banner.clone())
.size_full()
.object_fit(ObjectFit::Cover)
.rounded(theme.radius.overlay),
),
)
.child(
v_flex()
.size_full()
.justify_end()
.p_4()
.gap_6()
.child(img("backgrounds/headline.png").max_w_48())
.child(
v_flex()
.gap_2()
.w_full()
.child(
Button::new("join")
.label("Join now")
.variant(ButtonVariant::Primary)
.on_click(cx.listener(|this, _, _, cx| {
this.open_onboarding(cx)
})),
)
.child(
Button::new("import")
.label("Import identity")
.variant(ButtonVariant::Secondary)
.on_click(
cx.listener(|this, _, _, cx| this.open_import(cx)),
),
),
),
),
)
.when_some(self.onboarding.clone(), |el, view| el.child(view))
.when_some(self.import.clone(), |el, view| el.child(view))
}
}
+19 -13
View File
@@ -1,3 +1,6 @@
use std::sync::LazyLock;
use std::time::{SystemTime, UNIX_EPOCH};
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, Entity, InteractiveElement as _, IntoElement, ParentElement as _, SharedString,
@@ -12,12 +15,24 @@ use ui::icons::{Icon, IconRole};
use ui::theme::ActiveTheme as _;
use utils::relative_time;
use crate::app::AppRoot;
use crate::repo::actions::open_repo_panel;
use crate::repo::helpers::announcement_display_name;
use crate::workspace::Workspace;
use crate::repo::helpers::{announcement_display_name, upstream_display_name};
const RECENT_COUNT: usize = 10;
/// One of the three banner photos, picked per process launch.
pub fn pick_banner() -> SharedString {
static BANNER: LazyLock<SharedString> = LazyLock::new(|| {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|now| now.subsec_nanos())
.unwrap_or(0);
SharedString::from(format!("backgrounds/banner{}.jpg", nanos % 3 + 1))
});
BANNER.clone()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(super) enum RepoFilter {
#[default]
@@ -55,7 +70,7 @@ pub(super) fn render_card(
last_activity: Option<Timestamp>,
announcements: &[Announcement],
directory: &Entity<ProfileDirectory>,
workspace: &WeakEntity<Workspace>,
workspace: &WeakEntity<AppRoot>,
cx: &mut gpui::App,
) -> AnyElement {
let owner = directory.read(cx).profile(&announcement.owner, cx);
@@ -78,16 +93,7 @@ pub(super) fn render_card(
let fork_label: Option<SharedString> = announcement.upstream.as_ref().and_then(|upstream| {
let addr = upstream.addr.as_ref()?;
let name = announcements
.iter()
.find(|a| a.addr() == *addr)
.map(|a| {
a.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(a.id.clone()))
})
.unwrap_or_else(|| SharedString::from(addr.identifier().to_owned()));
let name = upstream_display_name(addr, announcements);
Some(SharedString::from(format!("forked from {name}")))
});
+140 -15
View File
@@ -1,24 +1,32 @@
mod helpers;
use std::sync::Arc;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ListAlignment, ListState,
ParentElement as _, Render, SharedString, Styled as _, Subscription, WeakEntity, Window, div,
list, px,
ObjectFit, ParentElement as _, Pixels, Render, SharedString, Styled as _, StyledImage as _,
Subscription, WeakEntity, Window, div, img, list, px,
};
use helpers::{RepoFilter, render_card};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
use signed_state::RepoListStore;
use signed_state::{Backend, RepoListStore};
use ui::button::{Button, ButtonVariant};
use ui::common::{h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent};
use ui::layout::panel::Panel;
use ui::layout::panel::{Panel, PanelSlot, SplitSide};
use ui::layout::root::RootContext as _;
use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _;
use crate::app::AppRoot;
use crate::explore::helpers::pick_banner;
use crate::identity::import::ImportDialog;
use crate::identity::onboarding::OnboardingDialog;
use crate::shared::panels;
use crate::workspace::Workspace;
mod helpers;
const COLUMNS: usize = 2;
// Name row, avatar strip, meta row, and their borders and gaps, in px.
@@ -26,7 +34,7 @@ const CARD_HEIGHT: f32 = 40. + 64. + 48. + 2. + 6.;
pub struct ExploreView {
store: Entity<RepoListStore>,
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
scroll_handle: ListState,
filter: RepoFilter,
/// Indices matching [`Self::filter`] into the store's `announcements`.
@@ -36,6 +44,8 @@ pub struct ExploreView {
directory: Entity<ProfileDirectory>,
_search_subscription: Subscription,
_store_subscription: Subscription,
/// Observes the panel stack for the onboarding sidebar, set once this view is in it.
_stack_subscription: Option<Subscription>,
}
impl ExploreView {
@@ -43,7 +53,7 @@ impl ExploreView {
pub(crate) const PANEL_ID: &'static str = "Explore";
/// Opens the explore panel in the main panel, reusing it when it is already cached.
pub(crate) fn open(workspace: &WeakEntity<Workspace>, window: &mut Window, cx: &mut App) {
pub(crate) fn open(workspace: &WeakEntity<AppRoot>, window: &mut Window, cx: &mut App) {
panels::open_primary(
workspace,
Self::PANEL_ID,
@@ -56,7 +66,7 @@ impl ExploreView {
);
}
pub fn new(workspace: WeakEntity<Workspace>, cx: &mut Context<Self>) -> Self {
pub fn new(workspace: WeakEntity<AppRoot>, cx: &mut Context<Self>) -> Self {
let store = RepoListStore::global(cx);
let directory = ProfileDirectory::new(cx);
@@ -73,9 +83,13 @@ impl ExploreView {
this.rebuild_rows(cx);
});
// The root and the stack are still being updated while this view is built.
cx.defer(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| this.rebuild_rows(cx)) {
log::warn!("failed to load explore rows: {error}");
if let Err(error) = weak.update(cx, |this, cx| {
this.rebuild_rows(cx);
this.watch_stack(cx);
}) {
log::warn!("failed to set up the explore panel: {error}");
}
});
@@ -89,6 +103,7 @@ impl ExploreView {
directory,
_search_subscription: search_subscription,
_store_subscription: store_subscription,
_stack_subscription: None,
}
}
@@ -123,6 +138,50 @@ impl ExploreView {
}
}
/// Observes the panel stack so the onboarding sidebar follows the shown panel.
fn watch_stack(&mut self, cx: &mut Context<Self>) {
let Ok(stack) = self
.workspace
.read_with(cx, |workspace, _| workspace.panels().clone())
else {
log::warn!("failed to watch the panel stack: the app root is gone");
return;
};
self._stack_subscription =
Some(cx.observe(&stack, |this, _stack, cx| this.sync_sidebar(cx)));
self.sync_sidebar(cx);
}
/// Shows the onboarding sidebar while signed out and an explore panel is shown, and closes it otherwise.
fn sync_sidebar(&mut self, cx: &mut Context<Self>) {
let signed_out = Backend::global(cx).read(cx).current_user().is_none();
let explore = SharedString::from(Self::PANEL_ID);
let sidebar = SharedString::from(OnboardingSidebar::PANEL_ID);
let result = self.workspace.update(cx, |workspace, cx| {
workspace.panels().clone().update(cx, |stack, cx| {
let shown = signed_out && stack.is_active(PanelSlot::Main, &explore);
if shown && !stack.is_open(PanelSlot::Split, &sidebar) {
let view = Arc::new(cx.new(|_| OnboardingSidebar));
stack.insert_split_at(
sidebar.clone(),
OnboardingSidebar::WIDTH,
SplitSide::Leading,
view,
cx,
);
} else if !shown {
stack.close(PanelSlot::Split, &sidebar, cx);
}
})
});
if let Err(error) = result {
log::warn!("failed to update the onboarding sidebar: {error}");
}
}
fn render_header(
search: Entity<InputState>,
filter: RepoFilter,
@@ -256,9 +315,75 @@ impl Render for ExploreView {
})
.size_full(),
)
.child(crate::shared::widgets::scroll_overlay(
"explore-scroll",
scroll_handle,
))
.child(Scrollbar::vertical("explore-scroll", scroll_handle))
}
}
/// The onboarding sidebar shown beside the explore panel while signed out.
struct OnboardingSidebar;
impl OnboardingSidebar {
/// The identifier of the sidebar in the panel stack; shown as its tab label.
const PANEL_ID: &'static str = "Onboarding";
/// The width the sidebar opens at.
const WIDTH: Pixels = px(300.);
}
impl Panel for OnboardingSidebar {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from(Self::PANEL_ID)
}
}
impl Render for OnboardingSidebar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
v_flex()
.size_full()
.relative()
.bg(colors.background)
.rounded(theme.radius.overlay)
.overflow_hidden()
.child(
div().absolute().inset_0().child(
img(pick_banner())
.size_full()
.object_fit(ObjectFit::Cover)
.rounded(theme.radius.overlay),
),
)
.child(
v_flex()
.size_full()
.justify_end()
.p_4()
.gap_6()
.child(img("backgrounds/headline.png").max_w_48())
.child(
v_flex()
.gap_2()
.w_full()
.child(
Button::new("join")
.label("Join now")
.variant(ButtonVariant::Primary)
.on_click(|_, _, cx| {
let dialog = OnboardingDialog::new(cx);
cx.open_dialog(dialog)
}),
)
.child(
Button::new("import")
.label("Import identity")
.variant(ButtonVariant::Secondary)
.on_click(|_, _, cx| {
let dialog = ImportDialog::new(cx);
cx.open_dialog(dialog)
}),
),
),
)
}
}
+13 -12
View File
@@ -4,14 +4,13 @@ use gpui::{
Styled as _, Window, div, px,
};
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::{DialogProgress, error_row, run_dialog_task};
use crate::shared::progress::{DialogProgress, dialog_submit_button, error_row, run_dialog_task};
pub struct OnboardingDialog {
handle: DialogHandle,
@@ -108,16 +107,18 @@ impl Render for OnboardingDialog {
let busy = action_state.read(cx).busy;
let this = this.clone();
let create: AnyElement = Button::new("create-identity")
.label("Create new identity")
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(
this.update(cx, |this, cx| this.create_identity(cx)),
);
})
.into_any_element();
let create: AnyElement = dialog_submit_button(
"create-identity",
"Create new identity",
None,
busy,
&this,
|this, _window, cx| {
this.create_identity(cx);
Ok(())
},
)
.into_any_element();
vec![create]
})
+16 -12
View File
@@ -4,14 +4,15 @@ use gpui::{
Styled as _, Subscription, Window, px,
};
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::icons::{Icon, IconRole};
use ui::icons::IconRole;
use ui::input::{Input, InputState, InputStateEvent};
use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task};
use crate::shared::progress::{
DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task,
};
pub struct PassphraseDialog {
handle: DialogHandle,
@@ -102,15 +103,18 @@ impl Render for PassphraseDialog {
let busy = action_state.read(cx).busy;
let this = this.clone();
let unlock: AnyElement = Button::new("unlock")
.label("Unlock")
.icon(Icon::named(IconRole::Unlock))
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(this.update(cx, |this, cx| this.unlock(cx)));
})
.into_any_element();
let unlock: AnyElement = dialog_submit_button(
"unlock",
"Unlock",
Some(IconRole::Unlock),
busy,
&this,
|this, _window, cx| {
this.unlock(cx);
Ok(())
},
)
.into_any_element();
vec![unlock]
})
+2 -2
View File
@@ -9,6 +9,7 @@ use ui::avatar::Avatar;
use ui::badge::Badge;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::status_dot::{StatusDot, StatusDotVariant};
use ui::theme::ActiveTheme as _;
use utils::relative_time;
@@ -101,8 +102,7 @@ pub fn thread(
.child(div().flex_1())
.when(unread, |this| {
this.child(
ui::status_dot::StatusDot::new(("inbox-unread", ix))
.variant(ui::status_dot::StatusDotVariant::Accent),
StatusDot::new(("inbox-unread", ix)).variant(StatusDotVariant::Accent),
)
}),
)
+5 -5
View File
@@ -15,6 +15,7 @@ use signed_state::{Backend, BackendEvent, Inbox, RefreshGate, RefreshRequest, Re
use ui::alert::{Alert, AlertSeverity, AlertStyle};
use ui::button::Button;
use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea;
@@ -23,10 +24,9 @@ mod helpers;
use helpers::{empty_section_row, repo_header, thread};
use crate::app::AppRoot;
use crate::repo::actions::{RepoItem, open_repo_item};
use crate::repo::helpers::announcement_display_name;
use crate::shared::widgets::empty_state;
use crate::workspace::Workspace;
const MAX_SUB_ACTIVITIES: usize = 5;
@@ -45,7 +45,7 @@ struct InboxSection {
}
pub struct InboxView {
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
threads: Arc<Vec<InboxItem>>,
sections: Arc<Vec<InboxSection>>,
rows: Arc<Vec<InboxRow>>,
@@ -60,7 +60,7 @@ pub struct InboxView {
}
impl InboxView {
pub fn new(workspace: WeakEntity<Workspace>, cx: &mut Context<Self>) -> Self {
pub fn new(workspace: WeakEntity<AppRoot>, cx: &mut Context<Self>) -> Self {
let backend = Backend::global(cx);
let inbox = backend.read(cx).inbox();
@@ -470,7 +470,7 @@ impl Render for InboxView {
.min_h_0()
.px_4()
.child(if rows.is_empty() {
empty_state("You're all caught up.")
EmptyState::centered("You're all caught up.")
} else {
ScrollArea::new("inbox-scroll")
.flex_1()
+9 -6
View File
@@ -8,13 +8,16 @@ use signed_core::GitEvent;
use signed_state::RepoStore;
use ui::avatar::Avatar;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::input::InputState;
use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea;
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _;
use utils::relative_time;
use crate::issues::helpers::{comment_form, comments_section, issue_roots, sidebar_section};
use crate::issues::helpers::{comment_form, comments_section, sidebar_section};
use crate::shared::log_dropped;
use crate::shared::widgets::status_badge;
pub struct IssueDetailView {
@@ -39,7 +42,7 @@ impl IssueDetailView {
let directory = ProfileDirectory::new(cx);
let weak = cx.entity().downgrade();
cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.track_participants(cx)));
log_dropped(weak.update(cx, |this, cx| this.track_participants(cx)));
});
Self {
@@ -94,9 +97,9 @@ impl Render for IssueDetailView {
let Some(issue) = store.issues.iter().find(|issue| issue.id == self.issue_id) else {
// A not-yet-loaded store is not the same as a missing issue.
return if store.loaded {
crate::shared::widgets::empty_state("Issue not found")
EmptyState::centered("Issue not found")
} else {
crate::shared::widgets::centered_spinner("issue-loading")
Spinner::centered("issue-loading")
};
};
@@ -189,7 +192,7 @@ impl Render for IssueDetailView {
.child(comment_form(
&self.store,
issue_id,
issue_roots,
&store.issues,
&self.comment_input,
"comment",
cx,
@@ -200,7 +203,7 @@ impl Render for IssueDetailView {
.child(sidebar_section(
&self.store,
issue_id,
issue_roots,
&store.issues,
true,
&self.directory,
cx,
+20 -20
View File
@@ -76,24 +76,16 @@ pub(crate) fn filter_by_status<'a>(
(visible, counts)
}
pub(crate) fn issue_roots(store: &RepoStore) -> &[Event] {
&store.issues
}
pub(crate) fn pr_roots(store: &RepoStore) -> &[Event] {
&store.pull_requests
}
pub(crate) fn sidebar_section(
store: &Entity<RepoStore>,
id: EventId,
roots: fn(&RepoStore) -> &[Event],
roots: &[Event],
top_gap: bool,
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> AnyElement {
let store = store.read(cx);
let Some(root) = roots(store).iter().find(|event| event.id == id) else {
let Some(root) = roots.iter().find(|event| event.id == id) else {
return div().into_any_element();
};
@@ -116,7 +108,13 @@ pub(crate) fn sidebar_section(
v_flex()
.when(top_gap, |this| this.mt_4())
.gap_2()
.child(crate::shared::widgets::section_label("Participants", cx))
.child(
div()
.text_xs()
.font_medium()
.text_color(cx.theme().colors.muted_foreground)
.child("Participants"),
)
.children(participants.iter().map(|pubkey| {
let profile = directory.read(cx).profile(pubkey, cx);
let name = profile.name();
@@ -136,7 +134,13 @@ pub(crate) fn sidebar_section(
.child(
v_flex()
.gap_2()
.child(crate::shared::widgets::section_label("Labels", cx))
.child(
div()
.text_xs()
.font_medium()
.text_color(cx.theme().colors.muted_foreground)
.child("Labels"),
)
.map(|this| {
if labels.is_empty() {
this.child(
@@ -215,11 +219,14 @@ pub(crate) fn comments_section(
pub(crate) fn comment_form(
store: &Entity<RepoStore>,
root: EventId,
roots: fn(&RepoStore) -> &[Event],
roots: &[Event],
comment_input: &Entity<InputState>,
button_id: &'static str,
cx: &App,
) -> AnyElement {
let Some(root) = roots.iter().find(|event| event.id == root).cloned() else {
return div().into_any_element();
};
let comment_input = comment_input.clone();
let store = store.clone();
@@ -254,13 +261,6 @@ pub(crate) fn comment_form(
if content.is_empty() {
return;
}
let Some(root) = roots(store.read(cx))
.iter()
.find(|event| event.id == root)
.cloned()
else {
return;
};
store.update(cx, |store, cx| {
store.comment(&root, content, cx);
});
+8 -7
View File
@@ -19,17 +19,18 @@ use utils::relative_time;
use std::rc::Rc;
use self::detail::IssueDetailView;
use crate::app::AppRoot;
use crate::repo::helpers::short_id;
use crate::shared::event_list::{EventList, EventRow};
use crate::shared::event_list::{EventHandler, EventList, EventRow, filter_toolbar};
use crate::shared::log_dropped;
use crate::shared::panels;
use crate::workspace::Workspace;
pub mod detail;
pub(crate) mod helpers;
pub mod new_issue;
pub struct IssuesView {
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
store: Entity<RepoStore>,
new_issue: Option<Entity<new_issue::NewIssueDialog>>,
filter: IssueFilter,
@@ -45,7 +46,7 @@ pub struct IssuesView {
impl IssuesView {
pub fn new(
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
store: Entity<RepoStore>,
cx: &mut Context<Self>,
) -> Self {
@@ -54,7 +55,7 @@ impl IssuesView {
});
let weak = cx.entity().downgrade();
cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.rebuild(cx)));
log_dropped(weak.update(cx, |this, cx| this.rebuild(cx)));
});
Self {
@@ -128,7 +129,7 @@ impl IssuesView {
let muted = cx.theme().colors.muted_foreground;
let weak = cx.entity().downgrade();
crate::shared::event_list::filter_toolbar(
filter_toolbar(
cx,
[
Segmented::new("issue-filter", self.filter)
@@ -190,7 +191,7 @@ impl Render for IssuesView {
let id_hex = issue.id.to_hex();
let status = store.read(cx).status_of(issue);
let on_click: crate::shared::event_list::EventHandler = {
let on_click: EventHandler = {
let workspace = workspace.clone();
let store = store.clone();
Rc::new(move |_, window, cx| {
+13 -10
View File
@@ -3,14 +3,13 @@ use gpui::{
Styled as _, Window, div,
};
use signed_state::RepoStore;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::DialogProgress;
use crate::shared::progress::{DialogProgress, dialog_submit_button};
pub struct NewIssueDialog {
handle: DialogHandle,
@@ -87,14 +86,18 @@ impl Render for NewIssueDialog {
let this = this.clone();
let busy = action_state.read(cx).busy;
vec![
Button::new("create-issue")
.label("Create issue")
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx)));
})
.into_any_element() as AnyElement,
dialog_submit_button(
"create-issue",
"Create issue",
None,
busy,
&this,
|this, _window, cx| {
this.submit(cx);
Ok(())
},
)
.into_any_element() as AnyElement,
]
})
}
+8 -4
View File
@@ -9,12 +9,16 @@ mod repo;
mod settings;
mod shared;
mod titlebar;
mod workspace;
pub use app::AppRoot;
pub use app::helpers::{apply_appearance, apply_appearance_mode};
pub use app::helpers::apply_appearance_mode;
use gpui::{App, AppContext as _, Entity, Window};
use ui::layout::root::Root;
pub fn root(window: &mut Window, cx: &mut App) -> Entity<AppRoot> {
cx.new(|cx| AppRoot::new(window, cx))
pub fn root(window: &mut Window, cx: &mut App) -> Entity<Root> {
let root = cx.new(|cx| Root::new(window, cx));
let content: Entity<AppRoot> = cx.new(|cx| AppRoot::new(window, cx));
root.update(cx, |root, cx| root.set_content(content, cx));
root
}
+34 -27
View File
@@ -16,19 +16,24 @@ use ui::avatar::Avatar;
use ui::button::Button;
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::input::InputState;
use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea;
use ui::spinner::Spinner;
use ui::tabs::{Tab, Tabs};
use ui::theme::ActiveTheme as _;
use utils::relative_time;
use super::dialogs;
use crate::issues::helpers::{comment_form, comments_section, pr_roots, sidebar_section};
use crate::app::AppRoot;
use crate::issues::helpers::{comment_form, comments_section, sidebar_section};
use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::shared::widgets::{empty_state, status_badge};
use crate::workspace::Workspace;
use crate::shared::event_list::commit_list;
use crate::shared::log_dropped;
use crate::shared::panels::open_detail;
use crate::shared::widgets::status_badge;
const NOT_FOUND: &str = "Pull request not found";
@@ -44,7 +49,7 @@ struct PrBinding {
}
pub struct PullRequestDetailView {
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
store: Entity<RepoStore>,
pr_id: EventId,
update_dialog: Option<Entity<dialogs::update::UpdatePrDialog>>,
@@ -67,7 +72,7 @@ pub struct PullRequestDetailView {
impl PullRequestDetailView {
pub fn new(
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
store: Entity<RepoStore>,
pr_id: EventId,
_window: &mut Window,
@@ -82,7 +87,7 @@ impl PullRequestDetailView {
});
cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.sync(cx)));
log_dropped(weak.update(cx, |this, cx| this.sync(cx)));
});
Self {
@@ -300,7 +305,7 @@ impl PullRequestDetailView {
};
let workspace = self.workspace.clone();
let commit_id = commit_id.to_owned();
crate::shared::panels::open_detail(
open_detail(
&workspace,
id,
move |window, cx| {
@@ -336,7 +341,7 @@ impl PullRequestDetailView {
]
})
.on_change(move |index, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.active_tab = index;
cx.notify();
}));
@@ -346,10 +351,10 @@ impl PullRequestDetailView {
fn render_discussion(&mut self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return centered_spinner();
return Spinner::centered("pr-loading");
}
if let Some(error) = self.error.clone() {
return empty_state(error);
return EmptyState::centered(error);
}
let (author, picture, age, root_id, pubkey) = {
let store = self.store.read(cx);
@@ -358,7 +363,7 @@ impl PullRequestDetailView {
.iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
else {
return empty_state(NOT_FOUND);
return EmptyState::centered(NOT_FOUND);
};
let profile = self.directory.read(cx).profile(&root.pubkey, cx);
(
@@ -370,6 +375,8 @@ impl PullRequestDetailView {
)
};
let store = self.store.read(cx);
h_flex()
.size_full()
.min_h_0()
@@ -416,7 +423,7 @@ impl PullRequestDetailView {
.child(comment_form(
&self.store,
root_id,
pr_roots,
&store.pull_requests,
&self.comment_input,
"pr-comment",
cx,
@@ -426,7 +433,7 @@ impl PullRequestDetailView {
.child(sidebar_section(
&self.store,
root_id,
pr_roots,
&store.pull_requests,
true,
&self.directory,
cx,
@@ -436,29 +443,29 @@ impl PullRequestDetailView {
fn render_files(&self, _cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return centered_spinner();
return Spinner::centered("pr-loading");
}
if let Some(error) = self.error.clone() {
return empty_state(error);
return EmptyState::centered(error);
}
self.pane.clone().into_any_element()
}
fn render_commits(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return centered_spinner();
return Spinner::centered("pr-loading");
}
if let Some(error) = self.error.clone() {
return empty_state(error);
return EmptyState::centered(error);
}
if self.commits.is_empty() {
return empty_state("No commits found");
return EmptyState::centered("No commits found");
}
let commits = Arc::clone(&self.commits);
let worktree = self.worktree.clone();
let view = cx.entity().downgrade();
crate::shared::event_list::commit_list(
commit_list(
"pr-commits",
"pr-commits-scroll",
commits,
@@ -467,12 +474,11 @@ impl PullRequestDetailView {
move |commit, window, cx| {
if let Some(worktree) = worktree.clone() {
let id = commit.id.clone();
crate::shared::log_dropped(view.update(cx, |this, cx| {
log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(worktree, &id, window, cx);
}));
}
},
cx,
)
}
@@ -503,8 +509,9 @@ impl PullRequestDetailView {
.px_4()
.py_2()
.gap_2()
// The top right corner is the panel toolbar's.
.child(
h_flex().gap_2().child(status_badge(status)).child(
h_flex().gap_2().pr_16().child(status_badge(status)).child(
div()
.flex_1()
.min_w_0()
@@ -528,7 +535,7 @@ impl PullRequestDetailView {
.when(can_update, |this| {
this.child(Button::new("update-pr").label("Update").small().on_click(
move |_, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
log_dropped(weak.update(cx, |this, cx| {
let root = this
.store
.read(cx)
@@ -577,6 +584,10 @@ impl Panel for PullRequestDetailView {
fn loading(&self, _cx: &App) -> bool {
self.loading
}
fn toolbar(&self, _cx: &App) -> bool {
true
}
}
impl Render for PullRequestDetailView {
@@ -595,7 +606,3 @@ impl Render for PullRequestDetailView {
})
}
}
fn centered_spinner() -> AnyElement {
crate::shared::widgets::centered_spinner("pr-loading")
}
@@ -4,14 +4,13 @@ use gpui::{
};
use nostr::prelude::Event;
use signed_state::RepoStore;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::DialogProgress;
use crate::shared::progress::{DialogProgress, dialog_submit_button};
pub struct UpdatePrDialog {
handle: DialogHandle,
@@ -80,14 +79,18 @@ impl Render for UpdatePrDialog {
let this = this.clone();
let busy = action_state.read(cx).busy;
vec![
Button::new("submit-update")
.label("Update pull request")
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx)));
})
.into_any_element() as AnyElement,
dialog_submit_button(
"submit-update",
"Update pull request",
None,
busy,
&this,
|this, _window, cx| {
this.submit(cx);
Ok(())
},
)
.into_any_element() as AnyElement,
]
})
}
@@ -7,6 +7,7 @@ use ui::menu::MenuItem;
use utils::middle_truncate;
use super::NewPullRequestView;
use crate::repo::helpers::announcement_display_name;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PullRequestFilter {
@@ -77,8 +78,10 @@ pub fn source_menu_items(
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
let target = view.clone();
let path_for_action = path.clone();
items.push(
MenuItem::new(truncate_label(&label))
.checked(active_path.as_ref() == Some(&path))
@@ -113,14 +116,12 @@ pub fn source_menu_items(
} else {
SharedString::from(format!("by {}", shorten_owner(&candidate.owner)))
};
let title = format!(
"{} — {}",
crate::repo::helpers::announcement_display_name(&candidate),
subtitle
);
let title = format!("{} — {}", announcement_display_name(&candidate), subtitle);
let target = view.clone();
let checked = active_fork == Some(candidate.addr());
let announcement = candidate;
items.push(
MenuItem::new(truncate_label(&title))
.checked(checked)
@@ -135,5 +136,6 @@ pub fn source_menu_items(
);
}
}
items
}
+14 -12
View File
@@ -29,13 +29,15 @@ use helpers::PullRequestFilter;
pub use new::NewPullRequestView;
pub use send_patch::SendPatchView;
use crate::app::AppRoot;
use crate::issues::helpers::{StatusCounts, filter_by_status};
use crate::repo::helpers::short_id;
use crate::shared::event_list::{EventList, EventRow};
use crate::workspace::Workspace;
use crate::shared::event_list::{EventHandler, EventList, EventRow, filter_toolbar};
use crate::shared::log_dropped;
use crate::shared::panels::open_detail;
pub struct PullRequestsView {
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
store: Entity<RepoStore>,
filter: PullRequestFilter,
visible_prs: Vec<usize>,
@@ -49,7 +51,7 @@ pub struct PullRequestsView {
impl PullRequestsView {
pub fn new(
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
store: Entity<RepoStore>,
cx: &mut Context<Self>,
) -> Self {
@@ -59,7 +61,7 @@ impl PullRequestsView {
});
cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.rebuild(cx);
}));
});
@@ -139,7 +141,7 @@ impl PullRequestsView {
let workspace_for_build = workspace.clone();
let store = self.store.clone();
crate::shared::panels::open_detail(
open_detail(
&workspace,
id.clone(),
move |window, cx| {
@@ -168,7 +170,7 @@ impl PullRequestsView {
let workspace_for_build = workspace.clone();
let store = self.store.clone();
crate::shared::panels::open_detail(
open_detail(
&workspace,
id.clone(),
move |window, cx| {
@@ -195,7 +197,7 @@ impl PullRequestsView {
let menu_open_weak = cx.entity().downgrade();
let patch_weak = cx.entity().downgrade();
crate::shared::event_list::filter_toolbar(
filter_toolbar(
cx,
[
Segmented::new("pr-filter", self.filter)
@@ -248,7 +250,7 @@ impl PullRequestsView {
}
})
.on_open_change(move |open, _, cx| {
crate::shared::log_dropped(menu_open_weak.update(cx, |this, cx| {
log_dropped(menu_open_weak.update(cx, |this, cx| {
this.new_pr_menu_open = open;
cx.notify();
}));
@@ -257,7 +259,7 @@ impl PullRequestsView {
vec![MenuItem::new("Send Patch").handler({
let weak = patch_weak.clone();
move |window, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.open_send_patch(window, cx);
}));
}
@@ -302,14 +304,14 @@ impl Render for PullRequestsView {
let id_hex = pr.id.to_hex();
let status = store.read(cx).status_of(pr);
let on_click: crate::shared::event_list::EventHandler = {
let on_click: EventHandler = {
let workspace = workspace.clone();
let store = store.clone();
Rc::new(move |_, window, cx| {
let id = SharedString::from(format!("pr:{pr_id}"));
let workspace_for_build = workspace.clone();
let store = store.clone();
crate::shared::panels::open_detail(
open_detail(
&workspace,
id,
move |window, cx| {
+445 -63
View File
@@ -1,32 +1,38 @@
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle,
WeakEntity, Window, div, px,
ParentElement as _, PathPromptOptions, Render, SharedString, Styled as _, Subscription,
UniformListScrollHandle, WeakEntity, Window, div, px,
};
use signed_state::{CheckoutsStore, RepoStore};
use ui::button::Button;
use nostr::prelude::Url;
use signed_core::Announcement;
use signed_git::{GitCache, Repo};
use signed_state::{Backend, CheckoutsStore, Mirrors, RepoListStore, RepoStore};
use ui::button::{Button, ButtonVariant};
use ui::combobox::{Combobox, ComboboxState};
use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::layout::panel::Panel;
use ui::menu::Menu;
use ui::spinner::Spinner;
use ui::tabs::{Tab, Tabs};
use super::helpers::{ForkCompare, truncate_label};
use crate::app::AppRoot;
use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::repo::helpers::announcement_display_name;
use crate::shared::event_list::commit_list;
use crate::shared::log_dropped;
use crate::shared::panels::{close_detail, open_detail};
use crate::shared::progress::error_row;
use crate::shared::widgets::empty_state;
use crate::workspace::Workspace;
mod source;
pub struct NewPullRequestView {
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
panel_id: SharedString,
pub(super) store: Entity<RepoStore>,
pub(super) repo_path: Option<PathBuf>,
@@ -55,7 +61,7 @@ pub struct NewPullRequestView {
impl NewPullRequestView {
pub fn new(
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
panel_id: SharedString,
store: Entity<RepoStore>,
window: &mut Window,
@@ -73,7 +79,7 @@ impl NewPullRequestView {
let weak = weak.clone();
move |value, _window, cx| {
if let Some(base) = value {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
log_dropped(weak.update(cx, |this, cx| {
if this.base == base {
return;
}
@@ -94,7 +100,7 @@ impl NewPullRequestView {
let weak = weak.clone();
move |value, _window, cx| {
if let Some(compare) = value {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
log_dropped(weak.update(cx, |this, cx| {
if this.compare == compare {
return;
}
@@ -110,7 +116,7 @@ impl NewPullRequestView {
});
window.defer(cx, move |window, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
log_dropped(weak.update(cx, |this, cx| {
let Some(addr) = this.store.read(cx).addr().cloned() else {
return;
};
@@ -209,9 +215,7 @@ impl NewPullRequestView {
this.update(cx, |this, _cx| {
this.submitting = false;
})?;
crate::shared::log_dropped(
workspace.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)),
);
close_detail(&workspace, &panel_id, cx);
Ok(())
});
self.push_task(task);
@@ -227,7 +231,7 @@ impl NewPullRequestView {
};
let workspace = self.workspace.clone();
let commit_id = commit_id.to_owned();
crate::shared::panels::open_detail(
open_detail(
&workspace,
id,
move |window, cx| {
@@ -270,9 +274,7 @@ impl NewPullRequestView {
let active_fork = self.fork.as_ref().map(|fork| fork.announcement.addr());
let can_submit = self.submit_enabled(cx);
let source_label = match &self.fork {
Some(fork) => truncate_label(&crate::repo::helpers::announcement_display_name(
&fork.announcement,
)),
Some(fork) => truncate_label(&announcement_display_name(&fork.announcement)),
None => self.repo_path.as_ref().map_or_else(
|| SharedString::from("No source"),
|path| truncate_label(&path.display().to_string()),
@@ -289,42 +291,45 @@ impl NewPullRequestView {
.child(
v_flex()
.gap_1()
.child(label("Merge Into"))
.child(div().text_xs().font_medium().child("Merge Into"))
.child(div().w(px(160.)).child(self.base_select.clone())),
)
.child(
v_flex()
.gap_1()
.child(label("Pull From"))
.child(div().text_xs().font_medium().child("Pull From"))
.child(div().w(px(160.)).child(self.compare_select.clone())),
)
.child(
v_flex().gap_1().child(label("Source")).child(
Menu::new("pr-source")
.open(self.source_open)
.on_change(move |open, _, cx| {
crate::shared::log_dropped(weak_menu.update(cx, |this, cx| {
this.source_open = open;
cx.notify();
}));
})
.trigger(move |_, _| {
Button::new("compare-source")
.label(source_label.clone())
.variant(ui::button::ButtonVariant::Secondary)
.into_any_element()
})
.items(move |_, _| {
super::helpers::source_menu_items(
source_view.clone(),
associated.clone(),
active_path.clone(),
candidates.clone(),
user,
active_fork.clone(),
)
}),
),
v_flex()
.gap_1()
.child(div().text_xs().font_medium().child("Source"))
.child(
Menu::new("pr-source")
.open(self.source_open)
.on_change(move |open, _, cx| {
log_dropped(weak_menu.update(cx, |this, cx| {
this.source_open = open;
cx.notify();
}));
})
.trigger(move |_, _| {
Button::new("compare-source")
.label(source_label.clone())
.variant(ButtonVariant::Secondary)
.into_any_element()
})
.items(move |_, _| {
super::helpers::source_menu_items(
source_view.clone(),
associated.clone(),
active_path.clone(),
candidates.clone(),
user,
active_fork.clone(),
)
}),
),
)
.when_some(refresh_fork, |this, fork| {
this.child(
@@ -343,9 +348,7 @@ impl NewPullRequestView {
.loading(self.submitting)
.disabled(!can_submit)
.on_click(move |_, window, cx| {
crate::shared::log_dropped(
weak.update(cx, |this, cx| this.submit(window, cx)),
);
log_dropped(weak.update(cx, |this, cx| this.submit(window, cx)));
}),
)
.into_any_element()
@@ -366,7 +369,7 @@ impl NewPullRequestView {
]
})
.on_change(move |index, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.active_tab = index;
cx.notify();
}));
@@ -376,13 +379,13 @@ impl NewPullRequestView {
fn render_content(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return crate::shared::widgets::centered_spinner("new-pr-loading");
return Spinner::centered("new-pr-loading");
}
if !self.has_source() {
return empty_state("Choose a local checkout or an announced fork to compare");
return EmptyState::centered("Choose a local checkout or an announced fork to compare");
}
if self.commits.is_none() && self.error.is_some() {
return empty_state("Nothing to compare");
return EmptyState::centered("Nothing to compare");
}
match self.active_tab {
0 => self.pane.clone().into_any_element(),
@@ -392,15 +395,15 @@ impl NewPullRequestView {
fn render_commits(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(commits) = self.commits.as_ref() else {
return empty_state("No commits");
return EmptyState::centered("No commits");
};
if commits.is_empty() {
return empty_state("No commits between the branches");
return EmptyState::centered("No commits between the branches");
}
let commits = Arc::clone(commits);
let view = cx.entity().downgrade();
crate::shared::event_list::commit_list(
commit_list(
"new-pr-commits",
"new-pr-commits-scroll",
commits,
@@ -408,13 +411,383 @@ impl NewPullRequestView {
|_, _, _| None,
move |commit, window, cx| {
let id = commit.id.clone();
crate::shared::log_dropped(view.update(cx, |this, cx| {
log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(&id, window, cx);
}));
},
cx,
)
}
pub(super) fn has_source(&self) -> bool {
self.repo_path.is_some() || self.fork.is_some()
}
pub(super) fn work_path(&self) -> Option<PathBuf> {
match &self.fork {
Some(fork) => Some(fork.mirror_path.clone()),
None => self.repo_path.clone(),
}
}
pub(super) fn base_ref(&self) -> String {
match &self.fork {
Some(_) => ForkCompare::base_ref(&self.base),
None => self.base.to_string(),
}
}
pub(super) fn compare_ref(&self) -> String {
match &self.fork {
Some(fork) => fork.compare_ref(&self.compare),
None => self.compare.to_string(),
}
}
pub(crate) fn choose_checkout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Choose local checkout".into()),
});
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let picked = match prompt.await {
Ok(Ok(Some(mut paths))) => paths.pop(),
_ => None,
};
let Some(path) = picked else {
return Ok(());
};
this.update_in(cx, |this, window, cx| {
this.apply_folder_path(path, window, cx)
})?;
Ok(())
});
self.push_task(task);
}
pub(crate) fn apply_folder_path(
&mut self,
path: PathBuf,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.fork_generation = self.fork_generation.wrapping_add(1);
let generation = self.fork_generation;
let path_string = path.to_string_lossy().to_string();
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let info = cx
.background_spawn({
let path = path.clone();
async move {
let repo = Repo::try_open(&path)?;
match repo.branches() {
Ok(branches) => Some((branches, repo.current_branch())),
Err(error) => {
log::warn!("failed to list branches: {error}");
None
}
}
}
})
.await;
this.update_in(cx, |this, window, cx| {
if generation != this.fork_generation {
return;
}
this.apply_checkout(path_string, info, window, cx);
})?;
Ok(())
});
self.push_task(task);
}
fn apply_checkout(
&mut self,
path: String,
info: Option<(Vec<String>, Option<String>)>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.fork = None;
let Some((branches, current)) = info else {
self.error = Some("The chosen folder is not a git repository".into());
self.repo_path = None;
self.branches.clear();
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
cx.notify();
return;
};
if branches.is_empty() {
self.error = Some("The repository has no branches yet".into());
self.repo_path = None;
self.branches.clear();
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
cx.notify();
return;
}
let announced = self.store.read(cx).head.clone();
let base = preferred_branch(&branches, announced);
let compare = current
.filter(|branch| branches.contains(branch))
.unwrap_or_else(|| base.clone());
self.repo_path = Some(PathBuf::from(&path));
self.error = None;
self.branches = branches.into_iter().map(SharedString::from).collect();
if let Some(addr) = self.store.read(cx).addr().cloned() {
CheckoutsStore::global(cx).update(cx, |store, cx| {
store.record(PathBuf::from(&path), addr, cx);
});
}
self.base = SharedString::from(base);
self.compare = SharedString::from(compare);
self.sync_selectors(window, cx);
self.reload_compare(cx);
}
fn sync_selectors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let options: Vec<(SharedString, SharedString)> = self
.branches
.iter()
.map(|branch| (branch.clone(), branch.clone()))
.collect();
let base = self.base.clone();
let compare = self.compare.clone();
self.base_select.update(cx, |state, cx| {
state.set_options(options.clone(), cx);
state.set_selected(Some(base), window, cx);
});
self.compare_select.update(cx, |state, cx| {
state.set_options(options, cx);
state.set_selected(Some(compare), window, cx);
});
}
pub(super) fn fork_candidates(&self, cx: &App) -> Vec<Announcement> {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return Vec::new();
};
let euc = self
.store
.read(cx)
.announcement
.as_ref()
.and_then(|a| a.euc.clone());
let user = Backend::global(cx).read(cx).current_user();
let announcements = RepoListStore::global(cx).read(cx).announcements.clone();
Announcement::forks_in(&announcements, &addr, euc.as_deref(), user)
.into_iter()
.cloned()
.collect()
}
pub(crate) fn choose_fork(
&mut self,
announcement: Announcement,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(base) = self.store.read(cx).addr().cloned() else {
return;
};
let mirror_path = Mirrors::path(&base);
let namespace = GitCache::fork_namespace(&announcement);
let clone_urls: Vec<Url> = announcement.clone.clone();
let base_clone_urls: Vec<Url> = self
.store
.read(cx)
.announcement
.as_ref()
.map(|a| a.clone.clone())
.unwrap_or_default();
self.fork_generation = self.fork_generation.wrapping_add(1);
let generation = self.fork_generation;
let handle = window.window_handle();
self.loading = true;
self.error = None;
cx.notify();
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
let namespace = namespace.clone();
let mirror_path = mirror_path.clone();
async move {
Mirrors::ensure(&base, &base_clone_urls)?;
let repo = Repo::open(&mirror_path)?;
repo.delete_refs_with_prefix("refs/fork")?;
repo.fetch_refs(
&clone_urls,
&format!("+refs/heads/*:refs/fork/{namespace}/*"),
)?;
let strip = |refs: Vec<String>, prefix: &str| {
let mut names: Vec<String> = refs
.into_iter()
.filter_map(|name| {
name.strip_prefix(prefix)
.map(|rest| rest.trim_start_matches('/').to_owned())
})
.filter(|name| !name.is_empty())
.collect();
names.sort();
names
};
let base_branches = strip(
repo.refs_with_prefix("refs/remotes/origin")?,
"refs/remotes/origin",
);
let compare_branches = strip(
repo.refs_with_prefix(&format!("refs/fork/{namespace}"))?,
&format!("refs/fork/{namespace}"),
);
Ok::<_, anyhow::Error>((base_branches, compare_branches))
}
})
.await;
if let Err(error) = cx.update_window(handle, |_, window, cx| {
this.update(cx, |this, cx| {
if generation != this.fork_generation {
return;
}
this.apply_fork(announcement, mirror_path, namespace, result, window, cx);
})
}) {
log::warn!("failed to apply fork: {error}");
}
Ok(())
});
self.push_task(task);
}
fn apply_fork(
&mut self,
announcement: Announcement,
mirror_path: PathBuf,
namespace: String,
result: Result<(Vec<String>, Vec<String>), anyhow::Error>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.loading = false;
let (base_branches, compare_branches) = match result {
Ok(branches) => branches,
Err(error) => {
self.error = Some(format!("Could not compare against the fork: {error}").into());
cx.notify();
return;
}
};
if compare_branches.is_empty() {
self.error = Some("The fork has no branches to compare".into());
cx.notify();
return;
}
if base_branches.is_empty() {
self.error = Some("Could not list the target repository's branches.".into());
cx.notify();
return;
}
let announced = self.store.read(cx).head.clone();
let base = preferred_branch(&base_branches, announced);
let compare = compare_branches
.iter()
.find(|branch| branch.as_str() == "main")
.map(|branch| SharedString::from(branch.clone()))
.unwrap_or_else(|| SharedString::from(compare_branches[0].clone()));
self.fork = Some(ForkCompare {
announcement,
namespace,
mirror_path,
});
self.error = None;
self.base = SharedString::from(base);
self.compare = compare;
self.branches = base_branches.into_iter().map(SharedString::from).collect();
self.sync_selectors(window, cx);
self.reload_compare(cx);
}
pub(super) fn reload_compare(&mut self, cx: &mut Context<Self>) {
let Some(repo_path) = self.work_path() else {
return;
};
let base = self.base_ref();
let compare = self.compare_ref();
let base_name = self.base.to_string();
let compare_name = self.compare.to_string();
self.loading = true;
self.error = None;
self.compare_generation += 1;
let generation = self.compare_generation;
cx.notify();
if base == compare {
self.loading = false;
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
self.error = Some("Choose different base and compare branches".into());
cx.notify();
return;
}
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
async move {
let repo = Repo::open(Path::new(&repo_path))?;
let merge_base = repo.merge_base(&base, &compare)?.ok_or_else(|| {
anyhow::anyhow!(
"{base_name} and {compare_name} share no common ancestor"
)
})?;
let commits = repo.commit_range(&merge_base, &compare)?;
let diff = repo.range_diff(&merge_base, &compare)?;
Ok::<_, anyhow::Error>((merge_base, commits, diff))
}
})
.await;
this.update(cx, |this, cx| {
if generation != this.compare_generation {
return;
}
this.loading = false;
match result {
Ok((merge_base, commits, diff)) => {
this.merge_base = Some(merge_base);
this.commits = Some(Arc::new(commits));
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
}
Err(error) => {
this.merge_base = None;
this.commits = None;
this.pane.update(cx, |pane, cx| pane.clear(cx));
this.error = Some(error.to_string().into());
}
}
cx.notify();
})?;
Ok(())
});
self.push_task(task);
}
}
impl Panel for NewPullRequestView {
@@ -462,6 +835,15 @@ impl Render for NewPullRequestView {
}
}
fn label(text: &'static str) -> AnyElement {
div().text_xs().font_medium().child(text).into_any_element()
/// The announced head when listed, else `main`, else the first branch.
fn preferred_branch(branches: &[String], announced: Option<String>) -> String {
announced
.filter(|branch| branches.contains(branch))
.or_else(|| {
branches
.iter()
.find(|branch| branch.as_str() == "main")
.cloned()
})
.unwrap_or_else(|| branches[0].clone())
}
@@ -1,397 +0,0 @@
use std::path::{Path, PathBuf};
use std::sync::Arc;
use gpui::{App, AppContext as _, Context, PathPromptOptions, SharedString, Window};
use nostr::prelude::Url;
use signed_core::Announcement;
use signed_git::{GitCache, Repo};
use signed_state::{Backend, CheckoutsStore, Mirrors, RepoListStore};
use super::NewPullRequestView;
use crate::pull_requests::helpers::ForkCompare;
/// The announced head when listed, else `main`, else the first branch.
fn preferred_branch(branches: &[String], announced: Option<String>) -> String {
announced
.filter(|branch| branches.contains(branch))
.or_else(|| {
branches
.iter()
.find(|branch| branch.as_str() == "main")
.cloned()
})
.unwrap_or_else(|| branches[0].clone())
}
impl NewPullRequestView {
pub(super) fn has_source(&self) -> bool {
self.repo_path.is_some() || self.fork.is_some()
}
pub(super) fn work_path(&self) -> Option<PathBuf> {
match &self.fork {
Some(fork) => Some(fork.mirror_path.clone()),
None => self.repo_path.clone(),
}
}
pub(super) fn base_ref(&self) -> String {
match &self.fork {
Some(_) => ForkCompare::base_ref(&self.base),
None => self.base.to_string(),
}
}
pub(super) fn compare_ref(&self) -> String {
match &self.fork {
Some(fork) => fork.compare_ref(&self.compare),
None => self.compare.to_string(),
}
}
pub(crate) fn choose_checkout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Choose local checkout".into()),
});
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let picked = match prompt.await {
Ok(Ok(Some(mut paths))) => paths.pop(),
_ => None,
};
let Some(path) = picked else {
return Ok(());
};
this.update_in(cx, |this, window, cx| {
this.apply_folder_path(path, window, cx)
})?;
Ok(())
});
self.push_task(task);
}
pub(crate) fn apply_folder_path(
&mut self,
path: PathBuf,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.fork_generation = self.fork_generation.wrapping_add(1);
let generation = self.fork_generation;
let path_string = path.to_string_lossy().to_string();
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let info = cx
.background_spawn({
let path = path.clone();
async move {
let repo = Repo::try_open(&path)?;
match repo.branches() {
Ok(branches) => Some((branches, repo.current_branch())),
Err(error) => {
log::warn!("failed to list branches: {error}");
None
}
}
}
})
.await;
this.update_in(cx, |this, window, cx| {
if generation != this.fork_generation {
return;
}
this.apply_checkout(path_string, info, window, cx);
})?;
Ok(())
});
self.push_task(task);
}
fn apply_checkout(
&mut self,
path: String,
info: Option<(Vec<String>, Option<String>)>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.fork = None;
let Some((branches, current)) = info else {
self.error = Some("The chosen folder is not a git repository".into());
self.repo_path = None;
self.branches.clear();
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
cx.notify();
return;
};
if branches.is_empty() {
self.error = Some("The repository has no branches yet".into());
self.repo_path = None;
self.branches.clear();
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
cx.notify();
return;
}
let announced = self.store.read(cx).head.clone();
let base = preferred_branch(&branches, announced);
let compare = current
.filter(|branch| branches.contains(branch))
.unwrap_or_else(|| base.clone());
self.repo_path = Some(PathBuf::from(&path));
self.error = None;
self.branches = branches.into_iter().map(SharedString::from).collect();
if let Some(addr) = self.store.read(cx).addr().cloned() {
CheckoutsStore::global(cx).update(cx, |store, cx| {
store.record(PathBuf::from(&path), addr, cx);
});
}
self.base = SharedString::from(base);
self.compare = SharedString::from(compare);
self.sync_selectors(window, cx);
self.reload_compare(cx);
}
fn sync_selectors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let options: Vec<(SharedString, SharedString)> = self
.branches
.iter()
.map(|branch| (branch.clone(), branch.clone()))
.collect();
let base = self.base.clone();
let compare = self.compare.clone();
self.base_select.update(cx, |state, cx| {
state.set_options(options.clone(), cx);
state.set_selected(Some(base), window, cx);
});
self.compare_select.update(cx, |state, cx| {
state.set_options(options, cx);
state.set_selected(Some(compare), window, cx);
});
}
pub(super) fn fork_candidates(&self, cx: &App) -> Vec<Announcement> {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return Vec::new();
};
let euc = self
.store
.read(cx)
.announcement
.as_ref()
.and_then(|a| a.euc.clone());
let user = Backend::global(cx).read(cx).current_user();
let announcements = RepoListStore::global(cx).read(cx).announcements.clone();
Announcement::forks_in(&announcements, &addr, euc.as_deref(), user)
.into_iter()
.cloned()
.collect()
}
pub(crate) fn choose_fork(
&mut self,
announcement: Announcement,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(base) = self.store.read(cx).addr().cloned() else {
return;
};
let mirror_path = Mirrors::path(&base);
let namespace = GitCache::fork_namespace(&announcement);
let clone_urls: Vec<Url> = announcement.clone.clone();
let base_clone_urls: Vec<Url> = self
.store
.read(cx)
.announcement
.as_ref()
.map(|a| a.clone.clone())
.unwrap_or_default();
self.fork_generation = self.fork_generation.wrapping_add(1);
let generation = self.fork_generation;
let handle = window.window_handle();
self.loading = true;
self.error = None;
cx.notify();
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
let namespace = namespace.clone();
let mirror_path = mirror_path.clone();
async move {
Mirrors::ensure(&base, &base_clone_urls)?;
let repo = Repo::open(&mirror_path)?;
repo.delete_refs_with_prefix("refs/fork")?;
repo.fetch_refs(
&clone_urls,
&format!("+refs/heads/*:refs/fork/{namespace}/*"),
)?;
let strip = |refs: Vec<String>, prefix: &str| {
let mut names: Vec<String> = refs
.into_iter()
.filter_map(|name| {
name.strip_prefix(prefix)
.map(|rest| rest.trim_start_matches('/').to_owned())
})
.filter(|name| !name.is_empty())
.collect();
names.sort();
names
};
let base_branches = strip(
repo.refs_with_prefix("refs/remotes/origin")?,
"refs/remotes/origin",
);
let compare_branches = strip(
repo.refs_with_prefix(&format!("refs/fork/{namespace}"))?,
&format!("refs/fork/{namespace}"),
);
Ok::<_, anyhow::Error>((base_branches, compare_branches))
}
})
.await;
if let Err(error) = cx.update_window(handle, |_, window, cx| {
this.update(cx, |this, cx| {
if generation != this.fork_generation {
return;
}
this.apply_fork(announcement, mirror_path, namespace, result, window, cx);
})
}) {
log::warn!("failed to apply fork: {error}");
}
Ok(())
});
self.push_task(task);
}
fn apply_fork(
&mut self,
announcement: Announcement,
mirror_path: PathBuf,
namespace: String,
result: Result<(Vec<String>, Vec<String>), anyhow::Error>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.loading = false;
let (base_branches, compare_branches) = match result {
Ok(branches) => branches,
Err(error) => {
self.error = Some(format!("Could not compare against the fork: {error}").into());
cx.notify();
return;
}
};
if compare_branches.is_empty() {
self.error = Some("The fork has no branches to compare".into());
cx.notify();
return;
}
if base_branches.is_empty() {
self.error = Some("Could not list the target repository's branches.".into());
cx.notify();
return;
}
let announced = self.store.read(cx).head.clone();
let base = preferred_branch(&base_branches, announced);
let compare = compare_branches
.iter()
.find(|branch| branch.as_str() == "main")
.map(|branch| SharedString::from(branch.clone()))
.unwrap_or_else(|| SharedString::from(compare_branches[0].clone()));
self.fork = Some(ForkCompare {
announcement,
namespace,
mirror_path,
});
self.error = None;
self.base = SharedString::from(base);
self.compare = compare;
self.branches = base_branches.into_iter().map(SharedString::from).collect();
self.sync_selectors(window, cx);
self.reload_compare(cx);
}
pub(super) fn reload_compare(&mut self, cx: &mut Context<Self>) {
let Some(repo_path) = self.work_path() else {
return;
};
let base = self.base_ref();
let compare = self.compare_ref();
let base_name = self.base.to_string();
let compare_name = self.compare.to_string();
self.loading = true;
self.error = None;
self.compare_generation += 1;
let generation = self.compare_generation;
cx.notify();
if base == compare {
self.loading = false;
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
self.error = Some("Choose different base and compare branches".into());
cx.notify();
return;
}
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
async move {
let repo = Repo::open(Path::new(&repo_path))?;
let merge_base = repo.merge_base(&base, &compare)?.ok_or_else(|| {
anyhow::anyhow!(
"{base_name} and {compare_name} share no common ancestor"
)
})?;
let commits = repo.commit_range(&merge_base, &compare)?;
let diff = repo.range_diff(&merge_base, &compare)?;
Ok::<_, anyhow::Error>((merge_base, commits, diff))
}
})
.await;
this.update(cx, |this, cx| {
if generation != this.compare_generation {
return;
}
this.loading = false;
match result {
Ok((merge_base, commits, diff)) => {
this.merge_base = Some(merge_base);
this.commits = Some(Arc::new(commits));
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
}
Err(error) => {
this.merge_base = None;
this.commits = None;
this.pane.update(cx, |pane, cx| pane.clear(cx));
this.error = Some(error.to_string().into());
}
}
cx.notify();
})?;
Ok(())
});
self.push_task(task);
}
}
@@ -11,11 +11,13 @@ use ui::input::{Input, InputState};
use ui::layout::panel::Panel;
use ui::theme::ActiveTheme as _;
use crate::app::AppRoot;
use crate::shared::log_dropped;
use crate::shared::panels::close_detail;
use crate::shared::progress::error_row;
use crate::workspace::Workspace;
pub struct SendPatchView {
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
panel_id: SharedString,
store: Entity<RepoStore>,
subject: Entity<InputState>,
@@ -27,7 +29,7 @@ pub struct SendPatchView {
impl SendPatchView {
pub fn new(
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
panel_id: SharedString,
store: Entity<RepoStore>,
_window: &mut Window,
@@ -82,11 +84,7 @@ impl SendPatchView {
cx.spawn(async move |this, cx| match task.await {
Ok(()) => {
this.update(cx, |this, cx| {
let panel_id = this.panel_id.clone();
crate::shared::log_dropped(
this.workspace
.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)),
);
close_detail(&this.workspace, &this.panel_id, cx)
})
.log_err();
}
@@ -122,7 +120,7 @@ impl SendPatchView {
.loading(self.submitting)
.disabled(!can_submit)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.submit(cx)));
log_dropped(weak.update(cx, |this, cx| this.submit(cx)));
}),
)
.into_any_element()
+3 -3
View File
@@ -3,9 +3,9 @@ use nostr::prelude::EventId;
use signed_core::{Announcement, RepoAddr};
use signed_state::RepoStore;
use crate::app::AppRoot;
use crate::repo::RepoDetailView;
use crate::shared::panels;
use crate::workspace::Workspace;
/// An item of a repository to open from outside its detail panel.
pub enum RepoItem {
@@ -16,7 +16,7 @@ pub enum RepoItem {
/// Opens a repository as the main panel, keyed by its address.
pub fn open_repo_panel(
workspace: &WeakEntity<Workspace>,
workspace: &WeakEntity<AppRoot>,
addr: &RepoAddr,
hint: Option<&Announcement>,
window: &mut Window,
@@ -42,7 +42,7 @@ pub fn open_repo_panel(
/// Opens an issue or pull request using a store built here.
pub fn open_repo_item(
workspace: &WeakEntity<Workspace>,
workspace: &WeakEntity<AppRoot>,
addr: &RepoAddr,
hint: Option<&Announcement>,
item: RepoItem,
+31 -36
View File
@@ -14,20 +14,21 @@ use ui::badge::GroupedBadge;
use ui::button::{Button, ButtonVariant};
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::layout::resizable::{Resizable, ResizableState};
use ui::scrollbar::Scrollbar;
use ui::separator::Separator;
use ui::spinner::Spinner;
use ui::switch::Switch;
use ui::theme::ActiveTheme as _;
use ui::toggle::Toggle;
use ui::tooltip::Tooltip;
use ui::tree::{Tree, TreeItem};
use ui::tree::{Tree, TreeItem, TreeItemSeed};
use utils::relative_time_secs;
use super::helpers::{DiffRow, co_authors, diff_rows, render_diff_row, short_id};
use crate::shared::tree::{TreeItemSeed, TreeRow, build_tree_items, collect_expanded, flatten};
use crate::shared::widgets::{centered_spinner, empty_state, scroll_overlay};
use super::helpers::{DiffRow, co_authors, diff_rows, short_id};
/// Emitted when the user activates the Download commit button.
pub enum DiffPaneEvent {
@@ -59,7 +60,7 @@ pub struct DiffPane {
diff: Option<CommitDiff>,
seeds: Vec<TreeItemSeed>,
expanded: HashSet<String>,
rows: Vec<TreeRow>,
rows: Vec<TreeItem>,
selected_index: Option<usize>,
tree_visible: bool,
split: Entity<ResizableState>,
@@ -103,9 +104,9 @@ impl DiffPane {
.collect();
paths.sort();
self.seeds = build_tree_items(&paths);
self.expanded = collect_expanded(&self.seeds);
self.rows = flatten(&self.seeds, &self.expanded);
self.seeds = TreeItemSeed::from_paths(&paths);
self.expanded = TreeItemSeed::collect_expanded(&self.seeds);
self.rows = TreeItemSeed::flatten_all(&self.seeds, &self.expanded);
self.selected_index = None;
self.diff = Some(diff);
@@ -172,7 +173,10 @@ impl DiffPane {
}
fn select_tree_file(&mut self, path: &str, cx: &mut Context<Self>) {
self.selected_index = self.rows.iter().position(|row| row.id == path);
self.selected_index = self
.rows
.iter()
.position(|row| row.key().to_string() == path);
if self.expanded_files.insert(path.to_owned()) {
self.rebuild_rows();
}
@@ -249,7 +253,7 @@ impl DiffPane {
if !self.expanded.remove(id) {
self.expanded.insert(id.to_owned());
}
self.rows = flatten(&self.seeds, &self.expanded);
self.rows = TreeItemSeed::flatten_all(&self.seeds, &self.expanded);
self.selected_index = self
.selected_index
.and_then(|index| self.rows.get(index).map(|_| index));
@@ -269,22 +273,7 @@ impl DiffPane {
.child(
Tree::new("commit-diff-tree")
.selected(selected)
.items(move |_, _| {
rows.iter()
.map(|row| {
let item = TreeItem::new(row.id.clone(), row.label.clone())
.depth(row.depth)
.expandable(row.expandable)
.expanded(row.expanded);
if row.expandable {
item.icon(Icon::named(IconRole::Folder))
} else {
item.icon(Icon::named(IconRole::File))
}
})
.collect()
})
.items(move |_, _| rows.clone())
.on_change(move |index, window, cx| {
if let Some(index) = index
&& let Err(error) = change_view.update(cx, |this, cx| {
@@ -298,7 +287,7 @@ impl DiffPane {
let view = view;
move |index, _, cx| {
if let Err(error) = view.update(cx, |this, cx| {
let id = this.rows.get(index).map(|row| row.id.clone());
let id = this.rows.get(index).map(|row| row.key().to_string());
if let Some(id) = id {
this.toggle_folder(&id, cx);
}
@@ -315,8 +304,8 @@ impl DiffPane {
let Some(row) = self.rows.get(index) else {
return;
};
let id = row.id.clone();
let expandable = row.expandable;
let id = row.key().to_string();
let expandable = row.is_expandable();
self.selected_index = Some(index);
if expandable {
@@ -427,7 +416,7 @@ impl DiffPane {
fn render_file_list(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(diff) = self.diff.as_ref() else {
return empty_state("No changes");
return EmptyState::centered("No changes");
};
let files = diff.files.clone();
@@ -451,7 +440,7 @@ impl DiffPane {
.size_full()
.p_2(),
)
.child(scroll_overlay("commit-diff-files", self.list.clone()))
.child(Scrollbar::vertical("commit-diff-files", self.list.clone()))
.into_any_element()
}
}
@@ -562,7 +551,7 @@ fn render_pane_row(
.border_color(border)
.bg(surface)
.when(*last, |this| this.border_b_1().rounded_b_lg())
.child(render_diff_row(&file.hunks, *row, wrap, cx))
.child(row.render(&file.hunks, wrap, cx))
.into_any_element()
}
}
@@ -571,13 +560,13 @@ fn render_pane_row(
impl Render for DiffPane {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
if self.diff.is_none() {
return empty_state("No changes");
return EmptyState::centered("No changes");
}
let diff = self.diff.as_ref().expect("diff checked above");
if diff.files.is_empty() {
return empty_state("No files changed");
return EmptyState::centered("No files changed");
}
let toolbar = self.render_toolbar(cx);
@@ -785,9 +774,11 @@ impl CommitDiffView {
.gap_2()
.border_b_1()
.border_color(cx.theme().colors.border)
// The top right corner is the panel toolbar's.
.child(
div()
.min_w_0()
.pr_16()
.font_semibold()
.truncate()
.text_ellipsis()
@@ -893,14 +884,18 @@ impl Panel for CommitDiffView {
fn loading(&self, _cx: &App) -> bool {
self.loading
}
fn toolbar(&self, _cx: &App) -> bool {
true
}
}
impl Render for CommitDiffView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let body = if self.loading {
centered_spinner("commit-diff-loading")
Spinner::centered("commit-diff-loading")
} else if let Some(error) = self.error.clone() {
empty_state(error)
EmptyState::centered(error)
} else {
self.pane.clone().into_any_element()
};
+18 -19
View File
@@ -16,13 +16,15 @@ use ui::input::{Input, InputState};
use ui::tooltip::Tooltip;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::app::AppRoot;
use crate::repo::actions::open_repo_panel;
use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with};
use crate::workspace::Workspace;
use crate::shared::progress::{
DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task_with,
};
/// Progress of the create-repository flow, so async results can be rendered.
pub struct CreateRepoDialog {
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
handle: DialogHandle,
name_input: Entity<InputState>,
desc_input: Entity<InputState>,
@@ -35,11 +37,7 @@ pub struct CreateRepoDialog {
}
impl CreateRepoDialog {
pub fn new(
workspace: WeakEntity<Workspace>,
window: &mut Window,
cx: &mut App,
) -> Entity<Self> {
pub fn new(workspace: WeakEntity<AppRoot>, window: &mut Window, cx: &mut App) -> Entity<Self> {
let settings = SettingsStore::global(cx);
let grasp_settings = settings.read(cx).settings().grasp_servers.clone();
@@ -229,17 +227,18 @@ impl Render for CreateRepoDialog {
let busy = action_state.read(cx).busy;
let this = this.clone();
let create: AnyElement = Button::new("create-repository")
.label("Create repository")
.icon(Icon::named(IconRole::Plus))
.loading(busy)
.disabled(busy)
.on_click(move |_, window, cx| {
crate::shared::log_dropped(
this.update(cx, |this, cx| this.create(window, cx)),
);
})
.into_any_element();
let create: AnyElement = dialog_submit_button(
"create-repository",
"Create repository",
Some(IconRole::Plus),
busy,
&this,
|this, window, cx| {
this.create(window, cx);
Ok(())
},
)
.into_any_element();
vec![create]
})
+16 -14
View File
@@ -9,11 +9,10 @@ use settings::SettingsStore;
use signed_core::RepoAddr;
use signed_git::Repo;
use signed_state::Backend;
use ui::button::Button;
use ui::common::{ResultLogErr as _, v_flex};
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::icons::{Icon, IconRole};
use ui::icons::IconRole;
use ui::input::{Input, InputState};
use ui::layout::h_flex;
use ui::select::{Select, SelectOption};
@@ -21,7 +20,9 @@ use ui::theme::ActiveTheme as _;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::repo::RepoDetailView;
use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with};
use crate::shared::progress::{
DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task_with,
};
pub struct InitRepoDialog {
handle: DialogHandle,
@@ -246,17 +247,18 @@ impl Render for InitRepoDialog {
let busy = action_state.read(cx).busy;
let this = this.clone();
let init: AnyElement = Button::new("initialize-repository")
.label("Initialize")
.icon(Icon::named(IconRole::Plus))
.loading(busy)
.disabled(busy)
.on_click(move |_, window, cx| {
crate::shared::log_dropped(
this.update(cx, |this, cx| this.init_repository(window, cx)),
);
})
.into_any_element();
let init: AnyElement = dialog_submit_button(
"initialize-repository",
"Initialize",
Some(IconRole::Plus),
busy,
&this,
|this, window, cx| {
this.init_repository(window, cx);
Ok(())
},
)
.into_any_element();
vec![init]
})
+27 -40
View File
@@ -10,15 +10,14 @@ use gpui::{
use signed_git::{FileCommit, Repo, WorktreeSnapshot};
use ui::code::CodeViewState;
use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::empty_state::EmptyState;
use ui::markdown::MarkdownViewState;
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _;
use ui::tree::{Tree, TreeItem};
use ui::tree::{Tree, TreeItem, TreeItemSeed};
use super::helpers::{code_language, is_markdown_path, preview_spinner, source_hash};
use super::helpers::{code_language, is_markdown_path, source_hash};
use crate::repo::helpers::short_id;
use crate::shared::tree::{TreeItemSeed, TreeRow, collect_expanded, flatten};
use crate::shared::widgets::empty_state;
const MAX_PREVIEW_BYTES: usize = 1024 * 1024;
const MAX_PREVIEWED_FILES: usize = 32;
@@ -56,7 +55,7 @@ struct CodeView {
pub struct RepoFilesView {
seeds: Vec<TreeItemSeed>,
expanded: HashSet<String>,
rows: Vec<TreeRow>,
rows: Vec<TreeItem>,
selected_index: Option<usize>,
worktree: Option<PathBuf>,
worktree_paths: Vec<String>,
@@ -112,18 +111,19 @@ impl RepoFilesView {
) {
self.worktree_paths = paths;
self.seeds = tree;
let folder_ids = collect_expanded(&self.seeds);
let folder_ids = TreeItemSeed::collect_expanded(&self.seeds);
self.expanded.retain(|id| folder_ids.contains(id));
self.rebuild_rows();
cx.notify();
}
fn rebuild_rows(&mut self) {
self.rows = flatten(&self.seeds, &self.expanded);
self.selected_index = self
.selected_file
.as_ref()
.and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref()));
self.rows = TreeItemSeed::flatten_all(&self.seeds, &self.expanded);
self.selected_index = self.selected_file.as_ref().and_then(|path| {
self.rows
.iter()
.position(|row| row.key().to_string() == path.as_ref())
});
}
fn toggle_folder(&mut self, id: &str) {
@@ -235,8 +235,8 @@ impl RepoFilesView {
let Some(row) = self.rows.get(index) else {
return;
};
let id = row.id.clone();
let expandable = row.expandable;
let id = row.key().to_string();
let expandable = row.is_expandable();
self.selected_index = Some(index);
@@ -261,22 +261,7 @@ impl RepoFilesView {
.child(
Tree::new("repo-tree")
.selected(selected)
.items(move |_, _| {
rows.iter()
.map(|row| {
let item = TreeItem::new(row.id.clone(), row.label.clone())
.depth(row.depth)
.expandable(row.expandable)
.expanded(row.expanded);
if row.expandable {
item.icon(Icon::named(IconRole::Folder))
} else {
item.icon(Icon::named(IconRole::File))
}
})
.collect()
})
.items(move |_, _| rows.clone())
.on_change({
let view = change_view;
move |index, window, cx| {
@@ -293,7 +278,7 @@ impl RepoFilesView {
let view = disclosure_view;
move |index, _, cx| {
if let Err(error) = view.update(cx, |this, cx| {
let id = this.rows.get(index).map(|row| row.id.clone());
let id = this.rows.get(index).map(|row| row.key().to_string());
if let Some(id) = id {
this.toggle_folder(&id);
cx.emit(RepoFilesEvent::Activated);
@@ -319,15 +304,17 @@ impl RepoFilesView {
self.code_element(path.as_ref())
}
}
Some(FileContent::Binary) => empty_state("Binary file - preview not supported"),
Some(FileContent::TooLarge) => empty_state("File is too large to preview"),
Some(FileContent::Failed(message)) => empty_state(message),
None => preview_spinner(),
Some(FileContent::Binary) => {
EmptyState::centered("Binary file - preview not supported")
}
Some(FileContent::TooLarge) => EmptyState::centered("File is too large to preview"),
Some(FileContent::Failed(message)) => EmptyState::centered(message),
None => Spinner::centered("repo-preview-spinner"),
}
} else if self.readme_name.is_some() {
self.markdown_element(None)
} else {
empty_state("No README found")
EmptyState::centered("No README found")
};
let commit = match &self.selected_file {
@@ -426,7 +413,7 @@ impl RepoFilesView {
fn markdown_element(&self, path: Option<&str>) -> AnyElement {
let Some(md) = &self.md else {
return preview_spinner();
return Spinner::centered("repo-preview-spinner");
};
let ready = match path {
@@ -435,7 +422,7 @@ impl RepoFilesView {
};
if !ready {
return preview_spinner();
return Spinner::centered("repo-preview-spinner");
}
div()
@@ -481,10 +468,10 @@ impl RepoFilesView {
fn code_element(&self, path: &str) -> AnyElement {
let Some(code) = &self.code else {
return preview_spinner();
return Spinner::centered("repo-preview-spinner");
};
if code.path.as_ref() != path {
return preview_spinner();
return Spinner::centered("repo-preview-spinner");
}
div()
-455
View File
@@ -1,455 +0,0 @@
use std::collections::HashSet;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, Context, InteractiveElement as _, IntoElement, ParentElement as _, SharedString,
StatefulInteractiveElement as _, Styled as _, Window, div, px,
};
use signed_state::{Backend, Nip34Kind};
use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariant};
use ui::common::{Sizable, StyledExt as _, h_flex, v_flex};
use ui::dropdown_menu::DropdownMenu;
use ui::icons::{Icon, IconRole};
use ui::menu::MenuItem;
use ui::popover::Popover;
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use utils::relative_time_secs;
use super::helpers::{bound_repo_label, clone_group, fork_row, nostr_clone_url, repo_display_name};
use super::{RepoDetailView, actions, dialogs};
use crate::shared::widgets::clone_row;
impl RepoDetailView {
pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(addr) = self
.announcement(cx)
.and_then(|announcement| announcement.upstream.as_ref())
.and_then(|upstream| upstream.addr.clone())
else {
return;
};
actions::open_repo_panel(&self.workspace, &addr, None, window, cx);
}
/// Open the dialog that publishes the local repository to NIP-34.
fn open_init_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(local_path) = self.store.read(cx).path.clone() else {
return;
};
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 {
if self.store.read(cx).addr().is_none() {
return self.render_init_banner(cx);
}
let backend = Backend::global(cx);
let store = self.store.read(cx);
let pushing = store.pushing;
let cloning = store.cloning;
let Some(announcement) = store.announcement.clone() else {
return div().into_any_element();
};
let nip05 = self
.directory
.read(cx)
.profile(&announcement.owner, cx)
.metadata()
.nip05
.clone()
.filter(|nip05| !nip05.trim().is_empty());
let nostr_url = nostr_clone_url(&announcement, nip05.as_deref());
let ngit_command = SharedString::from(format!("git clone {nostr_url}"));
let nak_command = SharedString::from(format!("nak git clone {nostr_url}"));
let git_commands: Vec<String> = announcement.clone_urls();
let name = repo_display_name(self.store.read(cx));
let description = announcement.description();
let avatar = Avatar::new(format!("{}:{}", announcement.owner, announcement.id));
let announcement_for_menu = announcement.clone();
let weak_menu_open = cx.entity().downgrade();
let weak_menu_items = cx.entity().downgrade();
let weak_clone = cx.entity().downgrade();
let weak_download = cx.entity().downgrade();
let ngit_for_popover = ngit_command.clone();
let nak_for_popover = nak_command.clone();
let git_for_popover = git_commands.clone();
h_flex()
.p_6()
.w_full()
.gap_6()
.items_start()
.justify_between()
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_2()
.child(
h_flex()
.gap_2()
.text_sm()
.font_semibold()
.child(avatar)
.child(name),
)
.child(
div()
.min_w_0()
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.line_clamp(3)
.child(description),
)
.when_some(fork_row(&announcement, cx), |this, row| this.child(row)),
)
.child(
h_flex()
.flex_none()
.gap_2()
.justify_end()
.child(
Popover::new("code-popover")
.open(self.clone_open)
.on_change(move |open, _, cx| {
if let Err(error) = weak_clone.update(cx, |this, cx| {
this.clone_open = open;
cx.notify();
}) {
log::warn!("failed to update clone popover: {error}");
}
})
.trigger(move |_, _| {
Button::new("code")
.label("Code")
.icon(Icon::named(IconRole::GitClone))
.tooltip(Tooltip::text("Clone repository"))
.loading(cloning)
.disabled(cloning)
.into_any_element()
})
.content(move |_, cx| {
v_flex()
.w(px(440.))
.p_3()
.gap_4()
.child(clone_group(
"Clone with ngit",
"copy-ngit".into(),
&ngit_for_popover,
cx,
))
.child(clone_group(
"Clone with nak",
"copy-nak".into(),
&nak_for_popover,
cx,
))
.child(
v_flex()
.gap_1()
.child(
div()
.text_xs()
.font_semibold()
.child("Grasp Servers"),
)
.when(git_for_popover.is_empty(), |this| {
this.child(
div()
.text_xs()
.text_center()
.text_color(
cx.theme().colors.muted_foreground,
)
.child("No git clone urls."),
)
})
.children(git_for_popover.iter().enumerate().map(
|(ix, command)| {
clone_row(
SharedString::from(format!(
"copy-git-{ix}"
)),
command.clone().into(),
cx,
)
},
)),
)
.child(
h_flex().justify_end().child(
Button::new("download")
.icon(Icon::named(IconRole::GitClone))
.label("Download")
.on_click({
let weak = weak_download.clone();
move |_, window, cx| {
if let Err(error) =
weak.update(cx, |this, cx| {
this.clone_to_folder(window, cx);
})
{
log::warn!("failed to clone: {error}");
}
}
}),
),
)
.into_any_element()
}),
)
.child(
DropdownMenu::new("repo-menu")
.icon(IconRole::EllipsisVertical)
.variant(ButtonVariant::Ghost)
.disabled(pushing)
.open(self.repo_menu_open)
.on_open_change(move |open, _, cx| {
if let Err(error) = weak_menu_open.update(cx, |this, cx| {
this.repo_menu_open = open;
cx.notify();
}) {
log::warn!("failed to update repo menu: {error}");
}
})
.items(move |_, cx| {
let owner = backend.read(cx).current_user()
== Some(announcement_for_menu.owner);
let mut items = vec![MenuItem::new("About").handler({
let weak = weak_menu_items.clone();
let announcement = announcement_for_menu.clone();
move |_, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.about = Some(dialogs::about::AboutDialog::new(
announcement.clone(),
this.directory.clone(),
cx,
));
cx.notify();
}) {
log::warn!("failed to open about: {error}");
}
}
})];
if owner {
items.push(MenuItem::new("Republish").handler({
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.push_repository(window, cx);
}) {
log::warn!("failed to republish: {error}");
}
}
}));
items.push(MenuItem::new("Reset remote to local").handler({
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.reset_remote(window, cx);
}) {
log::warn!("failed to reset remote: {error}");
}
}
}));
items.push(MenuItem::separator());
items.push(MenuItem::new("Delete").destructive(true).handler(
{
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.delete_repository(window, cx);
}) {
log::warn!("failed to delete: {error}");
}
}
},
));
}
items
}),
),
)
.into_any_element()
}
fn render_init_banner(&self, cx: &mut Context<Self>) -> AnyElement {
let binding = self
.store
.read(cx)
.nip34
.as_ref()
.filter(|binding| binding.kind == Nip34Kind::Initialized);
let path = self
.store
.read(cx)
.path
.as_ref()
.map(|path| path.display().to_string())
.unwrap_or_default();
v_flex()
.flex_none()
.p_6()
.h_32()
.w_full()
.items_center()
.justify_center()
.gap_2()
.map(|this| match binding {
Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)),
None => this.child(
Button::new("init")
.icon(Icon::named(IconRole::ArrowUp))
.label("Initialize on Nostr")
.tooltip(Tooltip::text("Publish this repository to Nostr"))
.on_click(cx.listener(|this, _, window, cx| {
this.open_init_dialog(window, cx);
})),
),
})
.child(
div()
.min_w_0()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(path),
)
.into_any_element()
}
pub(super) fn render_metadata(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.px_6()
.h_12()
.w_full()
.gap_4()
.items_center()
.justify_between()
.child(self.render_maintainers(cx))
.child(self.render_ref_controls(cx))
.into_any_element()
}
fn render_ref_controls(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.justify_end()
.flex_none()
.gap_2()
.when_some(self.render_last_commit(cx), |this, commit| {
this.child(commit)
})
.child(self.refs.branch_select.clone())
.child(self.refs.tag_select.clone())
.into_any_element()
}
fn render_last_commit(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
let commit = self.head_commit.as_ref()?;
let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned();
let history = self.history.clone();
let commit_id = commit.id.clone();
Some(
h_flex()
.id("last-commit")
.h_8()
.px_2()
.gap_2()
.min_w_0()
.rounded(cx.theme().radius.control)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.tooltip(Tooltip::text("View latest commit"))
.on_click(move |_, window, cx| {
history.update(cx, |history, cx| {
history.open_commit_diff(&commit_id, window, cx);
});
})
.child(Icon::named(IconRole::GitCommit).color(cx.theme().colors.muted_foreground))
.child(
div()
.font_family(cx.theme().mono_font)
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(short)),
)
.child(
div()
.max_w(px(220.))
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
)
.child(
div()
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(relative_time_secs(commit.time)),
)
.into_any_element(),
)
}
fn render_maintainers(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(announcement) = self.announcement(cx) else {
return div().into_any_element();
};
let mut seen = HashSet::new();
let rest: Vec<_> = announcement
.maintainers
.iter()
.copied()
.filter(|key| key != &announcement.owner && seen.insert(*key))
.collect();
let owner = self.directory.read(cx).profile(&announcement.owner, cx);
let owner_name = owner.name();
h_flex()
.min_w_0()
.gap_2()
.child(
h_flex()
.gap_2()
.child(
Avatar::new(announcement.owner)
.name(owner_name.clone())
.picture(owner.picture())
.small(),
)
.child(div().text_xs().whitespace_nowrap().child(owner_name)),
)
.when(!rest.is_empty(), |this| {
this.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(format!("+{}", rest.len()))),
)
})
.into_any_element()
}
}
+97 -147
View File
@@ -8,22 +8,92 @@ use gpui::{
};
use metadata::ProfileDirectory;
use nostr::prelude::{RelayUrl, ToBech32};
use signed_core::Announcement;
use signed_core::{Announcement, RepoAddr};
use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo, WorktreeSnapshot};
use signed_state::{Nip34Binding, RepoListStore, RepoStore};
use ui::avatar::Avatar;
use ui::clipboard::CopyRow;
use ui::combobox::ComboboxState;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::theme::ActiveTheme as _;
use utils::relative_time_secs;
use super::RepoDetailView;
use crate::shared::tree::{TreeItemSeed, build_tree_items, sorted_worktree_paths};
use ui::tree::TreeItemSeed;
const GUTTER_WIDTH: f32 = 44.;
pub const DIFF_ROW_HEIGHT: f32 = 20.;
pub const COMMIT_ROW_HEIGHT: f32 = 56.;
#[derive(Clone, Copy)]
pub(super) enum DiffRow {
Hunk {
old_start: u32,
old_lines: u32,
new_start: u32,
new_lines: u32,
},
Line {
hunk: usize,
line: usize,
},
}
impl DiffRow {
/// Renders one diff row against the file's hunks.
pub(super) fn render(self, hunks: &[DiffHunk], wrap: bool, cx: &App) -> AnyElement {
match self {
DiffRow::Hunk {
old_start,
old_lines,
new_start,
new_lines,
} => div()
.px_2()
.w_full()
.h(px(DIFF_ROW_HEIGHT))
.font_family(cx.theme().mono_font)
.text_xs()
.bg(cx.theme().colors.muted)
.border_y_1()
.border_color(cx.theme().colors.border)
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(format!(
"@@ -{},{} +{},{} @@",
old_start, old_lines, new_start, new_lines
)))
.into_any_element(),
DiffRow::Line { hunk, line } => {
match hunks.get(hunk).and_then(|h| h.lines.get(line)) {
Some(line) => render_diff_line(line, wrap, cx),
// A stale row index renders as a blank row rather than panicking.
None => div().w_full().h(px(DIFF_ROW_HEIGHT)).into_any_element(),
}
}
}
}
}
pub(super) struct RepoData {
pub(super) tree: Vec<TreeItemSeed>,
pub(super) entries: Vec<PathBuf>,
pub(super) readme_path: Option<PathBuf>,
pub(super) readme: Option<Vec<u8>>,
pub(super) worktree: Option<PathBuf>,
pub(super) branches: Vec<String>,
pub(super) tags: Vec<String>,
pub(super) current_branch: Option<String>,
pub(super) head_commit: Option<FileCommit>,
}
/// Sorted relative paths of a worktree snapshot.
pub(crate) fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec<String> {
let mut paths: Vec<String> = entries
.iter()
.map(|path| path.to_string_lossy().into_owned())
.collect();
paths.sort();
paths
}
/// The announcement's name, falling back to its id.
pub fn announcement_display_name(announcement: &Announcement) -> SharedString {
@@ -67,43 +137,12 @@ pub(super) fn snapshot_worktree(
worktree: PathBuf,
) -> Result<(WorktreeSnapshot, Vec<TreeItemSeed>, Vec<String>), Error> {
let snapshot = Repo::open(&worktree)?.snapshot()?;
let tree = build_tree_items(&snapshot.entries);
let tree = TreeItemSeed::from_paths(&snapshot.entries);
let paths = sorted_worktree_paths(&snapshot.entries);
Ok((snapshot, tree, paths))
}
#[derive(Clone, Copy)]
pub(super) enum DiffRow {
Hunk {
old_start: u32,
old_lines: u32,
new_start: u32,
new_lines: u32,
},
Line {
hunk: usize,
line: usize,
},
}
pub(super) struct RepoData {
pub(super) tree: Vec<TreeItemSeed>,
pub(super) entries: Vec<PathBuf>,
pub(super) readme_path: Option<PathBuf>,
pub(super) readme: Option<Vec<u8>>,
pub(super) worktree: Option<PathBuf>,
pub(super) branches: Vec<String>,
pub(super) tags: Vec<String>,
pub(super) current_branch: Option<String>,
pub(super) head_commit: Option<FileCommit>,
}
pub(super) fn clone_group(
label: &str,
id: SharedString,
command: &SharedString,
cx: &App,
) -> AnyElement {
pub(super) fn clone_group(label: &str, id: SharedString, command: &SharedString) -> AnyElement {
v_flex()
.gap_1()
.min_w_0()
@@ -113,7 +152,7 @@ pub(super) fn clone_group(
.font_semibold()
.child(SharedString::from(label)),
)
.child(crate::shared::widgets::clone_row(id, command.clone(), cx))
.child(CopyRow::new(id, command.clone()))
.into_any_element()
}
@@ -134,6 +173,23 @@ pub(super) fn nostr_clone_url(announcement: &Announcement, nip05: Option<&str>)
SharedString::from(url)
}
/// The display name of the announcement addressing `addr`, falling back to its identifier.
pub(crate) fn upstream_display_name(
addr: &RepoAddr,
announcements: &[Announcement],
) -> SharedString {
announcements
.iter()
.find(|a| a.addr() == *addr)
.map(|a| {
a.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(a.id.clone()))
})
.unwrap_or_else(|| SharedString::from(addr.identifier().to_owned()))
}
pub(super) fn fork_row(
announcement: &Announcement,
cx: &mut Context<RepoDetailView>,
@@ -142,18 +198,8 @@ pub(super) fn fork_row(
let (label, clickable) = match &upstream.addr {
Some(addr) => {
let name = RepoListStore::global(cx)
.read(cx)
.announcements
.iter()
.find(|a| a.addr() == *addr)
.map(|a| {
a.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(a.id.clone()))
})
.unwrap_or_else(|| SharedString::from(addr.identifier().to_owned()));
let name =
upstream_display_name(addr, &RepoListStore::global(cx).read(cx).announcements);
(SharedString::from(format!("Forked from {name}")), true)
}
None => (SharedString::from(upstream.display().as_str()), false),
@@ -180,7 +226,7 @@ pub(super) fn fork_row(
pub(super) fn load_repo_data(repo: &Repo) -> Result<RepoData, Error> {
let snapshot = repo.snapshot()?;
let worktree = repo.workdir().map(Path::to_path_buf);
let tree = build_tree_items(&snapshot.entries);
let tree = TreeItemSeed::from_paths(&snapshot.entries);
Ok(RepoData {
tree,
@@ -267,10 +313,6 @@ pub(super) fn source_hash(text: &str) -> u64 {
hasher.finish()
}
pub(super) fn preview_spinner() -> AnyElement {
crate::shared::widgets::centered_spinner("repo-preview-spinner")
}
/// The kit grammar for a path; only four languages are supported.
pub(super) fn code_language(path: &str) -> ui::highlight::Language {
use ui::highlight::Language;
@@ -318,41 +360,6 @@ pub(super) fn diff_rows(file: &FileDiff) -> Vec<DiffRow> {
rows
}
pub(super) fn render_diff_row(
hunks: &[DiffHunk],
row: DiffRow,
wrap: bool,
cx: &App,
) -> AnyElement {
match row {
DiffRow::Hunk {
old_start,
old_lines,
new_start,
new_lines,
} => div()
.px_2()
.w_full()
.h(px(DIFF_ROW_HEIGHT))
.font_family(cx.theme().mono_font)
.text_xs()
.bg(cx.theme().colors.muted)
.border_y_1()
.border_color(cx.theme().colors.border)
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(format!(
"@@ -{},{} +{},{} @@",
old_start, old_lines, new_start, new_lines
)))
.into_any_element(),
DiffRow::Line { hunk, line } => match hunks.get(hunk).and_then(|h| h.lines.get(line)) {
Some(line) => render_diff_line(line, wrap, cx),
// A stale row index renders as a blank row rather than panicking.
None => div().w_full().h(px(DIFF_ROW_HEIGHT)).into_any_element(),
},
}
}
fn render_diff_line(line: &DiffLine, wrap: bool, cx: &App) -> AnyElement {
let bg = match line.kind {
DiffLineKind::Addition => Some(cx.theme().ramps.success.base.opacity(0.2)),
@@ -399,63 +406,6 @@ fn render_diff_line(line: &DiffLine, wrap: bool, cx: &App) -> AnyElement {
.into_any_element()
}
pub(crate) fn commit_row(
ix: usize,
commit: &FileCommit,
action: Option<AnyElement>,
on_click: impl Fn(&mut Window, &mut gpui::App) + 'static,
cx: &gpui::App,
) -> gpui::AnyElement {
h_flex()
.id(ix)
.px_4()
.h(px(COMMIT_ROW_HEIGHT))
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.justify_center()
.child(
h_flex()
.gap_2()
.overflow_hidden()
.child(
div()
.font_family(cx.theme().mono_font)
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(short_id(&commit.id)),
)
.child(
div()
.flex_1()
.min_w_0()
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
),
)
.child(
h_flex()
.gap_2()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(commit.author.clone())
.child(relative_time_secs(commit.time)),
),
)
.when_some(action, |row, action| row.child(action))
.on_click(move |_, window, cx| on_click(window, cx))
.into_any_element()
}
pub(super) fn sync_selector(
select: &Entity<ComboboxState<SharedString>>,
cached: &mut Vec<SharedString>,
+8 -7
View File
@@ -12,19 +12,21 @@ use signed_state::{Backend, RepoStore, SyncStatusDirectory};
use ui::alert::{Alert, AlertSeverity, AlertStyle};
use ui::button::{Button, ButtonVariant};
use ui::common::{Sizable as _, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use super::RepoDetailView;
use super::commit_diff::CommitDiffView;
use crate::app::AppRoot;
use crate::shared::event_list::commit_list;
use crate::shared::panels;
use crate::workspace::Workspace;
pub struct RepoHistoryView {
store: Entity<RepoStore>,
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
detail: WeakEntity<RepoDetailView>,
sync_directory: Entity<SyncStatusDirectory>,
worktree: Option<PathBuf>,
@@ -41,7 +43,7 @@ pub struct RepoHistoryView {
impl RepoHistoryView {
pub fn new(
store: Entity<RepoStore>,
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
detail: WeakEntity<RepoDetailView>,
sync_directory: Entity<SyncStatusDirectory>,
) -> Self {
@@ -159,7 +161,7 @@ impl Render for RepoHistoryView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(list) = self.all_commits.as_ref() else {
return if self.loading_all_commits {
crate::shared::widgets::centered_spinner("commits-loading")
Spinner::centered("commits-loading")
} else if let Some(error) = self.error.clone() {
let weak = cx.entity().downgrade();
v_flex()
@@ -183,12 +185,12 @@ impl Render for RepoHistoryView {
)
.into_any_element()
} else {
crate::shared::widgets::empty_state("Failed to load commits")
EmptyState::centered("Failed to load commits")
};
};
if self.commits.is_empty() {
return crate::shared::widgets::empty_state("No commits found");
return EmptyState::centered("No commits found");
}
let commits = Arc::clone(&self.commits);
@@ -261,7 +263,6 @@ impl Render for RepoHistoryView {
log::warn!("failed to open commit diff: {error}");
}
},
cx,
);
v_flex()
+454 -17
View File
@@ -5,48 +5,56 @@ use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, PathPromptOptions, Render, SharedString, Styled as _, Subscription,
SystemNotification, Task, WeakEntity, Window, div,
ParentElement as _, PathPromptOptions, Render, SharedString, StatefulInteractiveElement as _,
Styled as _, Subscription, SystemNotification, Task, WeakEntity, Window, div, px,
};
use metadata::ProfileDirectory;
use nostr::prelude::{PublicKey, Url};
use signed_core::{Announcement, RepoAddr};
use signed_git::{FileCommit, GitCache, Repo};
use signed_state::{
Backend, BackendEvent, LocalReposStore, Mirrors, Nip34Binding, PushStepStatus, RepoStore,
SyncStatusDirectory,
Backend, BackendEvent, LocalReposStore, Mirrors, Nip34Binding, Nip34Kind, PushStepStatus,
RepoStore, SyncStatusDirectory,
};
use ui::alert::{Alert, AlertSeverity};
use ui::avatar::Avatar;
use ui::badge::Badge;
use ui::button::{Button, ButtonVariant};
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::clipboard::CopyRow;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::dialog::Dialog;
use ui::dropdown_menu::DropdownMenu;
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::menu::MenuItem;
use ui::popover::Popover;
use ui::sidebar::{Sidebar, SidebarEntry};
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
pub mod actions;
pub mod commit_diff;
pub mod dialogs;
pub mod files;
mod header;
pub mod helpers;
pub mod history;
pub mod refs;
use files::RepoFilesView;
use helpers::{RepoData, announcement_display_name, load_repo_data, snapshot_worktree};
use helpers::{
RepoData, announcement_display_name, bound_repo_label, clone_group, fork_row, load_repo_data,
nostr_clone_url, repo_display_name, snapshot_worktree,
};
use history::RepoHistoryView;
use refs::RefSwitcher;
use utils::relative_time_secs;
use crate::app::AppRoot;
use crate::issues::IssuesView;
use crate::pull_requests::PullRequestsView;
use crate::repo::helpers::{short_id, sorted_worktree_paths};
use crate::shared::log_dropped;
use crate::shared::tree::sorted_worktree_paths;
use crate::workspace::Workspace;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum RepoSection {
@@ -65,7 +73,7 @@ pub enum RefKind {
}
pub struct RepoDetailView {
pub(super) workspace: WeakEntity<Workspace>,
pub(super) workspace: WeakEntity<AppRoot>,
pub(super) store: Entity<RepoStore>,
about: Option<Entity<dialogs::about::AboutDialog>>,
init: Option<Entity<dialogs::init::InitRepoDialog>>,
@@ -104,7 +112,7 @@ pub struct RepoDetailView {
impl RepoDetailView {
pub fn new(
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
addr: RepoAddr,
hint: Option<Announcement>,
window: &mut Window,
@@ -115,7 +123,7 @@ impl RepoDetailView {
}
pub fn new_local(
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
local_path: PathBuf,
nip34: Option<Nip34Binding>,
window: &mut Window,
@@ -127,7 +135,7 @@ impl RepoDetailView {
/// A local repository whose detected binding matches an announcement.
pub fn new_local_announced(
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
announcement: Announcement,
local_path: PathBuf,
window: &mut Window,
@@ -139,7 +147,7 @@ impl RepoDetailView {
}
fn new_common(
workspace: WeakEntity<Workspace>,
workspace: WeakEntity<AppRoot>,
store: Entity<RepoStore>,
window: &mut Window,
cx: &mut Context<Self>,
@@ -193,7 +201,7 @@ impl RepoDetailView {
let store_for_attach = store.clone();
window.defer(cx, move |window, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.attach_store(&store_for_attach, window, cx);
this.load_repo(window, cx);
}));
@@ -470,6 +478,7 @@ impl RepoDetailView {
if let Ok(Some((moved, snapshot))) = refresh {
let branches: Vec<SharedString> =
snapshot.branches.iter().map(Into::into).collect();
let tags: Vec<SharedString> = snapshot.tags.iter().map(Into::into).collect();
let current_branch = snapshot.current_branch.clone();
let head_commit = snapshot.head_commit.clone();
@@ -828,7 +837,7 @@ impl RepoDetailView {
match result {
Ok(()) => {
if let Some(tag) = &tag {
let short = crate::repo::helpers::short_id(&commit);
let short = short_id(&commit);
let (title, body) = match store.read(cx).last_push_warning.clone() {
Some(warning) => ("Sync partially failed", warning),
None => ("Sync complete", format!("Synced up to {short}")),
@@ -978,7 +987,7 @@ impl RepoDetailView {
(Some(2), true) => RepoSection::PullRequests,
_ => return,
};
crate::shared::log_dropped(weak.update(cx, |this, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.active_section = section;
cx.notify();
}));
@@ -1028,6 +1037,434 @@ impl RepoDetailView {
RepoSection::PullRequests => self.pulls.clone().into_any_element(),
}
}
pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(addr) = self
.announcement(cx)
.and_then(|announcement| announcement.upstream.as_ref())
.and_then(|upstream| upstream.addr.clone())
else {
return;
};
actions::open_repo_panel(&self.workspace, &addr, None, window, cx);
}
/// Open the dialog that publishes the local repository to NIP-34.
fn open_init_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(local_path) = self.store.read(cx).path.clone() else {
return;
};
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 {
if self.store.read(cx).addr().is_none() {
return self.render_init_banner(cx);
}
let backend = Backend::global(cx);
let store = self.store.read(cx);
let pushing = store.pushing;
let cloning = store.cloning;
let Some(announcement) = store.announcement.clone() else {
return div().into_any_element();
};
let nip05 = self
.directory
.read(cx)
.profile(&announcement.owner, cx)
.metadata()
.nip05
.clone()
.filter(|nip05| !nip05.trim().is_empty());
let nostr_url = nostr_clone_url(&announcement, nip05.as_deref());
let ngit_command = SharedString::from(format!("git clone {nostr_url}"));
let nak_command = SharedString::from(format!("nak git clone {nostr_url}"));
let git_commands: Vec<String> = announcement.clone_urls();
let name = repo_display_name(self.store.read(cx));
let description = announcement.description();
let avatar = Avatar::new(format!("{}:{}", announcement.owner, announcement.id));
let announcement_for_menu = announcement.clone();
let weak_menu_open = cx.entity().downgrade();
let weak_menu_items = cx.entity().downgrade();
let weak_clone = cx.entity().downgrade();
let weak_download = cx.entity().downgrade();
let ngit_for_popover = ngit_command.clone();
let nak_for_popover = nak_command.clone();
let git_for_popover = git_commands.clone();
h_flex()
.p_6()
.w_full()
.gap_6()
.items_start()
.justify_between()
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_2()
.child(
h_flex()
.gap_2()
.text_sm()
.font_semibold()
.child(avatar)
.child(name),
)
.child(
div()
.min_w_0()
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.line_clamp(3)
.child(description),
)
.when_some(fork_row(&announcement, cx), |this, row| this.child(row)),
)
.child(
h_flex()
.flex_none()
.gap_2()
.justify_end()
.child(
Popover::new("code-popover")
.open(self.clone_open)
.on_change(move |open, _, cx| {
if let Err(error) = weak_clone.update(cx, |this, cx| {
this.clone_open = open;
cx.notify();
}) {
log::warn!("failed to update clone popover: {error}");
}
})
.trigger(move |_, _| {
Button::new("code")
.label("Code")
.icon(Icon::named(IconRole::GitClone))
.tooltip(Tooltip::text("Clone repository"))
.loading(cloning)
.disabled(cloning)
.into_any_element()
})
.content(move |_, cx| {
v_flex()
.w(px(440.))
.p_3()
.gap_4()
.child(clone_group(
"Clone with ngit",
"copy-ngit".into(),
&ngit_for_popover,
))
.child(clone_group(
"Clone with nak",
"copy-nak".into(),
&nak_for_popover,
))
.child(
v_flex()
.gap_1()
.child(
div()
.text_xs()
.font_semibold()
.child("Grasp Servers"),
)
.when(git_for_popover.is_empty(), |this| {
this.child(
div()
.text_xs()
.text_center()
.text_color(
cx.theme().colors.muted_foreground,
)
.child("No git clone urls."),
)
})
.children(git_for_popover.iter().enumerate().map(
|(ix, command)| {
CopyRow::new(
SharedString::from(format!(
"copy-git-{ix}"
)),
command.clone(),
)
},
)),
)
.child(
h_flex().justify_end().child(
Button::new("download")
.icon(Icon::named(IconRole::GitClone))
.label("Download")
.on_click({
let weak = weak_download.clone();
move |_, window, cx| {
if let Err(error) =
weak.update(cx, |this, cx| {
this.clone_to_folder(window, cx);
})
{
log::warn!("failed to clone: {error}");
}
}
}),
),
)
.into_any_element()
}),
)
.child(
DropdownMenu::new("repo-menu")
.icon(IconRole::EllipsisVertical)
.variant(ButtonVariant::Ghost)
.disabled(pushing)
.open(self.repo_menu_open)
.on_open_change(move |open, _, cx| {
if let Err(error) = weak_menu_open.update(cx, |this, cx| {
this.repo_menu_open = open;
cx.notify();
}) {
log::warn!("failed to update repo menu: {error}");
}
})
.items(move |_, cx| {
let owner = backend.read(cx).current_user()
== Some(announcement_for_menu.owner);
let mut items = vec![MenuItem::new("About").handler({
let weak = weak_menu_items.clone();
let announcement = announcement_for_menu.clone();
move |_, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.about = Some(dialogs::about::AboutDialog::new(
announcement.clone(),
this.directory.clone(),
cx,
));
cx.notify();
}) {
log::warn!("failed to open about: {error}");
}
}
})];
if owner {
items.push(MenuItem::new("Republish").handler({
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.push_repository(window, cx);
}) {
log::warn!("failed to republish: {error}");
}
}
}));
items.push(MenuItem::new("Reset remote to local").handler({
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.reset_remote(window, cx);
}) {
log::warn!("failed to reset remote: {error}");
}
}
}));
items.push(MenuItem::separator());
items.push(MenuItem::new("Delete").destructive(true).handler(
{
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.delete_repository(window, cx);
}) {
log::warn!("failed to delete: {error}");
}
}
},
));
}
items
}),
),
)
.into_any_element()
}
fn render_init_banner(&self, cx: &mut Context<Self>) -> AnyElement {
let binding = self
.store
.read(cx)
.nip34
.as_ref()
.filter(|binding| binding.kind == Nip34Kind::Initialized);
let path = self
.store
.read(cx)
.path
.as_ref()
.map(|path| path.display().to_string())
.unwrap_or_default();
v_flex()
.flex_none()
.p_6()
.h_32()
.w_full()
.items_center()
.justify_center()
.gap_2()
.map(|this| match binding {
Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)),
None => this.child(
Button::new("init")
.icon(Icon::named(IconRole::ArrowUp))
.label("Initialize on Nostr")
.tooltip(Tooltip::text("Publish this repository to Nostr"))
.on_click(cx.listener(|this, _, window, cx| {
this.open_init_dialog(window, cx);
})),
),
})
.child(
div()
.min_w_0()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(path),
)
.into_any_element()
}
pub(super) fn render_metadata(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.px_6()
.h_12()
.w_full()
.gap_4()
.items_center()
.justify_between()
.child(self.render_maintainers(cx))
.child(self.render_ref_controls(cx))
.into_any_element()
}
fn render_ref_controls(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.justify_end()
.flex_none()
.gap_2()
.when_some(self.render_last_commit(cx), |this, commit| {
this.child(commit)
})
.child(self.refs.branch_select.clone())
.child(self.refs.tag_select.clone())
.into_any_element()
}
fn render_last_commit(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
let commit = self.head_commit.as_ref()?;
let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned();
let history = self.history.clone();
let commit_id = commit.id.clone();
Some(
h_flex()
.id("last-commit")
.h_8()
.px_2()
.gap_2()
.min_w_0()
.rounded(cx.theme().radius.control)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.tooltip(Tooltip::text("View latest commit"))
.on_click(move |_, window, cx| {
history.update(cx, |history, cx| {
history.open_commit_diff(&commit_id, window, cx);
});
})
.child(Icon::named(IconRole::GitCommit).color(cx.theme().colors.muted_foreground))
.child(
div()
.font_family(cx.theme().mono_font)
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(short)),
)
.child(
div()
.max_w(px(220.))
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
)
.child(
div()
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(relative_time_secs(commit.time)),
)
.into_any_element(),
)
}
fn render_maintainers(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(announcement) = self.announcement(cx) else {
return div().into_any_element();
};
let mut seen = HashSet::new();
let rest: Vec<_> = announcement
.maintainers
.iter()
.copied()
.filter(|key| key != &announcement.owner && seen.insert(*key))
.collect();
let owner = self.directory.read(cx).profile(&announcement.owner, cx);
let owner_name = owner.name();
h_flex()
.min_w_0()
.gap_2()
.child(
h_flex()
.gap_2()
.child(
Avatar::new(announcement.owner)
.name(owner_name.clone())
.picture(owner.picture())
.small(),
)
.child(div().text_xs().whitespace_nowrap().child(owner_name)),
)
.when(!rest.is_empty(), |this| {
this.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(format!("+{}", rest.len()))),
)
})
.into_any_element()
}
}
impl Panel for RepoDetailView {
+104 -112
View File
@@ -1,11 +1,11 @@
use std::path::PathBuf;
use gpui::{
AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, PathPromptOptions,
SharedString, Styled as _, Window, div, px,
AnyElement, App, AppContext as _, Div, Entity, IntoElement, ParentElement as _,
PathPromptOptions, SharedString, Styled as _, Window, div, px,
};
use settings::{AppearanceMode, EventFetchingStrategy, SettingsStore};
use ui::button::Button;
use ui::button::{Button, ButtonVariant};
use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
@@ -13,8 +13,26 @@ use ui::select::{Select, SelectOption};
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use crate::apply_appearance_mode;
use crate::repo::dialogs::grasp_servers::{normalize_server, server_host};
/// The title and description a settings row or block opens with.
fn setting_header(
cx: &App,
title: impl Into<SharedString>,
description: impl Into<SharedString>,
) -> Div {
v_flex()
.gap_1()
.child(div().text_sm().font_semibold().child(title.into()))
.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(description.into()),
)
}
/// A settings row with the label and description on the left and the control on the right.
pub fn setting_row(
cx: &App,
@@ -26,19 +44,7 @@ pub fn setting_row(
.w_full()
.justify_between()
.gap_4()
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(div().text_sm().font_semibold().child(title.into()))
.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(description.into()),
),
)
.child(setting_header(cx, title, description))
.child(div().w(px(200.)).flex_shrink_0().child(control))
.into_any_element()
}
@@ -53,17 +59,7 @@ pub fn setting_block(
v_flex()
.w_full()
.gap_3()
.child(
v_flex()
.gap_1()
.child(div().text_sm().font_semibold().child(title.into()))
.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(description.into()),
),
)
.child(setting_header(cx, title, description))
.child(control)
.into_any_element()
}
@@ -84,7 +80,7 @@ pub fn appearance_select(cx: &App) -> Select<AppearanceMode> {
SettingsStore::global(cx).update(cx, |store, cx| {
store.edit(|settings| settings.appearance = mode, cx);
});
crate::apply_appearance_mode(mode, cx);
apply_appearance_mode(mode, cx);
})
}
@@ -106,6 +102,36 @@ pub fn event_fetching_select(cx: &App) -> Select<EventFetchingStrategy> {
})
}
/// One editable value: a muted row with a trailing remove button.
fn editor_value_row(
id: String,
text: SharedString,
on_remove: impl Fn(&mut App) + 'static,
cx: &App,
) -> AnyElement {
h_flex()
.gap_1()
.child(
h_flex()
.flex_1()
.h_8()
.px_2()
.bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground)
.text_xs()
.rounded(cx.theme().radius.control)
.child(text),
)
.child(
Button::new(id)
.icon(Icon::named(IconRole::Close))
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click(move |_, _, cx| on_remove(cx)),
)
.into_any_element()
}
pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement {
let store = SettingsStore::global(cx);
let servers = store
@@ -119,48 +145,30 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
.gap_2()
.children(servers.iter().enumerate().map(|(ix, server)| {
let server = server.clone();
h_flex()
.gap_1()
.child(
h_flex()
.flex_1()
.h_8()
.px_2()
.bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground)
.text_xs()
.rounded(cx.theme().radius.control)
.child(display_server(&server)),
)
.child(
Button::new(format!("settings-remove-server:{ix}"))
.icon(Icon::named(IconRole::Close))
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click({
let store = store.clone();
move |_, _, cx| {
store.update(cx, |store, cx| {
store.edit(
|settings| {
// A row's index can desync after a prior
// removal; match by value.
if let Some(at) = settings
.grasp_servers
.default_servers
.iter()
.position(|known| known == &server)
{
settings.grasp_servers.default_servers.remove(at);
}
},
cx,
);
});
}
}),
)
.into_any_element()
editor_value_row(
format!("settings-remove-server:{ix}"),
display_server(&server),
move |cx| {
let store = SettingsStore::global(cx);
store.update(cx, |store, cx| {
store.edit(
|settings| {
// A row's index can desync after a prior removal; match by value.
if let Some(at) = settings
.grasp_servers
.default_servers
.iter()
.position(|known| known == &server)
{
settings.grasp_servers.default_servers.remove(at);
}
},
cx,
);
});
},
cx,
)
}))
.child(
h_flex()
@@ -173,7 +181,7 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
.child(
Button::new("settings-add-server")
.icon(Icon::named(IconRole::Plus))
.variant(ui::button::ButtonVariant::Ghost)
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Add grasp server"))
.on_click({
let input = input.clone();
@@ -229,46 +237,30 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement {
.gap_2()
.children(scan_paths.iter().enumerate().map(|(ix, path)| {
let path = path.clone();
h_flex()
.gap_1()
.child(
h_flex()
.flex_1()
.h_8()
.px_2()
.bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground)
.text_xs()
.rounded(cx.theme().radius.control)
.child(path.display().to_string()),
)
.child(
Button::new(format!("settings-remove-path:{ix}"))
.icon(Icon::named(IconRole::Close))
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click(move |_, _, cx| {
let store = SettingsStore::global(cx);
store.update(cx, |store, cx| {
store.edit(
|settings| {
// A row's index can desync after a prior
// removal; match by value.
if let Some(at) = settings
.local_repos
.scan_paths
.iter()
.position(|known| known == &path)
{
settings.local_repos.scan_paths.remove(at);
}
},
cx,
);
});
}),
)
.into_any_element()
editor_value_row(
format!("settings-remove-path:{ix}"),
SharedString::from(path.display().to_string()),
move |cx| {
let store = SettingsStore::global(cx);
store.update(cx, |store, cx| {
store.edit(
|settings| {
// A row's index can desync after a prior removal; match by value.
if let Some(at) = settings
.local_repos
.scan_paths
.iter()
.position(|known| known == &path)
{
settings.local_repos.scan_paths.remove(at);
}
},
cx,
);
});
},
cx,
)
}))
.child(
h_flex().justify_end().child(
@@ -328,7 +320,7 @@ pub fn default_folder_selector(default_folder: &Entity<InputState>) -> AnyElemen
.child(
Button::new("settings-choose-folder")
.icon(Icon::named(IconRole::Folder))
.variant(ui::button::ButtonVariant::Ghost)
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Choose folder"))
.on_click(move |_, window, cx| {
choose_default_folder(&folder, window, cx);
+137 -75
View File
@@ -15,30 +15,22 @@ use signed_core::RepoStatus;
use signed_git::FileCommit;
use ui::avatar::Avatar;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::scrollbar::Scrollbar;
use ui::theme::ActiveTheme as _;
use utils::relative_time_secs;
use crate::repo::helpers::commit_row;
use crate::shared::widgets::{empty_state, scroll_overlay, status_badge};
use crate::repo::helpers::short_id;
use crate::shared::widgets::status_badge;
/// The height of one issue or pull-request row.
pub const ROW_HEIGHT: f32 = 73.;
/// The height of one commit row in the commit list.
pub const COMMIT_ROW_HEIGHT: f32 = 56.;
/// A row's activation handler.
pub type EventHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
/// The toolbar above the issue and pull-request lists: a filter and its actions.
pub fn filter_toolbar(cx: &App, children: impl IntoIterator<Item = AnyElement>) -> AnyElement {
h_flex()
.px_4()
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.bg(cx.theme().colors.muted)
.children(children)
.into_any_element()
}
/// One issue or pull-request row's display data and click handler.
pub struct EventRow {
pub id: ElementId,
@@ -52,8 +44,68 @@ pub struct EventRow {
pub on_click: EventHandler,
}
/// The shared issue and pull-request list: toolbar, uniform rows, scrollbar
/// overlay, and empty state.
impl EventRow {
/// Renders one issue or pull-request row.
fn render(&self, row_height: Pixels, cx: &App) -> AnyElement {
h_flex()
.id(self.id.clone())
.w_full()
.h(row_height)
.gap_4()
.px_4()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.on_click({
let on_click = self.on_click.clone();
move |event, window, cx| on_click(event, window, cx)
})
.child(status_badge(self.status))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(
div()
.text_base()
.text_ellipsis()
.whitespace_nowrap()
.child(self.title.clone()),
)
.child(self.meta_row(cx)),
)
.into_any_element()
}
/// The author, age, and id line under a row's title.
fn meta_row(&self, cx: &App) -> AnyElement {
h_flex()
.gap_2()
.text_xs()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(self.pubkey)
.name(self.author.clone())
.picture(self.picture.clone())
.small(),
)
.child(div().child(self.author.clone())),
)
.child(SharedString::from("opened"))
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(self.short_id.clone()),
)
.child(self.age.clone())
.into_any_element()
}
}
/// The shared issue and pull-request list,
pub struct EventList {
id: ElementId,
toolbar: Option<AnyElement>,
@@ -118,86 +170,39 @@ impl EventList {
let Some(row) = rows.get(ix) else {
return div().into_any_element();
};
event_row(row, row_height, cx)
row.render(row_height, cx)
})
.collect()
})
.track_scroll(&self.scroll_handle)
.size_full(),
)
.child(scroll_overlay(
.child(Scrollbar::vertical(
(self.id.clone(), "scroll"),
self.scroll_handle.clone(),
))
})
.when(count == 0, |this| {
this.child(empty_state(self.empty_message))
this.child(EmptyState::centered(self.empty_message))
})
.into_any_element()
}
}
/// Renders one issue or pull-request row.
pub fn event_row(row: &EventRow, row_height: Pixels, cx: &App) -> AnyElement {
/// The toolbar above the issue and pull-request lists: a filter and its actions.
pub fn filter_toolbar(cx: &App, children: impl IntoIterator<Item = AnyElement>) -> AnyElement {
h_flex()
.id(row.id.clone())
.w_full()
.h(row_height)
.gap_4()
.px_4()
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.on_click({
let on_click = row.on_click.clone();
move |event, window, cx| on_click(event, window, cx)
})
.child(status_badge(row.status))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(
div()
.text_base()
.text_ellipsis()
.whitespace_nowrap()
.child(row.title.clone()),
)
.child(event_meta_row(row, cx)),
)
.into_any_element()
}
/// The author, age, and id line under a row's title.
pub fn event_meta_row(row: &EventRow, cx: &App) -> AnyElement {
h_flex()
.gap_2()
.text_xs()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(row.pubkey)
.name(row.author.clone())
.picture(row.picture.clone())
.small(),
)
.child(div().child(row.author.clone())),
)
.child(SharedString::from("opened"))
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(row.short_id.clone()),
)
.child(row.age.clone())
.bg(cx.theme().colors.muted)
.children(children)
.into_any_element()
}
/// A scrollable commit list: uniform `commit_row`s under a scrollbar overlay.
#[allow(clippy::too_many_arguments)]
pub fn commit_list(
id: &'static str,
scroll_id: &'static str,
@@ -205,7 +210,6 @@ pub fn commit_list(
scroll_handle: UniformListScrollHandle,
action: impl Fn(usize, &FileCommit, &App) -> Option<AnyElement> + 'static,
on_click: impl Fn(&FileCommit, &mut Window, &mut App) + Clone + 'static,
_cx: &App,
) -> AnyElement {
let count = commits.len();
@@ -234,6 +238,64 @@ pub fn commit_list(
.track_scroll(&scroll_handle)
.size_full(),
)
.child(scroll_overlay(scroll_id, scroll_handle))
.child(Scrollbar::vertical(scroll_id, scroll_handle))
.into_any_element()
}
/// One copyable commit summary row: id, subject, author, and age.
pub(crate) fn commit_row(
ix: usize,
commit: &FileCommit,
action: Option<AnyElement>,
on_click: impl Fn(&mut Window, &mut gpui::App) + 'static,
cx: &gpui::App,
) -> gpui::AnyElement {
h_flex()
.id(ix)
.px_4()
.h(px(COMMIT_ROW_HEIGHT))
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.justify_center()
.child(
h_flex()
.gap_2()
.overflow_hidden()
.child(
div()
.font_family(cx.theme().mono_font)
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(short_id(&commit.id)),
)
.child(
div()
.flex_1()
.min_w_0()
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
),
)
.child(
h_flex()
.gap_2()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(commit.author.clone())
.child(relative_time_secs(commit.time)),
),
)
.when_some(action, |row, action| row.child(action))
.on_click(move |_, window, cx| on_click(window, cx))
.into_any_element()
}
+1 -1
View File
@@ -5,7 +5,7 @@ use nostr::prelude::PublicKey;
pub mod event_list;
pub mod panels;
pub mod progress;
pub mod tree;
pub mod widgets;
/// Logs a discarded `Result` with its source location instead of dropping it silently.
+42 -46
View File
@@ -1,13 +1,35 @@
use std::sync::Arc;
use gpui::{App, AppContext, Entity, SharedString, WeakEntity, Window};
use ui::layout::panel::{Panel, PanelSlot};
use gpui::{App, Entity, SharedString, WeakEntity, Window};
use ui::layout::panel::{Panel, PanelView};
use crate::app::AppRoot;
use crate::shared::log_dropped;
use crate::workspace::Workspace;
/// Opens a panel in `slot`, reusing it when it is already open.
fn open_slot<P, F>(
slot: PanelSlot,
workspace: &WeakEntity<AppRoot>,
id: impl Into<SharedString>,
build: F,
window: &mut Window,
cx: &mut App,
) where
P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{
let result = workspace.update(cx, |workspace, cx| {
workspace
.panels()
.clone()
.update(cx, |panels, cx| panels.open(slot, id, build, window, cx))
});
if let Err(error) = result {
log::warn!("failed to open panel: {error}");
}
}
/// Opens a repository in the main panel, reusing it when it is already cached.
/// Opens a repository in the main panel, reusing it when it is already open.
pub fn open_primary<P, F>(
workspace: &WeakEntity<Workspace>,
workspace: &WeakEntity<AppRoot>,
id: impl Into<SharedString>,
build: F,
window: &mut Window,
@@ -16,30 +38,12 @@ pub fn open_primary<P, F>(
P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{
let id = id.into();
if workspace
.read_with(cx, |workspace, _| workspace.has_main(&id))
.unwrap_or(false)
{
if let Err(error) = workspace.update(cx, |workspace, cx| workspace.activate_main(&id, cx)) {
log::warn!("failed to activate repository {id}: {error}");
}
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
if let Err(error) = workspace.update(cx, |workspace, cx| {
workspace.show_main(id.clone(), view, cx)
}) {
log::warn!("failed to open repository {id}: {error}");
}
open_slot(PanelSlot::Main, workspace, id, build, window, cx);
}
/// Opens a detail panel beside the main panel, reusing it when it is already cached.
/// Opens a detail panel beside the main panel, reusing it when it is already open.
pub fn open_detail<P, F>(
workspace: &WeakEntity<Workspace>,
workspace: &WeakEntity<AppRoot>,
id: impl Into<SharedString>,
build: F,
window: &mut Window,
@@ -48,24 +52,16 @@ pub fn open_detail<P, F>(
P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{
let id = id.into();
open_slot(PanelSlot::Split, workspace, id, build, window, cx);
}
if workspace
.read_with(cx, |workspace, _| workspace.has_detail(&id))
.unwrap_or(false)
{
if let Err(error) = workspace.update(cx, |workspace, cx| workspace.activate_detail(&id, cx))
{
log::warn!("failed to activate detail panel {id}: {error}");
}
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
if let Err(error) = workspace.update(cx, |workspace, cx| {
workspace.show_detail(id.clone(), view, cx)
}) {
log::warn!("failed to open detail panel {id}: {error}");
}
/// Closes the detail panel open under `id`.
pub fn close_detail(workspace: &WeakEntity<AppRoot>, id: &SharedString, cx: &mut impl AppContext) {
let result = workspace.update(cx, |workspace, cx| {
workspace
.panels()
.clone()
.update(cx, |panels, cx| panels.close(PanelSlot::Split, id, cx))
});
log_dropped(result);
}
+31 -1
View File
@@ -1,15 +1,45 @@
use gpui::{
AnyElement, App, AsyncApp, Context, Entity, IntoElement as _, ParentElement as _, SharedString,
Styled as _, Subscription, Task, div,
Styled as _, Subscription, Task, WeakEntity, Window, div,
};
use signed_core::RepoAddr;
use signed_state::{Backend, BackendEvent, PushStepStatus};
use ui::button::Button;
use ui::common::{h_flex, v_flex};
use ui::dialog::DialogHandle;
use ui::icons::{Icon, IconRole};
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _;
use super::log_dropped;
/// The dialog's submit button: loading/disabled while busy, closing over the dialog's submit.
pub fn dialog_submit_button<T, F>(
id: &'static str,
label: impl Into<SharedString>,
icon: Option<IconRole>,
busy: bool,
this: &WeakEntity<T>,
submit: F,
) -> Button
where
T: 'static,
F: Fn(&mut T, &mut Window, &mut Context<T>) -> Result<(), anyhow::Error> + 'static,
{
let mut button = Button::new(id).label(label);
if let Some(icon) = icon {
button = button.icon(Icon::named(icon));
}
let this = this.clone();
button
.loading(busy)
.disabled(busy)
.on_click(move |_, window, cx| {
log_dropped(this.update(cx, |this, cx| submit(this, window, cx)));
})
}
/// Progress of an async dialog action: a busy flag that disables the form and an error shown below it.
#[derive(Debug, Default)]
pub struct DialogProgress {
-188
View File
@@ -1,188 +0,0 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
pub struct TreeItemSeed {
/// Path of the node, relative to the worktree root.
pub id: String,
pub label: String,
pub children: Vec<TreeItemSeed>,
}
/// One visible row of the flattened tree.
#[derive(Clone)]
pub struct TreeRow {
pub id: String,
pub label: String,
pub depth: usize,
pub expandable: bool,
pub expanded: bool,
}
/// Flattens the seeds into the rows a flat tree renders, honoring `expanded`.
pub fn flatten(seeds: &[TreeItemSeed], expanded: &HashSet<String>) -> Vec<TreeRow> {
fn push(
seed: &TreeItemSeed,
depth: usize,
expanded: &HashSet<String>,
rows: &mut Vec<TreeRow>,
) {
let is_expanded = expanded.contains(&seed.id);
rows.push(TreeRow {
id: seed.id.clone(),
label: seed.label.clone(),
depth,
expandable: !seed.children.is_empty(),
expanded: is_expanded,
});
if is_expanded {
for child in &seed.children {
push(child, depth + 1, expanded, rows);
}
}
}
let mut rows = Vec::new();
for seed in seeds {
push(seed, 0, expanded, &mut rows);
}
rows
}
/// Every folder id, for starting with the tree fully expanded.
pub fn collect_expanded(seeds: &[TreeItemSeed]) -> HashSet<String> {
fn push(seed: &TreeItemSeed, expanded: &mut HashSet<String>) {
if !seed.children.is_empty() {
expanded.insert(seed.id.clone());
for child in &seed.children {
push(child, expanded);
}
}
}
let mut expanded = HashSet::new();
for seed in seeds {
push(seed, &mut expanded);
}
expanded
}
/// Build nested tree items from a flat entry list sorted dirs-first.
pub fn build_tree_items(entries: &[PathBuf]) -> Vec<TreeItemSeed> {
// Node indices by full path, so parents resolve in constant time while inserting.
let mut index: HashMap<String, usize> = HashMap::new();
let mut nodes: Vec<(String, String, Vec<usize>)> = Vec::new();
let mut roots: Vec<usize> = Vec::new();
for entry in entries {
let mut parent: Option<usize> = None;
let mut path = String::new();
for part in entry.components() {
let label = part.as_os_str().to_string_lossy().into_owned();
path = if path.is_empty() {
label.clone()
} else {
format!("{path}/{label}")
};
let ix = *index.entry(path.clone()).or_insert_with(|| {
let ix = nodes.len();
nodes.push((path.clone(), label.clone(), Vec::new()));
match parent {
Some(parent) => nodes[parent].2.push(ix),
None => roots.push(ix),
}
ix
});
parent = Some(ix);
}
}
fn assemble(ix: usize, nodes: &[(String, String, Vec<usize>)]) -> TreeItemSeed {
let (id, label, children) = &nodes[ix];
TreeItemSeed {
id: id.clone(),
label: label.clone(),
children: children
.iter()
.map(|child| assemble(*child, nodes))
.collect(),
}
}
roots.iter().map(|root| assemble(*root, &nodes)).collect()
}
/// Sorted relative paths of a worktree snapshot.
pub fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec<String> {
let mut paths: Vec<String> = entries
.iter()
.map(|path| path.to_string_lossy().into_owned())
.collect();
paths.sort();
paths
}
#[cfg(test)]
mod tests {
use super::*;
fn ids(rows: &[TreeRow]) -> Vec<(&str, usize)> {
rows.iter()
.map(|row| (row.id.as_str(), row.depth))
.collect()
}
#[test]
fn collapsed_folders_hide_children() {
let seeds = build_tree_items(&[
PathBuf::from("src"),
PathBuf::from("src/lib.rs"),
PathBuf::from("README.md"),
]);
let rows = flatten(&seeds, &HashSet::new());
assert_eq!(ids(&rows), vec![("src", 0), ("README.md", 0)]);
assert!(rows[0].expandable);
assert!(!rows[0].expanded);
}
#[test]
fn expanding_a_folder_shows_children_in_order() {
let seeds = build_tree_items(&[
PathBuf::from("src"),
PathBuf::from("src/lib.rs"),
PathBuf::from("src/views/mod.rs"),
PathBuf::from("README.md"),
]);
let expanded = HashSet::from(["src".to_owned(), "src/views".to_owned()]);
let rows = flatten(&seeds, &expanded);
assert_eq!(
ids(&rows),
vec![
("src", 0),
("src/lib.rs", 1),
("src/views", 1),
("src/views/mod.rs", 2),
("README.md", 0),
]
);
}
#[test]
fn indices_map_to_row_ids() {
let seeds = build_tree_items(&[
PathBuf::from("docs"),
PathBuf::from("docs/guide.md"),
PathBuf::from("README.md"),
]);
let expanded = HashSet::from(["docs".to_owned()]);
let rows = flatten(&seeds, &expanded);
assert_eq!(rows[0].id, "docs");
assert_eq!(rows[1].id, "docs/guide.md");
assert_eq!(rows[2].id, "README.md");
}
}
-81
View File
@@ -1,15 +1,6 @@
use gpui::{
AnyElement, App, ElementId, IntoElement, ParentElement as _, SharedString, Styled as _, div,
};
use signed_core::RepoStatus;
use ui::badge::{Badge, BadgeVariant};
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::scrollbar::{Scrollbar, ScrollbarHandle};
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
/// The status pill shown on issue and pull-request rows.
@@ -26,75 +17,3 @@ pub fn status_badge(status: RepoStatus) -> Badge {
.icon(Icon::named(icon))
.tooltip(Tooltip::text(label))
}
/// A centered empty-state message filling the available space.
pub fn empty_state(message: impl Into<SharedString>) -> AnyElement {
let message = message.into();
v_flex()
.size_full()
.items_center()
.justify_center()
.child(EmptyState::new(message))
.into_any_element()
}
/// A centered spinner filling the available space.
pub fn centered_spinner(id: impl Into<ElementId>) -> AnyElement {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new(id))
.into_any_element()
}
/// The vertical scrollbar pinned over a uniform list's full extent.
pub fn scroll_overlay<I, H>(id: I, handle: H) -> AnyElement
where
I: Into<ElementId>,
H: ScrollbarHandle,
{
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(id, handle))
.into_any_element()
}
/// One copyable clone command with its text visible next to the copy icon.
pub fn clone_row(id: SharedString, command: SharedString, cx: &App) -> AnyElement {
h_flex()
.h_8()
.px_2()
.gap_2()
.min_w_0()
.bg(cx.theme().colors.secondary)
.rounded(cx.theme().radius.control)
.text_color(cx.theme().colors.secondary_foreground)
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.font_family(cx.theme().mono_font)
.text_xs()
.child(command.clone()),
)
.child(ClipboardButton::new(id, command).xsmall())
.into_any_element()
}
/// A one-line muted label used by section headers.
pub fn section_label(text: impl Into<SharedString>, cx: &App) -> AnyElement {
div()
.text_xs()
.font_medium()
.text_color(cx.theme().colors.muted_foreground)
.child(text.into())
.into_any_element()
}
+64 -141
View File
@@ -2,7 +2,7 @@ use std::rc::Rc;
use std::sync::Arc;
use gpui::{
AnyElement, AnyView, App, AppContext as _, Context, Entity, IntoElement, KeyBinding,
AnyElement, App, AppContext as _, Context, Entity, IntoElement, KeyBinding,
KeyBindingContextPredicate, ParentElement as _, SharedString, Subscription, WeakEntity, Window,
};
use metadata::{Profile, ProfileDirectory};
@@ -15,17 +15,16 @@ use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariant};
use ui::command_palette::{Command, CommandPalette, CommandPaletteState};
use ui::icons::{Icon, IconRole};
use ui::layout::panel::PanelView;
use ui::layout::root::RootContext as _;
use ui::menu::{Menu, MenuItem};
use ui::tabs::{Tab, Tabs, TabsVariant};
use ui::tooltip::Tooltip;
use crate::app::AppRoot;
use crate::explore::ExploreView;
use crate::identity::exit::ExitDialog;
use crate::repo::{RepoDetailView, actions, dialogs};
use crate::settings::SettingsDialog;
use crate::shared::{log_dropped, panels};
use crate::workspace::Workspace;
mod repository_switcher;
@@ -56,83 +55,33 @@ pub(crate) struct SwitchRepository {
#[action(namespace = signed, no_json)]
pub(crate) struct CreateRepository;
pub(crate) fn bind_repository_shortcuts(cx: &mut App) {
let context = match KeyBindingContextPredicate::parse(REPOSITORY_KEY_CONTEXT) {
Ok(context) => Some(Rc::new(context)),
Err(error) => {
log::error!("failed to parse repository key context: {error}");
return;
}
};
let bindings = REPOSITORY_KEYSTROKES
.into_iter()
.enumerate()
.map(|(index, keystroke)| {
KeyBinding::load(
keystroke,
Box::new(SwitchRepository { index }),
context.clone(),
false,
None,
cx,
)
})
.chain(std::iter::once(KeyBinding::load(
CREATE_KEYSTROKE,
Box::new(CreateRepository),
context.clone(),
false,
None,
cx,
)))
.collect::<Result<Vec<_>, _>>();
let bindings = match bindings {
Ok(bindings) => bindings,
Err(error) => {
log::error!("failed to parse repository shortcut keystrokes: {error}");
return;
}
};
cx.bind_keys(bindings);
}
pub struct TitlebarView {
weak: WeakEntity<Self>,
workspace: WeakEntity<Workspace>,
app: WeakEntity<AppRoot>,
/// User's announced repositories.
announcements: Arc<Vec<Announcement>>,
/// Local repositories found by the scan that are not announced yet.
local_repos: Arc<Vec<ResolvedLocalRepo>>,
/// Profiles rendered by the repository switcher.
directory: Entity<ProfileDirectory>,
/// The command palette opened from the titlebar.
palette: Entity<CommandPaletteState>,
repository_switcher: Entity<RepositorySwitcher>,
settings: Option<Entity<SettingsDialog>>,
exit: Option<Entity<ExitDialog>>,
create: Option<Entity<dialogs::create::CreateRepoDialog>>,
user_menu_open: bool,
_subscriptions: Vec<Subscription>,
}
impl TitlebarView {
pub fn new(
workspace: WeakEntity<Workspace>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
pub fn new(app: WeakEntity<AppRoot>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let backend = Backend::global(cx);
let repos = RepoListStore::global(cx);
let local = LocalReposStore::global(cx);
let weak = cx.entity().downgrade();
let palette = Self::new_palette(weak.clone(), window, cx);
let directory = ProfileDirectory::new(cx);
let entity = cx.entity();
let weak = entity.downgrade();
let palette = Self::new_palette(weak.clone(), window, cx);
cx.open_palette(palette);
let mut subscriptions = Vec::new();
let repository_switcher = cx.new(|cx| {
@@ -195,15 +144,11 @@ impl TitlebarView {
Self {
weak: cx.entity().downgrade(),
workspace,
app,
announcements: Arc::new(Vec::new()),
local_repos: Arc::new(Vec::new()),
directory,
palette,
repository_switcher,
settings: None,
exit: None,
create: None,
user_menu_open: false,
_subscriptions: subscriptions,
}
@@ -258,10 +203,6 @@ impl TitlebarView {
]
}
pub fn palette(&self) -> Entity<CommandPaletteState> {
self.palette.clone()
}
fn refresh(&mut self, cx: &mut Context<Self>) -> bool {
let backend = Backend::global(cx);
let user = backend.read(cx).current_user();
@@ -351,57 +292,6 @@ impl TitlebarView {
self.repository_switcher.clone()
}
/// Tabs for the repositories opened in the main panel.
pub fn render_repo_tabs(&self, workspace: &Workspace) -> Option<Tabs> {
let open = workspace.open_mains();
if open.is_empty() {
return None;
}
let tabs: Vec<_> = open
.iter()
.map(|id| (id.clone(), workspace.main_view(id)))
.collect();
let selected = workspace
.active_main_id()
.and_then(|id| open.iter().position(|open_id| open_id == id))
.unwrap_or(usize::MAX);
let change_workspace = self.workspace.clone();
let close_workspace = self.workspace.clone();
let open_for_change = open.to_vec();
Some(
Tabs::new("signed-repo-tabs")
.variant(TabsVariant::Titlebar)
.overflow_scroll(true)
.selected(selected)
.tabs(move |_, cx| {
tabs.iter()
.map(|(id, view)| match view {
Some(view) => view.tab(id.clone().into(), cx).closeable(true),
None => Tab::new(id.clone(), id.clone()).closeable(true),
})
.collect()
})
.on_change(move |index, _, cx| {
let Some(id) = open_for_change.get(index).cloned() else {
return;
};
log_dropped(change_workspace.update(cx, |workspace, cx| {
workspace.activate_main(&id, cx);
}));
})
.on_close(move |index, _, cx| {
log_dropped(close_workspace.update(cx, |workspace, cx| {
workspace.close_main_at(index, cx);
}));
}),
)
}
pub(crate) fn activate_shortcut(
&mut self,
index: usize,
@@ -420,37 +310,27 @@ impl TitlebarView {
}
fn open_settings(&mut self, cx: &mut Context<Self>) {
self.settings = Some(SettingsDialog::new(cx));
let dialog = SettingsDialog::new(cx);
cx.open_dialog(dialog);
cx.notify();
}
fn open_exit(&mut self, cx: &mut Context<Self>) {
self.exit = Some(ExitDialog::new(cx));
let dialog = ExitDialog::new(cx);
cx.open_dialog(dialog);
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);
let view = dialogs::create::CreateRepoDialog::new(self.app.clone(), window, cx);
cx.open_dialog(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>) {
if let Some(announcement) = self.announcements.get(index) {
let addr = announcement.addr();
actions::open_repo_panel(&self.workspace, &addr, Some(announcement), window, cx);
actions::open_repo_panel(&self.app, &addr, Some(announcement), window, cx);
return;
}
@@ -479,7 +359,7 @@ impl TitlebarView {
if let Some(announcement) = announcement {
let id = SharedString::from(format!("repo:{}", announcement.addr()));
let workspace = self.workspace.clone();
let workspace = self.app.clone();
let workspace_for_build = workspace.clone();
panels::open_primary(
&workspace,
@@ -502,7 +382,7 @@ impl TitlebarView {
}
let id = SharedString::from(format!("repo-local:{}", path.display()));
let workspace = self.workspace.clone();
let workspace = self.app.clone();
let workspace_for_build = workspace.clone();
panels::open_primary(
@@ -534,7 +414,7 @@ impl TitlebarView {
}
pub fn render_explore(&self) -> AnyElement {
let workspace = self.workspace.clone();
let workspace = self.app.clone();
Button::new("open-explore")
.icon(IconRole::Grid)
@@ -626,3 +506,46 @@ fn local_key(entry: &ResolvedLocalRepo) -> SharedString {
None => SharedString::from(format!("repo-local:{}", entry.path.display())),
}
}
pub(crate) fn bind_repository_shortcuts(cx: &mut App) {
let context = match KeyBindingContextPredicate::parse(REPOSITORY_KEY_CONTEXT) {
Ok(context) => Some(Rc::new(context)),
Err(error) => {
log::error!("failed to parse repository key context: {error}");
return;
}
};
let bindings = REPOSITORY_KEYSTROKES
.into_iter()
.enumerate()
.map(|(index, keystroke)| {
KeyBinding::load(
keystroke,
Box::new(SwitchRepository { index }),
context.clone(),
false,
None,
cx,
)
})
.chain(std::iter::once(KeyBinding::load(
CREATE_KEYSTROKE,
Box::new(CreateRepository),
context.clone(),
false,
None,
cx,
)))
.collect::<Result<Vec<_>, _>>();
let bindings = match bindings {
Ok(bindings) => bindings,
Err(error) => {
log::error!("failed to parse repository shortcut keystrokes: {error}");
return;
}
};
cx.bind_keys(bindings);
}
@@ -165,12 +165,6 @@ impl Render for RepositorySwitcher {
let list_weak = row_weak.clone();
let list_on_open = on_open.clone();
let list_scroll_handle = scroll_handle.clone();
let create_hint = Kbd::binding_for_action(
&CreateRepository,
Some(REPOSITORY_KEY_CONTEXT),
window,
);
v_flex()
.w(px(380.))
.p_2()
@@ -265,7 +259,14 @@ impl Render for RepositorySwitcher {
.full_width(true)
.icon(Icon::named(IconRole::CirclePlus))
.child(div().flex_1().child("Create Repository"))
.when_some(create_hint, |button, hint| button.child(hint))
.when_some(
Kbd::binding_for_action(
&CreateRepository,
Some(REPOSITORY_KEY_CONTEXT),
window,
),
|button, hint| button.child(hint),
)
.on_click(move |_, window, cx| {
log_dropped(create_weak.update(cx, |this, cx| {
this.close(cx);
-243
View File
@@ -1,243 +0,0 @@
use std::collections::HashMap;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div,
};
use ui::common::v_flex;
use ui::layout::panel::{Panel, PanelView};
use ui::tabs::{Tab, Tabs, TabsVariant};
use crate::shared::log_dropped;
/// The repository shown in the main panel and the detail panels opened beside it.
#[derive(Default)]
pub struct Workspace {
main: Option<SharedString>,
main_order: Vec<SharedString>,
main_views: HashMap<SharedString, Arc<dyn PanelView>>,
details: Vec<SharedString>,
detail_views: HashMap<SharedString, Arc<dyn PanelView>>,
active_detail: Option<SharedString>,
}
impl Workspace {
pub fn new() -> Self {
Self::default()
}
pub fn active_main(&self) -> Option<Arc<dyn PanelView>> {
self.main
.as_ref()
.and_then(|id| self.main_views.get(id))
.cloned()
}
pub fn active_main_id(&self) -> Option<&SharedString> {
self.main.as_ref()
}
pub fn open_mains(&self) -> &[SharedString] {
&self.main_order
}
/// The open main panel with this id.
pub fn main_view(&self, id: &SharedString) -> Option<Arc<dyn PanelView>> {
self.main_views.get(id).cloned()
}
pub fn active_detail(&self) -> Option<Arc<dyn PanelView>> {
self.active_detail
.as_ref()
.and_then(|id| self.detail_views.get(id))
.cloned()
}
pub fn has_main(&self, id: &SharedString) -> bool {
self.main_views.contains_key(id)
}
pub fn has_details(&self) -> bool {
!self.details.is_empty()
}
pub fn has_detail(&self, id: &SharedString) -> bool {
self.detail_views.contains_key(id)
}
pub fn show_main(
&mut self,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut Context<Self>,
) {
if self.main.as_ref() != Some(&id) {
self.clear_details();
}
if !self.main_views.contains_key(&id) {
self.main_order.push(id.clone());
}
self.main_views.insert(id.clone(), view);
self.main = Some(id);
cx.notify();
}
pub fn activate_main(&mut self, id: &SharedString, cx: &mut Context<Self>) {
if self.main.as_ref() != Some(id) {
self.clear_details();
}
self.main = Some(id.clone());
cx.notify();
}
pub fn activate_detail(&mut self, id: &SharedString, cx: &mut Context<Self>) {
if self.detail_views.contains_key(id) {
self.active_detail = Some(id.clone());
cx.notify();
}
}
pub fn show_detail(
&mut self,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut Context<Self>,
) {
if !self.details.contains(&id) {
self.details.push(id.clone());
}
self.detail_views.insert(id.clone(), view);
self.active_detail = Some(id);
cx.notify();
}
pub fn close_detail(&mut self, id: &SharedString, cx: &mut Context<Self>) {
let Some(index) = self.details.iter().position(|open| open == id) else {
return;
};
self.close_detail_at(index, cx);
}
pub fn close_main_at(&mut self, index: usize, cx: &mut Context<Self>) {
if index >= self.main_order.len() {
return;
}
let id = self.main_order.remove(index);
self.main_views.remove(&id);
if self.main.as_ref() == Some(&id) {
self.main = self
.main_order
.get(index)
.or_else(|| {
index
.checked_sub(1)
.and_then(|prev| self.main_order.get(prev))
})
.cloned();
self.clear_details();
}
cx.notify();
}
pub fn clear(&mut self, cx: &mut Context<Self>) {
self.main = None;
self.main_order.clear();
self.main_views.clear();
self.clear_details();
cx.notify();
}
fn clear_details(&mut self) {
self.details.clear();
self.detail_views.clear();
self.active_detail = None;
}
fn close_detail_at(&mut self, index: usize, cx: &mut Context<Self>) {
if index >= self.details.len() {
return;
}
let id = self.details.remove(index);
self.detail_views.remove(&id);
if self.active_detail.as_ref() == Some(&id) {
self.active_detail = self
.details
.get(index)
.or_else(|| index.checked_sub(1).and_then(|prev| self.details.get(prev)))
.cloned();
}
cx.notify();
}
fn activate_detail_at(&mut self, index: usize, cx: &mut Context<Self>) {
let Some(id) = self.details.get(index) else {
return;
};
self.active_detail = Some(id.clone());
cx.notify();
}
}
impl Panel for Workspace {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Workspace")
}
}
impl Render for Workspace {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let selected = self
.active_detail
.as_ref()
.and_then(|active| self.details.iter().position(|id| id == active))
.unwrap_or(usize::MAX);
let details: Vec<_> = self
.details
.iter()
.map(|id| (id.clone(), self.detail_views.get(id).cloned()))
.collect();
let weak = cx.entity().downgrade();
let body = self.active_detail().map(|view| view.view());
v_flex()
.size_full()
.gap_2()
.when(self.details.len() > 1, |this| {
let close_weak = weak.clone();
let tabs = Tabs::new("signed-detail-tabs")
.variant(TabsVariant::Pill)
.overflow_scroll(true)
.selected(selected)
.tabs(move |_, cx| {
details
.iter()
.map(|(id, view)| match view {
Some(view) => view.tab(id.clone().into(), cx).closeable(true),
None => Tab::new(id.clone(), id.clone()).closeable(true),
})
.collect()
})
.on_change(move |index, _, cx| {
log_dropped(weak.update(cx, |workspace, cx| {
workspace.activate_detail_at(index, cx);
}));
})
.on_close(move |index, _, cx| {
log_dropped(close_weak.update(cx, |workspace, cx| {
workspace.close_detail_at(index, cx);
}));
});
this.child(tabs)
})
.child(div().flex_1().min_h_0().w_full().children(body))
}
}