chore: improve ui consistently (#35)
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run

Reviewed-on: #35
This commit was merged in pull request #35.
This commit is contained in:
2026-11-20 12:28:25 +00:00
parent 51dd5c8630
commit f850f4c4c1
90 changed files with 2859 additions and 2061 deletions
+3
View File
@@ -20,3 +20,6 @@ nostr.workspace = true
anyhow.workspace = true
futures.workspace = true
log.workspace = true
[lints]
workspace = true
+1 -1
View File
@@ -131,7 +131,7 @@ impl Render for AppRoot {
div()
.relative()
.size_full()
.font_family(".SystemUIFont")
.font_family(cx.theme().ui_font())
.text_color(cx.theme().colors.foreground)
.key_context(REPOSITORY_KEY_CONTEXT)
.on_action(cx.listener(|this, action: &SwitchRepository, window, cx| {
+2 -5
View File
@@ -13,6 +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::workspace::Workspace;
const RECENT_COUNT: usize = 10;
@@ -62,11 +63,7 @@ pub(super) fn render_card(
let workspace = workspace.clone();
let announcement = announcement.clone();
let name = announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()));
let name = announcement_display_name(&announcement);
let description = announcement
.description
+22 -33
View File
@@ -14,7 +14,6 @@ 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 _;
@@ -22,6 +21,7 @@ use crate::shared::panels;
use crate::workspace::Workspace;
const COLUMNS: usize = 2;
// Name row, avatar strip, meta row, and their borders and gaps, in px.
const CARD_HEIGHT: f32 = 40. + 64. + 48. + 2. + 6.;
pub struct ExploreView {
@@ -153,29 +153,23 @@ impl ExploreView {
),
)
.child(
div()
.absolute()
.left_0()
.bottom_0()
.pl_4()
.pb_4()
.child(
Segmented::new("explore-filter", filter)
.options(vec![
SegmentedOption::new(RepoFilter::All, "All")
.icon(Icon::named(IconRole::Grid).small().color(muted)),
SegmentedOption::new(RepoFilter::Recent, "Recent")
.icon(Icon::named(IconRole::Clock).small().color(muted)),
])
.on_change(move |filter, _, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.filter = filter;
this.rebuild_rows(cx);
}) {
log::warn!("failed to change explore filter: {error}");
}
}),
),
div().absolute().left_0().bottom_0().pl_4().pb_4().child(
Segmented::new("explore-filter", filter)
.options(vec![
SegmentedOption::new(RepoFilter::All, "All")
.icon(Icon::named(IconRole::Grid).small().color(muted)),
SegmentedOption::new(RepoFilter::Recent, "Recent")
.icon(Icon::named(IconRole::Clock).small().color(muted)),
])
.on_change(move |filter, _, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.filter = filter;
this.rebuild_rows(cx);
}) {
log::warn!("failed to change explore filter: {error}");
}
}),
),
)
.into_any_element()
}
@@ -262,14 +256,9 @@ impl Render for ExploreView {
})
.size_full(),
)
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical("explore-scroll", scroll_handle)),
)
.child(crate::shared::widgets::scroll_overlay(
"explore-scroll",
scroll_handle,
))
}
}
+9 -9
View File
@@ -11,7 +11,7 @@ use ui::field::Field;
use ui::input::{Input, InputState, InputStateEvent};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::{DialogProgress, error_row};
use crate::shared::progress::{DialogProgress, error_row, run_dialog_task_with};
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum Stage {
@@ -347,17 +347,17 @@ fn finish_import<T: 'static>(
handle: &DialogHandle,
cx: &mut App,
) {
let state = state.clone();
let handle = handle.clone();
cx.spawn(async move |cx| match task.await {
Ok(_) => cx.update(|cx| handle.close(cx)),
Err(error) => {
let state = state.clone();
run_dialog_task_with(
task,
cx,
move |_, cx| cx.update(|cx| handle.close(cx)),
move |error, cx| {
state.update(cx, |state, cx| {
state.progress.fail(error.to_string());
cx.notify();
});
}
})
.detach();
},
);
}
+2 -14
View File
@@ -11,7 +11,7 @@ use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::{DialogProgress, error_row};
use crate::shared::progress::{DialogProgress, error_row, run_dialog_task};
pub struct OnboardingDialog {
handle: DialogHandle,
@@ -61,19 +61,7 @@ impl OnboardingDialog {
let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| backend.create_identity(&name, &pass, cx));
let state = self.state.clone();
let handle = self.handle.clone();
cx.spawn(async move |_this, cx| match task.await {
Ok(_) => cx.update(|cx| handle.close(cx)),
Err(error) => {
state.update(cx, |state, cx| {
state.fail(error.to_string());
cx.notify();
});
}
})
.detach();
run_dialog_task(task, &self.state, &self.handle, cx);
}
}
+2 -14
View File
@@ -11,7 +11,7 @@ use ui::field::Field;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent};
use crate::shared::progress::{DialogProgress, error_row, push_steps_row};
use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task};
pub struct PassphraseDialog {
handle: DialogHandle,
@@ -64,19 +64,7 @@ impl PassphraseDialog {
let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| backend.restore_with_passphrase(&pass, cx));
let state = self.state.clone();
let handle = self.handle.clone();
cx.spawn(async move |_this, cx| match task.await {
Ok(_) => cx.update(|cx| handle.close(cx)),
Err(error) => {
state.update(cx, |state, cx| {
state.fail(error.to_string());
cx.notify();
});
}
})
.detach();
run_dialog_task(task, &self.state, &self.handle, cx);
}
}
+3 -29
View File
@@ -1,7 +1,7 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Div, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
SharedString, Stateful, Styled as _, div, px,
SharedString, Stateful, Styled as _, div,
};
use metadata::ProfileDirectory;
use nostr::prelude::{Event, Kind, PublicKey};
@@ -101,11 +101,8 @@ pub fn thread(
.child(div().flex_1())
.when(unread, |this| {
this.child(
div()
.flex_shrink_0()
.size_2()
.rounded_full()
.bg(cx.theme().colors.primary),
ui::status_dot::StatusDot::new(("inbox-unread", ix))
.variant(ui::status_dot::StatusDotVariant::Accent),
)
}),
)
@@ -167,26 +164,3 @@ fn activity_phrase(kind: Kind) -> &'static str {
_ => "did something",
}
}
pub fn empty_state(message: &'static str, cx: &App) -> AnyElement {
v_flex()
.w_full()
.flex_1()
.min_h_0()
.items_center()
.justify_center()
.gap_2()
.py_8()
.child(
Icon::named(IconRole::Inbox)
.size(px(24.))
.color(cx.theme().colors.muted_foreground),
)
.child(
div()
.text_base()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(message)),
)
.into_any_element()
}
+41 -11
View File
@@ -2,6 +2,7 @@ use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity,
@@ -11,6 +12,7 @@ use metadata::ProfileDirectory;
use nostr::prelude::{Event, EventId, Kind, PublicKey, Timestamp};
use signed_core::{InboxItem, InboxReadState, RepoAddr};
use signed_state::{Backend, BackendEvent, Inbox, RefreshGate, RefreshRequest, RepoListStore};
use ui::alert::{Alert, AlertSeverity, AlertStyle};
use ui::button::Button;
use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
@@ -19,9 +21,11 @@ use ui::scroll_area::ScrollArea;
mod helpers;
use helpers::{empty_section_row, empty_state, repo_header, thread};
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;
@@ -50,6 +54,8 @@ pub struct InboxView {
refresh: RefreshGate,
tasks: Vec<Task<Result<(), Error>>>,
directory: Entity<ProfileDirectory>,
/// The last refresh failure, shown inline until the next refresh succeeds.
error: Option<SharedString>,
_subscriptions: Vec<Subscription>,
}
@@ -92,6 +98,7 @@ impl InboxView {
refresh: RefreshGate::default(),
tasks: vec![],
directory: ProfileDirectory::new(cx),
error: None,
_subscriptions: subscriptions,
}
}
@@ -164,6 +171,12 @@ impl InboxView {
self.run_refresh(cx);
}
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn run_refresh(&mut self, cx: &mut Context<Self>) {
self.refresh.begin();
let backend = Backend::global(cx);
@@ -178,12 +191,16 @@ impl InboxView {
let state = self.state.clone();
let work = cx.background_spawn(async move { Inbox::query(&client, me, &state).await });
self.tasks.push(cx.spawn(async move |this, cx| {
self.push_task(cx.spawn(async move |this, cx| {
let (threads, _unread_count) = match work.await {
Ok(results) => results,
Err(error) => {
log::warn!("inbox refresh failed: {error}");
return this.update(cx, |this, _cx| this.refresh.abort());
return this.update(cx, |this, cx| {
this.error = Some(error.to_string().into());
this.refresh.abort();
cx.notify();
});
}
};
@@ -193,6 +210,7 @@ impl InboxView {
return false;
}
this.threads = Arc::new(threads);
this.error = None;
this.rebuild(cx);
cx.notify();
this.refresh.finish()
@@ -427,6 +445,24 @@ impl Render for InboxView {
.on_click(cx.listener(|this, _, _, cx| this.mark_all_read(cx))),
),
)
.when_some(self.error.clone(), |this, error| {
let weak = cx.entity().downgrade();
this.child(
Alert::new("inbox-error")
.severity(AlertSeverity::Danger)
.title("Inbox")
.message(error)
.style(AlertStyle::Inline)
.on_dismiss(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.error = None;
cx.notify();
}) {
log::warn!("failed to dismiss inbox error: {error}");
}
}),
)
})
.child(
div()
.relative()
@@ -434,7 +470,7 @@ impl Render for InboxView {
.min_h_0()
.px_4()
.child(if rows.is_empty() {
empty_state("You're all caught up.", cx)
empty_state("You're all caught up.")
} else {
ScrollArea::new("inbox-scroll")
.flex_1()
@@ -455,12 +491,6 @@ fn repo_name(addr: Option<&RepoAddr>, cx: &App) -> SharedString {
.announcements
.iter()
.find(|announcement| announcement.addr() == *addr)
.map(|announcement| {
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()))
})
.map(announcement_display_name)
.unwrap_or_else(|| SharedString::from("Untitled"))
}
+17 -27
View File
@@ -3,12 +3,11 @@ use gpui::{
ScrollHandle, SharedString, Styled as _, Subscription, Window, div,
};
use metadata::ProfileDirectory;
use nostr::prelude::{EventId, PublicKey};
use nostr::prelude::EventId;
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;
@@ -56,27 +55,23 @@ impl IssueDetailView {
/// Track the issue author, everyone who commented and the repository owner.
fn track_participants(&mut self, cx: &mut Context<Self>) {
let store = self.store.read(cx);
let mut keys: Vec<PublicKey> = store
let author = store
.issues
.iter()
.find(|issue| issue.id == self.issue_id)
.map(|issue| issue.pubkey)
.into_iter()
.map(|issue| issue.pubkey);
let owner = store.announcement.as_ref().map(|a| a.owner);
let comments: Vec<_> = store
.comments_of(&self.issue_id)
.map(|comment| comment.pubkey)
.collect();
keys.extend(
store
.comments_of(&self.issue_id)
.map(|comment| comment.pubkey),
crate::shared::track_event_participants(
author,
owner,
comments.into_iter(),
&self.directory,
cx,
);
if let Some(owner) = store.announcement.as_ref().map(|a| a.owner) {
keys.push(owner);
}
self.directory.update(cx, |directory, cx| {
directory.track(keys, cx);
});
}
}
@@ -97,17 +92,12 @@ impl Render for IssueDetailView {
let store = self.store.read(cx);
let Some(issue) = store.issues.iter().find(|issue| issue.id == self.issue_id) else {
let message = if store.loaded {
"Issue not found"
// 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")
} else {
"Loading issue..."
crate::shared::widgets::centered_spinner("issue-loading")
};
return v_flex()
.size_full()
.items_center()
.justify_center()
.child(EmptyState::new(message))
.into_any_element();
};
let (title, author, status, age, issue_id, content, pubkey) = {
+72 -157
View File
@@ -1,36 +1,33 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _,
Subscription, UniformListScrollHandle, WeakEntity, Window, div, px, uniform_list,
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div,
};
use helpers::{IssueFilter, StatusCounts, filter_by_status};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
use signed_core::GitEvent;
use signed_state::RepoStore;
use ui::avatar::Avatar;
use ui::button::Button;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::common::v_flex;
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _;
use utils::relative_time;
use std::rc::Rc;
use self::detail::IssueDetailView;
use crate::repo::helpers::short_id;
use crate::shared::event_list::{EventList, EventRow};
use crate::shared::panels;
use crate::shared::widgets::status_badge;
use crate::workspace::Workspace;
pub mod detail;
pub(crate) mod helpers;
pub mod new_issue;
const ISSUE_ROW_HEIGHT: f32 = 73.;
pub struct IssuesView {
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
@@ -131,14 +128,9 @@ impl IssuesView {
let muted = cx.theme().colors.muted_foreground;
let weak = cx.entity().downgrade();
h_flex()
.px_4()
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.bg(cx.theme().colors.muted)
.child(
crate::shared::event_list::filter_toolbar(
cx,
[
Segmented::new("issue-filter", self.filter)
.options(vec![
SegmentedOption::new(IssueFilter::All, format!("All ({})", counts.total))
@@ -158,18 +150,18 @@ impl IssuesView {
}) {
log::warn!("failed to switch issue filter: {error}");
}
}),
)
.child(div().flex_1())
.child(
})
.into_any_element(),
div().flex_1().into_any_element(),
Button::new("new-issue")
.label("New issue")
.icon(Icon::named(IconRole::CirclePlus))
.on_click(cx.listener(|this, _, _, cx| {
this.open_new_issue(cx);
})),
)
.into_any_element()
}))
.into_any_element(),
],
)
}
}
@@ -182,147 +174,70 @@ impl Panel for IssuesView {
impl Render for IssuesView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let filter = self.filter;
let count = self.visible_issues.len();
let visible_issues = self.visible_issues.clone();
let directory = self.directory.clone();
let store = self.store.clone();
let workspace = self.workspace.clone();
let rows = visible_issues
.iter()
.enumerate()
.filter_map(|(ix, &issue_ix)| {
// The store re-read per frame can shrink below a captured index.
let issue = store.read(cx).issues.get(issue_ix)?;
let profile = directory.read(cx).profile(&issue.pubkey, cx);
let issue_id = issue.id;
let id_hex = issue.id.to_hex();
let status = store.read(cx).status_of(issue);
let on_click: crate::shared::event_list::EventHandler = {
let workspace = workspace.clone();
let store = store.clone();
Rc::new(move |_, window, cx| {
let id = SharedString::from(format!("issue:{issue_id}"));
let store = store.clone();
panels::open_detail(
&workspace,
id,
move |_, cx| {
cx.new(|cx| IssueDetailView::new(store.clone(), issue_id, cx))
},
window,
cx,
);
})
};
Some(EventRow {
id: ix.into(),
status,
title: issue.activity_subject().into(),
author: profile.name(),
picture: profile.picture(),
pubkey: issue.pubkey,
short_id: short_id(&id_hex),
age: SharedString::from(relative_time(issue.created_at)),
on_click,
})
})
.collect();
let empty_message = match filter {
IssueFilter::All => "No issues",
IssueFilter::Open => "No open issues",
IssueFilter::Closed => "No closed issues",
};
v_flex()
.size_full()
.child(self.render_header(cx))
.when_some(self.new_issue.clone(), |el, view| el.child(view))
.child(
v_flex()
.relative()
.flex_1()
.min_h_0()
.w_full()
.when(count > 0, |this| {
this.child(
uniform_list("issues", count, move |range, _, cx| {
range
.map(|ix| {
let issue_ix = visible_issues[ix];
let issue = &store.read(cx).issues[issue_ix];
let title = issue.activity_subject();
let id_hex = issue.id.to_hex();
let profile = directory.read(cx).profile(&issue.pubkey, cx);
let author = profile.name();
let age = relative_time(issue.created_at);
let status = store.read(cx).status_of(issue);
let issue_id = issue.id;
let workspace = workspace.clone();
let store = store.clone();
h_flex()
.id(ix)
.w_full()
.h(px(ISSUE_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(move |_, window, cx| {
let id =
SharedString::from(format!("issue:{issue_id}"));
let store = store.clone();
panels::open_detail(
&workspace,
id,
move |_, cx| {
cx.new(|cx| {
IssueDetailView::new(
store.clone(),
issue_id,
cx,
)
})
},
window,
cx,
);
})
.child(status_badge(status))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(
div()
.text_base()
.text_ellipsis()
.whitespace_nowrap()
.child(title),
)
.child(
h_flex()
.gap_2()
.text_xs()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(issue.pubkey)
.name(author.clone())
.picture(
profile.picture(),
)
.small(),
)
.child(div().child(author)),
)
.child(SharedString::from("opened"))
.child(
div()
.text_color(
cx.theme()
.colors
.muted_foreground,
)
.child(SharedString::from(
&id_hex[..8],
)),
)
.child(SharedString::from(age)),
),
)
.into_any_element()
})
.collect()
})
.track_scroll(&self.scroll_handle)
.size_full(),
)
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(
"issues-scroll",
self.scroll_handle.clone(),
)),
)
})
.when(count == 0, |this| {
let message = match filter {
IssueFilter::All => "No issues",
IssueFilter::Open => "No open issues",
IssueFilter::Closed => "No closed issues",
};
this.child(
v_flex()
.size_full()
.items_center()
.justify_center()
.child(EmptyState::new(message)),
)
}),
EventList::new("issues")
.toolbar(self.render_header(cx))
.scroll_handle(self.scroll_handle.clone())
.rows(rows)
.empty_message(empty_message)
.render(cx),
)
.into_any_element()
}
+15 -1
View File
@@ -10,31 +10,41 @@ use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::DialogProgress;
pub struct NewIssueDialog {
handle: DialogHandle,
store: Entity<RepoStore>,
subject: Entity<InputState>,
content: Entity<InputState>,
state: Entity<DialogProgress>,
}
impl NewIssueDialog {
pub fn new(store: Entity<RepoStore>, cx: &mut App) -> Entity<Self> {
let subject = InputState::new(cx);
let content = InputState::builder().multiline().build(cx);
let state = cx.new(|_| DialogProgress::default());
cx.new(|_| Self {
handle: DialogHandle::new(true),
store,
subject,
content,
state,
})
}
fn submit(&mut self, cx: &mut Context<Self>) {
// The publish runs detached in the store; one submission per dialog.
if self.state.read(cx).busy {
return;
}
let subject = self.subject.read(cx).value().to_string();
let content = self.content.read(cx).value().to_string();
let subject = (!subject.trim().is_empty()).then_some(subject);
self.state.update(cx, |state, _| state.begin());
self.store.update(cx, |store, cx| {
store.open_issue(subject, content, cx);
});
@@ -48,6 +58,7 @@ impl Render for NewIssueDialog {
let subject = self.subject.clone();
let content = self.content.clone();
let this = cx.entity().downgrade();
let action_state = self.state.clone();
Dialog::new("new-issue-dialog")
.handle(self.handle.clone())
@@ -72,11 +83,14 @@ impl Render for NewIssueDialog {
)
.into_any_element()
})
.actions(move |_, _| {
.actions(move |_, cx| {
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)));
})
+46 -69
View File
@@ -1,13 +1,15 @@
use std::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, uniform_list,
WeakEntity, Window, div,
};
use metadata::ProfileDirectory;
use nostr::prelude::{EventId, Kind, PublicKey, Url};
use nostr::prelude::{EventId, Kind, Url};
use signed_core::{GitEvent, PullRequest, RepoAddr};
use signed_git::{FileCommit, PatchParser};
use signed_state::{Backend, Mirrors, RepoStore};
@@ -19,8 +21,6 @@ use ui::icons::{Icon, IconRole};
use ui::input::InputState;
use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea;
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::tabs::{Tab, Tabs};
use ui::theme::ActiveTheme as _;
use utils::relative_time;
@@ -28,7 +28,6 @@ use utils::relative_time;
use super::dialogs;
use crate::issues::helpers::{comment_form, comments_section, pr_roots, sidebar_section};
use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::repo::helpers::commit_row;
use crate::shared::widgets::{empty_state, status_badge};
use crate::workspace::Workspace;
@@ -54,7 +53,7 @@ pub struct PullRequestDetailView {
worktree: Option<PathBuf>,
description: SharedString,
current_commit: Option<SharedString>,
commits: Vec<FileCommit>,
commits: Arc<Vec<FileCommit>>,
loading: bool,
error: Option<SharedString>,
bound: Option<PrBinding>,
@@ -96,7 +95,7 @@ impl PullRequestDetailView {
worktree: None,
description: SharedString::default(),
current_commit: None,
commits: Vec::new(),
commits: Arc::new(Vec::new()),
loading: true,
error: None,
bound: None,
@@ -112,18 +111,23 @@ impl PullRequestDetailView {
fn track_participants(&mut self, cx: &mut Context<Self>) {
let store = self.store.read(cx);
let mut keys: Vec<PublicKey> = store
let author = store
.pull_requests
.iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
.map(|root| vec![root.pubkey])
.unwrap_or_default();
keys.extend(store.comments_of(&self.pr_id).map(|comment| comment.pubkey));
if let Some(owner) = store.announcement.as_ref().map(|a| a.owner) {
keys.push(owner);
}
self.directory
.update(cx, |directory, cx| directory.track(keys, cx));
.map(|root| root.pubkey);
let owner = store.announcement.as_ref().map(|a| a.owner);
let comments: Vec<_> = store
.comments_of(&self.pr_id)
.map(|comment| comment.pubkey)
.collect();
crate::shared::track_event_participants(
author,
owner,
comments.into_iter(),
&self.directory,
cx,
);
}
fn sync(&mut self, cx: &mut Context<Self>) {
@@ -181,6 +185,12 @@ impl PullRequestDetailView {
self.load_diff(binding, cx);
}
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: gpui::Task<Result<(), anyhow::Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn load_diff(&mut self, binding: PrBinding, cx: &mut Context<Self>) {
self.loading = true;
self.error = None;
@@ -266,7 +276,7 @@ impl PullRequestDetailView {
}
this.loading = false;
this.worktree = worktree;
this.commits = commits;
this.commits = Arc::new(commits);
match diff {
Ok(diff) => this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx)),
Err(error) => this.error = Some(error.to_string().into()),
@@ -275,7 +285,7 @@ impl PullRequestDetailView {
})?;
Ok(())
});
self.tasks.push(task);
self.push_task(task);
}
fn open_commit_diff(
@@ -443,54 +453,26 @@ impl PullRequestDetailView {
if self.commits.is_empty() {
return empty_state("No commits found");
}
let commits = self.commits.clone();
let commits = Arc::clone(&self.commits);
let worktree = self.worktree.clone();
let view = cx.entity().downgrade();
v_flex()
.relative()
.flex_1()
.min_h_0()
.child(
uniform_list("pr-commits", commits.len(), move |range, _, cx| {
range
.map(|ix| {
let commit = commits[ix].clone();
let id = commit.id.clone();
let worktree = worktree.clone();
let view = view.clone();
commit_row(
ix,
&commit,
None,
move |window, cx| {
if let Some(worktree) = worktree.clone() {
crate::shared::log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(worktree, &id, window, cx);
}));
}
},
cx,
)
})
.collect()
})
.track_scroll(&self.commit_scroll_handle)
.size_full(),
)
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(
"pr-commits-scroll",
self.commit_scroll_handle.clone(),
)),
)
.into_any_element()
crate::shared::event_list::commit_list(
"pr-commits",
"pr-commits-scroll",
commits,
self.commit_scroll_handle.clone(),
|_, _, _| None,
move |commit, window, cx| {
if let Some(worktree) = worktree.clone() {
let id = commit.id.clone();
crate::shared::log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(worktree, &id, window, cx);
}));
}
},
cx,
)
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
@@ -614,10 +596,5 @@ impl Render for PullRequestDetailView {
}
fn centered_spinner() -> AnyElement {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new("pr-loading"))
.into_any_element()
crate::shared::widgets::centered_spinner("pr-loading")
}
@@ -11,29 +11,39 @@ use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::DialogProgress;
pub struct UpdatePrDialog {
handle: DialogHandle,
store: Entity<RepoStore>,
root: Event,
patch: Entity<InputState>,
state: Entity<DialogProgress>,
}
impl UpdatePrDialog {
pub fn new(store: Entity<RepoStore>, root: Event, cx: &mut App) -> Entity<Self> {
let patch = InputState::builder().multiline().build(cx);
let state = cx.new(|_| DialogProgress::default());
cx.new(|_| Self {
handle: DialogHandle::new(true),
store,
root,
patch,
state,
})
}
fn submit(&mut self, cx: &mut Context<Self>) {
// The publish runs detached in the store; one submission per dialog.
if self.state.read(cx).busy {
return;
}
let patch = self.patch.read(cx).value().to_string();
if patch.trim().is_empty() {
return;
}
self.state.update(cx, |state, _| state.begin());
self.store.update(cx, |store, cx| {
store.update_pull_request(&self.root, patch, cx);
});
@@ -45,6 +55,7 @@ impl Render for UpdatePrDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let patch = self.patch.clone();
let this = cx.entity().downgrade();
let action_state = self.state.clone();
Dialog::new("update-pr-dialog")
.handle(self.handle.clone())
@@ -65,11 +76,14 @@ impl Render for UpdatePrDialog {
)
.into_any_element()
})
.actions(move |_, _| {
.actions(move |_, cx| {
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)));
})
@@ -55,14 +55,6 @@ impl ForkCompare {
}
}
pub fn fork_display_name(announcement: &Announcement) -> SharedString {
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()))
}
pub fn shorten_owner(owner: &PublicKey) -> String {
owner.to_hex().chars().take(10).collect()
}
@@ -121,7 +113,11 @@ pub fn source_menu_items(
} else {
SharedString::from(format!("by {}", shorten_owner(&candidate.owner)))
};
let title = format!("{} — {}", fork_display_name(&candidate), subtitle);
let title = format!(
"{} — {}",
crate::repo::helpers::announcement_display_name(&candidate),
subtitle
);
let target = view.clone();
let checked = active_fork == Some(candidate.addr());
let announcement = candidate;
+74 -147
View File
@@ -1,21 +1,19 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _,
Subscription, UniformListScrollHandle, WeakEntity, Window, div, px, uniform_list,
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div,
};
use metadata::ProfileDirectory;
use nostr::prelude::{Kind, PublicKey};
use signed_core::GitEvent;
use signed_state::RepoStore;
use std::rc::Rc;
use ui::alert::{Alert, AlertSeverity};
use ui::avatar::Avatar;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::common::v_flex;
use ui::dropdown_menu::DropdownMenu;
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::menu::MenuItem;
use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _;
use utils::relative_time;
@@ -32,11 +30,10 @@ pub use new::NewPullRequestView;
pub use send_patch::SendPatchView;
use crate::issues::helpers::{StatusCounts, filter_by_status};
use crate::shared::widgets::{empty_state, status_badge};
use crate::repo::helpers::short_id;
use crate::shared::event_list::{EventList, EventRow};
use crate::workspace::Workspace;
const ROW_HEIGHT: f32 = 73.;
pub struct PullRequestsView {
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
@@ -198,14 +195,9 @@ impl PullRequestsView {
let menu_open_weak = cx.entity().downgrade();
let patch_weak = cx.entity().downgrade();
h_flex()
.px_4()
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.bg(cx.theme().colors.muted)
.child(
crate::shared::event_list::filter_toolbar(
cx,
[
Segmented::new("pr-filter", self.filter)
.options(vec![
SegmentedOption::new(
@@ -241,10 +233,9 @@ impl PullRequestsView {
}) {
log::warn!("failed to switch PR filter: {error}");
}
}),
)
.child(div().flex_1())
.child(
})
.into_any_element(),
div().flex_1().into_any_element(),
DropdownMenu::new("new-pr-actions")
.label("New")
.icon(Icon::named(IconRole::GitPullRequest))
@@ -271,9 +262,10 @@ impl PullRequestsView {
}));
}
})]
}),
)
.into_any_element()
})
.into_any_element(),
],
)
}
}
@@ -286,7 +278,6 @@ impl Panel for PullRequestsView {
impl Render for PullRequestsView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let filter = self.filter;
let count = self.visible_prs.len();
let visible = self.visible_prs.clone();
let directory = self.directory.clone();
let store = self.store.clone();
@@ -300,9 +291,60 @@ impl Render for PullRequestsView {
let dismiss_warning_store = self.store.clone();
let dismiss_error_store = self.store.clone();
let rows = visible
.iter()
.enumerate()
.filter_map(|(ix, &pr_ix)| {
// The store re-read per frame can shrink below a captured index.
let pr = store.read(cx).pull_requests.get(pr_ix)?;
let profile = directory.read(cx).profile(&pr.pubkey, cx);
let pr_id = pr.id;
let id_hex = pr.id.to_hex();
let status = store.read(cx).status_of(pr);
let on_click: crate::shared::event_list::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(
&workspace,
id,
move |window, cx| {
cx.new(|cx| {
PullRequestDetailView::new(
workspace_for_build.clone(),
store.clone(),
pr_id,
window,
cx,
)
})
},
window,
cx,
);
})
};
Some(EventRow {
id: ix.into(),
status,
title: pr.activity_subject().into(),
author: profile.name(),
picture: profile.picture(),
pubkey: pr.pubkey,
short_id: short_id(&id_hex),
age: SharedString::from(relative_time(pr.created_at)),
on_click,
})
})
.collect();
v_flex()
.size_full()
.child(self.render_header(cx))
.when_some(last_warning, |this, warning| {
this.child(
Alert::new("pr-warning")
@@ -326,127 +368,12 @@ impl Render for PullRequestsView {
)
})
.child(
v_flex()
.relative()
.flex_1()
.min_h_0()
.w_full()
.when(count > 0, |this| {
this.child(
uniform_list("prl", count, move |range, _, cx| {
range
.map(|ix| {
let pr_ix = visible[ix];
let pr = &store.read(cx).pull_requests[pr_ix];
let pr_id = pr.id;
let title = pr.activity_subject();
let id_hex = pr.id.to_hex();
let age = relative_time(pr.created_at);
let status = store.read(cx).status_of(pr);
let profile = directory.read(cx).profile(&pr.pubkey, cx);
let author = profile.name();
let workspace = workspace.clone();
let store = store.clone();
h_flex()
.id(ix)
.w_full()
.h(px(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(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(
&workspace,
id,
move |window, cx| {
cx.new(|cx| {
PullRequestDetailView::new(
workspace_for_build.clone(),
store.clone(),
pr_id,
window,
cx,
)
})
},
window,
cx,
);
})
.child(status_badge(status))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(
div()
.text_base()
.text_ellipsis()
.whitespace_nowrap()
.child(title),
)
.child(
h_flex()
.gap_2()
.text_xs()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(pr.pubkey)
.name(author.clone())
.picture(
profile.picture(),
)
.small(),
)
.child(div().child(author)),
)
.child(SharedString::from("opened"))
.child(
div()
.text_color(
cx.theme()
.colors
.muted_foreground,
)
.child(SharedString::from(
&id_hex[..8],
)),
)
.child(SharedString::from(age)),
),
)
.into_any_element()
})
.collect()
})
.track_scroll(&self.scroll_handle)
.size_full(),
)
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(
"prl-scroll",
self.scroll_handle.clone(),
)),
)
})
.when(count == 0, |this| {
this.child(empty_state(filter.empty_message()))
}),
EventList::new("prl")
.toolbar(self.render_header(cx))
.scroll_handle(self.scroll_handle.clone())
.rows(rows)
.empty_message(filter.empty_message())
.render(cx),
)
.into_any_element()
}
+33 -65
View File
@@ -1,10 +1,12 @@
use std::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, uniform_list,
WeakEntity, Window, div, px,
};
use signed_state::{CheckoutsStore, RepoStore};
use ui::button::Button;
@@ -14,14 +16,11 @@ use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::layout::panel::Panel;
use ui::menu::Menu;
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::tabs::{Tab, Tabs};
use ui::theme::ActiveTheme as _;
use super::helpers::{ForkCompare, fork_display_name, truncate_label};
use super::helpers::{ForkCompare, truncate_label};
use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::repo::helpers::commit_row;
use crate::shared::progress::error_row;
use crate::shared::widgets::empty_state;
use crate::workspace::Workspace;
@@ -41,7 +40,7 @@ pub struct NewPullRequestView {
subject: Entity<InputState>,
description: Entity<InputState>,
pub(super) merge_base: Option<String>,
pub(super) commits: Option<Vec<signed_git::FileCommit>>,
pub(super) commits: Option<Arc<Vec<signed_git::FileCommit>>>,
pub(super) loading: bool,
pub(super) error: Option<SharedString>,
submitting: bool,
@@ -159,6 +158,12 @@ impl NewPullRequestView {
}
}
/// Reaps finished tasks, then queues another.
pub(super) fn push_task(&mut self, task: gpui::Task<Result<(), anyhow::Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn submit(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
if self.submitting || self.loading {
return;
@@ -210,7 +215,7 @@ impl NewPullRequestView {
);
Ok(())
});
self.tasks.push(task);
self.push_task(task);
}
fn open_commit_diff(&mut self, commit_id: &str, window: &mut Window, cx: &mut Context<Self>) {
@@ -264,7 +269,9 @@ 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(&fork_display_name(&fork.announcement)),
Some(fork) => truncate_label(&crate::repo::helpers::announcement_display_name(
&fork.announcement,
)),
None => self.repo_path.as_ref().map_or_else(
|| SharedString::from("No source"),
|path| truncate_label(&path.display().to_string()),
@@ -368,12 +375,7 @@ impl NewPullRequestView {
fn render_content(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new("new-pr-loading"))
.into_any_element();
return crate::shared::widgets::centered_spinner("new-pr-loading");
}
if !self.has_source() {
return empty_state("Choose a local checkout or an announced fork to compare");
@@ -394,50 +396,23 @@ impl NewPullRequestView {
if commits.is_empty() {
return empty_state("No commits between the branches");
}
let commits = commits.clone();
let commits = Arc::clone(commits);
let view = cx.entity().downgrade();
v_flex()
.relative()
.flex_1()
.min_h_0()
.child(
uniform_list("new-pr-commits", commits.len(), move |range, _, cx| {
range
.map(|ix| {
let commit = commits[ix].clone();
let id = commit.id.clone();
let view = view.clone();
commit_row(
ix,
&commit,
None,
move |window, cx| {
crate::shared::log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(&id, window, cx);
}));
},
cx,
)
})
.collect()
})
.track_scroll(&self.scroll_handle)
.size_full(),
)
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(
"new-pr-commits-scroll",
self.scroll_handle.clone(),
)),
)
.into_any_element()
crate::shared::event_list::commit_list(
"new-pr-commits",
"new-pr-commits-scroll",
commits,
self.scroll_handle.clone(),
|_, _, _| None,
move |commit, window, cx| {
let id = commit.id.clone();
crate::shared::log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(&id, window, cx);
}));
},
cx,
)
}
}
@@ -472,14 +447,7 @@ impl Render for NewPullRequestView {
.rows(3)
.placeholder("Describe..."),
)
.when_some(self.error.clone(), |this, error| {
this.child(
div()
.text_xs()
.text_color(cx.theme().ramps.destructive.base)
.child(error),
)
}),
.when_some(error_row(&self.error, cx), |this, error| this.child(error)),
)
.child(self.render_tabs(cx)),
)
@@ -1,4 +1,5 @@
use std::path::{Path, PathBuf};
use std::sync::Arc;
use gpui::{App, AppContext as _, Context, PathPromptOptions, SharedString, Window};
use nostr::prelude::Url;
@@ -9,6 +10,19 @@ 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()
@@ -56,7 +70,7 @@ impl NewPullRequestView {
})?;
Ok(())
});
self.tasks.push(task);
self.push_task(task);
}
pub(crate) fn apply_folder_path(
@@ -93,7 +107,7 @@ impl NewPullRequestView {
})?;
Ok(())
});
self.tasks.push(task);
self.push_task(task);
}
fn apply_checkout(
@@ -126,12 +140,7 @@ impl NewPullRequestView {
}
let announced = self.store.read(cx).head.clone();
let base = announced
.as_ref()
.filter(|branch| branches.contains(branch))
.cloned()
.or_else(|| branches.iter().find(|branch| *branch == "main").cloned())
.unwrap_or_else(|| branches[0].clone());
let base = preferred_branch(&branches, announced);
let compare = current
.filter(|branch| branches.contains(branch))
.unwrap_or_else(|| base.clone());
@@ -266,7 +275,7 @@ impl NewPullRequestView {
}
Ok(())
});
self.tasks.push(task);
self.push_task(task);
}
fn apply_fork(
@@ -299,16 +308,7 @@ impl NewPullRequestView {
}
let announced = self.store.read(cx).head.clone();
let base = announced
.filter(|branch| base_branches.contains(branch))
.map(SharedString::from)
.or_else(|| {
base_branches
.iter()
.find(|branch| branch.as_str() == "main")
.map(|branch| SharedString::from(branch.clone()))
})
.unwrap_or_else(|| SharedString::from(base_branches[0].clone()));
let base = preferred_branch(&base_branches, announced);
let compare = compare_branches
.iter()
.find(|branch| branch.as_str() == "main")
@@ -321,7 +321,7 @@ impl NewPullRequestView {
mirror_path,
});
self.error = None;
self.base = base;
self.base = SharedString::from(base);
self.compare = compare;
self.branches = base_branches.into_iter().map(SharedString::from).collect();
self.sync_selectors(window, cx);
@@ -378,7 +378,7 @@ impl NewPullRequestView {
match result {
Ok((merge_base, commits, diff)) => {
this.merge_base = Some(merge_base);
this.commits = Some(commits);
this.commits = Some(Arc::new(commits));
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
}
Err(error) => {
@@ -392,6 +392,6 @@ impl NewPullRequestView {
})?;
Ok(())
});
self.tasks.push(task);
self.push_task(task);
}
}
@@ -5,12 +5,13 @@ use gpui::{
};
use signed_state::RepoStore;
use ui::button::Button;
use ui::common::{h_flex, v_flex};
use ui::common::{ResultLogErr as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::layout::panel::Panel;
use ui::theme::ActiveTheme as _;
use crate::shared::progress::error_row;
use crate::workspace::Workspace;
pub struct SendPatchView {
@@ -65,7 +66,7 @@ impl SendPatchView {
self.error = None;
cx.notify();
let sync_error = self.store.update(cx, |store, cx| {
let task = self.store.update(cx, |store, cx| {
store.open_pull_request(
(!subject.is_empty()).then_some(subject),
description,
@@ -75,22 +76,30 @@ impl SendPatchView {
None,
None,
cx,
);
store.last_error.clone()
)
});
if let Some(error) = sync_error {
self.submitting = false;
self.error = Some(error.into());
cx.notify();
return;
}
let panel_id = self.panel_id.clone();
crate::shared::log_dropped(
self.workspace
.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)),
);
cx.spawn(async move |this, cx| match task.await {
Ok(()) => {
this.update(cx, |this, cx| {
let panel_id = this.panel_id.clone();
crate::shared::log_dropped(
this.workspace
.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)),
);
})
.log_err();
}
Err(error) => {
this.update(cx, |this, cx| {
this.submitting = false;
this.error = Some(error.to_string().into());
cx.notify();
})
.log_err();
}
})
.detach();
}
fn render_footer(&self, cx: &Context<Self>) -> AnyElement {
@@ -159,14 +168,7 @@ impl Render for SendPatchView {
.rows(12)
.placeholder("diff --git a/file.txt b/file.txt"),
)
.when_some(self.error.clone(), |this, error| {
this.child(
div()
.text_xs()
.text_color(cx.theme().ramps.destructive.base)
.child(error),
)
}),
.when_some(error_row(&self.error, cx), |this, error| this.child(error)),
)
.child(self.render_footer(cx))
}
+2 -1
View File
@@ -88,6 +88,7 @@ pub fn open_repo_item(
cx,
);
}
RepoItem::Patch => {}
// Opening a patch series directly is not a feature.
_ => {}
}
}
+20 -28
View File
@@ -14,8 +14,6 @@ use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::layout::resizable::{Resizable, ResizableState};
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _;
use ui::tree::{Tree, TreeItem};
use utils::relative_time_secs;
@@ -257,18 +255,10 @@ impl DiffPane {
.track_scroll(&self.scroll_handle)
.size_full(),
)
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(
"commit-diff-scroll",
self.scroll_handle.clone(),
)),
)
.child(crate::shared::widgets::scroll_overlay(
"commit-diff-scroll",
self.scroll_handle.clone(),
))
.into_any_element()
};
@@ -304,14 +294,12 @@ impl DiffPane {
.gap_2()
.text_xs()
.child(
div()
.text_color(cx.theme().ramps.success.base)
.child(format!("+{}", file.insertions)),
Badge::new("file-insertions", format!("+ {}", file.insertions))
.variant(BadgeVariant::Success),
)
.child(
div()
.text_color(cx.theme().ramps.destructive.base)
.child(format!("-{}", file.deletions)),
Badge::new("file-deletions", format!("- {}", file.deletions))
.variant(BadgeVariant::Danger),
),
)
}),
@@ -334,7 +322,10 @@ impl Render for DiffPane {
Resizable::new("commit-diff-split", self.split.clone())
.axis(Axis::Horizontal)
.pane_with_min(tree, px(120.))
.pane_with_min(detail, px(240.)),
.pane_with_min(detail, px(240.))
.flex_1()
.min_w_0()
.h_full(),
)
}
}
@@ -381,6 +372,12 @@ impl CommitDiffView {
}
}
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), anyhow::Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn load(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.loading = true;
self.error = None;
@@ -424,7 +421,7 @@ impl CommitDiffView {
Ok(())
});
self.tasks.push(task);
self.push_task(task);
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
@@ -513,12 +510,7 @@ impl Panel for CommitDiffView {
impl Render for CommitDiffView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let body: AnyElement = if self.loading {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new("commit-diff-loading"))
.into_any_element()
crate::shared::widgets::centered_spinner("commit-diff-loading")
} else if let Some(error) = self.error.clone() {
empty_state(error)
} else {
+23 -20
View File
@@ -8,7 +8,7 @@ use gpui::{
use settings::SettingsStore;
use signed_state::{Backend, CheckoutsStore};
use ui::button::{Button, ButtonVariant};
use ui::common::{h_flex, v_flex};
use ui::common::{ResultLogErr as _, h_flex, v_flex};
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::icons::{Icon, IconRole};
@@ -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};
use crate::shared::progress::{DialogProgress, 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.
@@ -94,17 +94,26 @@ impl CreateRepoDialog {
let servers = self.grasp_state.read(cx).grasp_servers.clone();
if name.is_empty() {
self.fail("Repository name is required", cx);
self.state.update(cx, |state, cx| {
state.fail("Repository name is required");
cx.notify();
});
return;
}
if servers.is_empty() {
self.fail("Add at least one grasp server", cx);
self.state.update(cx, |state, cx| {
state.fail("Add at least one grasp server");
cx.notify();
});
return;
}
let backend = Backend::global(cx);
let Some(user) = backend.read(cx).current_user() else {
self.fail("Sign in to create a repository", cx);
self.state.update(cx, |state, cx| {
state.fail("Sign in to create a repository");
cx.notify();
});
return;
};
@@ -123,8 +132,10 @@ impl CreateRepoDialog {
let close = self.handle.clone();
let handle = window.window_handle();
cx.spawn(async move |_this, cx| match task.await {
Ok((announcement, local_path)) => {
run_dialog_task_with(
task,
cx,
move |(announcement, local_path), cx| {
cx.update_window(handle, |_, window, cx| {
let checkouts = CheckoutsStore::global(cx);
checkouts.update(cx, |store, cx| {
@@ -140,23 +151,15 @@ impl CreateRepoDialog {
);
close.close(cx);
})
.ok();
}
Err(error) => {
.log_err();
},
move |error, cx| {
state.update(cx, |state, cx| {
state.fail(error.to_string());
cx.notify();
});
}
})
.detach();
}
fn fail(&mut self, message: impl Into<gpui::SharedString>, cx: &mut Context<Self>) {
self.state.update(cx, |state, cx| {
state.fail(message);
cx.notify();
});
},
);
}
}
@@ -13,6 +13,8 @@ use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use crate::shared::progress::error_row;
/// State of the grasp-server section of a publish dialog, so async results can be rendered.
#[derive(Default)]
pub struct GraspServersState {
@@ -137,14 +139,7 @@ pub fn grasp_servers_field(
.child("Loading your grasp servers..."),
)
})
.when_some(error, |section, error| {
section.child(
div()
.text_xs()
.text_color(cx.theme().ramps.destructive.base)
.child(error),
)
})
.when_some(error_row(&error, cx), |section, error| section.child(error))
})
.into_any_element()
}
@@ -155,6 +150,7 @@ fn render_server_row(
state: Entity<GraspServersState>,
cx: &App,
) -> AnyElement {
let relay = relay.clone();
h_flex()
.w_full()
.gap_1()
@@ -168,7 +164,7 @@ fn render_server_row(
.text_color(cx.theme().colors.muted_foreground)
.text_xs()
.rounded(cx.theme().radius.control)
.child(server_host(relay)),
.child(server_host(&relay)),
)
.child(
Button::new(SharedString::from(format!("remove-relay:{ix}")))
@@ -176,9 +172,12 @@ fn render_server_row(
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click(move |_, _, cx| {
// A row's index can desync after a prior removal; match by value.
state.update(cx, |state, cx| {
if ix < state.grasp_servers.len() {
state.grasp_servers.remove(ix);
if let Some(at) =
state.grasp_servers.iter().position(|known| known == &relay)
{
state.grasp_servers.remove(at);
cx.notify();
}
});
+35 -23
View File
@@ -10,7 +10,7 @@ use signed_core::RepoAddr;
use signed_git::Repo;
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::common::{ResultLogErr as _, v_flex};
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::icons::{Icon, IconRole};
@@ -20,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};
use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with};
pub struct InitRepoDialog {
handle: DialogHandle,
@@ -105,17 +105,26 @@ impl InitRepoDialog {
.filter(|branch| !branch.is_empty());
if name.is_empty() {
self.fail("Repository name is required", cx);
self.state.update(cx, |state, cx| {
state.fail("Repository name is required");
cx.notify();
});
return;
}
if servers.is_empty() {
self.fail("Add at least one grasp server", cx);
self.state.update(cx, |state, cx| {
state.fail("Add at least one grasp server");
cx.notify();
});
return;
}
let backend = Backend::global(cx);
let Some(user) = backend.read(cx).current_user() else {
self.fail("Sign in to publish a repository", cx);
self.state.update(cx, |state, cx| {
state.fail("Sign in to publish a repository");
cx.notify();
});
return;
};
@@ -134,31 +143,25 @@ impl InitRepoDialog {
let close = self.handle.clone();
let handle = window.window_handle();
cx.spawn(async move |_this, cx| match task.await {
Ok(announcement) => {
run_dialog_task_with(
task,
cx,
move |announcement, cx| {
cx.update_window(handle, |_, _window, cx| {
close.close(cx);
if let Some(view) = view.upgrade() {
view.update(cx, |this, cx| this.apply_announcement(announcement, cx));
}
})
.ok();
}
Err(error) => {
.log_err();
},
move |error, cx| {
state.update(cx, |state, cx| {
state.fail(error.to_string());
cx.notify();
});
}
})
.detach();
}
fn fail(&mut self, message: impl Into<SharedString>, cx: &mut Context<Self>) {
self.state.update(cx, |state, cx| {
state.fail(message);
cx.notify();
});
},
);
}
}
@@ -271,9 +274,18 @@ fn load_branches(dialog: Entity<InitRepoDialog>, cx: &mut App) {
})
.await;
let Ok((branches, current)) = loaded else {
log::warn!("failed to list branches for the default branch selector");
return;
let (branches, current) = match loaded {
Ok(loaded) => loaded,
Err(error) => {
log::warn!("failed to list branches for the default branch selector: {error}");
dialog.update(cx, |dialog, cx| {
dialog.state.update(cx, |state, cx| {
state.fail("Could not list the repository's branches");
cx.notify();
});
});
return;
}
};
dialog.update(cx, |dialog, cx| {
+31 -7
View File
@@ -1,25 +1,31 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div, px,
};
use signed_state::RepoStore;
use ui::button::{Button, ButtonVariant};
use ui::common::v_flex;
use ui::common::{ResultLogErr as _, v_flex};
use ui::dialog::{Dialog, DialogHandle};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::{DialogProgress, error_row};
pub struct ResetRemoteDialog {
handle: DialogHandle,
store: Entity<RepoStore>,
deleted: Vec<String>,
state: Entity<DialogProgress>,
}
impl ResetRemoteDialog {
pub fn new(store: Entity<RepoStore>, deleted: Vec<String>, cx: &mut App) -> Entity<Self> {
let state = cx.new(|_| DialogProgress::default());
cx.new(|_| Self {
handle: DialogHandle::new(true),
store,
deleted,
state,
})
}
}
@@ -30,12 +36,16 @@ impl Render for ResetRemoteDialog {
let store = self.store.clone();
let cancel_close = self.handle.clone();
let confirm_close = self.handle.clone();
let content_state = self.state.clone();
let action_state = self.state.clone();
Dialog::new("reset-remote-dialog")
.handle(self.handle.clone())
.min_width(px(480.))
.title("Reset remote to local")
.content(move |_, cx| {
let progress = content_state.read(cx);
v_flex()
.gap_2()
.child(
@@ -60,12 +70,15 @@ impl Render for ResetRemoteDialog {
}))
.into_any_element()
})
.when_some(error_row(&progress.error, cx), |el, error| el.child(error))
.into_any_element()
})
.actions(move |_, _| {
.actions(move |_, cx| {
let busy = action_state.read(cx).busy;
let store = store.clone();
let cancel_close = cancel_close.clone();
let confirm_close = confirm_close.clone();
let confirm_state = action_state.clone();
let cancel: AnyElement = Button::new("cancel-reset-remote")
.label("Cancel")
@@ -76,15 +89,26 @@ impl Render for ResetRemoteDialog {
let confirm: AnyElement = Button::new("confirm-reset-remote")
.label("Reset remote")
.variant(ButtonVariant::Destructive)
.on_click(move |_, _, cx| {
.loading(busy)
.disabled(busy)
.on_click(move |_, window, cx| {
let task = store.update(cx, |store, cx| store.reset_repository(cx));
cx.spawn(async move |_cx| {
if let Err(error) = task.await {
log::error!("failed to reset remote: {error:#}");
let state = confirm_state.clone();
let close = confirm_close.clone();
let handle = window.window_handle();
cx.spawn(async move |cx| match task.await {
Ok(()) => {
cx.update_window(handle, |_, _, cx| close.close(cx))
.log_err();
}
Err(error) => {
state.update(cx, |state, cx| {
state.fail(error.to_string());
cx.notify();
});
}
})
.detach();
confirm_close.close(cx);
})
.into_any_element();
+15 -2
View File
@@ -493,6 +493,12 @@ impl RepoFilesView {
.into_any_element()
}
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn open_file(&mut self, path: &str, window: &mut Window, cx: &mut Context<Self>) {
self.selected_file = Some(path.into());
@@ -528,7 +534,14 @@ impl RepoFilesView {
return;
};
// Tree paths originate from git, so symlink escapes are accepted; only
// crafted components are rejected, and visibly.
if unsafe_path {
self.files.insert(
path.to_string(),
FileContent::Failed("Cannot open file".into()),
);
cx.notify();
return;
}
@@ -600,7 +613,7 @@ impl RepoFilesView {
Ok(())
});
self.tasks.push(task);
self.push_task(task);
}
fn drop_preview_of(&mut self, path: &str) {
@@ -705,6 +718,6 @@ impl RepoFilesView {
Ok(())
});
self.tasks.push(task);
self.push_task(task);
}
}
+2 -3
View File
@@ -17,10 +17,9 @@ use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use utils::relative_time_secs;
use super::helpers::{
bound_repo_label, clone_group, clone_row, fork_row, nostr_clone_url, repo_display_name,
};
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>) {
+34 -43
View File
@@ -9,10 +9,9 @@ use gpui::{
use metadata::ProfileDirectory;
use nostr::prelude::{RelayUrl, ToBech32};
use signed_core::Announcement;
use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo};
use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo, WorktreeSnapshot};
use signed_state::{Nip34Binding, RepoListStore, RepoStore};
use ui::avatar::Avatar;
use ui::clipboard::ClipboardButton;
use ui::combobox::ComboboxState;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
@@ -20,12 +19,36 @@ use ui::theme::ActiveTheme as _;
use utils::relative_time_secs;
use super::RepoDetailView;
use crate::shared::tree::{TreeItemSeed, build_tree_items};
use crate::shared::tree::{TreeItemSeed, build_tree_items, sorted_worktree_paths};
const GUTTER_WIDTH: f32 = 44.;
pub const DIFF_ROW_HEIGHT: f32 = 20.;
pub const COMMIT_ROW_HEIGHT: f32 = 56.;
/// The announcement's name, falling back to its id.
pub fn announcement_display_name(announcement: &Announcement) -> SharedString {
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()))
}
/// The first eight hex characters of an object id, for row labels.
pub fn short_id(hex: &str) -> SharedString {
SharedString::from(hex.get(..8).unwrap_or(hex).to_owned())
}
/// Snapshots the worktree and derives the explorer's tree rows and paths.
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 paths = sorted_worktree_paths(&snapshot.entries);
Ok((snapshot, tree, paths))
}
#[derive(Clone, Copy)]
pub(super) enum DiffRow {
Hunk {
@@ -67,32 +90,7 @@ pub(super) fn clone_group(
.font_semibold()
.child(SharedString::from(label)),
)
.child(clone_row(id, command.clone(), cx))
.into_any_element()
}
/// One copyable clone command with its text visible next to the copy icon.
pub(super) 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())
.child(crate::shared::widgets::clone_row(id, command.clone(), cx))
.into_any_element()
}
@@ -193,13 +191,7 @@ pub fn repo_display_name(store: &RepoStore) -> SharedString {
store
.announcement
.as_ref()
.map(|announcement| {
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()))
})
.map(announcement_display_name)
.unwrap_or_default()
}
@@ -253,12 +245,7 @@ pub(super) fn source_hash(text: &str) -> u64 {
}
pub(super) fn preview_spinner() -> AnyElement {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(ui::spinner::Spinner::new("repo-preview-spinner"))
.into_any_element()
crate::shared::widgets::centered_spinner("repo-preview-spinner")
}
/// The kit grammar for a path; only four languages are supported.
@@ -330,7 +317,11 @@ pub(super) fn render_diff_row(hunks: &[DiffHunk], row: DiffRow, cx: &App) -> Any
old_start, old_lines, new_start, new_lines
)))
.into_any_element(),
DiffRow::Line { hunk, line } => render_diff_line(&hunks[hunk].lines[line], cx),
DiffRow::Line { hunk, line } => match hunks.get(hunk).and_then(|h| h.lines.get(line)) {
Some(line) => render_diff_line(line, 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(),
},
}
}
+95 -83
View File
@@ -1,24 +1,24 @@
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString,
Styled as _, Task, UniformListScrollHandle, WeakEntity, Window, div, uniform_list,
Styled as _, Task, UniformListScrollHandle, WeakEntity, Window, div,
};
use signed_git::{CommitList, Repo};
use signed_git::{CommitList, FileCommit, Repo};
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::icons::{Icon, IconRole};
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use super::RepoDetailView;
use super::commit_diff::CommitDiffView;
use super::helpers::commit_row;
use crate::shared::event_list::commit_list;
use crate::shared::panels;
use crate::workspace::Workspace;
@@ -28,8 +28,12 @@ pub struct RepoHistoryView {
detail: WeakEntity<RepoDetailView>,
sync_directory: Entity<SyncStatusDirectory>,
worktree: Option<PathBuf>,
all_commits: Option<CommitList>,
all_commits: Option<Arc<CommitList>>,
loading_all_commits: bool,
/// The loaded commit list, shared with the render without a per-frame copy.
commits: Arc<Vec<FileCommit>>,
/// The last load failure, shown instead of the empty list.
error: Option<SharedString>,
scroll_handle: UniformListScrollHandle,
tasks: Vec<Task<Result<(), Error>>>,
}
@@ -49,6 +53,8 @@ impl RepoHistoryView {
worktree: None,
all_commits: None,
loading_all_commits: false,
commits: Arc::new(Vec::new()),
error: None,
scroll_handle: UniformListScrollHandle::new(),
tasks: Vec::new(),
}
@@ -74,6 +80,12 @@ impl RepoHistoryView {
self.load(cx);
}
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn load(&mut self, cx: &mut Context<Self>) {
if self.loading_all_commits || self.all_commits.is_some() {
return;
@@ -93,8 +105,13 @@ impl RepoHistoryView {
.await;
this.update(cx, |this, cx| {
if let Ok(list) = result {
this.all_commits = Some(list);
match result {
Ok(list) => {
this.commits = Arc::new(list.commits.clone());
this.all_commits = Some(Arc::new(list));
this.error = None;
}
Err(error) => this.error = Some(error.to_string().into()),
}
this.loading_all_commits = false;
cx.notify();
@@ -103,7 +120,7 @@ impl RepoHistoryView {
Ok(())
});
self.tasks.push(task);
self.push_task(task);
}
pub fn open_commit_diff(
@@ -140,22 +157,39 @@ 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")
} else if let Some(error) = self.error.clone() {
let weak = cx.entity().downgrade();
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new("commits-loading"))
.child(
Alert::new("commits-error")
.severity(AlertSeverity::Danger)
.title("Failed to load commits")
.message(error)
.style(AlertStyle::Inline)
.on_dismiss(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.error = None;
cx.notify();
}) {
log::warn!("failed to dismiss commits error: {error}");
}
}),
)
.into_any_element()
} else {
crate::shared::widgets::empty_state("Failed to load commits")
};
};
if list.commits.is_empty() {
if self.commits.is_empty() {
return crate::shared::widgets::empty_state("No commits found");
}
let commits = list.commits.clone();
let commits = Arc::clone(&self.commits);
let shown = commits.len();
let total = list.total;
let view = cx.entity().downgrade();
@@ -180,70 +214,60 @@ impl Render for RepoHistoryView {
let pushing = self.store.read(cx).pushing;
let list = commit_list(
"commits",
"commits-scroll",
commits,
self.scroll_handle.clone(),
move |ix, commit, _| {
ahead
.iter()
.find(|(id, _)| id.starts_with(commit.id.as_str()))
.map(|(ahead_id, path)| {
let detail = detail.clone();
let path = path.clone();
let target = ahead_id.clone();
let short = commit.id.clone();
Button::new(("sync-commit", ix))
.label("Sync")
.icon(Icon::named(IconRole::ArrowUp))
.variant(ButtonVariant::Secondary)
.small()
.disabled(pushing)
.tooltip(Tooltip::text(format!("Sync up to {short}")))
.on_click(move |_, window, cx| {
cx.stop_propagation();
if let Some(detail) = detail.upgrade() {
detail.update(cx, |this, cx| {
this.sync_checkout_commit(
path.clone(),
target.clone(),
window,
cx,
);
});
}
})
.into_any_element()
})
},
move |commit, window, cx| {
if let Err(error) = view.update(cx, |this, cx| {
this.open_commit_diff(&commit.id, window, cx);
}) {
log::warn!("failed to open commit diff: {error}");
}
},
cx,
);
v_flex()
.relative()
.flex_1()
.w_full()
.min_h_0()
.child(
uniform_list("commits", shown, move |range, _, cx| {
range
.map(|ix| {
let commit = commits[ix].clone();
let id = commit.id.clone();
let view = view.clone();
let action = ahead
.iter()
.find(|(id, _)| id.starts_with(commit.id.as_str()))
.map(|(ahead, path)| {
let detail = detail.clone();
let path = path.clone();
let target = ahead.clone();
let short = commit.id.clone();
Button::new(("sync-commit", ix))
.label("Sync")
.icon(Icon::named(IconRole::ArrowUp))
.variant(ButtonVariant::Secondary)
.small()
.disabled(pushing)
.tooltip(Tooltip::text(format!("Sync up to {short}")))
.on_click(move |_, window, cx| {
cx.stop_propagation();
if let Some(detail) = detail.upgrade() {
detail.update(cx, |this, cx| {
this.sync_checkout_commit(
path.clone(),
target.clone(),
window,
cx,
);
});
}
})
.into_any_element()
});
commit_row(
ix,
&commit,
action,
move |window, cx| {
if let Err(error) = view.update(cx, |this, cx| {
this.open_commit_diff(&id, window, cx);
}) {
log::warn!("failed to open commit diff: {error}");
}
},
cx,
)
})
.collect()
})
.track_scroll(&self.scroll_handle)
.size_full(),
)
.child(list)
.when(shown < total, |this| {
this.child(
div()
@@ -254,18 +278,6 @@ impl Render for RepoHistoryView {
.child(format!("Showing {shown} of {total} commits")),
)
})
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(
"commits-scroll",
self.scroll_handle.clone(),
)),
)
.into_any_element()
}
}
+6 -20
View File
@@ -38,14 +38,14 @@ pub mod history;
pub mod refs;
use files::RepoFilesView;
use helpers::{RepoData, load_repo_data};
use helpers::{RepoData, announcement_display_name, load_repo_data, snapshot_worktree};
use history::RepoHistoryView;
use refs::RefSwitcher;
use crate::issues::IssuesView;
use crate::pull_requests::PullRequestsView;
use crate::shared::log_dropped;
use crate::shared::tree::{build_tree_items, sorted_worktree_paths};
use crate::shared::tree::sorted_worktree_paths;
use crate::workspace::Workspace;
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -685,12 +685,7 @@ impl RepoDetailView {
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn(async move {
let snapshot = Repo::open(&worktree)?.snapshot()?;
let tree = build_tree_items(&snapshot.entries);
let paths = sorted_worktree_paths(&snapshot.entries);
Ok::<_, Error>((snapshot, tree, paths))
})
.background_spawn(async move { snapshot_worktree(worktree) })
.await;
this.update(cx, |this, cx| {
@@ -734,12 +729,7 @@ impl RepoDetailView {
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn(async move {
let snapshot = Repo::open(&worktree)?.snapshot()?;
let tree = build_tree_items(&snapshot.entries);
let paths = sorted_worktree_paths(&snapshot.entries);
Ok::<_, Error>((snapshot, tree, paths))
})
.background_spawn(async move { snapshot_worktree(worktree) })
.await;
this.update(cx, |this, cx| match result {
@@ -838,7 +828,7 @@ impl RepoDetailView {
match result {
Ok(()) => {
if let Some(tag) = &tag {
let short = commit.chars().take(7).collect::<String>();
let short = crate::repo::helpers::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}")),
@@ -1047,11 +1037,7 @@ impl Panel for RepoDetailView {
return SharedString::from(name.to_string_lossy().into_owned());
}
if let Some(announcement) = store.announcement.as_ref() {
return announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()));
return announcement_display_name(announcement);
}
SharedString::from("Repository")
}
+2
View File
@@ -1,5 +1,6 @@
use gpui::{App, AppContext as _, Entity, SharedString, WeakEntity, Window};
use ui::combobox::{Combobox, ComboboxState};
use ui::icons::{IconRole, icon};
use super::RepoDetailView;
use super::helpers::sync_selector;
@@ -19,6 +20,7 @@ impl RefSwitcher {
ComboboxState::new(
Combobox::new("branch-select", "Branch", Vec::new())
.placeholder("Branch")
.selected_icon(icon(IconRole::GitBranch))
.on_change(move |value, window, cx| {
if let Some(name) = value
&& let Err(error) = branch_view.update(cx, |this, cx| {
+23 -3
View File
@@ -118,6 +118,7 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
v_flex()
.gap_2()
.children(servers.iter().enumerate().map(|(ix, server)| {
let server = server.clone();
h_flex()
.gap_1()
.child(
@@ -129,7 +130,7 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
.text_color(cx.theme().colors.muted_foreground)
.text_xs()
.rounded(cx.theme().radius.control)
.child(display_server(server)),
.child(display_server(&server)),
)
.child(
Button::new(format!("settings-remove-server:{ix}"))
@@ -142,7 +143,16 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
store.update(cx, |store, cx| {
store.edit(
|settings| {
settings.grasp_servers.default_servers.remove(ix);
// 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,
);
@@ -218,6 +228,7 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement {
v_flex()
.gap_2()
.children(scan_paths.iter().enumerate().map(|(ix, path)| {
let path = path.clone();
h_flex()
.gap_1()
.child(
@@ -241,7 +252,16 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement {
store.update(cx, |store, cx| {
store.edit(
|settings| {
settings.local_repos.scan_paths.remove(ix);
// 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,
);
+1
View File
@@ -60,6 +60,7 @@ impl Render for SettingsDialog {
Dialog::new("settings-dialog")
.handle(self.handle.clone())
.width(px(600.))
.height(px(560.))
.title("Settings")
.content(move |_, cx| {
+239
View File
@@ -0,0 +1,239 @@
//! The shared issue and pull-request lists: toolbar, uniform rows, scrollbar
//! overlay, and empty state, plus the scrollable commit list.
use std::rc::Rc;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, ClickEvent, ElementId, InteractiveElement as _, IntoElement,
ParentElement as _, Pixels, SharedString, StatefulInteractiveElement as _, Styled as _,
UniformListScrollHandle, Window, div, px, uniform_list,
};
use nostr::prelude::PublicKey;
use signed_core::RepoStatus;
use signed_git::FileCommit;
use ui::avatar::Avatar;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::theme::ActiveTheme as _;
use crate::repo::helpers::commit_row;
use crate::shared::widgets::{empty_state, scroll_overlay, status_badge};
/// The height of one issue or pull-request row.
pub const ROW_HEIGHT: f32 = 73.;
/// 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,
pub status: RepoStatus,
pub title: SharedString,
pub author: SharedString,
pub picture: Option<SharedString>,
pub pubkey: PublicKey,
pub short_id: SharedString,
pub age: SharedString,
pub on_click: EventHandler,
}
/// The shared issue and pull-request list: toolbar, uniform rows, scrollbar
/// overlay, and empty state.
pub struct EventList {
id: ElementId,
toolbar: Option<AnyElement>,
rows: Vec<EventRow>,
scroll_handle: UniformListScrollHandle,
empty_message: SharedString,
}
impl EventList {
/// Builds a list rendering `rows` under `toolbar`.
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
toolbar: None,
rows: Vec::new(),
scroll_handle: UniformListScrollHandle::new(),
empty_message: "Nothing here".into(),
}
}
/// Replaces the list's scroll handle with the caller's.
pub fn scroll_handle(mut self, handle: UniformListScrollHandle) -> Self {
self.scroll_handle = handle;
self
}
/// Sets the toolbar above the rows.
pub fn toolbar(mut self, toolbar: AnyElement) -> Self {
self.toolbar = Some(toolbar);
self
}
/// Sets the rendered rows.
pub fn rows(mut self, rows: Vec<EventRow>) -> Self {
self.rows = rows;
self
}
/// Sets the empty-state message shown when no rows match.
pub fn empty_message(mut self, message: impl Into<SharedString>) -> Self {
self.empty_message = message.into();
self
}
/// Renders the list.
pub fn render(self, _cx: &App) -> AnyElement {
let count = self.rows.len();
let rows = self.rows;
let row_height = px(ROW_HEIGHT);
v_flex()
.relative()
.flex_1()
.min_h_0()
.w_full()
.children(self.toolbar)
.when(count > 0, |this| {
this.child(
uniform_list((self.id.clone(), "rows"), count, move |range, _, cx| {
range
.map(|ix| {
let Some(row) = rows.get(ix) else {
return div().into_any_element();
};
event_row(row, row_height, cx)
})
.collect()
})
.track_scroll(&self.scroll_handle)
.size_full(),
)
.child(scroll_overlay(
(self.id.clone(), "scroll"),
self.scroll_handle.clone(),
))
})
.when(count == 0, |this| {
this.child(empty_state(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 {
h_flex()
.id(row.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 = 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())
.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,
commits: Arc<Vec<FileCommit>>,
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();
v_flex()
.relative()
.flex_1()
.min_h_0()
.child(
uniform_list(id, count, move |range, _, cx| {
range
.map(|ix| {
let commit = commits[ix].clone();
let action = action(ix, &commit, cx);
let on_click = on_click.clone();
let row_commit = commit.clone();
commit_row(
ix,
&commit,
action,
move |window, cx| on_click(&row_commit, window, cx),
cx,
)
})
.collect()
})
.track_scroll(&scroll_handle)
.size_full(),
)
.child(scroll_overlay(scroll_id, scroll_handle))
.into_any_element()
}
+20
View File
@@ -1,3 +1,8 @@
use gpui::{App, Entity};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
pub mod event_list;
pub mod panels;
pub mod progress;
pub mod tree;
@@ -15,3 +20,18 @@ pub fn log_dropped<T>(result: Result<T, anyhow::Error>) {
);
}
}
/// Tracks a detail view's author, commenters, and repository owner for
/// profile prefetch.
pub fn track_event_participants(
author: Option<PublicKey>,
owner: Option<PublicKey>,
comments: impl Iterator<Item = PublicKey>,
directory: &Entity<ProfileDirectory>,
cx: &mut App,
) {
let mut keys: Vec<PublicKey> = author.into_iter().collect();
keys.extend(comments);
keys.extend(owner);
directory.update(cx, |directory, cx| directory.track(keys, cx));
}
+40 -2
View File
@@ -1,10 +1,11 @@
use gpui::{
AnyElement, App, Context, IntoElement as _, ParentElement as _, SharedString, Styled as _,
Subscription, div,
AnyElement, App, AsyncApp, Context, Entity, IntoElement as _, ParentElement as _, SharedString,
Styled as _, Subscription, Task, div,
};
use signed_core::RepoAddr;
use signed_state::{Backend, BackendEvent, PushStepStatus};
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 _;
@@ -126,3 +127,40 @@ pub fn push_steps_row(steps: &[PushStepStatus], cx: &App) -> Option<AnyElement>
Some(v_flex().gap_1().children(rows).into_any_element())
}
/// Runs a dialog task to completion.
pub fn run_dialog_task<T: 'static>(
task: Task<Result<T, anyhow::Error>>,
state: &Entity<DialogProgress>,
handle: &DialogHandle,
cx: &mut App,
) {
let state = state.clone();
let handle = handle.clone();
run_dialog_task_with(
task,
cx,
move |_, cx| cx.update(|cx| handle.close(cx)),
move |error, cx| {
state.update(cx, |state, cx| {
state.fail(error.to_string());
cx.notify();
});
},
);
}
/// Runs a dialog task to completion, with explicit success and failure sinks.
pub fn run_dialog_task_with<T: 'static>(
task: Task<Result<T, anyhow::Error>>,
cx: &mut App,
on_success: impl FnOnce(T, &mut AsyncApp) + 'static,
on_error: impl FnOnce(anyhow::Error, &mut AsyncApp) + 'static,
) {
cx.spawn(async move |cx| match task.await {
Ok(value) => on_success(value, cx),
Err(error) => on_error(error, cx),
})
.detach();
}
+59 -3
View File
@@ -1,9 +1,14 @@
use gpui::{AnyElement, App, IntoElement, ParentElement as _, SharedString, Styled as _, div};
use gpui::{
AnyElement, App, ElementId, IntoElement, ParentElement as _, SharedString, Styled as _, div,
};
use signed_core::RepoStatus;
use ui::badge::{Badge, BadgeVariant};
use ui::common::StyledExt as _;
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;
@@ -25,7 +30,7 @@ pub fn status_badge(status: RepoStatus) -> Badge {
/// A centered empty-state message filling the available space.
pub fn empty_state(message: impl Into<SharedString>) -> AnyElement {
let message = message.into();
ui::common::v_flex()
v_flex()
.size_full()
.items_center()
.justify_center()
@@ -33,6 +38,57 @@ pub fn empty_state(message: impl Into<SharedString>) -> AnyElement {
.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()
@@ -1,4 +1,5 @@
use std::rc::Rc;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
@@ -50,7 +51,7 @@ impl RepositoryEntry {
pub(crate) struct RepositorySwitcher {
search: Entity<InputState>,
directory: Entity<ProfileDirectory>,
entries: Vec<RepositoryEntry>,
entries: Arc<Vec<RepositoryEntry>>,
open: bool,
on_open: OpenHandler,
on_create: CreateHandler,
@@ -71,7 +72,7 @@ impl RepositorySwitcher {
Self {
search,
directory,
entries: Vec::new(),
entries: Arc::new(Vec::new()),
open: false,
on_open: Rc::new(on_open),
on_create: Rc::new(on_create),
@@ -81,7 +82,7 @@ impl RepositorySwitcher {
}
pub(super) fn set_entries(&mut self, entries: Vec<RepositoryEntry>, cx: &mut Context<Self>) {
self.entries = entries;
self.entries = Arc::new(entries);
cx.notify();
}
@@ -97,7 +98,7 @@ impl Render for RepositorySwitcher {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = *cx.theme();
let weak = cx.entity().downgrade();
let entries = self.entries.clone();
let entries = Arc::clone(&self.entries);
let search = self.search.clone();
let directory = self.directory.clone();
@@ -147,15 +148,19 @@ impl Render for RepositorySwitcher {
}
});
let visible: Vec<RepositoryEntry> = entries
.iter()
.filter(|entry| query.is_empty() || entry.label.to_lowercase().contains(&query))
.cloned()
.collect();
let visible: Arc<Vec<RepositoryEntry>> = Arc::new(
entries
.iter()
.filter(|entry| {
query.is_empty() || entry.label.to_lowercase().contains(&query)
})
.cloned()
.collect(),
);
let row_height = rems(2.0).to_pixels(window.rem_size()) + px(2.);
let list_height = (row_height * visible.len() as f32).min(px(280.));
let list_entries = visible.clone();
let list_entries = Arc::clone(&visible);
let list_directory = directory.clone();
let list_weak = row_weak.clone();
let list_on_open = on_open.clone();
@@ -218,7 +223,7 @@ impl Render for RepositorySwitcher {
.h(row_height)
.px_3()
.gap_2()
.rounded(theme.radius.control)
.rounded(theme.radius.full)
.text_sm()
.hover(|row| row.bg(theme.colors.muted))
.child(entry.avatar(&list_directory, cx))