chore: restructure ui components
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s

This commit is contained in:
2026-11-27 21:05:37 +07:00
parent db3d53f2aa
commit 44c2dc6345
114 changed files with 9117 additions and 7675 deletions
+343 -174
View File
@@ -1,11 +1,13 @@
use std::ops::Range;
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 _, Pixels, Render, ScrollHandle, SharedString,
StatefulInteractiveElement as _, Styled as _, Subscription, WeakEntity, Window, div, px,
AnyElement, App, AppContext as _, Context, ElementId, Entity, InteractiveElement as _,
IntoElement, ListAlignment, ListSizingBehavior, ListState, ParentElement as _, Pixels, Render,
ScrollHandle, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task,
WeakEntity, Window, div, list, px, rems, uniform_list,
};
use metadata::ProfileDirectory;
use nostr::prelude::{EventId, Kind, Url};
@@ -18,21 +20,21 @@ use ui::button::Button;
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, PanelSlot, SplitSide};
use ui::input::{Input, InputState};
use ui::layout::panel::{Panel, PanelSlot, PanelStack, SplitSide};
use ui::layout::root::RootContext as _;
use ui::scroll_area::ScrollArea;
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use utils::relative_time;
use crate::app::AppRoot;
use crate::issues::helpers::{comment_form, comments_section};
use crate::pull_requests::dialogs::update::UpdatePrDialog;
use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::repo::helpers::short_id;
use crate::shared::commit_diff::{CommitDiffView, DiffPane};
use crate::shared::labels::{ProfileDirectoryExt as _, ShortIdExt as _};
use crate::shared::log_dropped;
use crate::shared::widgets::status_badge;
use crate::shared::{log_dropped, track_event_participants};
const NOT_FOUND: &str = "Pull request not found";
const SIDEBAR_ID: &str = "Discussion";
@@ -41,7 +43,7 @@ const SIDEBAR_WIDTH: Pixels = px(320.);
#[derive(Clone, PartialEq, Eq)]
struct PrBinding {
description: String,
patch: String,
patch: Arc<str>,
tip: Option<String>,
base: Option<String>,
clone_urls: Vec<Url>,
@@ -51,10 +53,33 @@ struct PrBinding {
struct CommitRow {
commit: FileCommit,
/// The row's element id.
id: SharedString,
/// The abbreviated commit id shown in the row.
short: SharedString,
/// The stats badge's element id.
stats_id: SharedString,
insertions: usize,
deletions: usize,
}
impl CommitRow {
fn new(commit: FileCommit, insertions: usize, deletions: usize) -> Self {
let id = SharedString::from(commit.id.clone());
let short = commit.id.short_id();
let stats_id = SharedString::from(format!("pr-commit-stats:{}", commit.id));
Self {
commit,
id,
short,
stats_id,
insertions,
deletions,
}
}
}
pub struct PullRequestDetailView {
workspace: WeakEntity<AppRoot>,
store: Entity<RepoStore>,
@@ -68,9 +93,10 @@ pub struct PullRequestDetailView {
error: Option<SharedString>,
bound: Option<PrBinding>,
load_generation: u64,
_store_subscription: Subscription,
pane: Entity<DiffPane>,
scroll_handle: ScrollHandle,
tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
load_task: Option<gpui::Task<Result<(), anyhow::Error>>>,
}
impl PullRequestDetailView {
@@ -82,7 +108,12 @@ impl PullRequestDetailView {
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let pane = cx.new(DiffPane::new);
let pane = cx.new(|cx| DiffPane::new(false, cx));
// A new revision or a rebind must reach the panel without reopening it.
let store_subscription = cx.observe(&store, |this, _store, cx| {
this.sync(cx);
});
cx.defer_in(window, move |this, _window, cx| {
this.sync(cx);
@@ -101,14 +132,16 @@ impl PullRequestDetailView {
error: None,
bound: None,
load_generation: 0,
_store_subscription: store_subscription,
pane,
scroll_handle: ScrollHandle::new(),
tasks: Vec::new(),
load_task: None,
}
}
/// Opens the pull request in the main panel and its discussion in the split pane.
pub fn open(
panels: &Entity<PanelStack>,
workspace: &WeakEntity<AppRoot>,
store: Entity<RepoStore>,
pr_id: EventId,
@@ -120,47 +153,61 @@ impl PullRequestDetailView {
let detail_store = store.clone();
let directory = ProfileDirectory::new(cx);
log_dropped(workspace.update(cx, |root, cx| {
root.panels().update(cx, |panels, cx| {
panels.open(
PanelSlot::Main,
id,
{
let directory = directory.clone();
move |window, cx| {
cx.new(|cx| {
Self::new(
workspace_for_build.clone(),
detail_store.clone(),
pr_id,
directory.clone(),
window,
cx,
)
})
}
},
window,
cx,
);
panels.update(cx, |panels, cx| {
panels.open(
PanelSlot::Main,
id,
{
let directory = directory.clone();
move |window, cx| {
cx.new(|cx| {
Self::new(
workspace_for_build.clone(),
detail_store.clone(),
pr_id,
directory.clone(),
window,
cx,
)
})
}
},
window,
cx,
);
let sidebar = cx.new(|cx| {
PullRequestSidebarView::new(store.clone(), pr_id, directory.clone(), cx)
});
let sidebar = cx
.new(|cx| PullRequestSidebarView::new(store.clone(), pr_id, directory.clone(), cx));
panels.insert_split_at(
SIDEBAR_ID,
SIDEBAR_WIDTH,
SplitSide::Trailing,
Arc::new(sidebar),
cx,
);
})
}));
panels.insert_split_at(
SIDEBAR_ID,
SIDEBAR_WIDTH,
SplitSide::Trailing,
Arc::new(sidebar),
cx,
);
});
}
/// Opens the update dialog for the pull request's current revision.
fn open_update_dialog(&mut self, cx: &mut Context<Self>) {
let root = self
.store
.read(cx)
.pull_requests
.iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
.cloned();
if let Some(root) = root {
let dialog = UpdatePrDialog::new(self.store.clone(), root, cx);
cx.open_dialog(dialog);
}
}
fn sync(&mut self, cx: &mut Context<Self>) {
let loaded = self.store.read(cx).loaded;
let binding = {
let store = self.store.read(cx);
store.addr().and_then(|addr| {
@@ -185,7 +232,7 @@ impl PullRequestDetailView {
PrBinding {
description: root.content.clone(),
patch: PullRequest::new(root).patch(store.patches.iter()),
patch: PullRequest::new(root).patch(store.patches.iter()).into(),
tip,
base,
clone_urls,
@@ -237,24 +284,22 @@ impl PullRequestDetailView {
..
} = binding;
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let task: Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let nostr_diff = cx
.background_spawn({
let patch = patch.clone();
let patch = Arc::clone(&patch);
async move { PatchParser::patch_diffs(&patch) }
})
.await;
let nostr_commits = cx
.background_spawn({
let patch = patch.clone();
let patch = Arc::clone(&patch);
async move {
PatchParser::patch_commits_with_stats(&patch)
.into_iter()
.map(|(commit, insertions, deletions)| CommitRow {
commit,
insertions,
deletions,
.map(|(commit, insertions, deletions)| {
CommitRow::new(commit, insertions, deletions)
})
.collect::<Vec<_>>()
}
@@ -273,6 +318,7 @@ impl PullRequestDetailView {
let clone_urls = clone_urls.clone();
let base = base.clone();
let tip = tip.clone();
Some(
cx.background_spawn(async move {
let repo = Mirrors::ensure(&addr, &clone_urls)?;
@@ -315,11 +361,7 @@ impl PullRequestDetailView {
(0, 0)
}
};
CommitRow {
insertions,
deletions,
commit,
}
CommitRow::new(commit, insertions, deletions)
})
.collect::<Vec<_>>();
@@ -354,7 +396,8 @@ impl PullRequestDetailView {
Ok(())
});
self.tasks.push(task);
// Assigning drops the previous load task, cancelling superseded work.
self.load_task = Some(task);
}
fn open_commit_diff(
@@ -395,9 +438,9 @@ impl PullRequestDetailView {
}));
}
fn render_body(&self, cx: &mut Context<Self>) -> AnyElement {
fn render_body(&self, cx: &mut Context<Self>) -> impl IntoElement {
if self.bound.is_none() {
return div().into_any_element();
return div();
}
let description = if self.description.is_empty() {
@@ -413,13 +456,10 @@ impl PullRequestDetailView {
.p_2()
.text_sm()
.child(description)
.into_any_element()
}
fn render_commits(&self, cx: &mut Context<Self>) -> AnyElement {
fn render_commits(&self, cx: &mut Context<Self>) -> impl IntoElement {
let count = self.commits.len();
let worktree = self.worktree.clone();
let view = cx.entity().downgrade();
v_flex()
.w_full()
@@ -445,60 +485,68 @@ impl PullRequestDetailView {
.child("No commits found"),
)
})
.children(self.commits.iter().map(|row| {
let commit = &row.commit;
let row_id = commit.id.clone();
let worktree = worktree.clone();
let view = view.clone();
.when(count > 0, |this| {
this.child(v_flex().max_h(px(320.)).min_h_0().child(uniform_list(
"pr-commits",
count,
cx.processor(|this, range: Range<usize>, _window, cx| {
range.map(|index| this.render_commit(index, cx)).collect()
}),
)))
})
}
h_flex()
.id(commit.id.clone())
.px_2()
.h_12()
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.child(
div()
.w_20()
.flex_none()
.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(GroupedBadge::new(
format!("pr-commit-stats:{}", commit.id),
row.insertions,
row.deletions,
))
.on_click(move |_, window, cx| {
if let Some(worktree) = worktree.clone() {
log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(worktree, &row_id, window, cx);
}));
}
})
.into_any_element()
/// One commit row of the patch series.
fn render_commit(&mut self, index: usize, cx: &mut Context<Self>) -> AnyElement {
let Some(row) = self.commits.get(index) else {
return div().into_any_element();
};
let commit = &row.commit;
let row_id = row.id.clone();
let worktree = self.worktree.clone();
let theme = cx.theme();
h_flex()
.id(row.id.clone())
.px_2()
.h_12()
.w_full()
.gap_3()
.border_b_1()
.border_color(theme.colors.border)
.hover(|this| this.bg(theme.colors.muted_hover))
.child(
div()
.w_20()
.flex_none()
.text_sm()
.text_color(theme.colors.muted_foreground)
.child(row.short.clone()),
)
.child(
div()
.flex_1()
.min_w_0()
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
)
.child(GroupedBadge::new(
row.stats_id.clone(),
row.insertions,
row.deletions,
))
.on_click(cx.listener(move |this, _, window, cx| {
if let Some(worktree) = worktree.clone() {
this.open_commit_diff(worktree, &row_id, window, cx);
}
}))
.into_any_element()
}
fn render_changes(&self, cx: &App) -> AnyElement {
self.pane.read(cx).render_flow(self.pane.downgrade(), cx)
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
fn render_header(&self, cx: &mut Context<Self>) -> impl IntoElement {
let (title, status, branch, author, created_at, target_branch) = {
let store = self.store.read(cx);
let Some(root) = store
@@ -506,7 +554,7 @@ impl PullRequestDetailView {
.iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
else {
return div().into_any_element();
return div();
};
(
root.activity_subject(),
@@ -524,7 +572,6 @@ impl PullRequestDetailView {
let backend = Backend::global(cx);
let can_update = backend.read(cx).current_user() == Some(author);
let weak = cx.entity().downgrade();
let muted = cx.theme().colors.muted_foreground;
v_flex()
@@ -548,6 +595,7 @@ impl PullRequestDetailView {
.child(div().text_color(muted).child("opened by"))
.child(
h_flex()
.min_w_0()
.gap_1()
.child(
Avatar::new(author)
@@ -555,7 +603,7 @@ impl PullRequestDetailView {
.picture(author_picture)
.small(),
)
.child(author_name),
.child(div().min_w_0().truncate().child(author_name)),
)
.child(
div()
@@ -565,46 +613,41 @@ impl PullRequestDetailView {
.when_some(target_branch, |this, target| {
this.child(div().text_color(muted).child("targeting"))
.child(
Badge::new(format!("target-branch:{target}"), target)
.variant(BadgeVariant::Outline)
.small()
.flex_none(),
Badge::new(
(
ElementId::from("target-branch"),
SharedString::from(target.clone()),
),
target.clone(),
)
.variant(BadgeVariant::Outline)
.small()
.flex_none(),
)
})
.when_some(branch, |this, branch| {
this.child(div().text_color(muted).child("from")).child(
Badge::new(format!("source-branch:{branch}"), branch)
.variant(BadgeVariant::Outline)
.small()
.flex_none(),
Badge::new(
(
ElementId::from("source-branch"),
SharedString::from(branch.clone()),
),
branch.clone(),
)
.variant(BadgeVariant::Outline)
.small()
.flex_none(),
)
})
.child(div().flex_1())
.when(can_update, |this| {
this.child(Button::new("update-pr").label("Update").small().on_click(
move |_, _, cx| {
log_dropped(weak.update(cx, |this, cx| {
let root = this
.store
.read(cx)
.pull_requests
.iter()
.find(|pr| {
pr.id == this.pr_id && pr.kind == Kind::GitPullRequest
})
.cloned();
if let Some(root) = root {
let dialog =
UpdatePrDialog::new(this.store.clone(), root, cx);
cx.open_dialog(dialog);
}
}));
},
cx.listener(|this, _, _, cx| {
this.open_update_dialog(cx);
}),
))
}),
)
.into_any_element()
}
}
@@ -615,6 +658,7 @@ struct PullRequestSidebarView {
comment_input: Entity<InputState>,
directory: Entity<ProfileDirectory>,
scroll_handle: ScrollHandle,
comments_scroll: ListState,
_subscription: Subscription,
}
@@ -626,7 +670,7 @@ impl PullRequestSidebarView {
cx: &mut Context<Self>,
) -> Self {
let comment_input = InputState::builder().multiline().build(cx);
let weak = cx.entity().downgrade();
let weak = cx.weak_entity();
let subscription = cx.observe(&store, |this, _store, cx| {
this.track_participants(cx);
@@ -645,6 +689,7 @@ impl PullRequestSidebarView {
comment_input,
directory,
scroll_handle: ScrollHandle::new(),
comments_scroll: ListState::new(0, ListAlignment::Top, px(48.)),
_subscription: subscription,
}
}
@@ -664,7 +709,79 @@ impl PullRequestSidebarView {
.map(|comment| comment.pubkey)
.collect();
track_event_participants(author, owner, comments.into_iter(), &self.directory, cx);
self.directory
.track_participants(author, owner, comments.into_iter(), cx);
}
/// One comment card of the pull request's discussion.
fn render_comment(&self, ix: usize, cx: &App) -> AnyElement {
let Some(comment) = self.store.read(cx).comments_of(&self.pr_id).nth(ix) else {
return div().into_any_element();
};
let profile = self.directory.read(cx).profile(&comment.pubkey, cx);
let author = profile.name();
let age = relative_time(comment.created_at);
let content = SharedString::from(comment.content.as_str());
v_flex()
.gap_1()
.p_3()
.border_1()
.border_color(cx.theme().colors.border)
.rounded(cx.theme().radius.control)
.child(
h_flex()
.gap_2()
.text_sm()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(comment.pubkey)
.name(author.clone())
.picture(profile.picture())
.small(),
)
.child(author),
)
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child("commented"),
)
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(age)),
),
)
.child(div().text_sm().child(content))
.into_any_element()
}
/// Posts the sidebar composer's text as a comment on this pull request.
fn submit_comment(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let content = self.comment_input.read(cx).value().trim().to_string();
if content.is_empty() {
return;
}
let event = self
.store
.read(cx)
.pull_requests
.iter()
.find(|event| event.id == self.pr_id)
.cloned();
if let Some(event) = event {
self.store
.update(cx, |store, cx| store.comment(&event, content, cx));
}
self.comment_input
.update(cx, |input, cx| input.set_value("", window, cx));
}
}
@@ -684,37 +801,89 @@ impl Render for PullRequestSidebarView {
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
else {
return if store.loaded {
EmptyState::centered(NOT_FOUND)
EmptyState::centered(NOT_FOUND).into_any_element()
} else {
Spinner::centered("pr-loading")
Spinner::centered("pr-loading").into_any_element()
};
};
let root_id = root.id;
let discussion = ScrollArea::new("pr-discussion-scroll")
.handle(self.scroll_handle.clone())
.flex_1()
.min_h_0()
.child(v_flex().p_2().child(comments_section(
&self.store,
root_id,
&self.directory,
cx,
)))
.into_any_element();
let root_id = root.id;
let comments = self.store.read(cx).comments_of(&root_id).count();
if self.comments_scroll.item_count() != comments {
self.comments_scroll.reset(comments);
}
v_flex()
.size_full()
.min_h_0()
.child(discussion)
.child(div().flex_none().p_2().child(comment_form(
&self.store,
root_id,
&store.pull_requests,
&self.comment_input,
"pr-comment",
cx,
)))
.child(
ScrollArea::new("pr-discussion-scroll")
.handle(self.scroll_handle.clone())
.flex_1()
.min_h_0()
.child(
v_flex()
.p_2()
.gap_4()
.child(
h_flex()
.gap_2()
.child(Icon::named(IconRole::Message))
.child(div().text_sm().font_semibold().child("Discussion"))
.child(Badge::new(
format!("discussion-count:{root_id}"),
comments.to_string(),
)),
)
.child(
v_flex().max_h(rems(24.)).min_h_0().child(
list(
self.comments_scroll.clone(),
cx.processor(|this, ix: usize, _window, cx| {
this.render_comment(ix, cx)
}),
)
.with_sizing_behavior(ListSizingBehavior::Infer),
),
),
),
)
.child(
div().flex_none().p_2().child(
v_flex()
.gap_2()
.child(
Input::new("pr-comment-input", self.comment_input.clone())
.placeholder("Leave a comment...")
.rows(4),
)
.child(
h_flex()
.justify_between()
.child(
h_flex()
.gap_1()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(
Icon::named(IconRole::Markdown)
.size(px(12.))
.color(cx.theme().colors.muted_foreground),
)
.child("Markdown is supported"),
)
.child(
Button::new("pr-comment")
.label("Comment")
.tooltip(Tooltip::text("Post comment"))
.on_click(cx.listener(|this, _, window, cx| {
this.submit_comment(window, cx)
})),
),
),
),
)
.into_any_element()
}
}
@@ -780,7 +949,7 @@ impl Render for PullRequestDetailView {
.child(self.render_header(cx))
.child(self.render_body(cx))
.child(self.render_commits(cx))
.child(self.render_changes(cx)),
.child(self.pane.read(cx).render_flow(self.pane.downgrade(), cx)),
)
.into_any_element()
}
@@ -1,48 +1,51 @@
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div,
App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
Window, div,
};
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, dialog_submit_button};
use crate::shared::log_dropped;
pub struct UpdatePrDialog {
handle: DialogHandle,
store: Entity<RepoStore>,
root: Event,
patch: Entity<InputState>,
state: Entity<DialogProgress>,
busy: bool,
}
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,
busy: false,
})
}
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 {
if self.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.busy = true;
self.store.update(cx, |store, cx| {
store.update_pull_request(&self.root, patch, cx);
});
@@ -52,9 +55,11 @@ impl UpdatePrDialog {
impl Render for UpdatePrDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
const PATCH_HINT: &str = "Publish a new revision with the output of `git format-patch`.";
let patch = self.patch.clone();
let this = cx.entity().downgrade();
let action_state = self.state.clone();
let this = cx.weak_entity();
let busy = self.busy;
Dialog::new("update-pr-dialog")
.handle(self.handle.clone())
@@ -67,7 +72,7 @@ impl Render for UpdatePrDialog {
div()
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child("Publish a new revision with the output of `git format-patch`."),
.child(PATCH_HINT),
)
.child(
Field::new("update-patch", "Patch")
@@ -75,22 +80,17 @@ impl Render for UpdatePrDialog {
)
.into_any_element()
})
.actions(move |_, cx| {
.actions(move |_, _cx| {
let this = this.clone();
let busy = action_state.read(cx).busy;
vec![
dialog_submit_button(
"submit-update",
"Update pull request",
None,
busy,
&this,
|this, _window, cx| {
this.submit(cx);
Ok(())
},
)
.into_any_element() as AnyElement,
Button::new("submit-update")
.label("Update pull request")
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
log_dropped(this.update(cx, |this, cx| this.submit(cx)));
})
.into_any_element(),
]
})
}
+11 -10
View File
@@ -8,7 +8,7 @@ use ui::menu::MenuItem;
use utils::middle_truncate;
use super::NewPullRequestView;
use crate::repo::helpers::announcement_display_name;
use crate::shared::labels::AnnouncementExt as _;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PullRequestFilter {
@@ -90,9 +90,9 @@ pub fn source_menu_items(
let Some(path) = associated.get(index).cloned() else {
return;
};
if let Err(error) =
target.update(cx, |this, cx| this.apply_folder_path(path, window, cx))
{
if let Err(error) = target.update(cx, |this, cx| {
this.apply_folder_path(path, window, cx);
}) {
log::warn!("failed to apply checkout: {error}");
}
}),
@@ -102,8 +102,9 @@ pub fn source_menu_items(
let folder_view = view.clone();
items.push(
MenuItem::new("Choose another folder…").handler(move |window, cx| {
if let Err(error) = folder_view.update(cx, |this, cx| this.choose_checkout(window, cx))
{
if let Err(error) = folder_view.update(cx, |this, cx| {
this.choose_checkout(window, cx);
}) {
log::warn!("failed to choose checkout: {error}");
}
}),
@@ -120,7 +121,7 @@ pub fn source_menu_items(
SharedString::from(format!("by {}", shorten_owner(&candidate.owner)))
};
let title = format!("{} — {}", announcement_display_name(candidate), subtitle);
let title = format!("{} — {}", candidate.display_name(), subtitle);
let target = view.clone();
let candidates = Arc::clone(&candidates);
let checked = active_fork == Some(candidate.addr());
@@ -132,9 +133,9 @@ pub fn source_menu_items(
let Some(announcement) = candidates.get(index).cloned() else {
return;
};
if let Err(error) =
target.update(cx, |this, cx| this.choose_fork(announcement, window, cx))
{
if let Err(error) = target.update(cx, |this, cx| {
this.choose_fork(announcement, window, cx);
}) {
log::warn!("failed to choose fork: {error}");
}
}),
+153 -133
View File
@@ -1,3 +1,6 @@
use std::ops::Range;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
@@ -5,8 +8,8 @@ use gpui::{
Subscription, UniformListScrollHandle, WeakEntity, Window, div, uniform_list,
};
use metadata::ProfileDirectory;
use nostr::prelude::{Kind, PublicKey};
use signed_core::GitEvent;
use nostr::prelude::{EventId, Kind, PublicKey};
use signed_core::{GitEvent, RepoStatus};
use signed_state::RepoStore;
use ui::alert::{Alert, AlertSeverity};
use ui::avatar::Avatar;
@@ -33,16 +36,27 @@ pub use new::NewPullRequestView;
pub use send_patch::SendPatchView;
use crate::app::AppRoot;
use crate::issues::helpers::{StatusCounts, filter_by_status};
use crate::repo::helpers::short_id;
use crate::shared::labels::ShortIdExt as _;
use crate::shared::log_dropped;
use crate::shared::widgets::status_badge;
use crate::shared::widgets::{StatusCounts, status_badge};
/// One pull request row, with its display strings built on rebuild.
struct PrRow {
id: EventId,
/// The row's element id.
element_id: SharedString,
status: RepoStatus,
subject: SharedString,
author: PublicKey,
age: SharedString,
short: SharedString,
}
pub struct PullRequestsView {
workspace: WeakEntity<AppRoot>,
store: Entity<RepoStore>,
filter: PullRequestFilter,
visible_prs: Vec<usize>,
rows: Arc<Vec<PrRow>>,
counts: StatusCounts,
synced_filter: PullRequestFilter,
scroll_handle: UniformListScrollHandle,
@@ -57,7 +71,7 @@ impl PullRequestsView {
store: Entity<RepoStore>,
cx: &mut Context<Self>,
) -> Self {
let weak = cx.entity().downgrade();
let weak = cx.weak_entity();
let subscription = cx.observe(&store, |this, _store, cx| {
this.rebuild(cx);
});
@@ -72,7 +86,7 @@ impl PullRequestsView {
workspace,
store,
filter: PullRequestFilter::Open,
visible_prs: Vec::new(),
rows: Arc::new(Vec::new()),
counts: StatusCounts::default(),
synced_filter: PullRequestFilter::Open,
scroll_handle: UniformListScrollHandle::new(),
@@ -97,13 +111,29 @@ impl PullRequestsView {
.iter()
.filter(|pr| pr.kind == Kind::GitPullRequest);
filter_by_status(
StatusCounts::filter(
roots,
|pr| store.status_of(pr),
|status| filter.matches(status),
)
};
let rows: Vec<PrRow> = visible_prs
.iter()
.filter_map(|index| {
let pr = store.pull_requests.get(*index)?;
Some(PrRow {
id: pr.id,
element_id: SharedString::from(format!("pr:{}", pr.id.to_hex())),
status: store.status_of(pr),
subject: SharedString::from(pr.activity_subject()),
author: pr.pubkey,
age: SharedString::from(relative_time(pr.created_at)),
short: pr.id.to_hex().short_id(),
})
})
.collect();
let mut keys: Vec<PublicKey> = store
.pull_requests
.iter()
@@ -124,12 +154,14 @@ impl PullRequestsView {
});
let filter_changed = self.synced_filter != filter;
if !filter_changed && self.visible_prs == visible_prs && self.counts == counts {
if !filter_changed && self.rows.len() == rows.len() && self.counts == counts {
return;
}
self.synced_filter = filter;
self.visible_prs = visible_prs;
self.rows = Arc::new(rows);
self.counts = counts;
cx.notify();
}
@@ -199,14 +231,102 @@ impl PullRequestsView {
}));
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
/// One pull request row of the list.
fn render_pr(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
let Some(row) = self.rows.get(ix) else {
return div().into_any_element();
};
let profile = self.directory.read(cx).profile(&row.author, cx);
let pr_id = row.id;
let status = row.status;
h_flex()
.id(row.element_id.clone())
.w_full()
.h_16()
.px_2()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.on_click(cx.listener(move |this, _, window, cx| {
this.open_pr(pr_id, window, cx);
}))
.child(
h_flex()
.w_full()
.items_start()
.gap_2()
.child(h_flex().w_20().child(status_badge(status)))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(
div()
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(row.subject.clone()),
)
.child(
h_flex()
.gap_2()
.text_xs()
.child(
h_flex()
.min_w_0()
.gap_1()
.child(
Avatar::new(row.author)
.name(profile.name())
.picture(profile.picture())
.small(),
)
.child(
div().min_w_0().truncate().child(profile.name()),
),
)
.child("opened")
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(row.short.clone()),
)
.child(row.age.clone()),
),
),
)
.into_any_element()
}
/// Opens this pull request's detail panel in the split stack.
fn open_pr(&mut self, pr_id: EventId, window: &mut Window, cx: &mut Context<Self>) {
let panels = self
.workspace
.read_with(cx, |root, _| root.panels().clone());
let Ok(panels) = panels else {
log::warn!("pull request list outlived the app shell");
return;
};
PullRequestDetailView::open(
&panels,
&self.workspace,
self.store.clone(),
pr_id,
window,
cx,
);
}
fn render_header(&self, cx: &mut Context<Self>) -> impl IntoElement {
let counts = self.counts;
let colors = cx.theme().colors;
let muted = colors.muted_foreground;
let weak = cx.entity().downgrade();
let open_weak = cx.entity().downgrade();
let menu_open_weak = cx.entity().downgrade();
let patch_weak = cx.entity().downgrade();
let patch_weak = cx.weak_entity();
h_flex()
.px_2()
@@ -235,14 +355,10 @@ impl PullRequestsView {
.label(format!("Merged ({})", counts.applied))
.icon(Icon::named(IconRole::GitPullRequestMerged).color(muted)),
])
.on_change(move |filter, _, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.filter = filter;
this.rebuild(cx);
}) {
log::warn!("failed to switch PR filter: {error}");
}
}),
.on_change(cx.processor(|this, filter: PullRequestFilter, _, cx| {
this.filter = filter;
this.rebuild(cx);
})),
)
.child(div().flex_1())
.child(
@@ -251,19 +367,11 @@ impl PullRequestsView {
.icon(Icon::named(IconRole::GitPullRequest))
.small()
.open(self.new_pr_menu_open)
.on_click(move |_, window, cx| {
if let Err(error) =
open_weak.update(cx, |this, cx| this.open_new(window, cx))
{
log::warn!("failed to open new PR: {error}");
}
})
.on_open_change(move |open, _, cx| {
log_dropped(menu_open_weak.update(cx, |this, cx| {
this.new_pr_menu_open = open;
cx.notify();
}));
})
.on_click(cx.listener(|this, _, window, cx| this.open_new(window, cx)))
.on_open_change(cx.processor(|this, open: bool, _, cx| {
this.new_pr_menu_open = open;
cx.notify();
}))
.items(move |_, _| {
vec![MenuItem::new("Send Patch").handler({
let weak = patch_weak.clone();
@@ -275,7 +383,6 @@ impl PullRequestsView {
})]
}),
)
.into_any_element()
}
}
@@ -288,11 +395,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 visible = self.visible_prs.clone();
let directory = self.directory.clone();
let store = self.store.clone();
let workspace = self.workspace.clone();
let (last_error, last_warning) = {
let store = self.store.read(cx);
(store.last_error.clone(), store.last_warning.clone())
@@ -302,7 +404,7 @@ impl Render for PullRequestsView {
let dismiss_error_store = self.store.clone();
let scroll_handle = self.scroll_handle.clone();
let count = visible.len();
let count = self.rows.len();
v_flex()
.size_full()
@@ -345,95 +447,13 @@ impl Render for PullRequestsView {
.child(self.render_header(cx))
.when(count > 0, |this| {
this.child(
uniform_list("prl", count, move |range, _, cx| {
range
.map(|ix| {
// The store re-read per frame can shrink below a captured index.
let Some(pr) = visible.get(ix).and_then(|pr_ix| {
store.read(cx).pull_requests.get(*pr_ix)
}) else {
return div().into_any_element();
};
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 workspace = workspace.clone();
let store = store.clone();
h_flex()
.id(SharedString::from(format!("pr:{id_hex}")))
.w_full()
.h_16()
.px_2()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.on_click(move |_, window, cx| {
PullRequestDetailView::open(
&workspace,
store.clone(),
pr_id,
window,
cx,
);
})
.child(
h_flex()
.w_full()
.items_start()
.gap_2()
.child(h_flex().w_20().child(status_badge(status)))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(
div()
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(pr.activity_subject()),
)
.child(
h_flex()
.gap_2()
.text_xs()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(pr.pubkey)
.name(profile.name())
.picture(
profile.picture(),
)
.small(),
)
.child(
div().child(profile.name()),
),
)
.child("opened")
.child(
div()
.text_color(
cx.theme()
.colors
.muted_foreground,
)
.child(short_id(&id_hex)),
)
.child(relative_time(pr.created_at)),
),
),
)
.into_any_element()
})
.collect()
})
uniform_list(
"prl",
count,
cx.processor(|this, range: Range<usize>, _window, cx| {
range.map(|ix| this.render_pr(ix, cx)).collect()
}),
)
.track_scroll(&scroll_handle)
.size_full(),
)
+102 -62
View File
@@ -1,4 +1,5 @@
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
@@ -28,10 +29,9 @@ use utils::relative_time_secs;
use super::helpers::{ForkCompare, truncate_label};
use crate::app::AppRoot;
use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::repo::helpers::{announcement_display_name, short_id};
use crate::shared::commit_diff::{CommitDiffView, DiffPane};
use crate::shared::labels::{AnnouncementExt as _, ShortIdExt as _};
use crate::shared::log_dropped;
use crate::shared::progress::error_row;
pub struct NewPullRequestView {
workspace: WeakEntity<AppRoot>,
@@ -58,6 +58,8 @@ pub struct NewPullRequestView {
scroll_handle: UniformListScrollHandle,
pub(super) tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
source_open: bool,
/// The compare bar's source label, derived from `fork`/`repo_path`.
source_label: SharedString,
/// The checkouts, forks, and user the source menu lists.
checkouts: Arc<Vec<PathBuf>>,
forks: Arc<Vec<Announcement>>,
@@ -80,8 +82,8 @@ impl NewPullRequestView {
let subject = InputState::new(cx);
let description = InputState::builder().multiline().build(cx);
let pane = cx.new(DiffPane::new);
let weak = cx.entity().downgrade();
let pane = cx.new(|cx| DiffPane::new(false, cx));
let weak = cx.weak_entity();
let base_select = cx.new(|cx| {
ComboboxState::new(
@@ -188,6 +190,7 @@ impl NewPullRequestView {
scroll_handle: UniformListScrollHandle::new(),
tasks: Vec::new(),
source_open: false,
source_label: SharedString::from("No source"),
checkouts: Arc::default(),
forks: Arc::default(),
user: None,
@@ -195,22 +198,19 @@ 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;
}
let Some(merge_base) = self.merge_base.clone() else {
return;
};
let Some(repo_path) = self.work_path() else {
return;
};
let subject = self.subject.read(cx).value().to_string();
let description = self.description.read(cx).value().to_string();
let branch_name = self.compare.to_string();
@@ -236,6 +236,7 @@ impl NewPullRequestView {
cx,
)
});
if let Err(error) = publish.await {
this.update(cx, |this, cx| {
this.submitting = false;
@@ -244,29 +245,36 @@ impl NewPullRequestView {
})?;
return Ok(());
}
this.update(cx, |this, _cx| {
this.submitting = false;
})?;
log_dropped(workspace.update(cx, |root, cx| {
root.panels().clone().update(cx, |panels, cx| {
panels.close(PanelSlot::Split, &panel_id, cx)
})
}));
Ok(())
});
self.push_task(task);
self.tasks.push(task);
}
fn open_commit_diff(&mut self, commit_id: &str, window: &mut Window, cx: &mut Context<Self>) {
let Some(repo_path) = self.work_path() else {
return;
};
let id = match self.store.read(cx).addr() {
Some(addr) => SharedString::from(format!("commit:{addr}:{commit_id}")),
None => SharedString::from(format!("commit:{}:{commit_id}", repo_path.display())),
};
let workspace = self.workspace.clone();
let commit_id = commit_id.to_owned();
log_dropped(workspace.update(cx, |root, cx| {
root.panels().clone().update(cx, |panels, cx| {
panels.open(
@@ -303,9 +311,7 @@ impl NewPullRequestView {
}
fn render_compare_bar(&self, cx: &mut Context<Self>) -> AnyElement {
let weak = cx.entity().downgrade();
let weak_menu = cx.entity().downgrade();
let source_view = cx.entity().downgrade();
let source_view = cx.weak_entity();
let associated = Arc::clone(&self.checkouts);
let active_path = (self.fork.is_none())
@@ -313,17 +319,11 @@ impl NewPullRequestView {
.flatten();
let candidates = Arc::clone(&self.forks);
let user = signed_state::Backend::global(cx).read(cx).current_user();
let user = self.user;
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(&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()),
),
};
let source_label = self.source_label.clone();
let refresh_fork = self.fork.as_ref().map(|fork| fork.announcement.clone());
h_flex()
@@ -352,12 +352,10 @@ impl NewPullRequestView {
.child(
Menu::new("pr-source")
.open(self.source_open)
.on_change(move |open, _, cx| {
log_dropped(weak_menu.update(cx, |this, cx| {
this.source_open = open;
cx.notify();
}));
})
.on_change(cx.processor(|this, open: bool, _, cx| {
this.source_open = open;
cx.notify();
}))
.trigger(move |_, _| {
Button::new("compare-source")
.label(source_label.clone())
@@ -392,9 +390,9 @@ impl NewPullRequestView {
.icon(Icon::named(IconRole::Plus))
.loading(self.submitting)
.disabled(!can_submit)
.on_click(move |_, window, cx| {
log_dropped(weak.update(cx, |this, cx| this.submit(window, cx)));
}),
.on_click(cx.listener(|this, _, window, cx| {
this.submit(window, cx);
})),
)
.into_any_element()
}
@@ -402,7 +400,6 @@ impl NewPullRequestView {
fn render_tabs(&self, cx: &mut Context<Self>) -> AnyElement {
let files = self.pane.read(cx).diff().map_or(0, |diff| diff.files.len());
let commits = self.commits.as_ref().map_or(0, |commits| commits.len());
let weak = cx.entity().downgrade();
Tabs::new("new-pr-tabs")
.selected(self.active_tab)
@@ -413,26 +410,25 @@ impl NewPullRequestView {
.lead(Icon::named(IconRole::GitCommit)),
]
})
.on_change(move |index, _, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.active_tab = index;
cx.notify();
}));
})
.on_change(cx.processor(|this, index: usize, _, cx| {
this.active_tab = index;
cx.notify();
}))
.into_any_element()
}
fn render_content(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return Spinner::centered("new-pr-loading");
return Spinner::centered("new-pr-loading").into_any_element();
}
if !self.has_source() {
return EmptyState::centered("Choose a local checkout or an announced fork to compare");
return EmptyState::centered("Choose a local checkout or an announced fork to compare")
.into_any_element();
}
if self.commits.is_none() && self.error.is_some() {
return EmptyState::centered("Nothing to compare");
return EmptyState::centered("Nothing to compare").into_any_element();
}
match self.active_tab {
@@ -447,17 +443,20 @@ impl NewPullRequestView {
fn render_commits(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(commits) = self.commits.as_ref() else {
return EmptyState::centered("No commits");
return EmptyState::centered("No commits").into_any_element();
};
if commits.is_empty() {
return EmptyState::centered("No commits between the branches");
return EmptyState::centered("No commits between the branches").into_any_element();
}
let commits = Arc::clone(commits);
let view = cx.entity().downgrade();
let scroll_handle = self.scroll_handle.clone();
let open_commit = Rc::new(cx.processor(|this, commit_id: String, window, cx| {
this.open_commit_diff(&commit_id, window, cx);
}));
v_flex()
.relative()
.flex_1()
@@ -470,7 +469,7 @@ impl NewPullRequestView {
return div().into_any_element();
};
let row_id = commit.id.clone();
let view = view.clone();
let open_commit = open_commit.clone();
h_flex()
.id(commit.id.clone())
@@ -489,6 +488,7 @@ impl NewPullRequestView {
.justify_center()
.child(
h_flex()
.min_w_0()
.gap_2()
.overflow_hidden()
.child(
@@ -498,7 +498,7 @@ impl NewPullRequestView {
.text_color(
cx.theme().colors.muted_foreground,
)
.child(short_id(&commit.id)),
.child(commit.id.short_id()),
)
.child(
div()
@@ -520,9 +520,7 @@ impl NewPullRequestView {
),
)
.on_click(move |_, window, cx| {
log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(&row_id, window, cx);
}));
open_commit(row_id.clone(), window, cx);
})
.into_any_element()
})
@@ -581,7 +579,8 @@ impl NewPullRequestView {
})?;
Ok(())
});
self.push_task(task);
self.tasks.push(task);
}
pub(crate) fn apply_folder_path(
@@ -593,6 +592,7 @@ impl NewPullRequestView {
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
@@ -618,7 +618,8 @@ impl NewPullRequestView {
})?;
Ok(())
});
self.push_task(task);
self.tasks.push(task);
}
fn apply_checkout(
@@ -661,6 +662,7 @@ impl NewPullRequestView {
self.repo_path = Some(PathBuf::from(&path));
self.error = None;
self.refresh_source_label();
self.branches = branches.into_iter().map(SharedString::from).collect();
if let Some(addr) = self.store.read(cx).addr().cloned() {
@@ -681,6 +683,7 @@ impl NewPullRequestView {
.iter()
.map(|branch| (branch.clone(), branch.clone()))
.collect();
let base = self.base.clone();
let compare = self.compare.clone();
@@ -688,6 +691,7 @@ impl NewPullRequestView {
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);
@@ -709,8 +713,10 @@ impl NewPullRequestView {
let checkouts = CheckoutsStore::global(cx);
let repositories = RepoListStore::global(cx);
let backend = Backend::global(cx);
let user = backend.read(cx).current_user();
let checkouts = addr
.as_ref()
.map_or_else(Vec::new, |addr| checkouts.read(cx).associations_of(addr));
@@ -750,9 +756,11 @@ impl NewPullRequestView {
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)
@@ -760,6 +768,7 @@ impl NewPullRequestView {
.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();
@@ -775,12 +784,14 @@ impl NewPullRequestView {
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()
@@ -793,14 +804,17 @@ impl NewPullRequestView {
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))
}
})
@@ -816,9 +830,11 @@ impl NewPullRequestView {
}) {
log::warn!("failed to apply fork: {error}");
}
Ok(())
});
self.push_task(task);
self.tasks.push(task);
}
fn apply_fork(
@@ -868,6 +884,7 @@ impl NewPullRequestView {
mirror_path,
});
self.error = None;
self.refresh_source_label();
self.base = SharedString::from(base);
self.compare = compare;
self.branches = base_branches.into_iter().map(SharedString::from).collect();
@@ -875,23 +892,28 @@ impl NewPullRequestView {
self.reload_compare(cx);
}
/// Recomputes the compare bar's source label after a fork or checkout change.
fn refresh_source_label(&mut self) {
self.source_label = match &self.fork {
Some(fork) => truncate_label(&fork.announcement.display_name()),
None => self.repo_path.as_ref().map_or_else(
|| SharedString::from("No source"),
|path| truncate_label(&path.display().to_string()),
),
};
}
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 = self.compare_generation.wrapping_add(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));
@@ -900,6 +922,13 @@ impl NewPullRequestView {
return;
}
self.loading = true;
self.error = None;
self.compare_generation = self.compare_generation.wrapping_add(1);
let generation = self.compare_generation;
cx.notify();
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
@@ -922,6 +951,7 @@ impl NewPullRequestView {
return;
}
this.loading = false;
match result {
Ok((merge_base, commits, diff)) => {
this.merge_base = Some(merge_base);
@@ -935,11 +965,14 @@ impl NewPullRequestView {
this.error = Some(error.to_string().into());
}
}
cx.notify();
})?;
Ok(())
});
self.push_task(task);
self.tasks.push(task);
}
}
@@ -978,7 +1011,14 @@ impl Render for NewPullRequestView {
.rows(3)
.placeholder("Describe..."),
)
.when_some(error_row(&self.error, cx), |this, error| this.child(error)),
.when_some(self.error.clone(), |this, error| {
this.child(
div()
.text_sm()
.text_color(cx.theme().ramps.destructive.base)
.child(error),
)
}),
)
.child(self.render_tabs(cx)),
)
@@ -1,7 +1,7 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
Render, SharedString, Styled as _, WeakEntity, Window, div,
App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, Task, WeakEntity, Window, div,
};
use signed_state::RepoStore;
use ui::button::Button;
@@ -13,7 +13,6 @@ use ui::theme::ActiveTheme as _;
use crate::app::AppRoot;
use crate::shared::log_dropped;
use crate::shared::progress::error_row;
pub struct SendPatchView {
workspace: WeakEntity<AppRoot>,
@@ -24,6 +23,8 @@ pub struct SendPatchView {
patch: Entity<InputState>,
submitting: bool,
error: Option<SharedString>,
/// Holds the submit so a closed panel cancels it.
task: Option<Task<()>>,
}
impl SendPatchView {
@@ -47,6 +48,7 @@ impl SendPatchView {
patch,
submitting: false,
error: None,
task: None,
}
}
@@ -57,8 +59,8 @@ impl SendPatchView {
let subject = self.subject.read(cx).value().to_string();
let description = self.description.read(cx).value().to_string();
let patch = self.patch.read(cx).value().to_string();
if patch.is_empty() {
return;
}
@@ -79,10 +81,11 @@ impl SendPatchView {
cx,
)
});
let workspace = self.workspace.clone();
let panel_id = self.panel_id.clone();
cx.spawn(async move |this, cx| match task.await {
self.task = Some(cx.spawn(async move |this, cx| match task.await {
Ok(()) => {
log_dropped(workspace.update(cx, |root, cx| {
root.panels().clone().update(cx, |panels, cx| {
@@ -98,17 +101,16 @@ impl SendPatchView {
})
.log_err();
}
})
.detach();
}));
}
fn render_footer(&self, cx: &Context<Self>) -> AnyElement {
fn render_footer(&self, cx: &Context<Self>) -> impl IntoElement {
let can_submit = !self.submitting
&& !self.subject.read(cx).value().is_empty()
&& !self.patch.read(cx).value().is_empty();
let weak = cx.entity().downgrade();
h_flex()
.flex_none()
.px_4()
.py_2()
.w_full()
@@ -121,11 +123,8 @@ impl SendPatchView {
.icon(Icon::named(IconRole::ArrowUp))
.loading(self.submitting)
.disabled(!can_submit)
.on_click(move |_, _, cx| {
log_dropped(weak.update(cx, |this, cx| this.submit(cx)));
}),
.on_click(cx.listener(|this, _, _, cx| this.submit(cx))),
)
.into_any_element()
}
}
@@ -152,6 +151,7 @@ impl Render for SendPatchView {
v_flex()
.p_4()
.flex_1()
.min_h_0()
.gap_2()
.child(div().pr_16().child(
Input::new("patch-subject", self.subject.clone()).placeholder("Title"),
@@ -174,7 +174,14 @@ impl Render for SendPatchView {
.rows(12)
.placeholder("diff --git a/file.txt b/file.txt"),
)
.when_some(error_row(&self.error, cx), |this, error| this.child(error)),
.when_some(self.error.clone(), |this, error| {
this.child(
div()
.text_sm()
.text_color(cx.theme().ramps.destructive.base)
.child(error),
)
}),
)
.child(self.render_footer(cx))
}