refactor: consolidate shared ui helpers and prune unused code

This commit is contained in:
2026-11-22 18:23:21 +07:00
parent 4a72f2b4a0
commit 9daee9d54d
82 changed files with 3607 additions and 7184 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 {
+2 -2
View File
@@ -7,7 +7,7 @@ use gpui::{
AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
Render, Styled as _, Subscription, Window, div, px,
};
use helpers::apply_appearance;
use helpers::apply_appearance_mode;
use settings::SettingsStore;
use signed_state::{Backend, BackendEvent};
use ui::common::h_flex;
@@ -82,7 +82,7 @@ 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();
+9 -9
View File
@@ -45,15 +45,6 @@ impl Panel for SignedOutView {
}
}
/// 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();
@@ -110,3 +101,12 @@ impl Render for SignedOutView {
.when_some(self.import.clone(), |el, view| el.child(view))
}
}
/// 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()
}
+2 -11
View File
@@ -13,7 +13,7 @@ use ui::theme::ActiveTheme as _;
use utils::relative_time;
use crate::repo::actions::open_repo_panel;
use crate::repo::helpers::announcement_display_name;
use crate::repo::helpers::{announcement_display_name, upstream_display_name};
use crate::workspace::Workspace;
const RECENT_COUNT: usize = 10;
@@ -78,16 +78,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}")))
});
+2 -4
View File
@@ -14,6 +14,7 @@ use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent};
use ui::layout::panel::Panel;
use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _;
@@ -256,9 +257,6 @@ impl Render for ExploreView {
})
.size_full(),
)
.child(crate::shared::widgets::scroll_overlay(
"explore-scroll",
scroll_handle,
))
.child(Scrollbar::vertical("explore-scroll", scroll_handle))
}
}
+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]
})
+14 -12
View File
@@ -4,14 +4,13 @@ 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 +101,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),
)
}),
)
+2 -2
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;
@@ -25,7 +26,6 @@ use helpers::{empty_section_row, repo_header, thread};
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;
@@ -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);
});
+5 -4
View File
@@ -20,7 +20,8 @@ use std::rc::Rc;
use self::detail::IssueDetailView;
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;
@@ -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,
]
})
}
+1 -1
View File
@@ -12,7 +12,7 @@ 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};
pub fn root(window: &mut Window, cx: &mut App) -> Entity<AppRoot> {
+25 -23
View File
@@ -16,18 +16,23 @@ 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::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::shared::event_list::commit_list;
use crate::shared::log_dropped;
use crate::shared::panels::open_detail;
use crate::shared::widgets::status_badge;
use crate::workspace::Workspace;
const NOT_FOUND: &str = "Pull request not found";
@@ -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,
)
}
@@ -528,7 +534,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)
@@ -595,7 +601,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 {
@@ -115,7 +116,7 @@ pub fn source_menu_items(
};
let title = format!(
"{} — {}",
crate::repo::helpers::announcement_display_name(&candidate),
announcement_display_name(&candidate),
subtitle
);
let target = view.clone();
+11 -9
View File
@@ -31,7 +31,9 @@ pub use send_patch::SendPatchView;
use crate::issues::helpers::{StatusCounts, filter_by_status};
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::open_detail;
use crate::workspace::Workspace;
pub struct PullRequestsView {
@@ -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| {
+418 -31
View File
@@ -1,30 +1,36 @@
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::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::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>,
panel_id: SharedString,
@@ -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,7 +215,7 @@ impl NewPullRequestView {
this.update(cx, |this, _cx| {
this.submitting = false;
})?;
crate::shared::log_dropped(
log_dropped(
workspace.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)),
);
Ok(())
@@ -227,7 +233,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,7 +276,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(
Some(fork) => truncate_label(&announcement_display_name(
&fork.announcement,
)),
None => self.repo_path.as_ref().map_or_else(
@@ -289,21 +295,21 @@ 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(
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| {
crate::shared::log_dropped(weak_menu.update(cx, |this, cx| {
log_dropped(weak_menu.update(cx, |this, cx| {
this.source_open = open;
cx.notify();
}));
@@ -311,7 +317,7 @@ impl NewPullRequestView {
.trigger(move |_, _| {
Button::new("compare-source")
.label(source_label.clone())
.variant(ui::button::ButtonVariant::Secondary)
.variant(ButtonVariant::Secondary)
.into_any_element()
})
.items(move |_, _| {
@@ -343,7 +349,7 @@ impl NewPullRequestView {
.loading(self.submitting)
.disabled(!can_submit)
.on_click(move |_, window, cx| {
crate::shared::log_dropped(
log_dropped(
weak.update(cx, |this, cx| this.submit(window, cx)),
);
}),
@@ -366,7 +372,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 +382,15 @@ 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 +400,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 +416,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 +840,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,6 +11,7 @@ use ui::input::{Input, InputState};
use ui::layout::panel::Panel;
use ui::theme::ActiveTheme as _;
use crate::shared::log_dropped;
use crate::shared::progress::error_row;
use crate::workspace::Workspace;
@@ -83,7 +84,7 @@ impl SendPatchView {
Ok(()) => {
this.update(cx, |this, cx| {
let panel_id = this.panel_id.clone();
crate::shared::log_dropped(
log_dropped(
this.workspace
.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)),
);
@@ -122,7 +123,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()
+28 -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,10 @@ 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 +307,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 +419,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 +443,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 +554,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 +563,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);
@@ -898,9 +890,9 @@ impl Panel for CommitDiffView {
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()
};
+13 -12
View File
@@ -17,7 +17,7 @@ use ui::tooltip::Tooltip;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::repo::actions::open_repo_panel;
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};
use crate::workspace::Workspace;
/// Progress of the create-repository flow, so async results can be rendered.
@@ -229,17 +229,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]
})
+14 -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,7 @@ 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 +245,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]
})
+30 -37
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,22 @@ 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.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.id == path.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 +238,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 +264,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 +281,10 @@ 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 +310,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 +419,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 +428,7 @@ impl RepoFilesView {
};
if !ready {
return preview_spinner();
return Spinner::centered("repo-preview-spinner");
}
div()
@@ -481,10 +474,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()
}
}
+96 -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,20 @@ 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 +195,10 @@ 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 +225,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 +312,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 +359,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 +405,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>,
+5 -4
View File
@@ -12,7 +12,9 @@ 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;
@@ -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()
+448 -11
View File
@@ -5,49 +5,58 @@ 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::issues::IssuesView;
use crate::pull_requests::PullRequestsView;
use crate::shared::log_dropped;
use crate::shared::tree::sorted_worktree_paths;
use crate::workspace::Workspace;
use crate::repo::helpers::{short_id, sorted_worktree_paths};
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum RepoSection {
Files,
@@ -193,7 +202,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);
}));
@@ -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.
+96 -39
View File
@@ -5,6 +5,86 @@ use ui::layout::panel::{Panel, PanelView};
use crate::workspace::Workspace;
/// Which slot of the workspace a panel opens into.
#[derive(Clone, Copy)]
enum PanelSlot {
Main,
Detail,
}
impl PanelSlot {
/// Whether the slot already holds a panel under `id`.
fn has(self, workspace: &WeakEntity<Workspace>, id: &SharedString, cx: &App) -> bool {
match self {
PanelSlot::Main => workspace
.read_with(cx, |workspace, _| workspace.has_main(id))
.unwrap_or(false),
PanelSlot::Detail => workspace
.read_with(cx, |workspace, _| workspace.has_detail(id))
.unwrap_or(false),
}
}
/// Activates the slot's cached panel under `id`.
fn activate(self, workspace: &WeakEntity<Workspace>, id: &SharedString, cx: &mut App) {
let result = match self {
PanelSlot::Main => {
workspace.update(cx, |workspace, cx| workspace.activate_main(id, cx))
}
PanelSlot::Detail => {
workspace.update(cx, |workspace, cx| workspace.activate_detail(id, cx))
}
};
if let Err(error) = result {
log::warn!("failed to activate panel {id}: {error}");
}
}
/// Shows the panel in the slot.
fn show(
self,
workspace: &WeakEntity<Workspace>,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut App,
) {
let result = match self {
PanelSlot::Main => {
workspace.update(cx, |workspace, cx| workspace.show_main(id, view, cx))
}
PanelSlot::Detail => {
workspace.update(cx, |workspace, cx| workspace.show_detail(id, view, cx))
}
};
if let Err(error) = result {
log::warn!("failed to open panel: {error}");
}
}
}
/// Opens a panel in `slot`, reusing it when it is already cached.
fn open_slot<P, F>(
slot: PanelSlot,
workspace: &WeakEntity<Workspace>,
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 id = id.into();
if slot.has(workspace, &id, cx) {
slot.activate(workspace, &id, cx);
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
slot.show(workspace, id, view, cx);
}
/// Opens a repository in the main panel, reusing it when it is already cached.
pub fn open_primary<P, F>(
workspace: &WeakEntity<Workspace>,
@@ -16,25 +96,14 @@ 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.
@@ -48,24 +117,12 @@ pub fn open_detail<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_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}");
}
open_slot(
PanelSlot::Detail,
workspace,
id,
build,
window,
cx,
);
}
+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()
}
+43 -43
View File
@@ -56,49 +56,6 @@ 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>,
@@ -626,3 +583,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);
}