new layout (wip) (#34)
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

Reviewed-on: #34
This commit was merged in pull request #34.
This commit is contained in:
2026-11-19 07:43:44 +00:00
parent a249174026
commit 5a597f43c4
368 changed files with 38791 additions and 18423 deletions
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "signed_app"
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
metadata = { path = "../metadata" }
paths = { path = "../paths" }
settings = { path = "../settings" }
signed_core = { path = "../signed_core" }
signed_git = { path = "../signed_git" }
signed_nostr = { path = "../signed_nostr" }
signed_state = { path = "../signed_state" }
utils = { path = "../utils" }
gpui.workspace = true
ui = { path = "../ui" }
nostr.workspace = true
anyhow.workspace = true
futures.workspace = true
log.workspace = true
+17
View File
@@ -0,0 +1,17 @@
use gpui::App;
use settings::{AppearanceMode, Settings};
use ui::theme::{ThemeVariant, follow_system, set_mode_override};
/// Applies the persisted light/dark/system preference to the kit theme.
pub fn apply_appearance(settings: &Settings, cx: &mut App) {
apply_appearance_mode(settings.appearance, cx);
}
/// Applies one appearance mode to the kit theme.
pub fn apply_appearance_mode(mode: AppearanceMode, cx: &mut App) {
match mode {
AppearanceMode::System => follow_system(cx),
AppearanceMode::Light => set_mode_override(Some(ThemeVariant::Light), cx),
AppearanceMode::Dark => set_mode_override(Some(ThemeVariant::Dark), cx),
}
}
+177
View File
@@ -0,0 +1,177 @@
pub mod helpers;
mod placeholder;
mod sign_in;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
Render, Styled as _, Subscription, Window, div,
};
use helpers::apply_appearance;
use settings::SettingsStore;
use signed_state::{Backend, BackendEvent};
use ui::common::h_flex;
use ui::icons::IconRole;
use ui::layout::panel::PanelRow;
use ui::layout::shell::Shell;
use ui::layout::titlebar::Titlebar;
use ui::theme::ActiveTheme as _;
use ui::toast::{Toast, Toasts};
use crate::app::placeholder::PlaceholderView;
use crate::app::sign_in::SignedOutView;
use crate::explore::ExploreView;
use crate::identity::passphrase::PassphraseDialog;
use crate::shared::log_dropped;
use crate::titlebar::{
CreateRepository, REPOSITORY_KEY_CONTEXT, SwitchRepository, TitlebarView,
bind_repository_shortcuts,
};
use crate::workspace::Workspace;
pub struct AppRoot {
workspace: Entity<Workspace>,
titlebar: Entity<TitlebarView>,
toasts: Entity<Toasts>,
sign_in: Entity<SignedOutView>,
empty: Entity<PlaceholderView>,
passphrase: Option<Entity<PassphraseDialog>>,
_subscriptions: Vec<Subscription>,
}
impl AppRoot {
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
bind_repository_shortcuts(cx);
let workspace = cx.new(|_| Workspace::new());
let titlebar = cx.new(|cx| TitlebarView::new(workspace.downgrade(), window, cx));
let toasts = cx.new(|_| Toasts::default());
let sign_in = cx.new(|_| SignedOutView::new());
let empty = cx.new(|_| PlaceholderView::new("Select a repository"));
let backend = Backend::global(cx);
let settings = SettingsStore::global(cx);
let mut subscriptions = Vec::new();
subscriptions.push(cx.subscribe_in(
&backend,
window,
|this, backend, event, window, cx| match event {
BackendEvent::PassphraseRequired => {
this.open_passphrase(cx);
}
BackendEvent::Error(message) => {
this.toasts.update(cx, |toasts, cx| {
toasts.push(Toast::new(message.clone()).icon(IconRole::Warning), cx);
});
}
BackendEvent::SignerChanged => {
this.workspace.update(cx, |workspace, cx| {
workspace.clear(cx);
});
if backend.read(cx).current_user().is_some() {
ExploreView::open(&this.workspace.downgrade(), window, cx);
}
}
_ => {}
},
));
subscriptions.push(cx.observe(&settings, |_this, store, cx| {
let settings = store.read(cx).settings().clone();
apply_appearance(&settings, cx);
}));
let app = cx.entity().downgrade();
window.defer(cx, move |_window, cx| {
if backend.read(cx).passphrase_required() {
log_dropped(app.update(cx, |this, cx| this.open_passphrase(cx)));
}
});
Self {
workspace,
titlebar,
toasts,
sign_in,
empty,
passphrase: None,
_subscriptions: subscriptions,
}
}
fn open_passphrase(&mut self, cx: &mut Context<Self>) {
self.passphrase = Some(PassphraseDialog::new(cx));
cx.notify();
}
}
impl Render for AppRoot {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let backend = Backend::global(cx);
let signed_in = backend.read(cx).current_user().is_some();
let titlebar_view = self.titlebar.read(cx);
let workspace = self.workspace.read(cx);
let main = workspace.active_main();
let prefix = h_flex()
.gap_1()
.child(titlebar_view.render_new_repository())
.child(titlebar_view.render_explore())
.child(titlebar_view.repository_switcher());
let tab_bar = h_flex()
.gap_1()
.when_some(titlebar_view.render_repo_tabs(workspace), |bar, tabs| {
bar.child(tabs)
});
div()
.relative()
.size_full()
.font_family(".SystemUIFont")
.text_color(cx.theme().colors.foreground)
.key_context(REPOSITORY_KEY_CONTEXT)
.on_action(cx.listener(|this, action: &SwitchRepository, window, cx| {
this.titlebar.update(cx, |titlebar, cx| {
titlebar.activate_shortcut(action.index, window, cx);
});
}))
.on_action(cx.listener(|this, _: &CreateRepository, window, cx| {
this.titlebar.update(cx, |titlebar, cx| {
titlebar.create_repository(window, cx);
});
}))
.child(
Shell::new("signed-shell")
.titlebar(
Titlebar::new("signed-titlebar")
.prefix(prefix)
.tab_bar(tab_bar)
.when_some(titlebar_view.render_user_menu(cx), |titlebar, menu| {
titlebar.suffix(menu)
}),
)
.panel(
PanelRow::new("signed-panel")
.when_some(main.as_ref(), |row, main| {
row.main(main.clone()).when(workspace.has_details(), |row| {
row.split(self.workspace.clone())
})
})
.when(!main.is_some() && signed_in, |row| {
row.main(self.empty.clone())
})
.when(!main.is_some() && !signed_in, |row| {
row.main(self.sign_in.clone())
}),
)
.toasts(self.toasts.clone()),
)
.child(titlebar_view.palette())
.children(titlebar_view.dialogs())
.when_some(self.passphrase.clone(), |el, view| el.child(view))
}
}
+30
View File
@@ -0,0 +1,30 @@
use gpui::{
App, Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div,
};
use ui::empty_state::EmptyState;
use ui::layout::panel::Panel;
/// A tab that stands in for a screen that is not ported yet.
pub struct PlaceholderView {
title: SharedString,
}
impl PlaceholderView {
pub fn new(title: impl Into<SharedString>) -> Self {
Self {
title: title.into(),
}
}
}
impl Panel for PlaceholderView {
fn title(&self, _cx: &App) -> SharedString {
self.title.clone()
}
}
impl Render for PlaceholderView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(EmptyState::new(self.title.clone()))
}
}
+75
View File
@@ -0,0 +1,75 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Context, Entity, FontWeight, IntoElement, ParentElement as _, Render, SharedString,
Styled as _, Window, div,
};
use ui::button::{Button, ButtonVariant};
use ui::common::v_flex;
use ui::layout::panel::Panel;
use crate::identity::import::ImportDialog;
use crate::identity::onboarding::OnboardingDialog;
pub struct SignedOutView {
onboarding: Option<Entity<OnboardingDialog>>,
import: Option<Entity<ImportDialog>>,
}
impl SignedOutView {
pub fn new() -> Self {
Self {
onboarding: None,
import: None,
}
}
fn open_onboarding(&mut self, cx: &mut Context<Self>) {
self.onboarding = Some(OnboardingDialog::new(cx));
cx.notify();
}
fn open_import(&mut self, cx: &mut Context<Self>) {
self.import = Some(ImportDialog::new(cx));
cx.notify();
}
}
impl Panel for SignedOutView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Signed")
}
}
impl Render for SignedOutView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.size_full()
.items_center()
.justify_center()
.gap_4()
.child(
div()
.text_2xl()
.font_weight(FontWeight::SEMIBOLD)
.child("Signed"),
)
.child(
v_flex()
.gap_1()
.w_48()
.child(
Button::new("onboarding")
.label("Join now")
.on_click(cx.listener(|this, _, _, cx| this.open_onboarding(cx))),
)
.child(
Button::new("import")
.label("Import identity")
.variant(ButtonVariant::Secondary)
.on_click(cx.listener(|this, _, _, cx| this.open_import(cx))),
),
)
.when_some(self.onboarding.clone(), |el, view| el.child(view))
.when_some(self.import.clone(), |el, view| el.child(view))
}
}
+186
View File
@@ -0,0 +1,186 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, Entity, InteractiveElement as _, IntoElement, ParentElement as _, SharedString,
StatefulInteractiveElement as _, Styled as _, WeakEntity, div, px,
};
use metadata::ProfileDirectory;
use signed_core::Announcement;
use signed_state::{RepoListStore, Timestamp};
use ui::avatar::Avatar;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time;
use crate::repo::actions::open_repo_panel;
use crate::workspace::Workspace;
const RECENT_COUNT: usize = 10;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(super) enum RepoFilter {
#[default]
All,
Recent,
}
impl RepoFilter {
/// Indices into the store's `announcements` this filter includes, in display order.
pub(super) fn visible(self, store: &RepoListStore, query: &str) -> Vec<usize> {
let announcements = &store.announcements;
let mut indices: Vec<usize> = (0..announcements.len()).collect();
let query = query.trim().to_lowercase();
if !query.is_empty() {
indices.retain(|&ix| {
let announcement = &announcements[ix];
let name = announcement.name.as_deref().unwrap_or(&announcement.id);
name.to_lowercase().contains(&query)
});
}
match self {
Self::All => {}
Self::Recent => indices.truncate(RECENT_COUNT),
}
indices
}
}
pub(super) fn render_card(
ix: usize,
announcement: &Announcement,
last_activity: Option<Timestamp>,
announcements: &[Announcement],
directory: &Entity<ProfileDirectory>,
workspace: &WeakEntity<Workspace>,
cx: &mut gpui::App,
) -> AnyElement {
let owner = directory.read(cx).profile(&announcement.owner, cx);
let owner_name = owner.name();
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 description = announcement
.description
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from("No description"));
let activity = last_activity
.map(relative_time)
.map(|label| SharedString::from(format!("Updated {label}")))
.unwrap_or_default();
let fork_label: Option<SharedString> = announcement.upstream.as_ref().and_then(|upstream| {
let addr = upstream.addr.as_ref()?;
let name = announcements
.iter()
.find(|a| a.addr() == *addr)
.map(|a| {
a.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(a.id.clone()))
})
.unwrap_or_else(|| SharedString::from(addr.identifier().to_owned()));
Some(SharedString::from(format!("forked from {name}")))
});
v_flex()
.id(ix)
.flex_1()
.h_full()
.min_w_0()
.px_3()
.rounded(cx.theme().radius.control)
.border_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.child(
h_flex()
.h_10()
.gap_2()
.child(
div()
.min_w_0()
.typeset(TextRole::Headline, cx)
.whitespace_nowrap()
.text_ellipsis()
.child(name),
)
.when_some(fork_label, |this, label| {
this.child(
h_flex()
.gap_1()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.whitespace_nowrap()
.child(
Icon::named(IconRole::GitBranch)
.size(px(12.))
.color(cx.theme().colors.muted_foreground),
)
.child(label),
)
}),
)
.child(
div()
.h_16()
.min_w_0()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.line_clamp(2)
.child(description),
)
.child(
h_flex()
.h_12()
.gap_2()
.overflow_hidden()
.child(
h_flex()
.gap_2()
.child(
Avatar::new(announcement.owner)
.name(owner_name.clone())
.picture(owner.picture())
.small(),
)
.child(
div()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.whitespace_nowrap()
.child(owner_name),
),
)
.child(
h_flex()
.flex_1()
.justify_end()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.whitespace_nowrap()
.child(activity),
),
)
.on_click(move |_, window, cx| {
open_repo_panel(
&workspace,
&announcement.addr(),
Some(&announcement),
window,
cx,
);
})
.into_any_element()
}
+275
View File
@@ -0,0 +1,275 @@
mod helpers;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ListAlignment, ListState,
ParentElement as _, Render, SharedString, Styled as _, Subscription, WeakEntity, Window, div,
list, px,
};
use helpers::{RepoFilter, render_card};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
use signed_state::RepoListStore;
use ui::common::{h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent};
use ui::layout::panel::Panel;
use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _;
use crate::shared::panels;
use crate::workspace::Workspace;
const COLUMNS: usize = 2;
const CARD_HEIGHT: f32 = 40. + 64. + 48. + 2. + 6.;
pub struct ExploreView {
store: Entity<RepoListStore>,
workspace: WeakEntity<Workspace>,
scroll_handle: ListState,
filter: RepoFilter,
/// Indices matching [`Self::filter`] into the store's `announcements`.
visible: Vec<usize>,
search: Entity<InputState>,
/// Profiles for the card owners.
directory: Entity<ProfileDirectory>,
_search_subscription: Subscription,
_store_subscription: Subscription,
}
impl ExploreView {
/// The identifier of the explore panel in the workspace; shown as its tab label.
pub(crate) const PANEL_ID: &'static str = "Explore";
/// Opens the explore panel in the main panel, reusing it when it is already cached.
pub(crate) fn open(workspace: &WeakEntity<Workspace>, window: &mut Window, cx: &mut App) {
panels::open_primary(
workspace,
Self::PANEL_ID,
{
let workspace = workspace.clone();
move |_, cx| cx.new(|cx| Self::new(workspace.clone(), cx))
},
window,
cx,
);
}
pub fn new(workspace: WeakEntity<Workspace>, cx: &mut Context<Self>) -> Self {
let store = RepoListStore::global(cx);
let directory = ProfileDirectory::new(cx);
let weak = cx.entity().downgrade();
let search = InputState::new(cx);
let search_subscription = cx.subscribe(&search, |this, _search, event, cx| {
if matches!(event, InputStateEvent::TextChanged) {
this.rebuild_rows(cx);
}
});
let store_subscription = cx.observe(&store, |this, _store, cx| {
this.rebuild_rows(cx);
});
cx.defer(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| this.rebuild_rows(cx)) {
log::warn!("failed to load explore rows: {error}");
}
});
Self {
store,
workspace,
scroll_handle: ListState::new(1, ListAlignment::Top, px(320.)),
filter: RepoFilter::default(),
visible: Vec::new(),
search,
directory,
_search_subscription: search_subscription,
_store_subscription: store_subscription,
}
}
fn rebuild_rows(&mut self, cx: &mut Context<Self>) {
let filter = self.filter;
let query = self.search.read(cx).value().to_string();
let store = self.store.read(cx);
self.visible = filter.visible(store, &query);
let owners: Vec<PublicKey> = self
.visible
.iter()
.filter_map(|ix| store.announcements.get(*ix))
.map(|announcement| announcement.owner)
.collect();
self.directory.update(cx, |directory, cx| {
directory.track(owners, cx);
});
self.scroll_handle.reset(self.item_count());
cx.notify();
}
/// Header row, plus one row per card row, or the empty state when nothing matches.
fn item_count(&self) -> usize {
if self.visible.is_empty() {
2
} else {
self.visible.len().div_ceil(COLUMNS) + 1
}
}
fn render_header(
search: Entity<InputState>,
filter: RepoFilter,
weak: WeakEntity<Self>,
cx: &App,
) -> AnyElement {
let muted = cx.theme().colors.muted_foreground;
div()
.relative()
.h_96()
.w_full()
.child(
div()
.absolute()
.inset_0()
.flex()
.items_center()
.justify_center()
.px_4()
.child(
div().w_full().max_w(px(480.)).child(
Input::new("explore-search", search)
.placeholder("Search...")
.fully_rounded(true)
.prefix(Icon::named(IconRole::Search).small().color(muted)),
),
),
)
.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}");
}
}),
),
)
.into_any_element()
}
}
impl Panel for ExploreView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Explore")
}
fn prefix(&self, cx: &App) -> Option<AnyElement> {
Some(
Icon::named(IconRole::Grid)
.small()
.color(cx.theme().colors.muted_foreground)
.into_any_element(),
)
}
}
impl Render for ExploreView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let store = self.store.read(cx);
let announcements = store.announcements.clone();
let last_activity = store.last_activity.clone();
let visible = self.visible.clone();
let directory = self.directory.clone();
let workspace = self.workspace.clone();
let has_repos = !visible.is_empty();
let search = self.search.clone();
let filter = self.filter;
let weak = cx.entity().downgrade();
let scroll_handle = self.scroll_handle.clone();
div()
.relative()
.size_full()
.child(
list(self.scroll_handle.clone(), move |item, _, cx| {
if item == 0 {
return Self::render_header(search.clone(), filter, weak.clone(), cx);
}
if !has_repos {
return v_flex()
.w_full()
.h(px(320.))
.items_center()
.justify_center()
.child(EmptyState::new("No repositories match your search"))
.into_any_element();
}
let row = item - 1;
let mut cards = Vec::with_capacity(COLUMNS);
for col in 0..COLUMNS {
let Some(&ix) = visible.get(row * COLUMNS + col) else {
break;
};
let Some(announcement) = announcements.get(ix) else {
break;
};
let activity = last_activity.get(&announcement.addr()).copied();
cards.push(render_card(
ix,
announcement,
activity,
&announcements,
&directory,
&workspace,
cx,
));
}
h_flex()
.w_full()
.h(px(CARD_HEIGHT))
.gap_3()
.px_4()
.pt_4()
.children(cards)
.into_any_element()
})
.size_full(),
)
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical("explore-scroll", scroll_handle)),
)
}
}
+66
View File
@@ -0,0 +1,66 @@
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div,
};
use signed_state::Backend;
use ui::button::{Button, ButtonVariant};
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
pub struct ExitDialog {
handle: DialogHandle,
}
impl ExitDialog {
pub fn new(cx: &mut App) -> Entity<Self> {
cx.new(|_| Self {
handle: DialogHandle::new(true),
})
}
}
impl Render for ExitDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let cancel_close = self.handle.clone();
let confirm_close = self.handle.clone();
Dialog::new("exit-dialog")
.handle(self.handle.clone())
.title("Exit Signed?")
.content(|_, cx| {
v_flex()
.child(
div()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(
"You will be signed out on this device and will need to sign in again on the next session.",
),
)
.into_any_element()
})
.actions(move |_, _| {
let cancel_close = cancel_close.clone();
let confirm_close = confirm_close.clone();
let cancel: AnyElement = Button::new("cancel-exit")
.label("Cancel")
.variant(ButtonVariant::Secondary)
.on_click(move |_, _, cx| cancel_close.close(cx))
.into_any_element();
let exit: AnyElement = Button::new("confirm-exit")
.label("Exit")
.variant(ButtonVariant::Destructive)
.on_click(move |_, _, cx| {
let backend = Backend::global(cx);
backend.update(cx, |backend, cx| backend.sign_out(cx));
confirm_close.close(cx);
})
.into_any_element();
vec![cancel, exit]
})
}
}
+363
View File
@@ -0,0 +1,363 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Subscription, Task, Window, div, px,
};
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::input::{Input, InputState, InputStateEvent};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::progress::{DialogProgress, error_row};
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum Stage {
#[default]
Credential,
/// An `nsec` was entered; ask for a passphrase to encrypt it with.
Encrypt,
/// An `ncryptsec` was entered; ask for its passphrase to decrypt it.
Decrypt,
}
/// The credential entered on the first step.
enum Credential {
Nsec(String),
Ncryptsec(String),
Bunker(String),
}
impl Credential {
fn parse(input: &str) -> Option<Self> {
let input = input.trim();
if input.starts_with("nsec1") {
Some(Self::Nsec(input.to_owned()))
} else if input.starts_with("ncryptsec1") {
Some(Self::Ncryptsec(input.to_owned()))
} else if input.starts_with("bunker://") {
Some(Self::Bunker(input.to_owned()))
} else {
None
}
}
}
/// State of the import dialog, so the current step and async results can be rendered.
#[derive(Default)]
pub struct ImportState {
stage: Stage,
credential: String,
progress: DialogProgress,
}
pub struct ImportDialog {
handle: DialogHandle,
secret_input: Entity<InputState>,
pass_input: Entity<InputState>,
repass_input: Entity<InputState>,
state: Entity<ImportState>,
_subscriptions: Vec<Subscription>,
}
impl ImportDialog {
pub fn new(cx: &mut App) -> Entity<Self> {
let handle = DialogHandle::new(true);
let state = cx.new(|_| ImportState::default());
let secret_input = InputState::new(cx);
let pass_input = InputState::builder().password().build(cx);
let repass_input = InputState::builder().password().build(cx);
cx.new(|cx| {
let mut subscriptions = Vec::new();
for input in [&secret_input, &pass_input, &repass_input] {
let secret_input = secret_input.clone();
let pass_input = pass_input.clone();
let repass_input = repass_input.clone();
let state = state.clone();
let handle = handle.clone();
subscriptions.push(cx.subscribe(input, move |_this, _input, event, cx| {
if matches!(event, InputStateEvent::Submitted) {
submit(
&secret_input,
&pass_input,
&repass_input,
&state,
&handle,
cx,
);
}
}));
}
Self {
handle,
secret_input,
pass_input,
repass_input,
state,
_subscriptions: subscriptions,
}
})
}
}
impl Render for ImportDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let state = self.state.clone();
let secret_input = self.secret_input.clone();
let pass_input = self.pass_input.clone();
let repass_input = self.repass_input.clone();
let action_state = state.clone();
let action_secret = secret_input.clone();
let action_pass = pass_input.clone();
let action_repass = repass_input.clone();
let action_close = self.handle.clone();
Dialog::new("import-dialog")
.handle(self.handle.clone())
.min_width(px(520.))
.title("Import identity")
.content(move |_window, cx| {
let state = state.read(cx);
let stage = state.stage;
let description = match stage {
Stage::Credential => {
"Paste the secret key or bunker URI of an existing identity."
}
Stage::Encrypt => "Choose a passphrase to encrypt your key on this device.",
Stage::Decrypt => "Enter the passphrase used to encrypt this key.",
};
let form = match stage {
Stage::Credential => v_flex().gap_3().child(
Field::new("secret-field", "Secret key or bunker URI")
.child(Input::new("secret-input", secret_input.clone())),
),
Stage::Encrypt => v_flex()
.gap_3()
.child(
Field::new("passphrase-field", "Passphrase")
.child(Input::new("passphrase-input", pass_input.clone())),
)
.child(
Field::new("repeat-field", "Repeat passphrase")
.child(Input::new("repeat-input", repass_input.clone())),
),
Stage::Decrypt => v_flex().gap_3().child(
Field::new("passphrase-field", "Passphrase")
.child(Input::new("passphrase-input", pass_input.clone())),
),
};
v_flex()
.gap_3()
.child(
div()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(description),
)
.child(form)
.when_some(error_row(&state.progress.error, cx), |el, error| {
el.child(error)
})
.into_any_element()
})
.actions(move |_, cx| {
let state = action_state.read(cx);
let busy = state.progress.busy;
let label = match state.stage {
Stage::Credential => "Continue",
Stage::Encrypt => "Import identity",
Stage::Decrypt => "Unlock",
};
let secret = action_secret.clone();
let pass = action_pass.clone();
let repass = action_repass.clone();
let state = action_state.clone();
let handle = action_close.clone();
let import: AnyElement = Button::new("import-identity")
.label(label)
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
submit(&secret, &pass, &repass, &state, &handle, cx);
})
.into_any_element();
vec![import]
})
}
}
fn submit(
secret_input: &Entity<InputState>,
pass_input: &Entity<InputState>,
repass_input: &Entity<InputState>,
state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App,
) {
if state.read(cx).progress.busy {
return;
}
match state.read(cx).stage {
Stage::Credential => start_import(secret_input, state, handle, cx),
Stage::Encrypt => import_nsec(pass_input, repass_input, state, handle, cx),
Stage::Decrypt => import_ncryptsec(pass_input, state, handle, cx),
}
}
/// Parses the entered credential and either moves to the passphrase step or connects to a bunker.
fn start_import(
secret_input: &Entity<InputState>,
state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App,
) {
let credential = match Credential::parse(secret_input.read(cx).value()) {
Some(credential) => credential,
None => {
state.update(cx, |state, cx| {
state
.progress
.fail("Enter an nsec, ncryptsec or bunker:// URI");
cx.notify();
});
return;
}
};
match credential {
Credential::Nsec(secret) => {
state.update(cx, |state, cx| {
state.credential = secret;
state.stage = Stage::Encrypt;
state.progress.error = None;
cx.notify();
});
}
Credential::Ncryptsec(secret) => {
state.update(cx, |state, cx| {
state.credential = secret;
state.stage = Stage::Decrypt;
state.progress.error = None;
cx.notify();
});
}
Credential::Bunker(uri) => {
state.update(cx, |state, cx| {
state.progress.begin();
cx.notify();
});
let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| backend.import_bunker(&uri, cx));
finish_import(task, state, handle, cx);
}
}
}
/// Encrypts the entered `nsec` with the passphrase and signs in with it.
fn import_nsec(
pass_input: &Entity<InputState>,
repass_input: &Entity<InputState>,
state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App,
) {
let backend = Backend::global(cx);
let nsec = state.read(cx).credential.clone();
let pass = pass_input.read(cx).value().to_string();
let repass = repass_input.read(cx).value().to_string();
if pass.is_empty() {
state.update(cx, |state, cx| {
state.progress.fail("Passphrase must not be empty");
cx.notify();
});
return;
}
if pass != repass {
state.update(cx, |state, cx| {
state.progress.fail("Passphrases do not match");
cx.notify();
});
return;
}
state.update(cx, |state, cx| {
state.progress.begin();
cx.notify();
});
let task = backend.update(cx, |backend, cx| backend.import_nsec(&nsec, &pass, cx));
finish_import(task, state, handle, cx);
}
/// Decrypts the entered `ncryptsec` with the passphrase and signs in with it.
fn import_ncryptsec(
pass_input: &Entity<InputState>,
state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App,
) {
let backend = Backend::global(cx);
let ncryptsec = state.read(cx).credential.clone();
let pass = pass_input.read(cx).value().to_string();
if pass.is_empty() {
state.update(cx, |state, cx| {
state.progress.fail("Passphrase must not be empty");
cx.notify();
});
return;
}
state.update(cx, |state, cx| {
state.progress.begin();
cx.notify();
});
let task = backend.update(cx, |backend, cx| {
backend.import_ncryptsec(&ncryptsec, &pass, cx)
});
finish_import(task, state, handle, cx);
}
/// Runs the import task to completion, closing the dialog on success.
fn finish_import<T: 'static>(
task: Task<Result<T, anyhow::Error>>,
state: &Entity<ImportState>,
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) => {
state.update(cx, |state, cx| {
state.progress.fail(error.to_string());
cx.notify();
});
}
})
.detach();
}
+4
View File
@@ -0,0 +1,4 @@
pub mod exit;
pub mod import;
pub mod onboarding;
pub mod passphrase;
@@ -0,0 +1,137 @@
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::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::progress::{DialogProgress, error_row};
pub struct OnboardingDialog {
handle: DialogHandle,
name_input: Entity<InputState>,
pass_input: Entity<InputState>,
repass_input: Entity<InputState>,
state: Entity<DialogProgress>,
}
impl OnboardingDialog {
pub fn new(cx: &mut App) -> Entity<Self> {
let state = cx.new(|_| DialogProgress::default());
let name_input = InputState::new(cx);
let pass_input = InputState::builder().password().build(cx);
let repass_input = InputState::builder().password().build(cx);
cx.new(|_| Self {
handle: DialogHandle::new(true),
name_input,
pass_input,
repass_input,
state,
})
}
fn create_identity(&mut self, cx: &mut Context<Self>) {
if self.state.read(cx).busy {
return;
}
let name = self.name_input.read(cx).value().to_string();
let pass = self.pass_input.read(cx).value().to_string();
let repass = self.repass_input.read(cx).value().to_string();
if pass != repass {
self.state.update(cx, |state, cx| {
state.fail("Passphrases do not match");
cx.notify();
});
return;
}
self.state.update(cx, |state, cx| {
state.begin();
cx.notify();
});
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();
}
}
impl Render for OnboardingDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let name_input = self.name_input.clone();
let pass_input = self.pass_input.clone();
let repass_input = self.repass_input.clone();
let state = self.state.clone();
let action_state = state.clone();
let this = cx.entity().downgrade();
Dialog::new("onboarding-dialog")
.handle(self.handle.clone())
.min_width(px(520.))
.title("Create identity")
.content(move |_window, cx| {
let progress = state.read(cx);
v_flex()
.gap_3()
.child(
div()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child("Set up your Signed identity to get started."),
)
.child(
Field::new("name-field", "Name")
.description("Max 255 characters")
.child(Input::new("name-input", name_input.clone())),
)
.child(
Field::new("passphrase-field", "Passphrase")
.child(Input::new("passphrase-input", pass_input.clone())),
)
.child(
Field::new("repeat-field", "Repeat passphrase")
.child(Input::new("repeat-input", repass_input.clone())),
)
.when_some(error_row(&progress.error, cx), |el, error| el.child(error))
.into_any_element()
})
.actions(move |_, cx| {
let busy = action_state.read(cx).busy;
let this = this.clone();
let create: AnyElement = Button::new("create-identity")
.label("Create new identity")
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(
this.update(cx, |this, cx| this.create_identity(cx)),
);
})
.into_any_element();
vec![create]
})
}
}
@@ -0,0 +1,130 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Subscription, Window, px,
};
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent};
use crate::shared::progress::{DialogProgress, error_row, push_steps_row};
pub struct PassphraseDialog {
handle: DialogHandle,
pass_input: Entity<InputState>,
state: Entity<DialogProgress>,
_enter_subscription: Subscription,
}
impl PassphraseDialog {
pub fn new(cx: &mut App) -> Entity<Self> {
let state = cx.new(|_| DialogProgress::default());
let pass_input = InputState::builder().password().build(cx);
cx.new(|cx| {
let enter_subscription =
cx.subscribe(&pass_input, |this: &mut Self, _input, event, cx| {
if matches!(event, InputStateEvent::Submitted) {
this.unlock(cx);
}
});
Self {
handle: DialogHandle::new(true),
pass_input,
state,
_enter_subscription: enter_subscription,
}
})
}
fn unlock(&mut self, cx: &mut Context<Self>) {
if self.state.read(cx).busy {
return;
}
let pass = self.pass_input.read(cx).value().to_string();
if pass.is_empty() {
self.state.update(cx, |state, cx| {
state.fail("Passphrase must not be empty");
cx.notify();
});
return;
}
self.state.update(cx, |state, cx| {
state.begin();
cx.notify();
});
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();
}
}
impl Render for PassphraseDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let pass_input = self.pass_input.clone();
let state = self.state.clone();
let action_state = state.clone();
let this = cx.entity().downgrade();
Dialog::new("passphrase-dialog")
.handle(self.handle.clone())
.close_on_escape(false)
.close_on_backdrop(false)
.min_width(px(420.))
.title("Unlock your identity")
.content(move |_window, cx| {
let progress = state.read(cx);
v_flex()
.gap_3()
.child(
Field::new(
"passphrase-field",
"Enter the passphrase used to encrypt this identity.",
)
.child(Input::new("passphrase-input", pass_input.clone())),
)
.when_some(error_row(&progress.error, cx), |el, error| el.child(error))
.when_some(push_steps_row(&progress.push_steps, cx), |el, steps| {
el.child(steps)
})
.into_any_element()
})
.actions(move |_, cx| {
let busy = action_state.read(cx).busy;
let this = this.clone();
let unlock: AnyElement = Button::new("unlock")
.label("Unlock")
.icon(Icon::named(IconRole::Unlock))
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(this.update(cx, |this, cx| this.unlock(cx)));
})
.into_any_element();
vec![unlock]
})
}
}
+192
View File
@@ -0,0 +1,192 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Div, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
SharedString, Stateful, Styled as _, div, px,
};
use metadata::ProfileDirectory;
use nostr::prelude::{Event, Kind, PublicKey};
use ui::avatar::Avatar;
use ui::badge::Badge;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time;
pub fn repo_header(id: SharedString, name: SharedString, unread: usize, cx: &App) -> AnyElement {
h_flex()
.h_12()
.w_full()
.gap_2()
.child(
div()
.min_w_0()
.typeset(TextRole::Body, cx)
.whitespace_nowrap()
.text_ellipsis()
.child(name),
)
.when(unread > 0, |this| {
this.child(Badge::new(id.clone(), unread.to_string()))
})
.into_any_element()
}
pub fn empty_section_row(cx: &App) -> AnyElement {
h_flex()
.h_12()
.w_full()
.px_3()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.bg(cx.theme().colors.secondary)
.rounded(cx.theme().radius.control)
.child(SharedString::from("No activity yet."))
.into_any_element()
}
#[allow(clippy::too_many_arguments)]
pub fn thread(
prefix: &'static str,
ix: usize,
title: SharedString,
unread: bool,
first: bool,
last: bool,
events: Vec<Event>,
me: Option<PublicKey>,
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> Stateful<Div> {
let mut timeline = v_flex().gap_2().w_full();
for event in events {
timeline = timeline.child(sub_activity(&event, me, directory, cx));
}
v_flex()
.id((prefix, ix))
.w_full()
.px_3()
.py_2()
.gap_2()
.bg(cx.theme().colors.secondary)
.when(first, |this| this.rounded_t(cx.theme().radius.control))
.when(last, |this| this.rounded_b(cx.theme().radius.control))
.when(!last, |this| {
this.border_b_1().border_color(cx.theme().colors.background)
})
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.child(
h_flex()
.gap_2()
.typeset(TextRole::Body, cx)
.child(
h_flex()
.size_6()
.flex_shrink_0()
.items_center()
.justify_center()
.child(
Icon::named(IconRole::Inbox)
.small()
.color(cx.theme().colors.muted_foreground),
),
)
.child(
div()
.min_w_0()
.whitespace_nowrap()
.text_ellipsis()
.child(title),
)
.child(div().flex_1())
.when(unread, |this| {
this.child(
div()
.flex_shrink_0()
.size_2()
.rounded_full()
.bg(cx.theme().colors.primary),
)
}),
)
.child(timeline)
}
fn sub_activity(
event: &Event,
me: Option<PublicKey>,
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> AnyElement {
let profile = directory.read(cx).profile(&event.pubkey, cx);
let name = if Some(event.pubkey) == me {
SharedString::from("You")
} else {
profile.name()
};
h_flex()
.w_full()
.gap_2()
.child(div().w_6().flex_shrink_0())
.child(
h_flex()
.flex_1()
.min_w_0()
.gap_1()
.typeset(TextRole::Caption, cx)
.child(
Avatar::new(event.pubkey)
.name(name.clone())
.picture(profile.picture())
.small(),
)
.child(name)
.child(SharedString::from(activity_phrase(event.kind)))
.child(div().flex_1())
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(relative_time(event.created_at))),
),
)
.into_any_element()
}
fn activity_phrase(kind: Kind) -> &'static str {
match kind {
Kind::GitIssue => "opened an issue",
Kind::GitPullRequest => "opened a PR",
Kind::GitPullRequestUpdate => "updated a PR",
Kind::GitPatch => "created a patch",
Kind::Comment => "commented",
Kind::GitStatusOpen => "opened a status",
Kind::GitStatusApplied => "applied a status",
Kind::GitStatusClosed => "closed a status",
Kind::GitStatusDraft => "drafted a status",
_ => "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()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(message)),
)
.into_any_element()
}
+466
View File
@@ -0,0 +1,466 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Error;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity,
Window, div,
};
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::button::Button;
use ui::common::{h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea;
use ui::theme::{TextRole, Typeset as _};
mod helpers;
use helpers::{empty_section_row, empty_state, repo_header, thread};
use crate::repo::actions::{RepoItem, open_repo_item};
use crate::workspace::Workspace;
const MAX_SUB_ACTIVITIES: usize = 5;
#[derive(Clone, Copy)]
enum InboxRow {
Repo(usize),
Entry(usize, usize),
Empty,
}
struct InboxSection {
address: Option<RepoAddr>,
unread: usize,
entries: Vec<usize>,
latest: Timestamp,
}
pub struct InboxView {
workspace: WeakEntity<Workspace>,
threads: Arc<Vec<InboxItem>>,
sections: Arc<Vec<InboxSection>>,
rows: Arc<Vec<InboxRow>>,
state: InboxReadState,
state_loaded: bool,
refresh: RefreshGate,
tasks: Vec<Task<Result<(), Error>>>,
directory: Entity<ProfileDirectory>,
_subscriptions: Vec<Subscription>,
}
impl InboxView {
pub fn new(workspace: WeakEntity<Workspace>, cx: &mut Context<Self>) -> Self {
let backend = Backend::global(cx);
let inbox = backend.read(cx).inbox();
let repos = RepoListStore::global(cx);
let weak = cx.entity().downgrade();
let mut subscriptions = vec![];
subscriptions.push(cx.observe(&inbox, |this, _inbox, cx| {
this.sync_state(cx);
}));
subscriptions.push(cx.subscribe(&backend, |this, _backend, event, cx| {
this.handle_backend_event(event, cx);
}));
subscriptions.push(cx.observe(&repos, |this, _repos, cx| {
this.rebuild(cx);
cx.notify();
}));
cx.defer(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| this.sync_state(cx)) {
log::warn!("inbox dropped before bootstrap could run: {error}");
}
});
Self {
workspace,
threads: Arc::new(Vec::new()),
sections: Arc::new(Vec::new()),
rows: Arc::new(Vec::new()),
state: InboxReadState::default(),
state_loaded: false,
refresh: RefreshGate::default(),
tasks: vec![],
directory: ProfileDirectory::new(cx),
_subscriptions: subscriptions,
}
}
pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {
let Some(me) = Backend::global(cx).read(cx).current_user() else {
return;
};
let all: Vec<Event> = self
.threads
.iter()
.flat_map(|item| item.events.iter().cloned())
.collect();
let backend = Backend::global(cx);
let inbox = backend.read(cx).inbox();
inbox.update(cx, |inbox, cx| inbox.mark_all_read(&all, me, cx));
}
pub fn sync_state(&mut self, cx: &mut Context<Self>) {
let backend = Backend::global(cx);
let inbox = backend.read(cx).inbox();
let (loaded, state) = {
let inbox = inbox.read(cx);
(inbox.is_loaded(), inbox.state().clone())
};
if !loaded {
let was_present =
self.state_loaded || !self.threads.is_empty() || !self.sections.is_empty();
self.clear();
if was_present {
cx.notify();
}
return;
}
if !self.state_loaded {
self.state_loaded = true;
self.state = state;
self.refresh_initial(cx);
return;
}
if self.state != state {
self.state = state;
self.regroup(cx);
cx.notify();
}
}
fn handle_backend_event(&mut self, event: &BackendEvent, cx: &mut Context<Self>) {
match event {
BackendEvent::RepoUpdates(_) | BackendEvent::Synced => self.refresh(cx),
_ => {}
}
}
fn refresh_initial(&mut self, cx: &mut Context<Self>) {
if self.refresh.running() {
self.refresh.request();
return;
}
self.run_refresh(cx);
}
fn refresh(&mut self, cx: &mut Context<Self>) {
if !self.state_loaded || self.refresh.request() != RefreshRequest::Schedule {
return;
}
self.run_refresh(cx);
}
fn run_refresh(&mut self, cx: &mut Context<Self>) {
self.refresh.begin();
let backend = Backend::global(cx);
let (me, client) = {
let backend = backend.read(cx);
(backend.current_user(), backend.client())
};
let Some(me) = me else {
self.refresh.abort();
return;
};
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| {
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());
}
};
let again = this.update(cx, |this, cx| {
if backend.read(cx).current_user() != Some(me) {
this.refresh.abort();
return false;
}
this.threads = Arc::new(threads);
this.rebuild(cx);
cx.notify();
this.refresh.finish()
})?;
if again {
this.update(cx, |this, cx| this.refresh(cx))?;
}
Ok(())
}));
}
fn regroup(&mut self, cx: &mut Context<Self>) {
let mut items = (*self.threads).clone();
for item in items.iter_mut() {
item.apply_state(&self.state);
}
self.threads = Arc::new(items);
self.rebuild(cx);
}
fn rebuild(&mut self, cx: &mut Context<Self>) {
let backend = Backend::global(cx);
let repo_list = RepoListStore::global(cx);
let mut sections = self.group_sections();
if let Some(me) = backend.read(cx).current_user() {
for announcement in repo_list.read(cx).announcements_of(&me) {
let address = announcement.addr();
let known = sections
.iter()
.any(|section| section.address.as_ref() == Some(&address));
if !known {
sections.push(InboxSection {
address: Some(address),
unread: 0,
entries: Vec::new(),
latest: Timestamp::default(),
});
}
}
}
sections.sort_by_key(|section| std::cmp::Reverse(section.latest));
let rows = self.flatten_rows(&sections);
self.sections = Arc::new(sections);
self.rows = Arc::new(rows);
let mut keys: Vec<PublicKey> = self
.threads
.iter()
.flat_map(|item| item.events.iter().map(|event| event.pubkey))
.collect();
keys.sort_by_key(PublicKey::to_hex);
keys.dedup();
self.directory
.update(cx, |directory, cx| directory.track(keys, cx));
}
fn group_sections(&self) -> Vec<InboxSection> {
let mut by_repo: HashMap<Option<RepoAddr>, InboxSection> = HashMap::new();
for (ix, item) in self.threads.iter().enumerate() {
if item.archived {
continue;
}
let address = item.address.clone();
let section = by_repo
.entry(address.clone())
.or_insert_with(move || InboxSection {
address,
unread: 0,
entries: Vec::new(),
latest: Timestamp::default(),
});
if item.is_unread() {
section.unread += 1;
}
section.latest = section.latest.max(item.latest_activity());
section.entries.push(ix);
}
let mut sections: Vec<InboxSection> = by_repo.into_values().collect();
for section in &mut sections {
section.entries.sort_by(|a, b| {
self.threads[*b]
.latest_activity()
.cmp(&self.threads[*a].latest_activity())
});
}
sections.sort_by_key(|section| std::cmp::Reverse(section.latest));
sections
}
fn flatten_rows(&self, sections: &[InboxSection]) -> Vec<InboxRow> {
let mut rows = Vec::new();
for (section_ix, section) in sections.iter().enumerate() {
rows.push(InboxRow::Repo(section_ix));
if section.entries.is_empty() {
rows.push(InboxRow::Empty);
continue;
}
rows.extend(
(0..section.entries.len()).map(|entry_ix| InboxRow::Entry(section_ix, entry_ix)),
);
}
rows
}
fn clear(&mut self) {
self.threads = Arc::new(Vec::new());
self.sections = Arc::new(Vec::new());
self.rows = Arc::new(Vec::new());
self.state = InboxReadState::default();
self.state_loaded = false;
self.refresh = RefreshGate::default();
}
fn open(
&self,
root: EventId,
kind: Option<Kind>,
address: Option<RepoAddr>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(address) = address else {
return;
};
let item = match kind {
Some(Kind::GitIssue) => RepoItem::Issue(root),
Some(Kind::GitPullRequest) => RepoItem::PullRequest(root),
Some(Kind::GitPatch) => RepoItem::Patch,
_ => return,
};
open_repo_item(&self.workspace, &address, None, item, window, cx);
}
fn render_entry(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
let Some(row) = self.rows.get(ix) else {
return div().into_any_element();
};
match *row {
InboxRow::Empty => empty_section_row(cx),
InboxRow::Repo(section_ix) => {
let Some(section) = self.sections.get(section_ix) else {
return div().into_any_element();
};
let name = repo_name(section.address.as_ref(), cx);
let id = SharedString::from(format!(
"inbox-unread:{}",
section
.address
.as_ref()
.map(ToString::to_string)
.unwrap_or_default()
));
repo_header(id, name, section.unread, cx)
}
InboxRow::Entry(section_ix, entry_ix) => {
let Some(section) = self.sections.get(section_ix) else {
return div().into_any_element();
};
let Some(&thread_ix) = section.entries.get(entry_ix) else {
return div().into_any_element();
};
let Some(item) = self.threads.get(thread_ix) else {
return div().into_any_element();
};
let root = item.root;
let kind = item.root_event.as_ref().map(|event| event.kind);
let address = section.address.clone();
let first = entry_ix == 0;
let last = entry_ix + 1 == section.entries.len();
let me = Backend::global(cx).read(cx).current_user();
thread(
"inbox-row",
ix,
SharedString::from(item.title()),
item.is_unread(),
first,
last,
item.timeline(MAX_SUB_ACTIVITIES),
me,
&self.directory,
cx,
)
.on_click(cx.listener(move |this, _ev, window, cx| {
this.open(root, kind, address.clone(), window, cx)
}))
.into_any_element()
}
}
}
}
impl Panel for InboxView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Inbox")
}
}
impl Render for InboxView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let rows = self.rows.clone();
let mut children = Vec::with_capacity(rows.len());
for ix in 0..rows.len() {
children.push(self.render_entry(ix, cx));
}
v_flex()
.size_full()
.child(
h_flex()
.px_4()
.h_12()
.w_full()
.gap_2()
.child(
div()
.typeset(TextRole::Headline, cx)
.child(SharedString::from("Inbox")),
)
.child(div().flex_1())
.child(
Button::new("mark-all")
.icon(Icon::named(IconRole::Check))
.label("Mark all read")
.on_click(cx.listener(|this, _, _, cx| this.mark_all_read(cx))),
),
)
.child(
div()
.relative()
.flex_1()
.min_h_0()
.px_4()
.child(if rows.is_empty() {
empty_state("You're all caught up.", cx)
} else {
ScrollArea::new("inbox-scroll")
.flex_1()
.child(v_flex().gap_2().py_2().children(children))
.into_any_element()
}),
)
.into_any_element()
}
}
fn repo_name(addr: Option<&RepoAddr>, cx: &App) -> SharedString {
let Some(addr) = addr else {
return SharedString::from("Untitled");
};
RepoListStore::global(cx)
.read(cx)
.announcements
.iter()
.find(|announcement| announcement.addr() == *addr)
.map(|announcement| {
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()))
})
.unwrap_or_else(|| SharedString::from("Untitled"))
}
+221
View File
@@ -0,0 +1,221 @@
use gpui::{
App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render,
ScrollHandle, SharedString, Styled as _, Subscription, Window, div,
};
use metadata::ProfileDirectory;
use nostr::prelude::{EventId, PublicKey};
use signed_core::GitEvent;
use signed_state::RepoStore;
use ui::avatar::Avatar;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::input::InputState;
use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time;
use crate::issues::helpers::{comment_form, comments_section, issue_roots, sidebar_section};
use crate::shared::widgets::status_badge;
pub struct IssueDetailView {
store: Entity<RepoStore>,
issue_id: EventId,
comment_input: Entity<InputState>,
/// Profiles for the author, commenters and the repository owner.
directory: Entity<ProfileDirectory>,
scroll_handle: ScrollHandle,
_subscription: Subscription,
}
impl IssueDetailView {
pub fn new(store: Entity<RepoStore>, issue_id: EventId, cx: &mut Context<Self>) -> Self {
let comment_input = InputState::builder().multiline().build(cx);
let subscription = cx.observe(&store, |this, _store, cx| {
this.track_participants(cx);
cx.notify();
});
let directory = ProfileDirectory::new(cx);
let weak = cx.entity().downgrade();
cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.track_participants(cx)));
});
Self {
store,
issue_id,
comment_input,
directory,
scroll_handle: ScrollHandle::new(),
_subscription: subscription,
}
}
/// 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
.issues
.iter()
.find(|issue| issue.id == self.issue_id)
.map(|issue| issue.pubkey)
.into_iter()
.collect();
keys.extend(
store
.comments_of(&self.issue_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);
});
}
}
impl Panel for IssueDetailView {
fn title(&self, _cx: &App) -> SharedString {
let hex = self.issue_id.to_hex();
let short = hex.get(..8).unwrap_or(&hex);
SharedString::from(format!("Issue {short}"))
}
fn loading(&self, cx: &App) -> bool {
!self.store.read(cx).loaded
}
}
impl Render for IssueDetailView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
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"
} else {
"Loading issue..."
};
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) = {
let profile = self.directory.read(cx).profile(&issue.pubkey, cx);
let content = if issue.content.is_empty() {
SharedString::from("No description provided.")
} else {
SharedString::from(&issue.content)
};
(
issue.activity_subject(),
profile.name(),
store.status_of(issue),
relative_time(issue.created_at),
issue.id,
content,
issue.pubkey,
)
};
let picture = self.directory.read(cx).profile(&pubkey, cx).picture();
h_flex()
.id("issue-detail")
.size_full()
.child(
ScrollArea::new("issue-detail-scroll")
.handle(self.scroll_handle.clone())
.flex_1()
.min_w_0()
.child(
v_flex()
.p_4()
.gap_6()
.child(
h_flex().gap_2().child(status_badge(status)).child(
div()
.flex_1()
.min_w_0()
.typeset(TextRole::Headline, cx)
.child(title),
),
)
.child(
v_flex()
.gap_8()
.child(
v_flex()
.gap_4()
.child(
h_flex()
.gap_2()
.typeset(TextRole::Body, cx)
.child(
h_flex()
.gap_1()
.child(
Avatar::new(pubkey)
.name(author.clone())
.picture(picture)
.small(),
)
.child(author),
)
.child(
div()
.text_color(
cx.theme().colors.muted_foreground,
)
.child("opened"),
)
.child(
div()
.text_color(
cx.theme().colors.muted_foreground,
)
.child(SharedString::from(age)),
),
)
.child(
div().typeset(TextRole::Body, cx).child(content),
),
)
.child(comments_section(
&self.store,
issue_id,
&self.directory,
cx,
))
.child(comment_form(
&self.store,
issue_id,
issue_roots,
&self.comment_input,
"comment",
cx,
)),
),
),
)
.child(sidebar_section(
&self.store,
issue_id,
issue_roots,
true,
&self.directory,
cx,
))
.into_any_element()
}
}
+279
View File
@@ -0,0 +1,279 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Entity, IntoElement, ParentElement as _, SharedString, Styled as _, div, px,
};
use metadata::ProfileDirectory;
use nostr::prelude::{Event, EventId, PublicKey};
use signed_core::RepoStatus;
use signed_state::RepoStore;
use ui::avatar::Avatar;
use ui::badge::{Badge, BadgeVariant};
use ui::button::Button;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tooltip::Tooltip;
use utils::relative_time;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IssueFilter {
All,
Open,
Closed,
}
impl IssueFilter {
pub(crate) fn matches(self, status: RepoStatus) -> bool {
match self {
Self::All => true,
Self::Open => status == RepoStatus::Open,
Self::Closed => matches!(status, RepoStatus::Closed | RepoStatus::Applied),
}
}
}
/// Root events counted by their resolved status.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct StatusCounts {
pub(crate) total: usize,
pub(crate) open: usize,
pub(crate) closed: usize,
pub(crate) draft: usize,
pub(crate) applied: usize,
}
impl StatusCounts {
fn record(&mut self, status: RepoStatus) {
self.total += 1;
match status {
RepoStatus::Open => self.open += 1,
RepoStatus::Closed => self.closed += 1,
RepoStatus::Draft => self.draft += 1,
RepoStatus::Applied => self.applied += 1,
}
}
}
/// Indices of `roots` whose status `keep` accepts, counting every root's status.
pub(crate) fn filter_by_status<'a>(
roots: impl IntoIterator<Item = &'a Event>,
status_of: impl Fn(&Event) -> RepoStatus,
keep: impl Fn(RepoStatus) -> bool,
) -> (Vec<usize>, StatusCounts) {
let mut counts = StatusCounts::default();
let visible = roots
.into_iter()
.enumerate()
.filter_map(|(index, root)| {
let status = status_of(root);
counts.record(status);
keep(status).then_some(index)
})
.collect();
(visible, counts)
}
pub(crate) fn issue_roots(store: &RepoStore) -> &[Event] {
&store.issues
}
pub(crate) fn pr_roots(store: &RepoStore) -> &[Event] {
&store.pull_requests
}
pub(crate) fn sidebar_section(
store: &Entity<RepoStore>,
id: EventId,
roots: fn(&RepoStore) -> &[Event],
top_gap: bool,
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> AnyElement {
let store = store.read(cx);
let Some(root) = roots(store).iter().find(|event| event.id == id) else {
return div().into_any_element();
};
let mut participants: Vec<PublicKey> = vec![root.pubkey];
participants.extend(store.comments_of(&root.id).map(|comment| comment.pubkey));
participants.sort_by_key(PublicKey::to_hex);
participants.dedup();
let labels: Vec<String> = root.tags.hashtags().map(|tag| tag.to_string()).collect();
v_flex()
.w(px(240.))
.h_full()
.flex_none()
.px_4()
.gap_4()
.border_l_1()
.border_color(cx.theme().colors.border)
.child(
v_flex()
.when(top_gap, |this| this.mt_4())
.gap_2()
.child(crate::shared::widgets::section_label("Participants", cx))
.children(participants.iter().map(|pubkey| {
let profile = directory.read(cx).profile(pubkey, cx);
let name = profile.name();
h_flex()
.gap_1()
.child(
Avatar::new(*pubkey)
.name(name.clone())
.picture(profile.picture())
.small(),
)
.child(
div()
.typeset(TextRole::Body, cx)
.text_ellipsis()
.child(name),
)
.into_any_element()
})),
)
.child(
v_flex()
.gap_2()
.child(crate::shared::widgets::section_label("Labels", cx))
.map(|this| {
if labels.is_empty() {
this.child(
div()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child("None yet."),
)
} else {
this.child(v_flex().gap_1().children(labels.iter().map(|label| {
Badge::new(SharedString::from(format!("label:{label}")), label.clone())
.variant(BadgeVariant::Outline)
})))
}
}),
)
.into_any_element()
}
pub(crate) fn comments_section(
store: &Entity<RepoStore>,
root: EventId,
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> AnyElement {
let store = store.read(cx);
let comments: Vec<&Event> = store.comments_of(&root).collect();
let title = SharedString::from(format!("Discussions {}", comments.len()));
v_flex()
.gap_4()
.child(div().typeset(TextRole::Caption2, cx).child(title))
.children(comments.iter().map(|comment| {
let profile = 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()
.typeset(TextRole::Body, cx)
.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().typeset(TextRole::Body, cx).child(content))
}))
.into_any_element()
}
pub(crate) fn comment_form(
store: &Entity<RepoStore>,
root: EventId,
roots: fn(&RepoStore) -> &[Event],
comment_input: &Entity<InputState>,
button_id: &'static str,
cx: &App,
) -> AnyElement {
let comment_input = comment_input.clone();
let store = store.clone();
v_flex()
.gap_2()
.child(
Input::new("comment-input", comment_input.clone())
.rows(4)
.placeholder("Leave a comment..."),
)
.child(
h_flex()
.justify_between()
.child(
h_flex()
.gap_1()
.typeset(TextRole::Caption, cx)
.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(button_id)
.label("Comment")
.tooltip(Tooltip::text("Post comment"))
.on_click(move |_, window, cx| {
let content = comment_input.read(cx).value().trim().to_string();
if content.is_empty() {
return;
}
let Some(root) = roots(store.read(cx))
.iter()
.find(|event| event.id == root)
.cloned()
else {
return;
};
store.update(cx, |store, cx| {
store.comment(&root, content, cx);
});
comment_input.update(cx, |input, cx| {
input.set_value("", window, cx);
});
}),
),
)
.into_any_element()
}
+329
View File
@@ -0,0 +1,329 @@
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,
};
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::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time;
use self::detail::IssueDetailView;
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>,
new_issue: Option<Entity<new_issue::NewIssueDialog>>,
filter: IssueFilter,
visible_issues: Vec<usize>,
counts: StatusCounts,
// A filter change notifies even when the visible rows are unchanged.
synced_filter: IssueFilter,
scroll_handle: UniformListScrollHandle,
/// Profiles for issue authors and the repository owner.
directory: Entity<ProfileDirectory>,
_subscription: Subscription,
}
impl IssuesView {
pub fn new(
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
cx: &mut Context<Self>,
) -> Self {
let subscription = cx.observe(&store, |this, _store, cx| {
this.rebuild(cx);
});
let weak = cx.entity().downgrade();
cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.rebuild(cx)));
});
Self {
workspace,
store: store.clone(),
new_issue: None,
filter: IssueFilter::Open,
visible_issues: Vec::new(),
counts: StatusCounts::default(),
synced_filter: IssueFilter::Open,
scroll_handle: UniformListScrollHandle::new(),
directory: ProfileDirectory::new(cx),
_subscription: subscription,
}
}
fn open_new_issue(&mut self, cx: &mut Context<Self>) {
self.new_issue = Some(new_issue::NewIssueDialog::new(self.store.clone(), cx));
cx.notify();
}
/// Total number of issues across all statuses, for the sidebar label.
pub fn total_count(&self) -> usize {
self.counts.total
}
fn rebuild(&mut self, cx: &mut Context<Self>) {
let filter = self.filter;
let (visible_issues, counts) = {
let store = self.store.read(cx);
filter_by_status(
&store.issues,
|issue| store.status_of(issue),
|status| filter.matches(status),
)
};
let store = self.store.read(cx);
let mut keys: Vec<PublicKey> = store.issues.iter().map(|issue| issue.pubkey).collect();
if let Some(owner) = store
.announcement
.as_ref()
.map(|announcement| announcement.owner)
{
keys.push(owner);
}
self.directory.update(cx, |directory, cx| {
directory.track(keys, cx);
});
let filter_changed = self.synced_filter != filter;
let visible_issues_changed = self.visible_issues != visible_issues;
let counts_changed = self.counts != counts;
if !filter_changed && !visible_issues_changed && !counts_changed {
return;
}
self.synced_filter = filter;
self.visible_issues = visible_issues;
self.counts = counts;
cx.notify();
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
let counts = self.counts;
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(
Segmented::new("issue-filter", self.filter)
.options(vec![
SegmentedOption::new(IssueFilter::All, format!("All ({})", counts.total))
.icon(Icon::named(IconRole::GitIssueDone).color(muted)),
SegmentedOption::new(IssueFilter::Open, format!("Open ({})", counts.open))
.icon(Icon::named(IconRole::GitIssueOngoing).color(muted)),
SegmentedOption::new(
IssueFilter::Closed,
format!("Closed ({})", counts.closed),
)
.icon(Icon::named(IconRole::GitIssueClosed).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 issue filter: {error}");
}
}),
)
.child(div().flex_1())
.child(
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()
}
}
impl Panel for IssuesView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Issues")
}
}
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();
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()
.typeset(TextRole::Body, cx)
.text_ellipsis()
.whitespace_nowrap()
.child(title),
)
.child(
h_flex()
.gap_2()
.typeset(TextRole::Caption, cx)
.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)),
)
}),
)
.into_any_element()
}
}
+87
View File
@@ -0,0 +1,87 @@
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div,
};
use signed_state::RepoStore;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
pub struct NewIssueDialog {
handle: DialogHandle,
store: Entity<RepoStore>,
subject: Entity<InputState>,
content: Entity<InputState>,
}
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);
cx.new(|_| Self {
handle: DialogHandle::new(true),
store,
subject,
content,
})
}
fn submit(&mut self, cx: &mut Context<Self>) {
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.store.update(cx, |store, cx| {
store.open_issue(subject, content, cx);
});
self.handle.close(cx);
}
}
impl Render for NewIssueDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let subject = self.subject.clone();
let content = self.content.clone();
let this = cx.entity().downgrade();
Dialog::new("new-issue-dialog")
.handle(self.handle.clone())
.min_width(gpui::px(520.))
.title("New issue")
.content(move |_, cx| {
v_flex()
.gap_3()
.child(
div()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child("Report a bug, ask a question, or propose a change."),
)
.child(
Field::new("issue-title", "Title")
.child(Input::new("issue-title-input", subject.clone())),
)
.child(
Field::new("issue-content", "Content")
.child(Input::new("issue-content-input", content.clone()).rows(6)),
)
.into_any_element()
})
.actions(move |_, _| {
let this = this.clone();
vec![
Button::new("create-issue")
.label("Create issue")
.on_click(move |_, _, cx| {
crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx)));
})
.into_any_element() as AnyElement,
]
})
}
}
+20
View File
@@ -0,0 +1,20 @@
mod app;
mod explore;
mod identity;
#[allow(dead_code)] // temporarily unlinked while the shell migrates
mod inbox;
mod issues;
mod pull_requests;
mod repo;
mod settings;
mod shared;
mod titlebar;
mod workspace;
pub use app::AppRoot;
pub use app::helpers::{apply_appearance, apply_appearance_mode};
use gpui::{App, AppContext as _, Entity, Window};
pub fn root(window: &mut Window, cx: &mut App) -> Entity<AppRoot> {
cx.new(|cx| AppRoot::new(window, cx))
}
@@ -0,0 +1,624 @@
use std::path::PathBuf;
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,
};
use metadata::ProfileDirectory;
use nostr::prelude::{EventId, Kind, PublicKey, Url};
use signed_core::{GitEvent, PullRequest, RepoAddr};
use signed_git::{FileCommit, PatchParser};
use signed_state::{Backend, Mirrors, RepoStore};
use ui::avatar::Avatar;
use ui::button::Button;
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, h_flex, v_flex};
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 _, TextRole, Typeset as _};
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;
const NOT_FOUND: &str = "Pull request not found";
#[derive(Clone, PartialEq, Eq)]
struct PrBinding {
description: String,
patch: String,
tip: Option<String>,
base: Option<String>,
clone_urls: Vec<Url>,
addr: RepoAddr,
has_patch_link: bool,
}
pub struct PullRequestDetailView {
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
pr_id: EventId,
update_dialog: Option<Entity<dialogs::update::UpdatePrDialog>>,
comment_input: Entity<InputState>,
worktree: Option<PathBuf>,
description: SharedString,
current_commit: Option<SharedString>,
commits: Vec<FileCommit>,
loading: bool,
error: Option<SharedString>,
bound: Option<PrBinding>,
load_generation: u64,
active_tab: usize,
pane: Entity<DiffPane>,
commit_scroll_handle: UniformListScrollHandle,
tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
directory: Entity<ProfileDirectory>,
_subscription: Subscription,
}
impl PullRequestDetailView {
pub fn new(
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
pr_id: EventId,
_window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let pane = cx.new(DiffPane::new);
let comment_input = InputState::builder().multiline().build(cx);
let weak = cx.entity().downgrade();
let subscription = cx.observe(&store, |this, _store, cx| {
this.sync(cx);
});
cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.sync(cx)));
});
Self {
workspace,
store,
pr_id,
update_dialog: None,
comment_input,
worktree: None,
description: SharedString::default(),
current_commit: None,
commits: Vec::new(),
loading: true,
error: None,
bound: None,
load_generation: 0,
active_tab: 0,
pane,
commit_scroll_handle: UniformListScrollHandle::new(),
tasks: Vec::new(),
directory: ProfileDirectory::new(cx),
_subscription: subscription,
}
}
fn track_participants(&mut self, cx: &mut Context<Self>) {
let store = self.store.read(cx);
let mut keys: Vec<PublicKey> = 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));
}
fn sync(&mut self, cx: &mut Context<Self>) {
self.track_participants(cx);
let loaded = self.store.read(cx).loaded;
let binding = {
let store = self.store.read(cx);
store.addr().and_then(|addr| {
store
.pull_requests
.iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
.map(|root| {
let update = PullRequest::latest_update(store.pull_requests.iter(), root);
let tip = update
.and_then(GitEvent::current_commit)
.or_else(|| root.current_commit());
let base = update
.and_then(GitEvent::merge_base)
.or_else(|| root.merge_base());
let clone_urls = root
.clone_urls()
.or_else(|| store.announcement.as_ref().map(|a| a.clone.clone()))
.unwrap_or_default();
PrBinding {
description: root.content.clone(),
patch: PullRequest::new(root).patch(store.patches.iter()),
tip,
base,
clone_urls,
addr: addr.clone(),
has_patch_link: root.tags.event_ids().next().is_some(),
}
})
})
};
let Some(binding) = binding else {
self.bound = None;
if !loaded {
self.loading = true;
self.error = None;
} else if self.error.as_deref() != Some(NOT_FOUND) {
self.loading = false;
self.error = Some(NOT_FOUND.into());
}
cx.notify();
return;
};
if self.bound.as_ref() == Some(&binding) {
return;
}
self.bound = Some(binding.clone());
self.load_diff(binding, cx);
}
fn load_diff(&mut self, binding: PrBinding, cx: &mut Context<Self>) {
self.loading = true;
self.error = None;
self.description = binding.description.clone().into();
self.current_commit = binding.tip.clone().map(SharedString::from);
cx.notify();
self.load_generation = self.load_generation.wrapping_add(1);
let generation = self.load_generation;
let PrBinding {
patch,
tip,
base,
clone_urls,
addr,
has_patch_link,
..
} = binding;
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let nostr_diff = cx
.background_spawn({
let patch = patch.clone();
async move { PatchParser::patch_diffs(&patch) }
})
.await;
let nostr_commits = cx
.background_spawn({
let patch = patch.clone();
async move { PatchParser::patch_commits(&patch) }
})
.await;
let use_nostr = match &nostr_diff {
Ok(diff) => has_patch_link || !diff.files.is_empty(),
Err(_) => true,
};
let git = if use_nostr {
None
} else {
let addr = addr.clone();
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)?;
let gix_repo = repo.inner();
let workdir = gix_repo
.workdir()
.ok_or_else(|| anyhow::anyhow!("repository has no worktree"))?
.to_path_buf();
let tip =
tip.ok_or_else(|| anyhow::anyhow!("pull request has no tip commit"))?;
let base = match base {
Some(base) => base,
None => {
let head = gix_repo
.head_id()
.map_err(|_| anyhow::anyhow!("repository has no HEAD"))?;
let tip_id = gix_repo.rev_parse_single(tip.as_bytes())?;
gix_repo.merge_base(tip_id, head)?.to_string()
}
};
let diff = repo.range_diff(&base, &tip)?;
let commits = repo.commit_range(&base, &tip)?;
Ok::<_, anyhow::Error>((diff, commits, workdir))
})
.await,
)
};
let (diff, commits, worktree) = match git {
Some(Ok((diff, commits, worktree))) => (Ok(diff), commits, Some(worktree)),
Some(Err(error)) => (Err(error), Vec::new(), None),
None => (nostr_diff, nostr_commits, None),
};
this.update(cx, |this, cx| {
if this.load_generation != generation {
return;
}
this.loading = false;
this.worktree = worktree;
this.commits = 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()),
}
cx.notify();
})?;
Ok(())
});
self.tasks.push(task);
}
fn open_commit_diff(
&mut self,
worktree: PathBuf,
commit_id: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
let id = match self.store.read(cx).addr() {
Some(addr) => SharedString::from(format!("commit:{addr}:{commit_id}")),
None => SharedString::from(format!("commit:{}:{commit_id}", worktree.display())),
};
let workspace = self.workspace.clone();
let commit_id = commit_id.to_owned();
crate::shared::panels::open_detail(
&workspace,
id,
move |window, cx| {
cx.new(|cx| CommitDiffView::new(worktree.clone(), commit_id.clone(), window, cx))
},
window,
cx,
);
}
fn render_tabs(&self, cx: &mut Context<Self>) -> AnyElement {
let files = self.pane.read(cx).diff().map(|diff| diff.files.len());
let commits = (!self.commits.is_empty()).then_some(self.commits.len());
let weak = cx.entity().downgrade();
let files_label = match files {
Some(count) => format!("Files ({count})"),
None => "Files".to_owned(),
};
let commits_label = match commits {
Some(count) => format!("Commits ({count})"),
None => "Commits".to_owned(),
};
Tabs::new("pr-tabs")
.selected(self.active_tab)
.tabs(move |_, _| {
vec![
Tab::new("discussion", "Discussion"),
Tab::new("files", files_label.clone()),
Tab::new("commits", commits_label.clone()),
]
})
.on_change(move |index, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
this.active_tab = index;
cx.notify();
}));
})
.into_any_element()
}
fn render_discussion(&mut self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return centered_spinner();
}
if let Some(error) = self.error.clone() {
return empty_state(error);
}
let (author, picture, age, root_id, pubkey) = {
let store = self.store.read(cx);
let Some(root) = store
.pull_requests
.iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
else {
return empty_state(NOT_FOUND);
};
let profile = self.directory.read(cx).profile(&root.pubkey, cx);
(
profile.name(),
profile.picture(),
relative_time(root.created_at),
root.id,
root.pubkey,
)
};
h_flex()
.size_full()
.min_h_0()
.child(
ScrollArea::new("pr-discussion-scroll")
.flex_1()
.min_w_0()
.child(
v_flex()
.p_4()
.gap_6()
.child(
v_flex()
.gap_4()
.child(
h_flex()
.gap_2()
.typeset(TextRole::Body, cx)
.child(
h_flex()
.gap_1()
.child(
Avatar::new(pubkey)
.name(author.clone())
.picture(picture)
.small(),
)
.child(author),
)
.child(SharedString::from("commented"))
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(age)),
),
)
.when(!self.description.is_empty(), |this| {
this.child(
div()
.typeset(TextRole::Body, cx)
.child(self.description.clone()),
)
}),
)
.child(comments_section(&self.store, root_id, &self.directory, cx))
.child(comment_form(
&self.store,
root_id,
pr_roots,
&self.comment_input,
"pr-comment",
cx,
)),
),
)
.child(sidebar_section(
&self.store,
root_id,
pr_roots,
true,
&self.directory,
cx,
))
.into_any_element()
}
fn render_files(&self, _cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return centered_spinner();
}
if let Some(error) = self.error.clone() {
return empty_state(error);
}
self.pane.clone().into_any_element()
}
fn render_commits(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return centered_spinner();
}
if let Some(error) = self.error.clone() {
return empty_state(error);
}
if self.commits.is_empty() {
return empty_state("No commits found");
}
let commits = self.commits.clone();
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()
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
let current_commit = self.current_commit.clone();
let (title, status, branch, author) = {
let store = self.store.read(cx);
let Some(root) = store
.pull_requests
.iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
else {
return div().into_any_element();
};
(
root.activity_subject(),
store.status_of(root),
root.branch_name(),
root.pubkey,
)
};
let can_update = Backend::global(cx).read(cx).current_user() == Some(author);
let weak = cx.entity().downgrade();
v_flex()
.flex_none()
.px_4()
.py_2()
.gap_2()
.child(
h_flex().gap_2().child(status_badge(status)).child(
div()
.flex_1()
.min_w_0()
.typeset(TextRole::Headline, cx)
.text_ellipsis()
.child(title),
),
)
.child(
h_flex()
.gap_3()
.when_some(branch, |this, branch| {
this.child(
Button::new("branch")
.label(branch)
.icon(Icon::named(IconRole::GitBranch))
.small(),
)
})
.when(can_update, |this| {
this.child(Button::new("update-pr").label("Update").small().on_click(
move |_, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
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 {
this.update_dialog =
Some(dialogs::update::UpdatePrDialog::new(
this.store.clone(),
root,
cx,
));
cx.notify();
}
}));
},
))
})
.when_some(current_commit, |this, id| {
this.child(
h_flex()
.gap_1()
.font_family(cx.theme().mono_font)
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(id.clone())
.child(ClipboardButton::new("pr-commit", &id)),
)
}),
)
.into_any_element()
}
}
impl Panel for PullRequestDetailView {
fn title(&self, _cx: &App) -> SharedString {
let hex = self.pr_id.to_hex();
let short = hex.get(..8).unwrap_or(&hex);
SharedString::from(format!("PR {short}"))
}
fn loading(&self, _cx: &App) -> bool {
self.loading
}
}
impl Render for PullRequestDetailView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.id("pull-request-detail")
.size_full()
.min_h_0()
.child(self.render_header(cx))
.when_some(self.update_dialog.clone(), |el, view| el.child(view))
.child(self.render_tabs(cx))
.map(|this| match self.active_tab {
0 => this.child(self.render_discussion(cx)),
1 => this.child(self.render_files(cx)),
_ => this.child(self.render_commits(cx)),
})
}
}
fn centered_spinner() -> AnyElement {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new("pr-loading"))
.into_any_element()
}
@@ -0,0 +1 @@
pub mod update;
@@ -0,0 +1,80 @@
use gpui::{
AnyElement, 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 _, TextRole, Typeset as _};
pub struct UpdatePrDialog {
handle: DialogHandle,
store: Entity<RepoStore>,
root: Event,
patch: Entity<InputState>,
}
impl UpdatePrDialog {
pub fn new(store: Entity<RepoStore>, root: Event, cx: &mut App) -> Entity<Self> {
let patch = InputState::builder().multiline().build(cx);
cx.new(|_| Self {
handle: DialogHandle::new(true),
store,
root,
patch,
})
}
fn submit(&mut self, cx: &mut Context<Self>) {
let patch = self.patch.read(cx).value().to_string();
if patch.trim().is_empty() {
return;
}
self.store.update(cx, |store, cx| {
store.update_pull_request(&self.root, patch, cx);
});
self.handle.close(cx);
}
}
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();
Dialog::new("update-pr-dialog")
.handle(self.handle.clone())
.min_width(gpui::px(520.))
.title("Update pull request")
.content(move |_, cx| {
v_flex()
.gap_3()
.child(
div()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child("Publish a new revision with the output of `git format-patch`."),
)
.child(
Field::new("update-patch", "Patch")
.child(Input::new("update-patch-input", patch.clone()).rows(6)),
)
.into_any_element()
})
.actions(move |_, _| {
let this = this.clone();
vec![
Button::new("submit-update")
.label("Update pull request")
.on_click(move |_, _, cx| {
crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx)));
})
.into_any_element() as AnyElement,
]
})
}
}
@@ -0,0 +1,143 @@
use std::path::PathBuf;
use gpui::{SharedString, WeakEntity};
use nostr::prelude::PublicKey;
use signed_core::{Announcement, RepoAddr, RepoStatus};
use ui::menu::MenuItem;
use utils::middle_truncate;
use super::NewPullRequestView;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PullRequestFilter {
All,
Open,
Closed,
Draft,
Merged,
}
impl PullRequestFilter {
pub fn matches(self, status: RepoStatus) -> bool {
match self {
Self::All => true,
Self::Open => status == RepoStatus::Open,
Self::Closed => status == RepoStatus::Closed,
Self::Draft => status == RepoStatus::Draft,
Self::Merged => status == RepoStatus::Applied,
}
}
pub fn empty_message(self) -> &'static str {
match self {
Self::All => "No pull requests",
Self::Open => "No open pull requests",
Self::Closed => "No closed pull requests",
Self::Draft => "No draft pull requests",
Self::Merged => "No merged pull requests",
}
}
}
pub struct ForkCompare {
pub announcement: Announcement,
pub namespace: String,
pub mirror_path: PathBuf,
}
impl ForkCompare {
pub fn base_ref(name: &str) -> String {
format!("refs/remotes/origin/{name}")
}
pub fn compare_ref(&self, name: &str) -> String {
format!("refs/fork/{}/{}", self.namespace, name)
}
}
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()
}
pub fn truncate_label(label: &str) -> SharedString {
SharedString::from(middle_truncate(label, 18, 0))
}
pub fn source_menu_items(
view: WeakEntity<NewPullRequestView>,
associated: Vec<PathBuf>,
active_path: Option<PathBuf>,
candidates: Vec<Announcement>,
user: Option<PublicKey>,
active_fork: Option<RepoAddr>,
) -> Vec<MenuItem> {
let mut items = Vec::new();
for path in associated {
let label = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
let target = view.clone();
let path_for_action = path.clone();
items.push(
MenuItem::new(truncate_label(&label))
.checked(active_path.as_ref() == Some(&path))
.handler(move |window, cx| {
let path = path_for_action.clone();
if let Err(error) =
target.update(cx, |this, cx| this.apply_folder_path(path, window, cx))
{
log::warn!("failed to apply checkout: {error}");
}
}),
);
}
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))
{
log::warn!("failed to choose checkout: {error}");
}
}),
);
items.push(MenuItem::separator());
if candidates.is_empty() {
items.push(MenuItem::new("No announced forks of this repository").disabled(true));
} else {
for candidate in candidates {
let subtitle = if Some(candidate.owner) == user {
SharedString::from("Your fork")
} else {
SharedString::from(format!("by {}", shorten_owner(&candidate.owner)))
};
let title = format!("{} — {}", fork_display_name(&candidate), subtitle);
let target = view.clone();
let checked = active_fork == Some(candidate.addr());
let announcement = candidate;
items.push(
MenuItem::new(truncate_label(&title))
.checked(checked)
.handler(move |window, cx| {
let announcement = announcement.clone();
if let Err(error) =
target.update(cx, |this, cx| this.choose_fork(announcement, window, cx))
{
log::warn!("failed to choose fork: {error}");
}
}),
);
}
}
items
}
+453
View File
@@ -0,0 +1,453 @@
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,
};
use metadata::ProfileDirectory;
use nostr::prelude::{Kind, PublicKey};
use signed_core::GitEvent;
use signed_state::RepoStore;
use ui::alert::{Alert, AlertSeverity};
use ui::avatar::Avatar;
use ui::common::{Sizable as _, h_flex, 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 _, TextRole, Typeset as _};
use utils::relative_time;
mod detail;
mod dialogs;
mod helpers;
mod new;
mod send_patch;
pub use detail::PullRequestDetailView;
use helpers::PullRequestFilter;
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::workspace::Workspace;
const ROW_HEIGHT: f32 = 73.;
pub struct PullRequestsView {
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
filter: PullRequestFilter,
visible_prs: Vec<usize>,
counts: StatusCounts,
synced_filter: PullRequestFilter,
scroll_handle: UniformListScrollHandle,
directory: Entity<ProfileDirectory>,
new_pr_menu_open: bool,
_subscription: Subscription,
}
impl PullRequestsView {
pub fn new(
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
cx: &mut Context<Self>,
) -> Self {
let weak = cx.entity().downgrade();
let subscription = cx.observe(&store, |this, _store, cx| {
this.rebuild(cx);
});
cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
this.rebuild(cx);
}));
});
Self {
workspace,
store,
filter: PullRequestFilter::Open,
visible_prs: Vec::new(),
counts: StatusCounts::default(),
synced_filter: PullRequestFilter::Open,
scroll_handle: UniformListScrollHandle::new(),
directory: ProfileDirectory::new(cx),
new_pr_menu_open: false,
_subscription: subscription,
}
}
/// Total number of pull requests across all statuses, for the sidebar label.
pub fn total_count(&self) -> usize {
self.counts.total
}
fn rebuild(&mut self, cx: &mut Context<Self>) {
let store = self.store.read(cx);
let filter = self.filter;
let (visible_prs, counts) = {
let roots = store
.pull_requests
.iter()
.filter(|pr| pr.kind == Kind::GitPullRequest);
filter_by_status(
roots,
|pr| store.status_of(pr),
|status| filter.matches(status),
)
};
let mut keys: Vec<PublicKey> = store
.pull_requests
.iter()
.filter(|pr| pr.kind == Kind::GitPullRequest)
.map(|pr| pr.pubkey)
.collect();
if let Some(owner) = store
.announcement
.as_ref()
.map(|announcement| announcement.owner)
{
keys.push(owner);
}
self.directory.update(cx, |directory, cx| {
directory.track(keys, cx);
});
let filter_changed = self.synced_filter != filter;
if !filter_changed && self.visible_prs == visible_prs && self.counts == counts {
return;
}
self.synced_filter = filter;
self.visible_prs = visible_prs;
self.counts = counts;
cx.notify();
}
fn open_new(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return;
};
let id = SharedString::from(format!("new-pr:{addr}"));
let workspace = self.workspace.clone();
let workspace_for_build = workspace.clone();
let store = self.store.clone();
crate::shared::panels::open_detail(
&workspace,
id.clone(),
move |window, cx| {
cx.new(|cx| {
NewPullRequestView::new(
workspace_for_build.clone(),
id.clone(),
store.clone(),
window,
cx,
)
})
},
window,
cx,
);
}
fn open_send_patch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return;
};
let id = SharedString::from(format!("send-patch:{addr}"));
let workspace = self.workspace.clone();
let workspace_for_build = workspace.clone();
let store = self.store.clone();
crate::shared::panels::open_detail(
&workspace,
id.clone(),
move |window, cx| {
cx.new(|cx| {
SendPatchView::new(
workspace_for_build.clone(),
id.clone(),
store.clone(),
window,
cx,
)
})
},
window,
cx,
);
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
let counts = self.counts;
let muted = cx.theme().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();
h_flex()
.px_4()
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.bg(cx.theme().colors.muted)
.child(
Segmented::new("pr-filter", self.filter)
.options(vec![
SegmentedOption::new(
PullRequestFilter::All,
format!("All ({})", counts.total),
)
.icon(Icon::named(IconRole::GitPullRequest).color(muted)),
SegmentedOption::new(
PullRequestFilter::Open,
format!("Open ({})", counts.open),
)
.icon(Icon::named(IconRole::GitPullRequest).color(muted)),
SegmentedOption::new(
PullRequestFilter::Closed,
format!("Closed ({})", counts.closed),
)
.icon(Icon::named(IconRole::GitPullRequestClosed).color(muted)),
SegmentedOption::new(
PullRequestFilter::Draft,
format!("Draft ({})", counts.draft),
)
.icon(Icon::named(IconRole::GitPullRequestDraft).color(muted)),
SegmentedOption::new(
PullRequestFilter::Merged,
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}");
}
}),
)
.child(div().flex_1())
.child(
DropdownMenu::new("new-pr-actions")
.label("New")
.icon(Icon::named(IconRole::GitPullRequest))
.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| {
crate::shared::log_dropped(menu_open_weak.update(cx, |this, cx| {
this.new_pr_menu_open = open;
cx.notify();
}));
})
.items(move |_, _| {
vec![MenuItem::new("Send Patch").handler({
let weak = patch_weak.clone();
move |window, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
this.open_send_patch(window, cx);
}));
}
})]
}),
)
.into_any_element()
}
}
impl Panel for PullRequestsView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Pull requests")
}
}
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();
let workspace = self.workspace.clone();
let (last_error, last_warning) = {
let store = self.store.read(cx);
(store.last_error.clone(), store.last_warning.clone())
};
let dismiss_warning_store = self.store.clone();
let dismiss_error_store = self.store.clone();
v_flex()
.size_full()
.child(self.render_header(cx))
.when_some(last_warning, |this, warning| {
this.child(
Alert::new("pr-warning")
.severity(AlertSeverity::Warning)
.title("Pull request warning")
.message(warning)
.on_dismiss(move |cx| {
dismiss_warning_store.update(cx, |store, _| store.last_warning = None);
}),
)
})
.when_some(last_error, |this, error| {
this.child(
Alert::new("pr-error")
.severity(AlertSeverity::Danger)
.title("Pull request error")
.message(error)
.on_dismiss(move |cx| {
dismiss_error_store.update(cx, |store, _| store.last_error = None);
}),
)
})
.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()
.typeset(TextRole::Body, cx)
.text_ellipsis()
.whitespace_nowrap()
.child(title),
)
.child(
h_flex()
.gap_2()
.typeset(TextRole::Caption, cx)
.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()))
}),
)
.into_any_element()
}
}
+501
View File
@@ -0,0 +1,501 @@
use std::path::PathBuf;
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,
};
use signed_state::{CheckoutsStore, RepoStore};
use ui::button::Button;
use ui::combobox::{Combobox, ComboboxState};
use ui::common::{h_flex, v_flex};
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 _, TextRole, Typeset as _};
use super::helpers::{ForkCompare, fork_display_name, truncate_label};
use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::repo::helpers::commit_row;
use crate::shared::widgets::empty_state;
use crate::workspace::Workspace;
mod source;
pub struct NewPullRequestView {
workspace: WeakEntity<Workspace>,
panel_id: SharedString,
pub(super) store: Entity<RepoStore>,
pub(super) repo_path: Option<PathBuf>,
pub(super) branches: Vec<SharedString>,
pub(super) fork: Option<ForkCompare>,
pub(super) base: SharedString,
pub(super) compare: SharedString,
pub(super) base_select: Entity<ComboboxState<SharedString>>,
pub(super) compare_select: Entity<ComboboxState<SharedString>>,
subject: Entity<InputState>,
description: Entity<InputState>,
pub(super) merge_base: Option<String>,
pub(super) commits: Option<Vec<signed_git::FileCommit>>,
pub(super) loading: bool,
pub(super) error: Option<SharedString>,
submitting: bool,
pub(super) compare_generation: u64,
pub(super) fork_generation: u64,
active_tab: usize,
pub(super) pane: Entity<DiffPane>,
scroll_handle: UniformListScrollHandle,
pub(super) tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
source_open: bool,
_subscriptions: Vec<Subscription>,
}
impl NewPullRequestView {
pub fn new(
workspace: WeakEntity<Workspace>,
panel_id: SharedString,
store: Entity<RepoStore>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let pane = cx.new(DiffPane::new);
let weak = cx.entity().downgrade();
let subject = InputState::new(cx);
let description = InputState::builder().multiline().build(cx);
let base_select = cx.new(|cx| {
ComboboxState::new(
Combobox::new("pr-base", "Base", Vec::new()).on_change({
let weak = weak.clone();
move |value, _window, cx| {
if let Some(base) = value {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
if this.base == base {
return;
}
this.base = base;
this.reload_compare(cx);
}));
}
}
}),
window,
cx,
)
});
let compare_select = cx.new(|cx| {
ComboboxState::new(
Combobox::new("pr-compare", "Compare", Vec::new()).on_change({
let weak = weak.clone();
move |value, _window, cx| {
if let Some(compare) = value {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
if this.compare == compare {
return;
}
this.compare = compare;
this.reload_compare(cx);
}));
}
}
}),
window,
cx,
)
});
window.defer(cx, move |window, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
let Some(addr) = this.store.read(cx).addr().cloned() else {
return;
};
let Some(path) = CheckoutsStore::global(cx)
.read(cx)
.associations_of(&addr)
.into_iter()
.next()
else {
return;
};
this.apply_folder_path(path, window, cx);
}));
});
Self {
workspace,
panel_id,
store,
repo_path: None,
branches: Vec::new(),
fork: None,
base: SharedString::default(),
compare: SharedString::default(),
base_select,
compare_select,
subject,
description,
merge_base: None,
commits: None,
loading: false,
error: None,
submitting: false,
compare_generation: 0,
fork_generation: 0,
active_tab: 0,
pane,
scroll_handle: UniformListScrollHandle::new(),
tasks: Vec::new(),
source_open: false,
_subscriptions: Vec::new(),
}
}
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();
let compare_ref = self.compare_ref();
let store = self.store.clone();
let workspace = self.workspace.clone();
let panel_id = self.panel_id.clone();
self.submitting = true;
self.error = None;
cx.notify();
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let publish = store.update(cx, |store, cx| {
store.open_pull_request_from_refs(
repo_path,
merge_base,
compare_ref,
(!subject.is_empty()).then_some(subject),
description,
Some(branch_name),
false,
cx,
)
});
if let Err(error) = publish.await {
this.update(cx, |this, cx| {
this.submitting = false;
this.error = Some(error.to_string().into());
cx.notify();
})?;
return Ok(());
}
this.update(cx, |this, _cx| {
this.submitting = false;
})?;
crate::shared::log_dropped(
workspace.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)),
);
Ok(())
});
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();
crate::shared::panels::open_detail(
&workspace,
id,
move |window, cx| {
cx.new(|cx| CommitDiffView::new(repo_path.clone(), commit_id.clone(), window, cx))
},
window,
cx,
);
}
fn submit_enabled(&self, cx: &App) -> bool {
self.has_source()
&& !self.loading
&& !self.submitting
&& self.merge_base.is_some()
&& self
.commits
.as_ref()
.is_some_and(|commits| !commits.is_empty())
&& !self.subject.read(cx).value().is_empty()
}
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 associated = self
.store
.read(cx)
.addr()
.map(|addr| CheckoutsStore::global(cx).read(cx).associations_of(addr))
.unwrap_or_default();
let active_path = (self.fork.is_none())
.then(|| self.repo_path.clone())
.flatten();
let candidates = self.fork_candidates(cx);
let user = signed_state::Backend::global(cx).read(cx).current_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(&fork_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 refresh_fork = self.fork.as_ref().map(|fork| fork.announcement.clone());
h_flex()
.px_4()
.py_2()
.w_full()
.gap_3()
.items_end()
.child(
v_flex()
.gap_1()
.child(label("Merge Into", cx))
.child(div().w(px(160.)).child(self.base_select.clone())),
)
.child(
v_flex()
.gap_1()
.child(label("Pull From", cx))
.child(div().w(px(160.)).child(self.compare_select.clone())),
)
.child(
v_flex().gap_1().child(label("Source", cx)).child(
Menu::new("pr-source")
.open(self.source_open)
.on_change(move |open, _, cx| {
crate::shared::log_dropped(weak_menu.update(cx, |this, cx| {
this.source_open = open;
cx.notify();
}));
})
.trigger(move |_, _| {
Button::new("compare-source")
.label(source_label.clone())
.variant(ui::button::ButtonVariant::Secondary)
.into_any_element()
})
.items(move |_, _| {
super::helpers::source_menu_items(
source_view.clone(),
associated.clone(),
active_path.clone(),
candidates.clone(),
user,
active_fork.clone(),
)
}),
),
)
.when_some(refresh_fork, |this, fork| {
this.child(
Button::new("refresh-fork")
.icon(Icon::named(IconRole::Refresh))
.on_click(cx.listener(move |this, _, window, cx| {
this.choose_fork(fork.clone(), window, cx);
})),
)
})
.child(div().flex_1())
.child(
Button::new("create-pr")
.label("Create pull request")
.icon(Icon::named(IconRole::Plus))
.loading(self.submitting)
.disabled(!can_submit)
.on_click(move |_, window, cx| {
crate::shared::log_dropped(
weak.update(cx, |this, cx| this.submit(window, cx)),
);
}),
)
.into_any_element()
}
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)
.tabs(move |_, _| {
vec![
Tab::new("files", format!("Files ({files})")).lead(Icon::named(IconRole::File)),
Tab::new("commits", format!("Commits ({commits})"))
.lead(Icon::named(IconRole::GitCommit)),
]
})
.on_change(move |index, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
this.active_tab = index;
cx.notify();
}));
})
.into_any_element()
}
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();
}
if !self.has_source() {
return empty_state("Choose a local checkout or an announced fork to compare");
}
if self.commits.is_none() && self.error.is_some() {
return empty_state("Nothing to compare");
}
match self.active_tab {
0 => self.pane.clone().into_any_element(),
_ => self.render_commits(cx),
}
}
fn render_commits(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(commits) = self.commits.as_ref() else {
return empty_state("No commits");
};
if commits.is_empty() {
return empty_state("No commits between the branches");
}
let commits = commits.clone();
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()
}
}
impl Panel for NewPullRequestView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("New pull request")
}
fn loading(&self, _cx: &App) -> bool {
self.loading
}
}
impl Render for NewPullRequestView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.id("new-pr")
.size_full()
.child(
v_flex()
.gap_3()
.child(self.render_compare_bar(cx))
.child(
v_flex()
.px_4()
.gap_2()
.child(
Input::new("pr-title", self.subject.clone()).placeholder("Title"),
)
.child(
Input::new("pr-description", self.description.clone())
.rows(3)
.placeholder("Describe..."),
)
.when_some(self.error.clone(), |this, error| {
this.child(
div()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().ramps.destructive.base)
.child(error),
)
}),
)
.child(self.render_tabs(cx)),
)
.child(
v_flex()
.flex_1()
.min_h_0()
.w_full()
.child(self.render_content(cx)),
)
}
}
fn label(text: &'static str, cx: &App) -> AnyElement {
div()
.typeset(TextRole::Caption2, cx)
.child(text)
.into_any_element()
}
@@ -0,0 +1,397 @@
use std::path::{Path, PathBuf};
use gpui::{App, AppContext as _, Context, PathPromptOptions, SharedString, Window};
use nostr::prelude::Url;
use signed_core::Announcement;
use signed_git::{GitCache, Repo};
use signed_state::{Backend, CheckoutsStore, Mirrors, RepoListStore};
use super::NewPullRequestView;
use crate::pull_requests::helpers::ForkCompare;
impl NewPullRequestView {
pub(super) fn has_source(&self) -> bool {
self.repo_path.is_some() || self.fork.is_some()
}
pub(super) fn work_path(&self) -> Option<PathBuf> {
match &self.fork {
Some(fork) => Some(fork.mirror_path.clone()),
None => self.repo_path.clone(),
}
}
pub(super) fn base_ref(&self) -> String {
match &self.fork {
Some(_) => ForkCompare::base_ref(&self.base),
None => self.base.to_string(),
}
}
pub(super) fn compare_ref(&self) -> String {
match &self.fork {
Some(fork) => fork.compare_ref(&self.compare),
None => self.compare.to_string(),
}
}
pub(crate) fn choose_checkout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Choose local checkout".into()),
});
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let picked = match prompt.await {
Ok(Ok(Some(mut paths))) => paths.pop(),
_ => None,
};
let Some(path) = picked else {
return Ok(());
};
this.update_in(cx, |this, window, cx| {
this.apply_folder_path(path, window, cx)
})?;
Ok(())
});
self.tasks.push(task);
}
pub(crate) fn apply_folder_path(
&mut self,
path: PathBuf,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.fork_generation = self.fork_generation.wrapping_add(1);
let generation = self.fork_generation;
let path_string = path.to_string_lossy().to_string();
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let info = cx
.background_spawn({
let path = path.clone();
async move {
let repo = Repo::try_open(&path)?;
match repo.branches() {
Ok(branches) => Some((branches, repo.current_branch())),
Err(error) => {
log::warn!("failed to list branches: {error}");
None
}
}
}
})
.await;
this.update_in(cx, |this, window, cx| {
if generation != this.fork_generation {
return;
}
this.apply_checkout(path_string, info, window, cx);
})?;
Ok(())
});
self.tasks.push(task);
}
fn apply_checkout(
&mut self,
path: String,
info: Option<(Vec<String>, Option<String>)>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.fork = None;
let Some((branches, current)) = info else {
self.error = Some("The chosen folder is not a git repository".into());
self.repo_path = None;
self.branches.clear();
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
cx.notify();
return;
};
if branches.is_empty() {
self.error = Some("The repository has no branches yet".into());
self.repo_path = None;
self.branches.clear();
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
cx.notify();
return;
}
let announced = self.store.read(cx).head.clone();
let base = 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 compare = current
.filter(|branch| branches.contains(branch))
.unwrap_or_else(|| base.clone());
self.repo_path = Some(PathBuf::from(&path));
self.error = None;
self.branches = branches.into_iter().map(SharedString::from).collect();
if let Some(addr) = self.store.read(cx).addr().cloned() {
CheckoutsStore::global(cx).update(cx, |store, cx| {
store.record(PathBuf::from(&path), addr, cx);
});
}
self.base = SharedString::from(base);
self.compare = SharedString::from(compare);
self.sync_selectors(window, cx);
self.reload_compare(cx);
}
fn sync_selectors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let options: Vec<(SharedString, SharedString)> = self
.branches
.iter()
.map(|branch| (branch.clone(), branch.clone()))
.collect();
let base = self.base.clone();
let compare = self.compare.clone();
self.base_select.update(cx, |state, cx| {
state.set_options(options.clone(), cx);
state.set_selected(Some(base), window, cx);
});
self.compare_select.update(cx, |state, cx| {
state.set_options(options, cx);
state.set_selected(Some(compare), window, cx);
});
}
pub(super) fn fork_candidates(&self, cx: &App) -> Vec<Announcement> {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return Vec::new();
};
let euc = self
.store
.read(cx)
.announcement
.as_ref()
.and_then(|a| a.euc.clone());
let user = Backend::global(cx).read(cx).current_user();
let announcements = RepoListStore::global(cx).read(cx).announcements.clone();
Announcement::forks_in(&announcements, &addr, euc.as_deref(), user)
.into_iter()
.cloned()
.collect()
}
pub(crate) fn choose_fork(
&mut self,
announcement: Announcement,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(base) = self.store.read(cx).addr().cloned() else {
return;
};
let mirror_path = Mirrors::path(&base);
let namespace = GitCache::fork_namespace(&announcement);
let clone_urls: Vec<Url> = announcement.clone.clone();
let base_clone_urls: Vec<Url> = self
.store
.read(cx)
.announcement
.as_ref()
.map(|a| a.clone.clone())
.unwrap_or_default();
self.fork_generation = self.fork_generation.wrapping_add(1);
let generation = self.fork_generation;
let handle = window.window_handle();
self.loading = true;
self.error = None;
cx.notify();
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
let namespace = namespace.clone();
let mirror_path = mirror_path.clone();
async move {
Mirrors::ensure(&base, &base_clone_urls)?;
let repo = Repo::open(&mirror_path)?;
repo.delete_refs_with_prefix("refs/fork")?;
repo.fetch_refs(
&clone_urls,
&format!("+refs/heads/*:refs/fork/{namespace}/*"),
)?;
let strip = |refs: Vec<String>, prefix: &str| {
let mut names: Vec<String> = refs
.into_iter()
.filter_map(|name| {
name.strip_prefix(prefix)
.map(|rest| rest.trim_start_matches('/').to_owned())
})
.filter(|name| !name.is_empty())
.collect();
names.sort();
names
};
let base_branches = strip(
repo.refs_with_prefix("refs/remotes/origin")?,
"refs/remotes/origin",
);
let compare_branches = strip(
repo.refs_with_prefix(&format!("refs/fork/{namespace}"))?,
&format!("refs/fork/{namespace}"),
);
Ok::<_, anyhow::Error>((base_branches, compare_branches))
}
})
.await;
if let Err(error) = cx.update_window(handle, |_, window, cx| {
this.update(cx, |this, cx| {
if generation != this.fork_generation {
return;
}
this.apply_fork(announcement, mirror_path, namespace, result, window, cx);
})
}) {
log::warn!("failed to apply fork: {error}");
}
Ok(())
});
self.tasks.push(task);
}
fn apply_fork(
&mut self,
announcement: Announcement,
mirror_path: PathBuf,
namespace: String,
result: Result<(Vec<String>, Vec<String>), anyhow::Error>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.loading = false;
let (base_branches, compare_branches) = match result {
Ok(branches) => branches,
Err(error) => {
self.error = Some(format!("Could not compare against the fork: {error}").into());
cx.notify();
return;
}
};
if compare_branches.is_empty() {
self.error = Some("The fork has no branches to compare".into());
cx.notify();
return;
}
if base_branches.is_empty() {
self.error = Some("Could not list the target repository's branches.".into());
cx.notify();
return;
}
let announced = self.store.read(cx).head.clone();
let base = 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 compare = compare_branches
.iter()
.find(|branch| branch.as_str() == "main")
.map(|branch| SharedString::from(branch.clone()))
.unwrap_or_else(|| SharedString::from(compare_branches[0].clone()));
self.fork = Some(ForkCompare {
announcement,
namespace,
mirror_path,
});
self.error = None;
self.base = base;
self.compare = compare;
self.branches = base_branches.into_iter().map(SharedString::from).collect();
self.sync_selectors(window, cx);
self.reload_compare(cx);
}
pub(super) fn reload_compare(&mut self, cx: &mut Context<Self>) {
let Some(repo_path) = self.work_path() else {
return;
};
let base = self.base_ref();
let compare = self.compare_ref();
let base_name = self.base.to_string();
let compare_name = self.compare.to_string();
self.loading = true;
self.error = None;
self.compare_generation += 1;
let generation = self.compare_generation;
cx.notify();
if base == compare {
self.loading = false;
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
self.error = Some("Choose different base and compare branches".into());
cx.notify();
return;
}
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
async move {
let repo = Repo::open(Path::new(&repo_path))?;
let merge_base = repo.merge_base(&base, &compare)?.ok_or_else(|| {
anyhow::anyhow!(
"{base_name} and {compare_name} share no common ancestor"
)
})?;
let commits = repo.commit_range(&merge_base, &compare)?;
let diff = repo.range_diff(&merge_base, &compare)?;
Ok::<_, anyhow::Error>((merge_base, commits, diff))
}
})
.await;
this.update(cx, |this, cx| {
if generation != this.compare_generation {
return;
}
this.loading = false;
match result {
Ok((merge_base, commits, diff)) => {
this.merge_base = Some(merge_base);
this.commits = Some(commits);
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
}
Err(error) => {
this.merge_base = None;
this.commits = None;
this.pane.update(cx, |pane, cx| pane.clear(cx));
this.error = Some(error.to_string().into());
}
}
cx.notify();
})?;
Ok(())
});
self.tasks.push(task);
}
}
@@ -0,0 +1,173 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
Render, SharedString, Styled as _, WeakEntity, Window, div,
};
use signed_state::RepoStore;
use ui::button::Button;
use ui::common::{h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::layout::panel::Panel;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::workspace::Workspace;
pub struct SendPatchView {
workspace: WeakEntity<Workspace>,
panel_id: SharedString,
store: Entity<RepoStore>,
subject: Entity<InputState>,
description: Entity<InputState>,
patch: Entity<InputState>,
submitting: bool,
error: Option<SharedString>,
}
impl SendPatchView {
pub fn new(
workspace: WeakEntity<Workspace>,
panel_id: SharedString,
store: Entity<RepoStore>,
_window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let subject = InputState::new(cx);
let description = InputState::builder().multiline().build(cx);
let patch = InputState::builder().multiline().build(cx);
Self {
workspace,
panel_id,
store,
subject,
description,
patch,
submitting: false,
error: None,
}
}
fn submit(&mut self, cx: &mut Context<Self>) {
if self.submitting {
return;
}
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;
}
self.submitting = true;
self.error = None;
cx.notify();
let sync_error = self.store.update(cx, |store, cx| {
store.open_pull_request(
(!subject.is_empty()).then_some(subject),
description,
None,
patch,
false,
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)),
);
}
fn render_footer(&self, cx: &Context<Self>) -> AnyElement {
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()
.px_4()
.py_2()
.w_full()
.justify_end()
.border_t_1()
.border_color(cx.theme().colors.border)
.child(
Button::new("send-patch")
.label("Send patch")
.icon(Icon::named(IconRole::ArrowUp))
.loading(self.submitting)
.disabled(!can_submit)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.submit(cx)));
}),
)
.into_any_element()
}
}
impl Panel for SendPatchView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Send patch")
}
fn loading(&self, _cx: &App) -> bool {
self.submitting
}
}
impl Render for SendPatchView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.id("send-patch")
.size_full()
.child(
v_flex()
.p_4()
.flex_1()
.gap_2()
.child(Input::new("patch-subject", self.subject.clone()).placeholder("Title"))
.child(
Input::new("patch-description", self.description.clone())
.rows(2)
.placeholder("Describe the change"),
)
.child(
div()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(
"You can paste a git diff or a git format-patch patch series here.",
),
)
.child(
Input::new("patch-body", self.patch.clone())
.rows(12)
.placeholder("diff --git a/file.txt b/file.txt"),
)
.when_some(self.error.clone(), |this, error| {
this.child(
div()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().ramps.destructive.base)
.child(error),
)
}),
)
.child(self.render_footer(cx))
}
}
+93
View File
@@ -0,0 +1,93 @@
use gpui::{App, AppContext as _, SharedString, WeakEntity, Window};
use nostr::prelude::EventId;
use signed_core::{Announcement, RepoAddr};
use signed_state::RepoStore;
use crate::repo::RepoDetailView;
use crate::shared::panels;
use crate::workspace::Workspace;
/// An item of a repository to open from outside its detail panel.
pub enum RepoItem {
Issue(EventId),
PullRequest(EventId),
Patch,
}
/// Opens a repository as the main panel, keyed by its address.
pub fn open_repo_panel(
workspace: &WeakEntity<Workspace>,
addr: &RepoAddr,
hint: Option<&Announcement>,
window: &mut Window,
cx: &mut App,
) {
let id = SharedString::from(format!("repo:{addr}"));
let addr = addr.clone();
let hint = hint.cloned();
let workspace_for_build = workspace.clone();
panels::open_primary(
workspace,
id,
move |window, cx| {
let addr = addr.clone();
let hint = hint.clone();
cx.new(|cx| RepoDetailView::new(workspace_for_build.clone(), addr, hint, window, cx))
},
window,
cx,
);
}
/// Opens an issue or pull request using a store built here.
pub fn open_repo_item(
workspace: &WeakEntity<Workspace>,
addr: &RepoAddr,
hint: Option<&Announcement>,
item: RepoItem,
window: &mut Window,
cx: &mut App,
) {
let store = cx.new(|cx| RepoStore::new(addr.clone(), hint.cloned(), cx));
match item {
RepoItem::Issue(issue_id) => {
let id = SharedString::from(format!("issue:{issue_id}"));
let store = store.clone();
panels::open_detail(
workspace,
id,
move |_, cx| {
cx.new(|cx| {
crate::issues::detail::IssueDetailView::new(store.clone(), issue_id, cx)
})
},
window,
cx,
);
}
RepoItem::PullRequest(pr_id) => {
let id = SharedString::from(format!("pr:{pr_id}"));
let workspace_for_build = workspace.clone();
let store = store.clone();
panels::open_detail(
workspace,
id,
move |window, cx| {
cx.new(|cx| {
crate::pull_requests::PullRequestDetailView::new(
workspace_for_build.clone(),
store.clone(),
pr_id,
window,
cx,
)
})
},
window,
cx,
);
}
RepoItem::Patch => {}
}
}
+535
View File
@@ -0,0 +1,535 @@
use std::collections::HashSet;
use std::path::PathBuf;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Axis, Context, Entity, IntoElement, ParentElement as _,
Render, ScrollStrategy, SharedString, Styled as _, Task, UniformListScrollHandle, Window, div,
px, uniform_list,
};
use signed_git::{CommitDiff, DiffStatus, FileCommit, FileDiff, Repo};
use ui::badge::{Badge, BadgeVariant};
use ui::clipboard::ClipboardButton;
use ui::common::{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 _, TextRole, Typeset as _};
use ui::tree::{Tree, TreeItem};
use utils::relative_time_secs;
use super::helpers::{DiffRow, diff_rows, render_diff_row};
use crate::shared::tree::{TreeItemSeed, TreeRow, build_tree_items, collect_expanded, flatten};
use crate::shared::widgets::empty_state;
pub struct DiffPane {
diff: Option<CommitDiff>,
seeds: Vec<TreeItemSeed>,
expanded: HashSet<String>,
rows: Vec<TreeRow>,
selected_file: Option<SharedString>,
selected_index: Option<usize>,
/// Rows of the selected file's diff, hunk headers and lines.
diff_rows: Vec<DiffRow>,
scroll_handle: UniformListScrollHandle,
split: Entity<ResizableState>,
}
impl DiffPane {
pub fn new(cx: &mut Context<Self>) -> Self {
Self {
diff: None,
seeds: Vec::new(),
expanded: HashSet::new(),
rows: Vec::new(),
selected_file: None,
selected_index: None,
diff_rows: Vec::new(),
scroll_handle: UniformListScrollHandle::new(),
split: {
let split = ResizableState::new(cx);
split.update(cx, |split, cx| split.set_sizes([px(260.)], cx));
split
},
}
}
pub fn diff(&self) -> Option<&CommitDiff> {
self.diff.as_ref()
}
pub fn set_diff(&mut self, diff: CommitDiff, cx: &mut Context<Self>) {
let mut paths: Vec<PathBuf> = diff
.files
.iter()
.map(|file| PathBuf::from(&file.path))
.collect();
paths.sort();
self.seeds = build_tree_items(&paths);
self.expanded = collect_expanded(&self.seeds);
self.rows = flatten(&self.seeds, &self.expanded);
let first = diff
.files
.first()
.map(|file| SharedString::from(file.path.as_str()));
self.selected_file = first.clone();
self.selected_index = first
.as_ref()
.and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref()));
self.diff = Some(diff);
if let Some(path) = first {
self.set_diff_rows(path.as_ref());
} else {
self.diff_rows.clear();
}
cx.notify();
}
pub fn clear(&mut self, cx: &mut Context<Self>) {
self.diff = None;
self.seeds.clear();
self.expanded.clear();
self.rows.clear();
self.selected_file = None;
self.selected_index = None;
self.diff_rows.clear();
cx.notify();
}
fn select_file(&mut self, path: &str, cx: &mut Context<Self>) {
self.selected_file = Some(path.into());
self.selected_index = self.rows.iter().position(|row| row.id == path);
self.set_diff_rows(path);
cx.notify();
}
fn set_diff_rows(&mut self, path: &str) {
let Some(diff) = self.diff.as_ref() else {
return;
};
let Some(file) = diff.files.iter().find(|file| file.path == path) else {
return;
};
self.diff_rows = diff_rows(file);
self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
}
fn toggle_folder(&mut self, id: &str, cx: &mut Context<Self>) {
if !self.expanded.remove(id) {
self.expanded.insert(id.to_owned());
}
self.rows = flatten(&self.seeds, &self.expanded);
self.selected_index = self
.selected_file
.as_ref()
.and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref()));
cx.notify();
}
fn render_tree_column(&self, cx: &mut Context<Self>) -> AnyElement {
let rows = self.rows.clone();
let selected = self.selected_index;
let view = cx.entity().downgrade();
let change_view = view.clone();
v_flex()
.h_full()
.min_h_0()
.p_2()
.child(
Tree::new("commit-diff-tree")
.selected(selected)
.items(move |_, _| {
rows.iter()
.map(|row| {
let item = TreeItem::new(row.id.clone(), row.label.clone())
.depth(row.depth)
.expandable(row.expandable)
.expanded(row.expanded);
if row.expandable {
item.icon(Icon::named(IconRole::Folder))
} else {
item.icon(Icon::named(IconRole::File))
}
})
.collect()
})
.on_change(move |index, window, cx| {
if let Some(index) = index
&& let Err(error) = change_view.update(cx, |this, cx| {
this.activate_row(index, window, cx);
})
{
log::warn!("failed to activate diff tree row: {error}");
}
})
.on_disclosure({
let view = view;
move |index, _, cx| {
if let Err(error) = view.update(cx, |this, cx| {
let id = this.rows.get(index).map(|row| row.id.clone());
if let Some(id) = id {
this.toggle_folder(&id, cx);
}
}) {
log::warn!("failed to toggle diff folder: {error}");
}
}
}),
)
.into_any_element()
}
fn activate_row(&mut self, index: usize, _window: &mut Window, cx: &mut Context<Self>) {
let Some(row) = self.rows.get(index) else {
return;
};
let id = row.id.clone();
let expandable = row.expandable;
self.selected_index = Some(index);
if expandable {
self.toggle_folder(&id, cx);
} else {
self.select_file(&id, cx);
}
}
fn render_detail_column(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(diff) = self.diff.as_ref() else {
return empty_state("No changes");
};
let Some(path) = self.selected_file.clone() else {
return if diff.files.is_empty() {
empty_state("No files changed")
} else {
empty_state("Select a file")
};
};
let Some(file) = diff.files.iter().find(|file| file.path == path.as_ref()) else {
return empty_state("File not found");
};
self.render_file_diff(file, cx)
}
fn render_file_diff(&self, file: &FileDiff, cx: &App) -> AnyElement {
let status_label = match file.status {
DiffStatus::Added => "A",
DiffStatus::Modified => "M",
DiffStatus::Deleted => "D",
DiffStatus::Renamed => "R",
DiffStatus::Copied => "C",
};
let status_color = match file.status {
DiffStatus::Added => cx.theme().ramps.success.base,
DiffStatus::Modified => cx.theme().ramps.info.base,
DiffStatus::Deleted => cx.theme().ramps.destructive.base,
DiffStatus::Renamed | DiffStatus::Copied => cx.theme().colors.muted_foreground,
};
let title = match &file.old_path {
Some(old) => format!("{old} → {}", file.path),
None => file.path.clone(),
};
let body: AnyElement = if file.binary {
empty_state("Diff not available")
} else if file.hunks.is_empty() {
empty_state("No content changes")
} else {
let hunks = file.hunks.clone();
let rows = self.diff_rows.clone();
v_flex()
.size_full()
.relative()
.child(
uniform_list("commit-diff-rows", rows.len(), move |range, _, cx| {
range
.map(|ix| render_diff_row(&hunks, rows[ix], cx))
.collect()
})
.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(),
)),
)
.into_any_element()
};
v_flex()
.flex_1()
.min_w_0()
.h_full()
.child(
h_flex()
.px_3()
.h_9()
.gap_2()
.child(
div()
.typeset(TextRole::Caption2, cx)
.text_color(status_color)
.child(status_label),
)
.child(
div()
.flex_1()
.min_w_0()
.typeset(TextRole::Caption2, cx)
.text_ellipsis()
.whitespace_nowrap()
.child(title),
)
.when(!file.binary, |this| {
this.child(
h_flex()
.gap_2()
.typeset(TextRole::Caption, cx)
.child(
div()
.text_color(cx.theme().ramps.success.base)
.child(format!("+{}", file.insertions)),
)
.child(
div()
.text_color(cx.theme().ramps.destructive.base)
.child(format!("-{}", file.deletions)),
),
)
}),
)
.child(div().flex_1().min_h_0().child(body))
.into_any_element()
}
}
impl Render for DiffPane {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let tree = self.render_tree_column(cx);
let detail = self.render_detail_column(cx);
h_flex()
.size_full()
.min_h_0()
.bg(cx.theme().colors.background)
.child(
Resizable::new("commit-diff-split", self.split.clone())
.axis(Axis::Horizontal)
.pane_with_min(tree, px(120.))
.pane_with_min(detail, px(240.)),
)
}
}
pub struct CommitDiffView {
worktree: PathBuf,
commit: FileCommit,
/// The diff is being computed on a background task.
loading: bool,
error: Option<SharedString>,
pane: Entity<DiffPane>,
tasks: Vec<Task<Result<(), anyhow::Error>>>,
}
impl CommitDiffView {
pub fn new(
worktree: PathBuf,
commit_id: String,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let pane = cx.new(DiffPane::new);
let weak = cx.entity().downgrade();
window.defer(cx, move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| this.load(window, cx)) {
log::warn!("failed to load commit diff: {error}");
}
});
Self {
worktree,
commit: FileCommit {
id: commit_id,
summary: String::new(),
description: None,
author: String::new(),
time: 0,
},
loading: true,
error: None,
pane,
tasks: Vec::new(),
}
}
fn load(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.loading = true;
self.error = None;
cx.notify();
let worktree = self.worktree.clone();
let id = self.commit.id.clone();
let task: Task<Result<(), anyhow::Error>> = cx.spawn_in(window, async move |this, cx| {
let commit = cx
.background_spawn({
let worktree = worktree.clone();
let id = id.clone();
async move { Repo::open(&worktree).and_then(|repo| repo.commit(&id)) }
})
.await;
let diff = cx
.background_spawn({
let worktree = worktree.clone();
let id = id.clone();
async move { Repo::open(&worktree).and_then(|repo| repo.commit_diff(&id)) }
})
.await;
this.update_in(cx, |this, _window, cx| {
this.loading = false;
if let Ok(Some(commit)) = commit {
this.commit = commit;
}
match diff {
Ok(diff) => {
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
}
Err(error) => {
this.error = Some(error.to_string().into());
}
}
cx.notify();
})?;
Ok(())
});
self.tasks.push(task);
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
let commit = &self.commit;
let (files, insertions, deletions) = self.pane.read(cx).diff().map_or((0, 0, 0), |diff| {
(
diff.files.len(),
diff.files.iter().map(|file| file.insertions).sum(),
diff.files.iter().map(|file| file.deletions).sum(),
)
});
v_flex()
.flex_none()
.px_4()
.py_3()
.w_full()
.gap_2()
.border_b_1()
.border_color(cx.theme().colors.border)
.child(
v_flex()
.child(
div()
.typeset(TextRole::Headline, cx)
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
)
.child(
h_flex()
.gap_2()
.typeset(TextRole::Body, cx)
.child(SharedString::from(format!("{} committed", commit.author)))
.child(
h_flex()
.gap_1()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(&commit.id))
.child(ClipboardButton::new("commit-id", &commit.id)),
)
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(relative_time_secs(commit.time)),
),
),
)
.when_some(commit.description.as_ref(), |this, description| {
this.child(
div()
.typeset(TextRole::Body, cx)
.child(SharedString::from(description)),
)
})
.child(
h_flex()
.gap_2()
.typeset(TextRole::Caption, cx)
.child(Badge::new("commit-files", format!("{files} files changed")))
.when(insertions > 0, |this| {
this.child(
Badge::new("commit-insertions", format!("+ {insertions}"))
.variant(BadgeVariant::Success),
)
})
.when(deletions > 0, |this| {
this.child(
Badge::new("commit-deletions", format!("- {deletions}"))
.variant(BadgeVariant::Danger),
)
}),
)
.into_any_element()
}
}
impl Panel for CommitDiffView {
fn title(&self, _cx: &App) -> SharedString {
let short = self.commit.id.get(..8).unwrap_or(&self.commit.id);
SharedString::from(format!("Commit {short}"))
}
fn loading(&self, _cx: &App) -> bool {
self.loading
}
}
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()
} else if let Some(error) = self.error.clone() {
empty_state(error)
} else {
self.pane.clone().into_any_element()
};
v_flex()
.size_full()
.min_h_0()
.child(self.render_header(cx))
.child(div().flex_1().min_h_0().child(body))
}
}
+256
View File
@@ -0,0 +1,256 @@
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, Window, div, px,
};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
use signed_core::Announcement;
use ui::avatar::Avatar;
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::dialog::{Dialog, DialogHandle};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::middle_truncate;
pub struct AboutDialog {
handle: DialogHandle,
announcement: Announcement,
directory: Entity<ProfileDirectory>,
}
impl AboutDialog {
pub fn new(
announcement: Announcement,
directory: Entity<ProfileDirectory>,
cx: &mut App,
) -> Entity<Self> {
cx.new(|_| Self {
handle: DialogHandle::new(true),
announcement,
directory,
})
}
}
impl Render for AboutDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let announcement = self.announcement.clone();
let directory = self.directory.clone();
Dialog::new("about-dialog")
.handle(self.handle.clone())
.min_width(px(500.))
.title("About")
.content(move |_, cx| announcement_rows(&announcement, &directory, cx))
.into_any_element()
}
}
fn announcement_rows(
announcement: &Announcement,
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> AnyElement {
let mut rows: Vec<AnyElement> = Vec::new();
rows.push(row(
"Name",
text(
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from("-")),
cx,
),
cx,
));
rows.push(row(
"Description",
text(
announcement
.description
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from("-")),
cx,
),
cx,
));
if !announcement.web.is_empty() {
rows.push(row(
"Web",
list(
"about-web",
announcement.web.iter().map(|url| url.to_string()),
cx,
),
cx,
));
}
if let Some(euc) = &announcement.euc {
rows.push(row(
"Earliest Commit",
copy_value("about-euc", euc.clone(), cx),
cx,
));
}
if let Some(upstream) = &announcement.upstream {
rows.push(row("Upstream", text(upstream.display(), cx), cx));
}
if !announcement.hashtags.is_empty() {
rows.push(row(
"Hashtags",
text(SharedString::from(announcement.hashtags.join(", ")), cx),
cx,
));
}
if !announcement.clone.is_empty() {
rows.push(row(
"Clone URLs",
list(
"about-clone",
announcement.clone.iter().map(|url| url.to_string()),
cx,
),
cx,
));
}
if !announcement.relays.is_empty() {
rows.push(row(
"Grasp Relays",
list(
"about-relays",
announcement.relays.iter().map(|url| url.to_string()),
cx,
),
cx,
));
}
if !announcement.maintainers.is_empty() {
rows.push(row(
"Maintainers",
maintainers(&announcement.maintainers, directory, cx),
cx,
));
}
v_flex().gap_3().w_full().children(rows).into_any_element()
}
fn row(label: &'static str, value: AnyElement, cx: &App) -> AnyElement {
v_flex()
.gap_1()
.min_w_0()
.child(
div()
.typeset(TextRole::Caption2, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(label),
)
.child(value)
.into_any_element()
}
fn text<T>(value: T, cx: &App) -> AnyElement
where
T: Into<SharedString>,
{
div()
.typeset(TextRole::Body, cx)
.w_full()
.min_w_0()
.child(value.into())
.into_any_element()
}
fn copy_value(id: &'static str, value: String, cx: &App) -> AnyElement {
h_flex()
.gap_2()
.items_center()
.min_w_0()
.child(
div()
.font_family(cx.theme().mono_font)
.typeset(TextRole::Caption, cx)
.min_w_0()
.child(SharedString::from(value.clone())),
)
.child(ClipboardButton::new(id, value))
.into_any_element()
}
fn maintainers(
maintainers: &[PublicKey],
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> AnyElement {
v_flex()
.gap_2()
.min_w_0()
.children(maintainers.iter().map(|pubkey| {
let profile = directory.read(cx).profile(pubkey, cx);
let name = profile.name();
h_flex()
.gap_2()
.items_center()
.min_w_0()
.child(
Avatar::new(*pubkey)
.name(name.clone())
.picture(profile.picture())
.small(),
)
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.typeset(TextRole::Body, cx)
.child(name),
)
.into_any_element()
}))
.into_any_element()
}
fn list(id: &'static str, items: impl IntoIterator<Item = String>, cx: &App) -> AnyElement {
v_flex()
.gap_2()
.min_w_0()
.children(items.into_iter().enumerate().map(|(ix, item)| {
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()
.whitespace_nowrap()
.text_ellipsis()
.typeset(TextRole::Body, cx)
.child(SharedString::from(middle_truncate(&item, 28, 16))),
)
.child(ClipboardButton::new(
SharedString::from(format!("{id}-{ix}")),
item,
))
.into_any_element()
}))
.into_any_element()
}
@@ -0,0 +1,279 @@
use std::path::PathBuf;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _,
PathPromptOptions, Render, Styled as _, Task, WeakEntity, Window, div, px,
};
use settings::SettingsStore;
use signed_state::{Backend, CheckoutsStore};
use ui::button::{Button, ButtonVariant};
use ui::common::{h_flex, v_flex};
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
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::workspace::Workspace;
/// Progress of the create-repository flow, so async results can be rendered.
pub struct CreateRepoDialog {
workspace: WeakEntity<Workspace>,
handle: DialogHandle,
name_input: Entity<InputState>,
desc_input: Entity<InputState>,
folder_input: Entity<InputState>,
relay_input: Entity<InputState>,
state: Entity<DialogProgress>,
grasp_state: Entity<GraspServersState>,
/// Held so the grasp-server load is cancelled when the dialog drops.
task: Option<Task<()>>,
}
impl CreateRepoDialog {
pub fn new(
workspace: WeakEntity<Workspace>,
window: &mut Window,
cx: &mut App,
) -> Entity<Self> {
let settings = SettingsStore::global(cx);
let grasp_settings = settings.read(cx).settings().grasp_servers.clone();
let name_input = InputState::new(cx);
let desc_input = InputState::builder().multiline().build(cx);
let default_folder = settings
.read(cx)
.settings()
.create_repository
.default_folder
.clone()
.unwrap_or_else(paths::desktop_dir);
let folder_input = InputState::builder()
.text(default_folder.to_string_lossy())
.read_only()
.build(cx);
let relay_input = InputState::new(cx);
let state = cx.new(|_| DialogProgress::default());
let grasp_state = cx.new(|_| GraspServersState::new_default(&grasp_settings));
cx.new(|cx| {
cx.defer_in(window, move |this: &mut Self, window, cx| {
let task = load_user_grasp_servers(this.grasp_state.clone(), window, cx);
this.task = Some(task);
});
Self {
workspace,
handle: DialogHandle::new(true),
name_input,
desc_input,
folder_input,
relay_input,
state,
grasp_state,
task: None,
}
})
}
fn create(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.state.read(cx).busy {
return;
}
let name = self.name_input.read(cx).value().trim().to_owned();
let description = self.desc_input.read(cx).value().trim().to_owned();
let folder = PathBuf::from(self.folder_input.read(cx).value().trim());
let servers = self.grasp_state.read(cx).grasp_servers.clone();
if name.is_empty() {
self.fail("Repository name is required", cx);
return;
}
if servers.is_empty() {
self.fail("Add at least one grasp server", cx);
return;
}
let backend = Backend::global(cx);
let Some(user) = backend.read(cx).current_user() else {
self.fail("Sign in to create a repository", cx);
return;
};
let addr =
signed_core::RepoAddr::new(user, signed_core::RepoAddr::identifier_from_name(&name));
self.state.update(cx, |state, cx| {
state.begin_push(addr, cx);
cx.notify();
});
let task = backend.update(cx, |backend, cx| {
backend.create_repository(&name, &description, folder, servers, cx)
});
let state = self.state.clone();
let workspace = self.workspace.clone();
let close = self.handle.clone();
let handle = window.window_handle();
cx.spawn(async move |_this, cx| match task.await {
Ok((announcement, local_path)) => {
cx.update_window(handle, |_, window, cx| {
let checkouts = CheckoutsStore::global(cx);
checkouts.update(cx, |store, cx| {
store.record(local_path.clone(), announcement.addr(), cx);
});
cx.open_with_system(&local_path);
open_repo_panel(
&workspace,
&announcement.addr(),
Some(&announcement),
window,
cx,
);
close.close(cx);
})
.ok();
}
Err(error) => {
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();
});
}
}
impl Render for CreateRepoDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let name_input = self.name_input.clone();
let desc_input = self.desc_input.clone();
let folder_input = self.folder_input.clone();
let relay_input = self.relay_input.clone();
let state = self.state.clone();
let grasp_state = self.grasp_state.clone();
let action_state = state.clone();
let this = cx.entity().downgrade();
Dialog::new("create-repo-dialog")
.handle(self.handle.clone())
.min_width(px(520.))
.title("Create Repository")
.content(move |_window, cx| {
let progress = state.read(cx);
v_flex()
.gap_3()
.child(
Field::new("repo-name", "Repository Name")
.description("Max 100 characters")
.child(Input::new("repo-name-input", name_input.clone())),
)
.child(
Field::new("repo-description", "Description").child(
Input::new("repo-description-input", desc_input.clone()).rows(3),
),
)
.child(
Field::new("repo-folder", "Folder")
.description("Where the repository's working copy is created.")
.child(
h_flex()
.gap_1()
.w_full()
.child(div().flex_1().child(Input::new(
"repo-folder-input",
folder_input.clone(),
)))
.child(
Button::new("choose-folder")
.icon(Icon::named(IconRole::Folder))
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Choose folder"))
.on_click({
let folder_input = folder_input.clone();
move |_, window, cx| {
choose_folder(&folder_input, window, cx);
}
}),
),
),
)
.child(grasp_servers_field(&grasp_state, &relay_input, cx))
.when_some(push_steps_row(&progress.push_steps, cx), |el, steps| {
el.child(steps)
})
.when_some(error_row(&progress.error, cx), |el, error| el.child(error))
.into_any_element()
})
.actions(move |_, cx| {
let busy = action_state.read(cx).busy;
let this = this.clone();
let create: AnyElement = Button::new("create-repository")
.label("Create repository")
.icon(Icon::named(IconRole::Plus))
.loading(busy)
.disabled(busy)
.on_click(move |_, window, cx| {
crate::shared::log_dropped(
this.update(cx, |this, cx| this.create(window, cx)),
);
})
.into_any_element();
vec![create]
})
}
}
fn choose_folder(folder_input: &Entity<InputState>, window: &mut Window, cx: &mut App) {
let store = SettingsStore::global(cx);
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Choose folder".into()),
});
let handle = window.window_handle();
let folder_input = folder_input.clone();
cx.spawn(async move |cx| {
if let Ok(Ok(Some(mut paths))) = prompt.await
&& let Some(path) = paths.pop()
&& let Err(error) = cx.update_window(handle, |_, window, cx| {
let text = path.to_string_lossy().to_string();
store.update(cx, |store, cx| {
store.edit(
|settings| {
settings.create_repository.default_folder = Some(path.clone());
},
cx,
);
});
folder_input.update(cx, |input, cx| input.set_value(text, window, cx));
})
{
log::warn!("failed to apply selected folder: {error}");
}
})
.detach();
}
@@ -0,0 +1,281 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, SharedString,
Styled as _, Task, Window, div,
};
use nostr::prelude::RelayUrl;
use settings::{DEFAULT_GRASP_SERVERS, GraspServersSettings};
use signed_state::Backend;
use ui::button::{Button, ButtonVariant};
use ui::common::{Sizable, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::switch::Switch;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tooltip::Tooltip;
/// State of the grasp-server section of a publish dialog, so async results can be rendered.
#[derive(Default)]
pub struct GraspServersState {
/// Set while the user's kind `10317` grasp list loads.
pub loading_servers: bool,
pub grasp_servers: Vec<RelayUrl>,
pub servers_enabled: bool,
/// Error from the last grasp-server edit, such as an invalid relay URL.
pub error: Option<SharedString>,
}
impl GraspServersState {
/// Defaults used until the user's grasp list loads and replaces them.
pub fn new_default(settings: &GraspServersSettings) -> Self {
let urls: Vec<String> = if settings.default_servers.is_empty() {
DEFAULT_GRASP_SERVERS
.iter()
.map(|url| (*url).to_owned())
.collect()
} else {
settings.default_servers.clone()
};
Self {
loading_servers: true,
servers_enabled: false,
grasp_servers: urls
.iter()
.filter_map(|url| RelayUrl::parse(url).ok())
.collect(),
..Default::default()
}
}
}
/// The Grasp servers section shared by the publish dialogs.
pub fn grasp_servers_field(
state: &Entity<GraspServersState>,
relay_input: &Entity<InputState>,
cx: &App,
) -> AnyElement {
let state = state.clone();
let relay_input = relay_input.clone();
let servers = state.read(cx).grasp_servers.clone();
let loading_servers = state.read(cx).loading_servers;
let servers_enabled = state.read(cx).servers_enabled;
let error = state.read(cx).error.clone();
let add_state = state.clone();
let add_input = relay_input.clone();
let toggle_state = state.clone();
v_flex()
.gap_2()
.child(
h_flex()
.justify_between()
.items_center()
.child(div().typeset(TextRole::Caption, cx).child("Grasp servers"))
.child(
Button::new("toggle-grasp-servers")
.icon(Icon::named(if servers_enabled {
IconRole::ChevronRight
} else {
IconRole::ChevronDown
}))
.small()
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text(if servers_enabled {
"Hide grasp servers"
} else {
"Show grasp servers"
}))
.on_click(move |_, _, cx| {
toggle_state.update(cx, |state, cx| {
state.servers_enabled = !state.servers_enabled;
cx.notify();
});
}),
),
)
.when(servers_enabled, |section| {
section
.child(
div()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.child("Where the repository is hosted"),
)
.child(
v_flex().gap_1().children(
servers
.iter()
.enumerate()
.map(|(ix, relay)| render_server_row(ix, relay, state.clone(), cx)),
),
)
.child(
h_flex()
.gap_1()
.items_center()
.child(
div()
.flex_1()
.child(Input::new("grasp-relay-input", relay_input.clone())),
)
.child(
Button::new("add-relay")
.icon(Icon::named(IconRole::Plus))
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Add grasp server"))
.on_click(move |_, window, cx| {
add_relay(&add_state, &add_input, window, cx);
}),
),
)
.when(loading_servers, |section| {
section.child(
div()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.child("Loading your grasp servers..."),
)
})
.when_some(error, |section, error| {
section.child(
div()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().ramps.destructive.base)
.child(error),
)
})
})
.into_any_element()
}
fn render_server_row(
ix: usize,
relay: &RelayUrl,
state: Entity<GraspServersState>,
cx: &App,
) -> AnyElement {
h_flex()
.w_full()
.gap_1()
.items_center()
.child(
h_flex()
.flex_1()
.h_8()
.px_2()
.bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground)
.typeset(TextRole::Caption, cx)
.rounded(cx.theme().radius.control)
.child(server_host(relay)),
)
.child(
Button::new(SharedString::from(format!("remove-relay:{ix}")))
.icon(Icon::named(IconRole::Close))
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click(move |_, _, cx| {
state.update(cx, |state, cx| {
if ix < state.grasp_servers.len() {
state.grasp_servers.remove(ix);
cx.notify();
}
});
}),
)
.into_any_element()
}
/// Accepts a bare host as well as a full URL.
fn add_relay(
state: &Entity<GraspServersState>,
input: &Entity<InputState>,
window: &mut Window,
cx: &mut App,
) {
let value = input.read(cx).value().trim().to_owned();
if value.is_empty() {
return;
}
match normalize_server(&value) {
Some((_, relay)) => {
state.update(cx, |state, cx| {
state.error = None;
if !state.grasp_servers.contains(&relay) {
state.grasp_servers.push(relay);
}
cx.notify();
});
input.update(cx, |input, cx| input.set_value("", window, cx));
}
None => {
state.update(cx, |state, cx| {
state.error = Some(format!("Invalid grasp server URL: {value}").into());
cx.notify();
});
}
}
}
/// Loads the user's kind `10317` grasp list from the local database.
pub fn load_user_grasp_servers(
state: Entity<GraspServersState>,
window: &mut Window,
cx: &mut App,
) -> Task<()> {
let backend = Backend::global(cx);
let (user, client) = {
let backend = backend.read(cx);
(backend.current_user(), backend.client())
};
let Some(user) = user else {
state.update(cx, |state, _| state.loading_servers = false);
return Task::ready(());
};
let task =
cx.background_spawn(
async move { signed_state::user_grasp_list_servers(&client, user).await },
);
let handle = window.window_handle();
cx.spawn(async move |cx| {
let result = task.await;
if let Err(error) = cx.update_window(handle, |_, _window, cx| {
state.update(cx, |state, cx| {
state.loading_servers = false;
if let Ok(servers) = result
&& !servers.is_empty()
{
state.grasp_servers = servers;
}
cx.notify();
});
}) {
log::warn!("failed to apply grasp servers: {error}");
}
})
}
/// Normalize a user-typed grasp server, adding a `wss://` scheme when none is given.
pub fn normalize_server(input: &str) -> Option<(String, RelayUrl)> {
let text = if input.contains("://") {
input.to_owned()
} else {
format!("wss://{input}")
};
RelayUrl::parse(&text).ok().map(|relay| (text, relay))
}
/// The host of a relay URL, which is what the server lists show; the scheme is implied.
pub fn server_host(relay: &RelayUrl) -> SharedString {
relay
.domain()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(relay.to_string()))
}
+286
View File
@@ -0,0 +1,286 @@
use std::path::PathBuf;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, Task, WeakEntity, Window, div, px,
};
use settings::SettingsStore;
use signed_core::RepoAddr;
use signed_git::Repo;
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::select::{Select, SelectOption};
use ui::theme::{ActiveTheme as _, TextRole, Typeset 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};
pub struct InitRepoDialog {
handle: DialogHandle,
local_path: PathBuf,
name_input: Entity<InputState>,
desc_input: Entity<InputState>,
relay_input: Entity<InputState>,
state: Entity<DialogProgress>,
grasp_state: Entity<GraspServersState>,
branches: Vec<SharedString>,
selected_branch: Option<SharedString>,
view: WeakEntity<RepoDetailView>,
/// Held so the grasp-server load is cancelled when the dialog drops.
task: Option<Task<()>>,
}
impl InitRepoDialog {
pub fn new(
local_path: PathBuf,
view: WeakEntity<RepoDetailView>,
window: &mut Window,
cx: &mut App,
) -> Entity<Self> {
let default_name = local_path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
let grasp_settings = SettingsStore::global(cx)
.read(cx)
.settings()
.grasp_servers
.clone();
let state = cx.new(|_| DialogProgress::default());
let grasp_state = cx.new(|_| GraspServersState::new_default(&grasp_settings));
let name_input = InputState::builder()
.text(default_name)
.read_only()
.build(cx);
let desc_input = InputState::builder().multiline().build(cx);
let relay_input = InputState::new(cx);
let dialog = cx.new(|cx| {
cx.defer_in(window, move |this: &mut Self, window, cx| {
let task = load_user_grasp_servers(this.grasp_state.clone(), window, cx);
this.task = Some(task);
});
Self {
handle: DialogHandle::new(true),
local_path,
name_input,
desc_input,
relay_input,
state,
grasp_state,
branches: Vec::new(),
selected_branch: None,
view,
task: None,
}
});
load_branches(dialog.clone(), cx);
dialog
}
fn init_repository(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.state.read(cx).busy {
return;
}
let name = self.name_input.read(cx).value().trim().to_owned();
let description = self.desc_input.read(cx).value().trim().to_owned();
let servers = self.grasp_state.read(cx).grasp_servers.clone();
let default_branch = self
.selected_branch
.as_ref()
.map(|branch| branch.trim().to_owned())
.filter(|branch| !branch.is_empty());
if name.is_empty() {
self.fail("Repository name is required", cx);
return;
}
if servers.is_empty() {
self.fail("Add at least one grasp server", cx);
return;
}
let backend = Backend::global(cx);
let Some(user) = backend.read(cx).current_user() else {
self.fail("Sign in to publish a repository", cx);
return;
};
let addr = RepoAddr::new(user, RepoAddr::identifier_from_name(&name));
self.state.update(cx, |state, cx| {
state.begin_push(addr, cx);
cx.notify();
});
let local_path = self.local_path.clone();
let task = backend.update(cx, |backend, cx| {
backend.publish_local_repo(local_path, &name, &description, servers, default_branch, cx)
});
let state = self.state.clone();
let view = self.view.clone();
let close = self.handle.clone();
let handle = window.window_handle();
cx.spawn(async move |_this, cx| match task.await {
Ok(announcement) => {
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) => {
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();
});
}
}
impl Render for InitRepoDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let name_input = self.name_input.clone();
let desc_input = self.desc_input.clone();
let relay_input = self.relay_input.clone();
let state = self.state.clone();
let grasp_state = self.grasp_state.clone();
let action_state = state.clone();
let this = cx.entity().downgrade();
let folder = self.local_path.display().to_string();
let branches = self.branches.clone();
let selected_branch = self.selected_branch.clone();
Dialog::new("init-repo-dialog")
.handle(self.handle.clone())
.min_width(px(520.))
.title("Initialize repository")
.content(move |_, cx| {
let progress = state.read(cx);
v_flex()
.gap_3()
.child(
div()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child("Publish this local repository to Nostr."),
)
.child(
Field::new("init-name", "Repository name")
.description("Max 100 characters")
.child(Input::new("init-name-input", name_input.clone())),
)
.child(
Field::new("init-description", "Description").child(
Input::new("init-description-input", desc_input.clone()).rows(3),
),
)
.child(
Field::new("init-folder", "Folder")
.description("The local repository being published")
.child(
div()
.h_8()
.w_full()
.px_2()
.bg(cx.theme().colors.muted)
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.rounded(cx.theme().radius.control)
.child(folder.clone()),
),
)
.child(
Field::new("init-branch", "Default branch")
.description("The local branch to announce as the default")
.child(
Select::new("init-branch-select")
.options(
branches
.iter()
.cloned()
.map(|branch| SelectOption::new(branch.clone(), branch))
.collect::<Vec<_>>(),
)
.selected(selected_branch.clone())
.placeholder("Select branch"),
),
)
.child(grasp_servers_field(&grasp_state, &relay_input, cx))
.when_some(push_steps_row(&progress.push_steps, cx), |el, steps| {
el.child(steps)
})
.when_some(error_row(&progress.error, cx), |el, error| el.child(error))
.into_any_element()
})
.actions(move |_, cx| {
let busy = action_state.read(cx).busy;
let this = this.clone();
let init: AnyElement = Button::new("initialize-repository")
.label("Initialize")
.icon(Icon::named(IconRole::Plus))
.loading(busy)
.disabled(busy)
.on_click(move |_, window, cx| {
crate::shared::log_dropped(
this.update(cx, |this, cx| this.init_repository(window, cx)),
);
})
.into_any_element();
vec![init]
})
}
}
fn load_branches(dialog: Entity<InitRepoDialog>, cx: &mut App) {
let local_path = dialog.read(cx).local_path.clone();
cx.spawn(async move |cx| {
let loaded = cx
.background_spawn(async move {
let repo = Repo::open(&local_path)?;
let current: Option<SharedString> = repo.current_branch().map(Into::into);
Ok::<_, anyhow::Error>((repo.branches()?, current))
})
.await;
let Ok((branches, current)) = loaded else {
log::warn!("failed to list branches for the default branch selector");
return;
};
dialog.update(cx, |dialog, cx| {
dialog.branches = branches.into_iter().map(Into::into).collect();
dialog.selected_branch = current;
cx.notify();
});
})
.detach();
}
@@ -0,0 +1,5 @@
pub mod about;
pub mod create;
pub mod grasp_servers;
pub mod init;
pub mod reset;
@@ -0,0 +1,97 @@
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::dialog::{Dialog, DialogHandle};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
pub struct ResetRemoteDialog {
handle: DialogHandle,
store: Entity<RepoStore>,
deleted: Vec<String>,
}
impl ResetRemoteDialog {
pub fn new(store: Entity<RepoStore>, deleted: Vec<String>, cx: &mut App) -> Entity<Self> {
cx.new(|_| Self {
handle: DialogHandle::new(true),
store,
deleted,
})
}
}
impl Render for ResetRemoteDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let deleted = self.deleted.clone();
let store = self.store.clone();
let cancel_close = self.handle.clone();
let confirm_close = self.handle.clone();
Dialog::new("reset-remote-dialog")
.handle(self.handle.clone())
.min_width(px(480.))
.title("Reset remote to local")
.content(move |_, cx| {
v_flex()
.gap_2()
.child(
div()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(
"Grasp servers are overwritten to match the local mirror. Refs that do not exist locally are deleted from the servers. This cannot be undone.",
),
)
.child(if deleted.is_empty() {
div()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child("No server refs will be deleted.")
.into_any_element()
} else {
v_flex()
.gap_1()
.children(deleted.iter().map(|name| {
div()
.typeset(TextRole::Body, cx)
.font_family(cx.theme().mono_font)
.child(name.clone())
}))
.into_any_element()
})
.into_any_element()
})
.actions(move |_, _| {
let store = store.clone();
let cancel_close = cancel_close.clone();
let confirm_close = confirm_close.clone();
let cancel: AnyElement = Button::new("cancel-reset-remote")
.label("Cancel")
.variant(ButtonVariant::Secondary)
.on_click(move |_, _, cx| cancel_close.close(cx))
.into_any_element();
let confirm: AnyElement = Button::new("confirm-reset-remote")
.label("Reset remote")
.variant(ButtonVariant::Destructive)
.on_click(move |_, _, 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:#}");
}
})
.detach();
confirm_close.close(cx);
})
.into_any_element();
vec![cancel, confirm]
})
}
}
+709
View File
@@ -0,0 +1,709 @@
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Component, Path, PathBuf};
use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, EventEmitter, IntoElement,
ParentElement as _, SharedString, Styled as _, Task, WeakEntity, Window, div, px,
};
use signed_git::{FileCommit, Repo, WorktreeSnapshot};
use ui::code::CodeViewState;
use ui::common::{h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::markdown::MarkdownViewState;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tree::{Tree, TreeItem};
use super::helpers::{code_language, is_markdown_path, preview_spinner, source_hash};
use crate::shared::tree::{TreeItemSeed, TreeRow, collect_expanded, flatten};
use crate::shared::widgets::empty_state;
const MAX_PREVIEW_BYTES: usize = 1024 * 1024;
const MAX_PREVIEWED_FILES: usize = 32;
const MAX_PREVIEW_CACHE_BYTES: usize = 8 * 1024 * 1024;
/// The tree picked a folder or file, so the repository panel should show Files.
#[derive(Clone, Copy, Debug)]
pub enum RepoFilesEvent {
Activated,
}
enum FileContent {
Text(String),
Binary,
TooLarge,
Failed(String),
}
struct MarkdownView {
/// `None` means the repository README.
path: Option<SharedString>,
state: Entity<MarkdownViewState>,
/// Hash of the source, so the same document is not re-parsed on a refresh.
source_hash: u64,
}
struct CodeView {
/// Source path, relative to the worktree root.
path: SharedString,
state: Entity<CodeViewState>,
/// Hash of the source, so the same document is not re-parsed on a refresh.
source_hash: u64,
}
pub struct RepoFilesView {
seeds: Vec<TreeItemSeed>,
expanded: HashSet<String>,
rows: Vec<TreeRow>,
selected_index: Option<usize>,
worktree: Option<PathBuf>,
worktree_paths: Vec<String>,
md: Option<MarkdownView>,
code: Option<CodeView>,
readme_name: Option<SharedString>,
selected_file: Option<SharedString>,
files: HashMap<String, FileContent>,
file_order: VecDeque<String>,
preview_bytes: usize,
loading_files: HashSet<String>,
commits: HashMap<String, FileCommit>,
pending_commits: Vec<String>,
loading_commits: bool,
tasks: Vec<Task<Result<(), Error>>>,
}
impl EventEmitter<RepoFilesEvent> for RepoFilesView {}
impl RepoFilesView {
pub fn new(_cx: &mut Context<Self>) -> Self {
Self {
seeds: Vec::new(),
expanded: HashSet::new(),
rows: Vec::new(),
selected_index: None,
worktree: None,
worktree_paths: Vec::new(),
md: None,
code: None,
readme_name: None,
selected_file: None,
files: HashMap::new(),
file_order: VecDeque::new(),
preview_bytes: 0,
loading_files: HashSet::new(),
commits: HashMap::new(),
pending_commits: Vec::new(),
loading_commits: false,
tasks: Vec::new(),
}
}
pub fn set_worktree(&mut self, path: PathBuf) {
self.worktree = Some(path);
}
pub fn apply_entries(
&mut self,
tree: Vec<TreeItemSeed>,
paths: Vec<String>,
cx: &mut Context<Self>,
) {
self.worktree_paths = paths;
self.seeds = tree;
let folder_ids = collect_expanded(&self.seeds);
self.expanded.retain(|id| folder_ids.contains(id));
self.rebuild_rows();
cx.notify();
}
fn rebuild_rows(&mut self) {
self.rows = flatten(&self.seeds, &self.expanded);
self.selected_index = self
.selected_file
.as_ref()
.and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref()));
}
fn toggle_folder(&mut self, id: &str) {
if !self.expanded.remove(id) {
self.expanded.insert(id.to_owned());
}
self.rebuild_rows();
}
/// Point the README pane at `path`/`bytes`, or clear it when absent.
pub fn set_readme(
&mut self,
path: Option<PathBuf>,
bytes: Option<Vec<u8>>,
cx: &mut Context<Self>,
) -> bool {
let Some((path, bytes)) = path.zip(bytes) else {
let changed = self.readme_name.is_some() || self.md.is_some();
self.readme_name = None;
self.md = None;
return changed;
};
let name: SharedString = path.to_string_lossy().into();
let mut changed = self.readme_name.as_ref() != Some(&name);
self.readme_name = Some(name);
self.load_commit(&path.to_string_lossy(), cx);
if let Ok(text) = String::from_utf8(bytes) {
changed |= self.set_markdown(None, &text, cx);
}
changed
}
/// Drop every cached preview and the README, e.g. on a branch switch.
pub fn clear_previews(&mut self) {
self.selected_file = None;
self.selected_index = None;
self.files.clear();
self.file_order.clear();
self.preview_bytes = 0;
self.loading_files.clear();
self.commits.clear();
self.pending_commits.clear();
self.loading_commits = false;
self.md = None;
self.code = None;
self.readme_name = None;
}
/// Refresh after the mirror caught up with the remote.
pub fn catch_up(
&mut self,
snapshot: &WorktreeSnapshot,
tree: Vec<TreeItemSeed>,
paths: Vec<String>,
cx: &mut Context<Self>,
) -> bool {
let mut changed = false;
if paths != self.worktree_paths {
self.apply_entries(tree, paths, cx);
changed = true;
}
let present: HashSet<String> = snapshot
.entries
.iter()
.map(|path| path.to_string_lossy().into_owned())
.collect();
let mut previewed: Vec<String> = Vec::new();
previewed.extend(self.files.keys().cloned());
previewed.extend(self.selected_file.clone().map(|path| path.to_string()));
if let Some(path) = self.md.as_ref().and_then(|md| md.path.clone()) {
previewed.push(path.to_string());
}
if let Some(path) = self.code.as_ref().map(|code| code.path.clone()) {
previewed.push(path.to_string());
}
previewed.sort();
previewed.dedup();
for path in previewed {
if !present.contains(&path) {
self.drop_preview_of(&path);
changed = true;
}
}
if self.selected_file.is_none() {
changed |= self.set_readme(snapshot.readme_path.clone(), snapshot.readme.clone(), cx);
}
changed
}
fn pane_title(&self) -> SharedString {
self.selected_file
.clone()
.or_else(|| self.readme_name.clone())
.unwrap_or_else(|| "Overview".into())
}
fn activate_row(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
let Some(row) = self.rows.get(index) else {
return;
};
let id = row.id.clone();
let expandable = row.expandable;
self.selected_index = Some(index);
// Folder disclosure now toggles from the tree's row click handler.
if !expandable {
self.open_file(&id, window, cx);
}
cx.emit(RepoFilesEvent::Activated);
cx.notify();
}
pub fn render_tree(&self, view: WeakEntity<Self>) -> AnyElement {
let rows = self.rows.clone();
let selected = self.selected_index;
let change_view = view.clone();
let disclosure_view = view;
div()
.flex_1()
.min_h_0()
.w_full()
.child(
Tree::new("repo-tree")
.selected(selected)
.items(move |_, _| {
rows.iter()
.map(|row| {
let item = TreeItem::new(row.id.clone(), row.label.clone())
.depth(row.depth)
.expandable(row.expandable)
.expanded(row.expanded);
if row.expandable {
item.icon(Icon::named(IconRole::Folder))
} else {
item.icon(Icon::named(IconRole::File))
}
})
.collect()
})
.on_change({
let view = change_view;
move |index, window, cx| {
if let Some(index) = index
&& let Err(error) = view.update(cx, |this, cx| {
this.activate_row(index, window, cx);
})
{
log::warn!("failed to activate tree row: {error}");
}
}
})
.on_disclosure({
let view = disclosure_view;
move |index, _, cx| {
if let Err(error) = view.update(cx, |this, cx| {
let id = this.rows.get(index).map(|row| row.id.clone());
if let Some(id) = id {
this.toggle_folder(&id);
cx.emit(RepoFilesEvent::Activated);
cx.notify();
}
}) {
log::warn!("failed to toggle folder: {error}");
}
}
}),
)
.into_any_element()
}
pub fn render_content(&self, cx: &App) -> AnyElement {
let pane_title = self.pane_title();
let body: AnyElement = if let Some(path) = self.selected_file.clone() {
match self.files.get(path.as_ref()) {
Some(FileContent::Text(_)) => {
if is_markdown_path(path.as_ref()) {
self.markdown_element(Some(path.as_ref()))
} else {
self.code_element(path.as_ref())
}
}
Some(FileContent::Binary) => empty_state("Binary file - preview not supported"),
Some(FileContent::TooLarge) => empty_state("File is too large to preview"),
Some(FileContent::Failed(message)) => empty_state(message),
None => preview_spinner(),
}
} else if self.readme_name.is_some() {
self.markdown_element(None)
} else {
empty_state("No README found")
};
let commit = match &self.selected_file {
Some(path) => self.commits.get(path.as_ref()),
None => self
.readme_name
.as_ref()
.and_then(|name| self.commits.get(name.as_ref())),
};
v_flex()
.flex_1()
.min_w_0()
.h_full()
.child(
h_flex()
.px_3()
.h_9()
.gap_2()
.bg(cx.theme().colors.muted)
.border_b_1()
.border_color(cx.theme().colors.border)
.text_color(cx.theme().colors.muted_foreground)
.child(
div()
.typeset(TextRole::Caption2, cx)
.text_ellipsis()
.whitespace_nowrap()
.child(pane_title),
)
.when_some(commit, |this, commit| {
this.child(
h_flex()
.flex_1()
.gap_1()
.child(
div()
.typeset(TextRole::Caption, cx)
.font_family(cx.theme().mono_font)
.child(commit.id.clone()),
)
.child(
div()
.max_w(px(250.))
.typeset(TextRole::Caption, cx)
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
),
)
}),
)
.child(div().flex_1().min_h_0().child(body))
.into_any_element()
}
fn set_markdown(
&mut self,
path: Option<SharedString>,
text: &str,
cx: &mut Context<Self>,
) -> bool {
let hash = source_hash(text);
if let Some(md) = &self.md
&& md.path == path
&& md.source_hash == hash
{
return false;
}
if let Some(md) = self.md.take()
&& md.path == path
{
md.state.update(cx, |state, cx| {
state.set_source(text, cx);
});
self.md = Some(MarkdownView {
path,
state: md.state,
source_hash: hash,
});
return true;
}
let state = cx.new(|_| MarkdownViewState::new("repo-readme", text));
self.md = Some(MarkdownView {
path,
state,
source_hash: hash,
});
true
}
fn markdown_element(&self, path: Option<&str>) -> AnyElement {
let Some(md) = &self.md else {
return preview_spinner();
};
let ready = match path {
Some(path) => md.path.as_deref() == Some(path),
None => md.path.is_none(),
};
if !ready {
return preview_spinner();
}
div()
.p_4()
.size_full()
.overflow_hidden()
.child(md.state.clone())
.into_any_element()
}
fn set_code(&mut self, path: SharedString, text: &str, cx: &mut Context<Self>) {
let hash = source_hash(text);
let language = code_language(path.as_ref());
if let Some(code) = &self.code
&& code.path == path
&& code.source_hash == hash
{
return;
}
if let Some(code) = self.code.take()
&& code.path == path
{
code.state.update(cx, |state, cx| {
state.set_source(text, language, cx);
});
self.code = Some(CodeView {
path,
state: code.state,
source_hash: hash,
});
return;
}
let state = cx.new(|cx| CodeViewState::new("repo-code", text, language, cx));
self.code = Some(CodeView {
path,
state,
source_hash: hash,
});
}
fn code_element(&self, path: &str) -> AnyElement {
let Some(code) = &self.code else {
return preview_spinner();
};
if code.path.as_ref() != path {
return preview_spinner();
}
div()
.size_full()
.overflow_hidden()
.child(code.state.clone())
.into_any_element()
}
fn open_file(&mut self, path: &str, window: &mut Window, cx: &mut Context<Self>) {
self.selected_file = Some(path.into());
if self.files.contains_key(path) {
if let Some(FileContent::Text(text)) = self.files.get(path) {
let text = text.clone();
if is_markdown_path(path) {
if self.md.as_ref().map(|md| md.path.as_deref()) != Some(Some(path)) {
self.set_markdown(Some(path.into()), &text, cx);
}
} else if self.code.as_ref().map(|code| code.path.as_str()) != Some(path) {
self.set_code(path.into(), &text, cx);
}
}
cx.notify();
return;
}
if self.loading_files.contains(path) {
cx.notify();
return;
}
let rel = Path::new(path);
let unsafe_path = rel.is_absolute()
|| rel.components().any(|c| {
matches!(
c,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
});
let Some(worktree) = self.worktree.clone() else {
return;
};
if unsafe_path {
return;
}
self.loading_files.insert(path.to_string());
let path = path.to_string();
self.load_commit(&path, cx);
let task: Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
let path_for_read = path.clone();
let content = cx
.background_spawn(async move {
let full = worktree.join(&path_for_read);
let metadata = match std::fs::metadata(&full) {
Ok(metadata) => metadata,
Err(error) => return Err(anyhow::anyhow!("{}", error)),
};
if metadata.len() > MAX_PREVIEW_BYTES as u64 {
return Ok(FileContent::TooLarge);
}
let bytes = match std::fs::read(&full) {
Ok(bytes) => bytes,
Err(error) => return Err(anyhow::anyhow!("{}", error)),
};
match String::from_utf8(bytes) {
Ok(text) => Ok(FileContent::Text(text)),
Err(_) => Ok(FileContent::Binary),
}
})
.await;
this.update_in(cx, |this, _window, cx| {
this.loading_files.remove(&path);
match content {
Ok(kind) => {
if let FileContent::Text(text) = &kind {
if is_markdown_path(&path) {
let same = this.md.as_ref().map(|md| md.path.as_deref())
== Some(Some(path.as_str()));
if !same {
this.set_markdown(Some(path.clone().into()), text, cx);
}
} else {
let same = this.code.as_ref().map(|code| code.path.as_str())
== Some(path.as_str());
if !same {
this.set_code(path.clone().into(), text, cx);
}
}
this.preview_bytes += text.len();
}
this.files.insert(path.clone(), kind);
this.file_order.push_back(path);
this.evict_previews();
}
Err(error) => {
this.files
.insert(path, FileContent::Failed(error.to_string()));
}
}
cx.notify();
})?;
Ok(())
});
self.tasks.push(task);
}
fn drop_preview_of(&mut self, path: &str) {
if let Some(FileContent::Text(text)) = self.files.remove(path) {
self.preview_bytes -= text.len();
}
self.commits.remove(path);
if self.selected_file.as_deref() == Some(path) {
self.selected_file = None;
}
if self.md.as_ref().and_then(|md| md.path.as_deref()) == Some(path) {
self.md = None;
}
if self.code.as_ref().map(|code| code.path.as_ref()) == Some(path) {
self.code = None;
}
}
fn evict_previews(&mut self) {
while (self.files.len() > MAX_PREVIEWED_FILES
|| self.preview_bytes > MAX_PREVIEW_CACHE_BYTES)
&& self.file_order.len() > 1
{
let Some(path) = self.file_order.pop_front() else {
break;
};
if Some(path.as_str()) == self.selected_file.as_deref() {
self.file_order.push_back(path);
continue;
}
if let Some(FileContent::Text(text)) = self.files.remove(&path) {
self.preview_bytes -= text.len();
}
if self.md.as_ref().and_then(|md| md.path.as_deref()) == Some(path.as_str()) {
self.md = None;
}
if self
.code
.as_ref()
.is_some_and(|code| code.path.as_ref() == path.as_str())
{
self.code = None;
}
self.commits.remove(&path);
}
}
fn load_commit(&mut self, path: &str, cx: &mut Context<Self>) {
if self.commits.contains_key(path) || self.pending_commits.iter().any(|p| p == path) {
return;
}
self.pending_commits.push(path.to_string());
if !self.loading_commits {
self.load_commits(cx);
}
}
fn load_commits(&mut self, cx: &mut Context<Self>) {
if self.pending_commits.is_empty() || self.loading_commits {
return;
}
let Some(worktree) = self.worktree.clone() else {
self.pending_commits.clear();
return;
};
self.loading_commits = true;
let paths = std::mem::take(&mut self.pending_commits);
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let rels: Vec<PathBuf> = paths.iter().map(PathBuf::from).collect();
let result = cx
.background_spawn(async move {
Repo::open_cached(&worktree).and_then(|repo| repo.last_commits(&rels))
})
.await;
this.update(cx, |this, cx| {
this.loading_commits = false;
if let Ok(found) = result {
for (path, commit) in found {
this.commits
.insert(path.to_string_lossy().into_owned(), commit);
}
}
if !this.pending_commits.is_empty() {
this.load_commits(cx);
}
cx.notify();
})?;
Ok(())
});
self.tasks.push(task);
}
}
+454
View File
@@ -0,0 +1,454 @@
use std::collections::HashSet;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, Context, InteractiveElement as _, IntoElement, ParentElement as _, SharedString,
StatefulInteractiveElement as _, Styled as _, Window, div, px,
};
use signed_state::{Backend, Nip34Kind};
use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariant};
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable, h_flex, v_flex};
use ui::dropdown_menu::DropdownMenu;
use ui::icons::{Icon, IconRole};
use ui::menu::MenuItem;
use ui::popover::Popover;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tooltip::Tooltip;
use utils::relative_time_secs;
use super::helpers::{bound_repo_label, clone_group, fork_row, nostr_clone_url, repo_display_name};
use super::{RepoDetailView, actions, dialogs};
impl RepoDetailView {
pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(addr) = self
.announcement(cx)
.and_then(|announcement| announcement.upstream.as_ref())
.and_then(|upstream| upstream.addr.clone())
else {
return;
};
actions::open_repo_panel(&self.workspace, &addr, None, window, cx);
}
/// Open the dialog that publishes the local repository to NIP-34.
fn open_init_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(local_path) = self.store.read(cx).path.clone() else {
return;
};
self.init = Some(dialogs::init::InitRepoDialog::new(
local_path,
cx.entity().downgrade(),
window,
cx,
));
cx.notify();
}
pub(super) fn render_about(&mut self, cx: &mut Context<Self>) -> AnyElement {
if self.store.read(cx).addr().is_none() {
return self.render_init_banner(cx);
}
let backend = Backend::global(cx);
let store = self.store.read(cx);
let pushing = store.pushing;
let cloning = store.cloning;
let Some(announcement) = store.announcement.clone() else {
return div().into_any_element();
};
let nip05 = self
.directory
.read(cx)
.profile(&announcement.owner, cx)
.metadata()
.nip05
.clone()
.filter(|nip05| !nip05.trim().is_empty());
let nostr_url = nostr_clone_url(&announcement, nip05.as_deref());
let ngit_command = SharedString::from(format!("git clone {nostr_url}"));
let nak_command = SharedString::from(format!("nak git clone {nostr_url}"));
let git_commands: Vec<String> = announcement.clone_urls();
let name = repo_display_name(self.store.read(cx));
let description = announcement.description();
let avatar = Avatar::new(format!("{}:{}", announcement.owner, announcement.id));
let announcement_for_menu = announcement.clone();
let weak_menu_open = cx.entity().downgrade();
let weak_menu_items = cx.entity().downgrade();
let weak_clone = cx.entity().downgrade();
let weak_download = cx.entity().downgrade();
let ngit_for_popover = ngit_command.clone();
let nak_for_popover = nak_command.clone();
let git_for_popover = git_commands.clone();
h_flex()
.p_6()
.w_full()
.gap_6()
.items_start()
.justify_between()
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_2()
.child(
h_flex()
.gap_2()
.typeset(TextRole::Headline, cx)
.child(avatar)
.child(name),
)
.child(
div()
.min_w_0()
.typeset(TextRole::Callout, cx)
.text_color(cx.theme().colors.muted_foreground)
.line_clamp(3)
.child(description),
)
.when_some(fork_row(&announcement, cx), |this, row| this.child(row)),
)
.child(
h_flex()
.flex_none()
.gap_2()
.justify_end()
.child(
Popover::new("code-popover")
.open(self.clone_open)
.on_change(move |open, _, cx| {
if let Err(error) = weak_clone.update(cx, |this, cx| {
this.clone_open = open;
cx.notify();
}) {
log::warn!("failed to update clone popover: {error}");
}
})
.trigger(move |_, _| {
Button::new("code")
.label("Code")
.icon(Icon::named(IconRole::GitClone))
.tooltip(Tooltip::text("Clone repository"))
.loading(cloning)
.disabled(cloning)
.into_any_element()
})
.content(move |_, cx| {
v_flex()
.w(px(440.))
.p_3()
.gap_4()
.child(clone_group(
"Clone with ngit",
"copy-ngit",
&ngit_for_popover,
cx,
))
.child(clone_group(
"Clone with nak",
"copy-nak",
&nak_for_popover,
cx,
))
.child(
v_flex()
.gap_1()
.child(
div()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.child("Grasp Servers"),
)
.when(git_for_popover.is_empty(), |this| {
this.child(
div()
.typeset(TextRole::Caption, cx)
.child("No git clone urls."),
)
})
.children(git_for_popover.iter().enumerate().map(
|(ix, command)| {
ClipboardButton::new(
SharedString::from(format!(
"copy-git-{ix}"
)),
command.clone(),
)
},
)),
)
.child(
h_flex().justify_end().child(
Button::new("download")
.icon(Icon::named(IconRole::GitClone))
.label("Download")
.on_click({
let weak = weak_download.clone();
move |_, window, cx| {
if let Err(error) =
weak.update(cx, |this, cx| {
this.clone_to_folder(window, cx);
})
{
log::warn!("failed to clone: {error}");
}
}
}),
),
)
.into_any_element()
}),
)
.child(
DropdownMenu::new("repo-menu")
.icon(IconRole::EllipsisVertical)
.variant(ButtonVariant::Ghost)
.disabled(pushing)
.open(self.repo_menu_open)
.on_open_change(move |open, _, cx| {
if let Err(error) = weak_menu_open.update(cx, |this, cx| {
this.repo_menu_open = open;
cx.notify();
}) {
log::warn!("failed to update repo menu: {error}");
}
})
.items(move |_, cx| {
let owner = backend.read(cx).current_user()
== Some(announcement_for_menu.owner);
let mut items = vec![MenuItem::new("About").handler({
let weak = weak_menu_items.clone();
let announcement = announcement_for_menu.clone();
move |_, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.about = Some(dialogs::about::AboutDialog::new(
announcement.clone(),
this.directory.clone(),
cx,
));
cx.notify();
}) {
log::warn!("failed to open about: {error}");
}
}
})];
if owner {
items.push(MenuItem::new("Republish").handler({
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.push_repository(window, cx);
}) {
log::warn!("failed to republish: {error}");
}
}
}));
items.push(MenuItem::new("Reset remote to local").handler({
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.reset_remote(window, cx);
}) {
log::warn!("failed to reset remote: {error}");
}
}
}));
items.push(MenuItem::separator());
items.push(MenuItem::new("Delete").destructive(true).handler(
{
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.delete_repository(window, cx);
}) {
log::warn!("failed to delete: {error}");
}
}
},
));
}
items
}),
),
)
.into_any_element()
}
fn render_init_banner(&self, cx: &mut Context<Self>) -> AnyElement {
let binding = self
.store
.read(cx)
.nip34
.as_ref()
.filter(|binding| binding.kind == Nip34Kind::Initialized);
let path = self
.store
.read(cx)
.path
.as_ref()
.map(|path| path.display().to_string())
.unwrap_or_default();
v_flex()
.flex_none()
.p_6()
.h_32()
.w_full()
.items_center()
.justify_center()
.gap_2()
.map(|this| match binding {
Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)),
None => this.child(
Button::new("init")
.icon(Icon::named(IconRole::ArrowUp))
.label("Initialize on Nostr")
.tooltip(Tooltip::text("Publish this repository to Nostr"))
.on_click(cx.listener(|this, _, window, cx| {
this.open_init_dialog(window, cx);
})),
),
})
.child(
div()
.min_w_0()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(path),
)
.into_any_element()
}
pub(super) fn render_metadata(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.px_6()
.h_12()
.w_full()
.gap_4()
.items_center()
.justify_between()
.child(self.render_maintainers(cx))
.child(self.render_ref_controls(cx))
.into_any_element()
}
fn render_ref_controls(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.justify_end()
.flex_none()
.gap_2()
.when_some(self.render_last_commit(cx), |this, commit| {
this.child(commit)
})
.child(self.refs.branch_select.clone())
.child(self.refs.tag_select.clone())
.into_any_element()
}
fn render_last_commit(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
let commit = self.head_commit.as_ref()?;
let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned();
let history = self.history.clone();
let commit_id = commit.id.clone();
Some(
h_flex()
.id("last-commit")
.h_8()
.px_2()
.gap_2()
.min_w_0()
.rounded(cx.theme().radius.control)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.tooltip(Tooltip::text("View latest commit"))
.on_click(move |_, window, cx| {
history.update(cx, |history, cx| {
history.open_commit_diff(&commit_id, window, cx);
});
})
.child(Icon::named(IconRole::GitCommit).color(cx.theme().colors.muted_foreground))
.child(
div()
.font_family(cx.theme().mono_font)
.typeset(TextRole::Callout, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(short)),
)
.child(
div()
.max_w(px(220.))
.typeset(TextRole::Callout, cx)
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
)
.child(
div()
.typeset(TextRole::Callout, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(relative_time_secs(commit.time)),
)
.into_any_element(),
)
}
fn render_maintainers(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(announcement) = self.announcement(cx) else {
return div().into_any_element();
};
let mut seen = HashSet::new();
let rest: Vec<_> = announcement
.maintainers
.iter()
.copied()
.filter(|key| key != &announcement.owner && seen.insert(*key))
.collect();
let owner = self.directory.read(cx).profile(&announcement.owner, cx);
let owner_name = owner.name();
h_flex()
.min_w_0()
.gap_2()
.child(
h_flex()
.gap_2()
.child(
Avatar::new(announcement.owner)
.name(owner_name.clone())
.picture(owner.picture())
.small(),
)
.child(
div()
.typeset(TextRole::Caption, cx)
.whitespace_nowrap()
.child(owner_name),
),
)
.when(!rest.is_empty(), |this| {
this.child(
div()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(format!("+{}", rest.len()))),
)
})
.into_any_element()
}
}
+447
View File
@@ -0,0 +1,447 @@
use std::path::{Path, PathBuf};
use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, px,
};
use metadata::ProfileDirectory;
use nostr::prelude::{RelayUrl, ToBech32};
use signed_core::Announcement;
use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo};
use signed_state::{Nip34Binding, RepoListStore, RepoStore};
use ui::avatar::Avatar;
use ui::clipboard::ClipboardButton;
use ui::combobox::ComboboxState;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time_secs;
use super::RepoDetailView;
use crate::shared::tree::{TreeItemSeed, build_tree_items};
const GUTTER_WIDTH: f32 = 44.;
pub const DIFF_ROW_HEIGHT: f32 = 20.;
pub const COMMIT_ROW_HEIGHT: f32 = 56.;
#[derive(Clone, Copy)]
pub(super) enum DiffRow {
Hunk {
old_start: u32,
old_lines: u32,
new_start: u32,
new_lines: u32,
},
Line {
hunk: usize,
line: usize,
},
}
pub(super) struct RepoData {
pub(super) tree: Vec<TreeItemSeed>,
pub(super) entries: Vec<PathBuf>,
pub(super) readme_path: Option<PathBuf>,
pub(super) readme: Option<Vec<u8>>,
pub(super) worktree: Option<PathBuf>,
pub(super) branches: Vec<String>,
pub(super) tags: Vec<String>,
pub(super) current_branch: Option<String>,
pub(super) head_commit: Option<FileCommit>,
}
pub(super) fn clone_group(
label: &str,
id: &'static str,
command: &SharedString,
cx: &App,
) -> AnyElement {
v_flex()
.gap_1()
.child(
div()
.typeset(TextRole::Caption, cx)
.child(SharedString::from(label)),
)
.child(ClipboardButton::new(id, command.clone()))
.into_any_element()
}
pub(super) fn nostr_clone_url(announcement: &Announcement, nip05: Option<&str>) -> SharedString {
let owner = announcement.owner;
let user = nip05
.map(str::to_owned)
.unwrap_or_else(|| owner.to_bech32().unwrap_or_else(|_| owner.to_string()));
let mut url = format!("nostr://{user}");
if let Some(hint) = announcement.relays.first().and_then(RelayUrl::domain) {
url.push('/');
url.push_str(hint);
}
url.push('/');
url.push_str(&announcement.id);
SharedString::from(url)
}
pub(super) fn fork_row(
announcement: &Announcement,
cx: &mut Context<RepoDetailView>,
) -> Option<AnyElement> {
let upstream = announcement.upstream.as_ref()?;
let (label, clickable) = match &upstream.addr {
Some(addr) => {
let name = RepoListStore::global(cx)
.read(cx)
.announcements
.iter()
.find(|a| a.addr() == *addr)
.map(|a| {
a.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(a.id.clone()))
})
.unwrap_or_else(|| SharedString::from(addr.identifier().to_owned()));
(SharedString::from(format!("Forked from {name}")), true)
}
None => (SharedString::from(upstream.display().as_str()), false),
};
let row = h_flex()
.gap_1()
.min_w_0()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(Icon::named(IconRole::GitBranch).small())
.child(div().whitespace_nowrap().text_ellipsis().child(label));
Some(if clickable {
row.id("fork-upstream")
.cursor_pointer()
.on_click(cx.listener(|this, _, window, cx| this.open_upstream(window, cx)))
.into_any_element()
} else {
row.into_any_element()
})
}
pub(super) fn load_repo_data(repo: &Repo) -> Result<RepoData, Error> {
let snapshot = repo.snapshot()?;
let worktree = repo.workdir().map(Path::to_path_buf);
let tree = build_tree_items(&snapshot.entries);
Ok(RepoData {
tree,
entries: snapshot.entries,
readme_path: snapshot.readme_path,
readme: snapshot.readme,
worktree,
branches: snapshot.branches,
tags: snapshot.tags,
current_branch: snapshot.current_branch,
head_commit: snapshot.head_commit,
})
}
/// The announcement's name or ID for announced repositories, the directory name for local ones.
pub fn repo_display_name(store: &RepoStore) -> SharedString {
if store.addr().is_none() {
return store
.path
.as_ref()
.map(|path| {
SharedString::from(
path.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string()),
)
})
.unwrap_or_default();
}
store
.announcement
.as_ref()
.map(|announcement| {
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()))
})
.unwrap_or_default()
}
/// The owner and identifier a local repository is already bound to.
pub(super) fn bound_repo_label(
binding: &Nip34Binding,
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> AnyElement {
let profile = binding.owner.map(|pk| directory.read(cx).profile(&pk, cx));
h_flex()
.flex_shrink_0()
.gap_2()
.typeset(TextRole::Body, cx)
.child("Initialized by")
.text_color(cx.theme().colors.muted_foreground)
.when_some(profile, |this, profile| {
let name = profile.name();
this.child(
h_flex()
.gap_1()
.text_color(cx.theme().colors.foreground)
.child(
Avatar::new(profile.public_key())
.name(name.clone())
.picture(profile.picture())
.small(),
)
.child(name),
)
})
.when_some(binding.identifier.as_deref(), |this, ident| {
this.child(
div()
.typeset(TextRole::Caption2, cx)
.child(SharedString::from(format!("/{ident}"))),
)
})
.into_any_element()
}
/// Computes a source hash from the given text.
pub(super) fn source_hash(text: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
text.hash(&mut hasher);
hasher.finish()
}
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()
}
/// The kit grammar for a path; only four languages are supported.
pub(super) fn code_language(path: &str) -> ui::highlight::Language {
use ui::highlight::Language;
match Path::new(path)
.extension()
.and_then(|ext| ext.to_str())
.map(|ext| ext.to_ascii_lowercase())
.as_deref()
{
Some("rs") => Language::Rust,
Some("ts" | "mts" | "cts" | "tsx") => Language::TypeScript,
Some("js" | "mjs" | "cjs" | "jsx") => Language::JavaScript,
Some("py") => Language::Python,
_ => Language::Plain,
}
}
/// Whether a file path has a markdown extension.
pub(super) fn is_markdown_path(path: &str) -> bool {
Path::new(path)
.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| {
matches!(
ext.to_ascii_lowercase().as_str(),
"md" | "markdown" | "mdown" | "mkdn"
)
})
}
pub(super) fn diff_rows(file: &FileDiff) -> Vec<DiffRow> {
let mut rows = Vec::new();
for (hunk_ix, hunk) in file.hunks.iter().enumerate() {
rows.push(DiffRow::Hunk {
old_start: hunk.old_start,
old_lines: hunk.old_lines,
new_start: hunk.new_start,
new_lines: hunk.new_lines,
});
rows.extend((0..hunk.lines.len()).map(|line| DiffRow::Line {
hunk: hunk_ix,
line,
}));
}
rows
}
pub(super) fn render_diff_row(hunks: &[DiffHunk], row: DiffRow, cx: &App) -> AnyElement {
match row {
DiffRow::Hunk {
old_start,
old_lines,
new_start,
new_lines,
} => div()
.px_2()
.w_full()
.h(px(DIFF_ROW_HEIGHT))
.font_family(cx.theme().mono_font)
.typeset(TextRole::Caption, cx)
.bg(cx.theme().colors.muted)
.border_y_1()
.border_color(cx.theme().colors.border)
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(format!(
"@@ -{},{} +{},{} @@",
old_start, old_lines, new_start, new_lines
)))
.into_any_element(),
DiffRow::Line { hunk, line } => render_diff_line(&hunks[hunk].lines[line], cx),
}
}
fn render_diff_line(line: &DiffLine, cx: &App) -> AnyElement {
let bg = match line.kind {
DiffLineKind::Addition => Some(cx.theme().ramps.success.base.opacity(0.2)),
DiffLineKind::Deletion => Some(cx.theme().ramps.destructive.base.opacity(0.2)),
DiffLineKind::Context => None,
};
let gutter = cx.theme().colors.muted_foreground;
h_flex()
.w_full()
.h(px(DIFF_ROW_HEIGHT))
.font_family(cx.theme().mono_font)
.typeset(TextRole::Caption, cx)
.when_some(bg, |this, bg| this.bg(bg))
.child(
div()
.w(px(GUTTER_WIDTH))
.flex_none()
.pr_2()
.text_right()
.text_color(gutter)
.child(line.old.map(|n| n.to_string()).unwrap_or_default()),
)
.child(
div()
.w(px(GUTTER_WIDTH))
.flex_none()
.pr_2()
.text_right()
.text_color(gutter)
.child(line.new.map(|n| n.to_string()).unwrap_or_default()),
)
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_color(cx.theme().colors.foreground)
.child(line.text.clone()),
)
.into_any_element()
}
pub(crate) fn commit_row(
ix: usize,
commit: &FileCommit,
action: Option<AnyElement>,
on_click: impl Fn(&mut Window, &mut gpui::App) + 'static,
cx: &gpui::App,
) -> gpui::AnyElement {
h_flex()
.id(ix)
.px_4()
.h(px(COMMIT_ROW_HEIGHT))
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.justify_center()
.child(
h_flex()
.gap_2()
.overflow_hidden()
.child(
div()
.font_family(cx.theme().mono_font)
.typeset(TextRole::Callout, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(commit.id.clone()),
)
.child(
div()
.flex_1()
.min_w_0()
.typeset(TextRole::Callout, cx)
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
),
)
.child(
h_flex()
.gap_2()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(commit.author.clone())
.child(relative_time_secs(commit.time)),
),
)
.when_some(action, |row, action| row.child(action))
.on_click(move |_, window, cx| on_click(window, cx))
.into_any_element()
}
pub(super) fn sync_selector(
select: &Entity<ComboboxState<SharedString>>,
cached: &mut Vec<SharedString>,
items: Vec<SharedString>,
selected: Option<SharedString>,
window: &mut Window,
cx: &mut App,
) -> bool {
let items_changed = *cached != items;
let selection_changed = selected
.as_ref()
.is_some_and(|value| select.read(cx).selected() != Some(value));
if !items_changed && !selection_changed {
return false;
}
select.update(cx, |state, cx| {
if items_changed {
state.set_options(
items
.iter()
.map(|item| (item.clone(), item.clone()))
.collect(),
cx,
);
}
if let Some(value) = selected
&& (items_changed || selection_changed)
{
state.set_selected(Some(value), window, cx);
}
});
*cached = items;
true
}
+271
View File
@@ -0,0 +1,271 @@
use std::path::{Path, PathBuf};
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,
};
use signed_git::{CommitList, Repo};
use signed_state::{Backend, RepoStore, SyncStatusDirectory};
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 _, TextRole, Typeset as _};
use ui::tooltip::Tooltip;
use super::RepoDetailView;
use super::commit_diff::CommitDiffView;
use super::helpers::commit_row;
use crate::shared::panels;
use crate::workspace::Workspace;
pub struct RepoHistoryView {
store: Entity<RepoStore>,
workspace: WeakEntity<Workspace>,
detail: WeakEntity<RepoDetailView>,
sync_directory: Entity<SyncStatusDirectory>,
worktree: Option<PathBuf>,
all_commits: Option<CommitList>,
loading_all_commits: bool,
scroll_handle: UniformListScrollHandle,
tasks: Vec<Task<Result<(), Error>>>,
}
impl RepoHistoryView {
pub fn new(
store: Entity<RepoStore>,
workspace: WeakEntity<Workspace>,
detail: WeakEntity<RepoDetailView>,
sync_directory: Entity<SyncStatusDirectory>,
) -> Self {
Self {
store,
workspace,
detail,
sync_directory,
worktree: None,
all_commits: None,
loading_all_commits: false,
scroll_handle: UniformListScrollHandle::new(),
tasks: Vec::new(),
}
}
pub fn set_worktree(&mut self, path: Option<PathBuf>) {
self.worktree = path;
}
pub fn worktree(&self) -> Option<&Path> {
self.worktree.as_deref()
}
/// Number of commits reachable from HEAD, for the Commits tab label.
pub fn commit_count(&self) -> Option<usize> {
self.all_commits.as_ref().map(|list| list.total)
}
/// Drop the current list and walk HEAD again.
pub fn reload(&mut self, cx: &mut Context<Self>) {
self.all_commits = None;
self.loading_all_commits = false;
self.load(cx);
}
fn load(&mut self, cx: &mut Context<Self>) {
if self.loading_all_commits || self.all_commits.is_some() {
return;
}
let Some(worktree) = self.worktree.clone() else {
return;
};
self.loading_all_commits = true;
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn(async move {
Repo::open_cached(&worktree).and_then(|repo| repo.all_commits())
})
.await;
this.update(cx, |this, cx| {
if let Ok(list) = result {
this.all_commits = Some(list);
}
this.loading_all_commits = false;
cx.notify();
})?;
Ok(())
});
self.tasks.push(task);
}
pub fn open_commit_diff(
&mut self,
commit_id: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(worktree) = self.worktree.clone() else {
return;
};
let store = self.store.clone();
let commit_id = commit_id.to_owned();
let id = match store.read(cx).addr() {
Some(addr) => SharedString::from(format!("commit:{addr}:{commit_id}")),
None => SharedString::from(format!("commit:{}:{}", worktree.display(), commit_id)),
};
let workspace = self.workspace.clone();
panels::open_detail(
&workspace,
id,
move |window, cx| {
cx.new(|cx| CommitDiffView::new(worktree.clone(), commit_id.clone(), window, cx))
},
window,
cx,
);
}
}
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 {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new("commits-loading"))
.into_any_element()
} else {
crate::shared::widgets::empty_state("Failed to load commits")
};
};
if list.commits.is_empty() {
return crate::shared::widgets::empty_state("No commits found");
}
let commits = list.commits.clone();
let shown = commits.len();
let total = list.total;
let view = cx.entity().downgrade();
let detail = self.detail.clone();
let user = Backend::global(cx).read(cx).current_user();
let author = user.is_some_and(|user| self.store.read(cx).is_author(&user));
let checkout = self.worktree.clone();
let ahead = self
.store
.read(cx)
.addr()
.cloned()
.filter(|_| author)
.map(|addr| {
self.sync_directory.read_with(cx, |directory, cx| {
directory.ahead_commits_of(&addr, checkout.as_deref(), cx)
})
})
.unwrap_or_default();
let pushing = self.store.read(cx).pushing;
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(),
)
.when(shown < total, |this| {
this.child(
div()
.py_2()
.w_full()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.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()
}
}
File diff suppressed because it is too large Load Diff
+101
View File
@@ -0,0 +1,101 @@
use gpui::{App, AppContext as _, Entity, SharedString, WeakEntity, Window};
use ui::combobox::{Combobox, ComboboxState};
use super::RepoDetailView;
use super::helpers::sync_selector;
pub(super) struct RefSwitcher {
pub(super) branch_select: Entity<ComboboxState<SharedString>>,
pub(super) tag_select: Entity<ComboboxState<SharedString>>,
ref_branches: Vec<SharedString>,
ref_tags: Vec<SharedString>,
pub(super) switching_ref: bool,
}
impl RefSwitcher {
pub(super) fn new(view: WeakEntity<RepoDetailView>, window: &mut Window, cx: &mut App) -> Self {
let branch_view = view.clone();
let branch_select = cx.new(|cx| {
ComboboxState::new(
Combobox::new("branch-select", "Branch", Vec::new())
.placeholder("Branch")
.on_change(move |value, window, cx| {
if let Some(name) = value
&& let Err(error) = branch_view.update(cx, |this, cx| {
this.switch_ref(super::RefKind::Branch, name, window, cx);
})
{
log::warn!("failed to switch branch: {error}");
}
}),
window,
cx,
)
});
let tag_view = view;
let tag_select = cx.new(|cx| {
ComboboxState::new(
Combobox::new("tag-select", "Tag", Vec::new())
.placeholder("Tag")
.on_change(move |value, window, cx| {
if let Some(name) = value
&& let Err(error) = tag_view.update(cx, |this, cx| {
this.switch_ref(super::RefKind::Tag, name, window, cx);
})
{
log::warn!("failed to switch tag: {error}");
}
}),
window,
cx,
)
});
Self {
branch_select,
tag_select,
ref_branches: Vec::new(),
ref_tags: Vec::new(),
switching_ref: false,
}
}
pub(super) fn set_branches(
&mut self,
branches: Vec<SharedString>,
selected: Option<SharedString>,
window: &mut Window,
cx: &mut App,
) -> bool {
sync_selector(
&self.branch_select,
&mut self.ref_branches,
branches,
selected,
window,
cx,
)
}
pub(super) fn set_tags(
&mut self,
tags: Vec<SharedString>,
window: &mut Window,
cx: &mut App,
) -> bool {
sync_selector(&self.tag_select, &mut self.ref_tags, tags, None, window, cx)
}
pub(super) fn restore_selection(
&self,
select: &Entity<ComboboxState<SharedString>>,
previous: &Option<SharedString>,
window: &mut Window,
cx: &mut App,
) {
select.update(cx, |state, cx| {
state.set_selected(previous.clone(), window, cx)
});
}
}
+349
View File
@@ -0,0 +1,349 @@
use std::path::PathBuf;
use gpui::{
AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, PathPromptOptions,
SharedString, Styled as _, Window, div, px,
};
use settings::{AppearanceMode, EventFetchingStrategy, SettingsStore};
use ui::button::Button;
use ui::common::{h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::select::{Select, SelectOption};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tooltip::Tooltip;
use crate::repo::dialogs::grasp_servers::{normalize_server, server_host};
/// A settings row with the label and description on the left and the control on the right.
pub fn setting_row(
cx: &App,
title: impl Into<SharedString>,
description: impl Into<SharedString>,
control: impl IntoElement,
) -> AnyElement {
h_flex()
.w_full()
.justify_between()
.gap_4()
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(div().typeset(TextRole::Headline, cx).child(title.into()))
.child(
div()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(description.into()),
),
)
.child(div().w(px(200.)).flex_shrink_0().child(control))
.into_any_element()
}
/// A full-width settings block with title and subtitle in one header.
pub fn setting_block(
cx: &App,
title: impl Into<SharedString>,
description: impl Into<SharedString>,
control: impl IntoElement,
) -> AnyElement {
v_flex()
.w_full()
.gap_3()
.child(
v_flex()
.gap_1()
.child(div().typeset(TextRole::Headline, cx).child(title.into()))
.child(
div()
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(description.into()),
),
)
.child(control)
.into_any_element()
}
pub fn appearance_select(cx: &App) -> Select<AppearanceMode> {
let current = SettingsStore::global(cx).read(cx).settings().appearance;
Select::new("settings-appearance")
.options(vec![
SelectOption::new(AppearanceMode::System, "System"),
SelectOption::new(AppearanceMode::Light, "Light"),
SelectOption::new(AppearanceMode::Dark, "Dark"),
])
.selected(Some(current))
.on_change(|value, _, cx| {
let Some(mode) = value else {
return;
};
SettingsStore::global(cx).update(cx, |store, cx| {
store.edit(|settings| settings.appearance = mode, cx);
});
crate::apply_appearance_mode(mode, cx);
})
}
pub fn event_fetching_select(cx: &App) -> Select<EventFetchingStrategy> {
let current = SettingsStore::global(cx).read(cx).settings().event_fetching;
Select::new("settings-event-fetching")
.options(vec![
SelectOption::new(EventFetchingStrategy::Curated, "Curated"),
SelectOption::new(EventFetchingStrategy::Uncensored, "Uncensored"),
])
.selected(Some(current))
.on_change(|value, _, cx| {
let Some(strategy) = value else {
return;
};
SettingsStore::global(cx).update(cx, |store, cx| {
store.edit(|settings| settings.event_fetching = strategy, cx);
});
})
}
pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement {
let store = SettingsStore::global(cx);
let servers = store
.read(cx)
.settings()
.grasp_servers
.default_servers
.clone();
v_flex()
.gap_2()
.children(servers.iter().enumerate().map(|(ix, server)| {
h_flex()
.gap_1()
.child(
h_flex()
.flex_1()
.h_8()
.px_2()
.bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground)
.typeset(TextRole::Caption, cx)
.rounded(cx.theme().radius.control)
.child(display_server(server)),
)
.child(
Button::new(format!("settings-remove-server:{ix}"))
.icon(Icon::named(IconRole::Close))
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click({
let store = store.clone();
move |_, _, cx| {
store.update(cx, |store, cx| {
store.edit(
|settings| {
settings.grasp_servers.default_servers.remove(ix);
},
cx,
);
});
}
}),
)
.into_any_element()
}))
.child(
h_flex()
.gap_1()
.child(
div()
.flex_1()
.child(Input::new("settings-grasp-input", input.clone())),
)
.child(
Button::new("settings-add-server")
.icon(Icon::named(IconRole::Plus))
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Add grasp server"))
.on_click({
let input = input.clone();
move |_, window, cx| {
add_server(&input, window, cx);
}
}),
),
)
.into_any_element()
}
fn display_server(server: &str) -> SharedString {
match normalize_server(server) {
Some((_, relay)) => server_host(&relay),
None => SharedString::from(server.to_owned()),
}
}
fn add_server(input: &Entity<InputState>, window: &mut Window, cx: &mut App) {
let settings = SettingsStore::global(cx);
let value = input.read(cx).value().trim().to_owned();
if value.is_empty() {
return;
}
let Some((normalized, _)) = normalize_server(&value) else {
return;
};
settings.update(cx, |store, cx| {
store.edit(
|settings| {
if !settings.grasp_servers.default_servers.contains(&normalized) {
settings
.grasp_servers
.default_servers
.push(normalized.clone());
}
},
cx,
);
});
input.update(cx, |input, cx| input.set_value("", window, cx));
}
pub fn scan_paths_editor(cx: &App) -> AnyElement {
let store = SettingsStore::global(cx);
let scan_paths = store.read(cx).settings().local_repos.scan_paths.clone();
v_flex()
.gap_2()
.children(scan_paths.iter().enumerate().map(|(ix, path)| {
h_flex()
.gap_1()
.child(
h_flex()
.flex_1()
.h_8()
.px_2()
.bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground)
.typeset(TextRole::Caption, cx)
.rounded(cx.theme().radius.control)
.child(path.display().to_string()),
)
.child(
Button::new(format!("settings-remove-path:{ix}"))
.icon(Icon::named(IconRole::Close))
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click(move |_, _, cx| {
let store = SettingsStore::global(cx);
store.update(cx, |store, cx| {
store.edit(
|settings| {
settings.local_repos.scan_paths.remove(ix);
},
cx,
);
});
}),
)
.into_any_element()
}))
.child(
h_flex().justify_end().child(
Button::new("settings-add-path")
.icon(Icon::named(IconRole::Plus))
.label("Add directory")
.on_click(|_, _, cx| add_scan_path(cx)),
),
)
.into_any_element()
}
fn add_scan_path(cx: &mut App) {
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: true,
prompt: Some("Choose directories".into()),
});
cx.spawn(async move |cx| {
if let Ok(Ok(Some(paths))) = prompt.await {
cx.update(|cx| {
let store = SettingsStore::global(cx);
store.update(cx, |store, cx| {
store.edit(
|settings| {
for path in paths {
let path = path.to_string_lossy().to_string();
if !settings
.local_repos
.scan_paths
.iter()
.any(|existing| existing.to_string_lossy() == path)
{
settings.local_repos.scan_paths.push(PathBuf::from(path));
}
}
},
cx,
);
});
});
}
})
.detach();
}
pub fn default_folder_selector(default_folder: &Entity<InputState>) -> AnyElement {
let folder = default_folder.clone();
h_flex()
.gap_1()
.child(
div()
.flex_1()
.child(Input::new("settings-default-folder", folder.clone())),
)
.child(
Button::new("settings-choose-folder")
.icon(Icon::named(IconRole::Folder))
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Choose folder"))
.on_click(move |_, window, cx| {
choose_default_folder(&folder, window, cx);
}),
)
.into_any_element()
}
fn choose_default_folder(default_folder: &Entity<InputState>, window: &mut Window, cx: &mut App) {
let handle = window.window_handle();
let default_folder = default_folder.clone();
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Choose default folder".into()),
});
cx.spawn(async move |cx| {
if let Ok(Ok(Some(mut paths))) = prompt.await
&& let Some(path) = paths.pop()
{
let text = path.to_string_lossy().to_string();
if let Err(error) = cx.update_window(handle, |_, window, cx| {
let store = SettingsStore::global(cx);
store.update(cx, |store, cx| {
store.edit(
|settings| settings.create_repository.default_folder = Some(path.clone()),
cx,
);
});
default_folder.update(cx, |input, cx| input.set_value(text, window, cx));
}) {
log::warn!("failed to apply default folder: {error}");
}
}
})
.detach();
}
+104
View File
@@ -0,0 +1,104 @@
mod helpers;
use gpui::{
App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
Window, px,
};
use helpers::{
appearance_select, default_folder_selector, event_fetching_select, grasp_servers_editor,
scan_paths_editor, setting_block, setting_row,
};
use settings::SettingsStore;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::input::InputState;
use ui::separator::Separator;
pub struct SettingsDialog {
handle: DialogHandle,
grasp_input: Entity<InputState>,
default_folder: Entity<InputState>,
}
impl SettingsDialog {
pub fn new(cx: &mut App) -> Entity<Self> {
let store = SettingsStore::global(cx);
let settings = store.read(cx).settings().clone();
let grasp_input = InputState::new(cx);
let folder = settings
.create_repository
.default_folder
.clone()
.unwrap_or_else(paths::desktop_dir);
let default_folder = InputState::builder()
.text(folder.to_string_lossy())
.read_only()
.build(cx);
cx.new(|_| Self {
handle: DialogHandle::new(true),
grasp_input,
default_folder,
})
}
}
impl Render for SettingsDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
const APPEARANCE_DESC: &str =
"Choose whether the app follows the system theme or uses a light/dark theme.";
const FETCH_DESC: &str = "Curated fetches events from relays in the repository's announcement. Uncensored also fetches from every maintainer's relays.";
const GRASP_DESC: &str =
"Servers used to host your git repositories via the Grasp protocol";
const SCAN_DESC: &str = "Directories scanned for local git repositories.";
const FOLDER_DESC: &str = "The folder for newly created repositories.";
let grasp_input = self.grasp_input.clone();
let default_folder = self.default_folder.clone();
Dialog::new("settings-dialog")
.handle(self.handle.clone())
.height(px(560.))
.title("Settings")
.content(move |_, cx| {
v_flex()
.gap_4()
.child(setting_row(
cx,
"Appearance",
APPEARANCE_DESC,
appearance_select(cx),
))
.child(Separator::horizontal())
.child(setting_row(
cx,
"Event Fetching Strategy",
FETCH_DESC,
event_fetching_select(cx),
))
.child(Separator::horizontal())
.child(setting_block(
cx,
"Grasp Servers",
GRASP_DESC,
grasp_servers_editor(&grasp_input, cx),
))
.child(Separator::horizontal())
.child(setting_block(
cx,
"Scan Directories",
SCAN_DESC,
scan_paths_editor(cx),
))
.child(setting_block(
cx,
"Default Folder",
FOLDER_DESC,
default_folder_selector(&default_folder),
))
.into_any_element()
})
}
}
+17
View File
@@ -0,0 +1,17 @@
pub mod panels;
pub mod progress;
pub mod tree;
pub mod widgets;
/// Logs a discarded `Result` with its source location instead of dropping it silently.
#[track_caller]
pub fn log_dropped<T>(result: Result<T, anyhow::Error>) {
if let Err(error) = result {
let location = std::panic::Location::caller();
log::warn!(
"{}:{}: dropped result: {error}",
location.file(),
location.line()
);
}
}
+71
View File
@@ -0,0 +1,71 @@
use std::sync::Arc;
use gpui::{App, Entity, SharedString, WeakEntity, Window};
use ui::layout::panel::{Panel, PanelView};
use crate::workspace::Workspace;
/// Opens a repository in the main panel, reusing it when it is already cached.
pub fn open_primary<P, F>(
workspace: &WeakEntity<Workspace>,
id: impl Into<SharedString>,
build: F,
window: &mut Window,
cx: &mut App,
) where
P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{
let id = id.into();
if workspace
.read_with(cx, |workspace, _| workspace.has_main(&id))
.unwrap_or(false)
{
if let Err(error) = workspace.update(cx, |workspace, cx| workspace.activate_main(&id, cx)) {
log::warn!("failed to activate repository {id}: {error}");
}
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
if let Err(error) = workspace.update(cx, |workspace, cx| {
workspace.show_main(id.clone(), view, cx)
}) {
log::warn!("failed to open repository {id}: {error}");
}
}
/// Opens a detail panel beside the main panel, reusing it when it is already cached.
pub fn open_detail<P, F>(
workspace: &WeakEntity<Workspace>,
id: impl Into<SharedString>,
build: F,
window: &mut Window,
cx: &mut App,
) where
P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{
let id = id.into();
if workspace
.read_with(cx, |workspace, _| workspace.has_detail(&id))
.unwrap_or(false)
{
if let Err(error) = workspace.update(cx, |workspace, cx| workspace.activate_detail(&id, cx))
{
log::warn!("failed to activate detail panel {id}: {error}");
}
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
if let Err(error) = workspace.update(cx, |workspace, cx| {
workspace.show_detail(id.clone(), view, cx)
}) {
log::warn!("failed to open detail panel {id}: {error}");
}
}
+128
View File
@@ -0,0 +1,128 @@
use gpui::{
AnyElement, App, Context, IntoElement as _, ParentElement as _, SharedString, Styled as _,
Subscription, div,
};
use signed_core::RepoAddr;
use signed_state::{Backend, BackendEvent, PushStepStatus};
use ui::common::{h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::spinner::Spinner;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
/// Progress of an async dialog action: a busy flag that disables the form and an error shown below it.
#[derive(Debug, Default)]
pub struct DialogProgress {
pub busy: bool,
pub error: Option<SharedString>,
// The repository whose push checklist is shown; `None` outside a publish.
push_addr: Option<RepoAddr>,
pub push_steps: Vec<PushStepStatus>,
_push_subscription: Option<Subscription>,
}
impl DialogProgress {
/// Marks an action as started, disabling the form and clearing the previous error.
pub fn begin(&mut self) {
self.busy = true;
self.error = None;
}
/// Starts a publish for the repository at `addr` and listens for its push steps.
pub fn begin_push(&mut self, addr: RepoAddr, cx: &mut Context<Self>) {
self.begin();
self.push_addr = Some(addr);
self.push_steps.clear();
if self._push_subscription.is_none() {
let backend = Backend::global(cx);
self._push_subscription = Some(cx.subscribe(&backend, |this, _backend, event, cx| {
let BackendEvent::PushProgress { addr, status } = event else {
return;
};
if this.push_addr.as_ref() != Some(addr) {
return;
}
match this
.push_steps
.iter_mut()
.find(|step| step.step() == status.step())
{
Some(step) => *step = status.clone(),
None => this.push_steps.push(status.clone()),
}
cx.notify();
}));
}
}
/// Marks an action as failed, enabling the form and showing `message`.
pub fn fail(&mut self, message: impl Into<SharedString>) {
self.busy = false;
self.error = Some(message.into());
}
}
/// The shared error line under a dialog form, `None` when there is no error.
pub fn error_row(error: &Option<SharedString>, cx: &App) -> Option<AnyElement> {
error.as_ref().map(|message| {
div()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().ramps.destructive.base)
.child(message.clone())
.into_any_element()
})
}
/// The push checklist of a running publish, `None` before any step is reported.
pub fn push_steps_row(steps: &[PushStepStatus], cx: &App) -> Option<AnyElement> {
if steps.is_empty() {
return None;
}
let rows = steps
.iter()
.map(|status| {
let label = SharedString::from(status.step().label());
match status {
PushStepStatus::Running(_) => h_flex()
.gap_2()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(Spinner::new("push-step"))
.child(label)
.into_any_element(),
PushStepStatus::Done(_) => h_flex()
.gap_2()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.foreground)
.child(
Icon::named(IconRole::Check)
.small()
.color(cx.theme().colors.foreground),
)
.child(label)
.into_any_element(),
PushStepStatus::Failed(_, reason) => h_flex()
.gap_2()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().ramps.destructive.base)
.child(
Icon::named(IconRole::Close)
.small()
.color(cx.theme().ramps.destructive.base),
)
.child(SharedString::from(format!(
"{}: {reason}",
status.step().label()
)))
.into_any_element(),
}
})
.collect::<Vec<_>>();
Some(v_flex().gap_1().children(rows).into_any_element())
}
+188
View File
@@ -0,0 +1,188 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
pub struct TreeItemSeed {
/// Path of the node, relative to the worktree root.
pub id: String,
pub label: String,
pub children: Vec<TreeItemSeed>,
}
/// One visible row of the flattened tree.
#[derive(Clone)]
pub struct TreeRow {
pub id: String,
pub label: String,
pub depth: usize,
pub expandable: bool,
pub expanded: bool,
}
/// Flattens the seeds into the rows a flat tree renders, honoring `expanded`.
pub fn flatten(seeds: &[TreeItemSeed], expanded: &HashSet<String>) -> Vec<TreeRow> {
fn push(
seed: &TreeItemSeed,
depth: usize,
expanded: &HashSet<String>,
rows: &mut Vec<TreeRow>,
) {
let is_expanded = expanded.contains(&seed.id);
rows.push(TreeRow {
id: seed.id.clone(),
label: seed.label.clone(),
depth,
expandable: !seed.children.is_empty(),
expanded: is_expanded,
});
if is_expanded {
for child in &seed.children {
push(child, depth + 1, expanded, rows);
}
}
}
let mut rows = Vec::new();
for seed in seeds {
push(seed, 0, expanded, &mut rows);
}
rows
}
/// Every folder id, for starting with the tree fully expanded.
pub fn collect_expanded(seeds: &[TreeItemSeed]) -> HashSet<String> {
fn push(seed: &TreeItemSeed, expanded: &mut HashSet<String>) {
if !seed.children.is_empty() {
expanded.insert(seed.id.clone());
for child in &seed.children {
push(child, expanded);
}
}
}
let mut expanded = HashSet::new();
for seed in seeds {
push(seed, &mut expanded);
}
expanded
}
/// Build nested tree items from a flat entry list sorted dirs-first.
pub fn build_tree_items(entries: &[PathBuf]) -> Vec<TreeItemSeed> {
// Node indices by full path, so parents resolve in constant time while inserting.
let mut index: HashMap<String, usize> = HashMap::new();
let mut nodes: Vec<(String, String, Vec<usize>)> = Vec::new();
let mut roots: Vec<usize> = Vec::new();
for entry in entries {
let mut parent: Option<usize> = None;
let mut path = String::new();
for part in entry.components() {
let label = part.as_os_str().to_string_lossy().into_owned();
path = if path.is_empty() {
label.clone()
} else {
format!("{path}/{label}")
};
let ix = *index.entry(path.clone()).or_insert_with(|| {
let ix = nodes.len();
nodes.push((path.clone(), label.clone(), Vec::new()));
match parent {
Some(parent) => nodes[parent].2.push(ix),
None => roots.push(ix),
}
ix
});
parent = Some(ix);
}
}
fn assemble(ix: usize, nodes: &[(String, String, Vec<usize>)]) -> TreeItemSeed {
let (id, label, children) = &nodes[ix];
TreeItemSeed {
id: id.clone(),
label: label.clone(),
children: children
.iter()
.map(|child| assemble(*child, nodes))
.collect(),
}
}
roots.iter().map(|root| assemble(*root, &nodes)).collect()
}
/// Sorted relative paths of a worktree snapshot.
pub fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec<String> {
let mut paths: Vec<String> = entries
.iter()
.map(|path| path.to_string_lossy().into_owned())
.collect();
paths.sort();
paths
}
#[cfg(test)]
mod tests {
use super::*;
fn ids(rows: &[TreeRow]) -> Vec<(&str, usize)> {
rows.iter()
.map(|row| (row.id.as_str(), row.depth))
.collect()
}
#[test]
fn collapsed_folders_hide_children() {
let seeds = build_tree_items(&[
PathBuf::from("src"),
PathBuf::from("src/lib.rs"),
PathBuf::from("README.md"),
]);
let rows = flatten(&seeds, &HashSet::new());
assert_eq!(ids(&rows), vec![("src", 0), ("README.md", 0)]);
assert!(rows[0].expandable);
assert!(!rows[0].expanded);
}
#[test]
fn expanding_a_folder_shows_children_in_order() {
let seeds = build_tree_items(&[
PathBuf::from("src"),
PathBuf::from("src/lib.rs"),
PathBuf::from("src/views/mod.rs"),
PathBuf::from("README.md"),
]);
let expanded = HashSet::from(["src".to_owned(), "src/views".to_owned()]);
let rows = flatten(&seeds, &expanded);
assert_eq!(
ids(&rows),
vec![
("src", 0),
("src/lib.rs", 1),
("src/views", 1),
("src/views/mod.rs", 2),
("README.md", 0),
]
);
}
#[test]
fn indices_map_to_row_ids() {
let seeds = build_tree_items(&[
PathBuf::from("docs"),
PathBuf::from("docs/guide.md"),
PathBuf::from("README.md"),
]);
let expanded = HashSet::from(["docs".to_owned()]);
let rows = flatten(&seeds, &expanded);
assert_eq!(rows[0].id, "docs");
assert_eq!(rows[1].id, "docs/guide.md");
assert_eq!(rows[2].id, "README.md");
}
}
+42
View File
@@ -0,0 +1,42 @@
use gpui::{AnyElement, App, IntoElement, ParentElement as _, SharedString, Styled as _, div};
use signed_core::RepoStatus;
use ui::badge::{Badge, BadgeVariant};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tooltip::Tooltip;
/// The status pill shown on issue and pull-request rows.
pub fn status_badge(status: RepoStatus) -> Badge {
let (label, variant, icon) = match status {
RepoStatus::Open => ("Open", BadgeVariant::Neutral, IconRole::GitIssueOngoing),
RepoStatus::Closed => ("Closed", BadgeVariant::Danger, IconRole::GitIssueClosed),
RepoStatus::Draft => ("Draft", BadgeVariant::Warning, IconRole::GitIssueOngoing),
RepoStatus::Applied => ("Applied", BadgeVariant::Success, IconRole::GitIssueDone),
};
Badge::new(format!("status-{label}"), label)
.variant(variant)
.icon(Icon::named(icon))
.tooltip(Tooltip::text(label))
}
/// A centered empty-state message filling the available space.
pub fn empty_state(message: impl Into<SharedString>) -> AnyElement {
let message = message.into();
ui::common::v_flex()
.size_full()
.items_center()
.justify_center()
.child(EmptyState::new(message))
.into_any_element()
}
/// A one-line muted label used by section headers.
pub fn section_label(text: impl Into<SharedString>, cx: &App) -> AnyElement {
div()
.typeset(TextRole::Caption2, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(text.into())
.into_any_element()
}
+628
View File
@@ -0,0 +1,628 @@
use std::rc::Rc;
use std::sync::Arc;
use gpui::{
AnyElement, AnyView, App, AppContext as _, Context, Entity, IntoElement, KeyBinding,
KeyBindingContextPredicate, ParentElement as _, SharedString, Subscription, WeakEntity, Window,
};
use metadata::{Profile, ProfileDirectory};
use nostr::prelude::PublicKey;
use repository_switcher::RepositoryEntry;
pub(crate) use repository_switcher::RepositorySwitcher;
use signed_core::Announcement;
use signed_state::{Backend, BackendEvent, LocalReposStore, RepoListStore, ResolvedLocalRepo};
use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariant};
use ui::command_palette::{Command, CommandPalette, CommandPaletteState};
use ui::icons::{Icon, IconRole};
use ui::layout::panel::PanelView;
use ui::menu::{Menu, MenuItem};
use ui::tabs::{Tab, Tabs, TabsVariant};
use ui::tooltip::Tooltip;
use crate::explore::ExploreView;
use crate::identity::exit::ExitDialog;
use crate::repo::{RepoDetailView, actions, dialogs};
use crate::settings::SettingsDialog;
use crate::shared::{log_dropped, panels};
use crate::workspace::Workspace;
mod repository_switcher;
/// The key context the repository shortcuts bind against.
pub(crate) const REPOSITORY_KEY_CONTEXT: &str = "Signed";
const CREATE_KEYSTROKE: &str = "secondary-n";
const REPOSITORY_KEYSTROKES: [&str; 9] = [
"secondary-1",
"secondary-2",
"secondary-3",
"secondary-4",
"secondary-5",
"secondary-6",
"secondary-7",
"secondary-8",
"secondary-9",
];
/// Opens the repository at this index in the combined announced/local list.
#[derive(Clone, PartialEq, gpui::Action)]
#[action(namespace = signed, no_json)]
pub(crate) struct SwitchRepository {
pub index: usize,
}
/// Opens the create-repository dialog.
#[derive(Clone, PartialEq, gpui::Action)]
#[action(namespace = signed, no_json)]
pub(crate) struct CreateRepository;
pub(crate) fn bind_repository_shortcuts(cx: &mut App) {
let context = match KeyBindingContextPredicate::parse(REPOSITORY_KEY_CONTEXT) {
Ok(context) => Some(Rc::new(context)),
Err(error) => {
log::error!("failed to parse repository key context: {error}");
return;
}
};
let bindings = REPOSITORY_KEYSTROKES
.into_iter()
.enumerate()
.map(|(index, keystroke)| {
KeyBinding::load(
keystroke,
Box::new(SwitchRepository { index }),
context.clone(),
false,
None,
cx,
)
})
.chain(std::iter::once(KeyBinding::load(
CREATE_KEYSTROKE,
Box::new(CreateRepository),
context.clone(),
false,
None,
cx,
)))
.collect::<Result<Vec<_>, _>>();
let bindings = match bindings {
Ok(bindings) => bindings,
Err(error) => {
log::error!("failed to parse repository shortcut keystrokes: {error}");
return;
}
};
cx.bind_keys(bindings);
}
pub struct TitlebarView {
weak: WeakEntity<Self>,
workspace: WeakEntity<Workspace>,
/// User's announced repositories.
announcements: Arc<Vec<Announcement>>,
/// Local repositories found by the scan that are not announced yet.
local_repos: Arc<Vec<ResolvedLocalRepo>>,
/// Profiles rendered by the repository switcher.
directory: Entity<ProfileDirectory>,
/// The command palette opened from the titlebar.
palette: Entity<CommandPaletteState>,
repository_switcher: Entity<RepositorySwitcher>,
settings: Option<Entity<SettingsDialog>>,
exit: Option<Entity<ExitDialog>>,
create: Option<Entity<dialogs::create::CreateRepoDialog>>,
user_menu_open: bool,
_subscriptions: Vec<Subscription>,
}
impl TitlebarView {
pub fn new(
workspace: WeakEntity<Workspace>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let backend = Backend::global(cx);
let repos = RepoListStore::global(cx);
let local = LocalReposStore::global(cx);
let weak = cx.entity().downgrade();
let palette = Self::new_palette(weak.clone(), window, cx);
let directory = ProfileDirectory::new(cx);
let entity = cx.entity();
let mut subscriptions = Vec::new();
let repository_switcher = cx.new(|cx| {
RepositorySwitcher::new(
directory.clone(),
{
let weak = weak.clone();
move |index, window, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.activate(index, window, cx);
}));
}
},
{
let weak = weak.clone();
move |window, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.create_repository(window, cx);
}));
}
},
|cx| {
let local_repos = LocalReposStore::global(cx);
local_repos.update(cx, |store, cx| {
store.rescan(cx);
});
},
cx,
)
});
subscriptions.push(cx.subscribe(&backend, |this, _backend, event, cx| {
let signer_changed = matches!(event, BackendEvent::SignerChanged);
let signer_required = matches!(event, BackendEvent::SignerRequired);
if this.refresh(cx) || signer_changed || signer_required {
cx.notify();
}
}));
subscriptions.push(cx.observe(&repos, |this, _repos, cx| {
if this.refresh(cx) {
cx.notify();
}
}));
subscriptions.push(cx.observe(&local, |this, _local, cx| {
if this.refresh(cx) {
cx.notify();
}
}));
cx.defer(move |cx| {
entity.update(cx, |this, cx| {
if this.refresh(cx) {
cx.notify();
}
});
});
Self {
weak: cx.entity().downgrade(),
workspace,
announcements: Arc::new(Vec::new()),
local_repos: Arc::new(Vec::new()),
directory,
palette,
repository_switcher,
settings: None,
exit: None,
create: None,
user_menu_open: false,
_subscriptions: subscriptions,
}
}
fn new_palette(
weak: WeakEntity<Self>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Entity<CommandPaletteState> {
cx.new(|cx| {
let matcher = |query: &str, commands: &[Command]| {
let needle = query.to_lowercase();
commands
.iter()
.filter(|command| command.label.to_lowercase().contains(&needle))
.cloned()
.collect()
};
CommandPaletteState::new(
CommandPalette::new("command-palette", Self::palette_commands(), matcher)
.on_execute(move |command, window, cx| match command.id.as_ref() {
"create-repo" => {
log_dropped(weak.update(cx, |this, cx| this.open_create(window, cx)));
}
"rescan-repos" => {
let local_repos = LocalReposStore::global(cx);
local_repos.update(cx, |store, cx| store.rescan(cx));
}
"open-settings" => {
log_dropped(weak.update(cx, |this, cx| this.open_settings(cx)));
}
"exit" => {
log_dropped(weak.update(cx, |this, cx| this.open_exit(cx)));
}
_ => {}
}),
window,
cx,
)
})
}
fn palette_commands() -> Vec<Command> {
vec![
Command::new("create-repo", "Create repository").icon(Icon::named(IconRole::Plus)),
Command::new("rescan-repos", "Rescan for local repositories")
.icon(Icon::named(IconRole::Refresh)),
Command::new("open-settings", "Settings").icon(Icon::named(IconRole::Settings)),
Command::new("exit", "Exit"),
]
}
pub fn palette(&self) -> Entity<CommandPaletteState> {
self.palette.clone()
}
fn refresh(&mut self, cx: &mut Context<Self>) -> bool {
let backend = Backend::global(cx);
let user = backend.read(cx).current_user();
let (announcements, local_repos) = {
let repo_list = RepoListStore::global(cx).read(cx);
let announcements = user
.as_ref()
.map(|user| repo_list.announcements_of(user))
.unwrap_or_default();
let local = LocalReposStore::global(cx).read(cx);
let local_repos =
LocalReposStore::resolve(&local.repos, &repo_list.announcements, &announcements);
(announcements, local_repos)
};
let announcements_changed = *self.announcements != announcements;
let local_changed = *self.local_repos != local_repos;
self.announcements = Arc::new(announcements);
self.local_repos = Arc::new(local_repos);
let mut profiles: Vec<PublicKey> = user.into_iter().collect();
profiles.extend(
self.local_repos
.iter()
.filter_map(|entry| {
entry
.nip34
.as_ref()
.and_then(|binding| binding.owner)
.filter(|owner| !profiles.contains(owner))
})
.collect::<Vec<PublicKey>>(),
);
self.directory.update(cx, |directory, cx| {
directory.track(profiles, cx);
});
if announcements_changed || local_changed {
let entries = self.repository_entries();
self.repository_switcher.update(cx, |switcher, cx| {
switcher.set_entries(entries, cx);
});
}
announcements_changed || local_changed
}
fn repository_entries(&self) -> Vec<RepositoryEntry> {
let mut entries = Vec::with_capacity(self.announcements.len() + self.local_repos.len());
for (index, announcement) in self.announcements.iter().enumerate() {
let label = announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()));
entries.push(RepositoryEntry {
index,
key: announcement_key(announcement),
label,
owner: Some(announcement.owner),
});
}
for (local_index, entry) in self.local_repos.iter().enumerate() {
let owner = entry.nip34.as_ref().and_then(|binding| binding.owner);
entries.push(RepositoryEntry {
index: self.announcements.len() + local_index,
key: local_key(entry),
label: entry.name(),
owner,
});
}
entries
}
pub(crate) fn repository_switcher(&self) -> Entity<RepositorySwitcher> {
self.repository_switcher.clone()
}
/// Tabs for the repositories opened in the main panel.
pub fn render_repo_tabs(&self, workspace: &Workspace) -> Option<Tabs> {
let open = workspace.open_mains();
if open.is_empty() {
return None;
}
let tabs: Vec<_> = open
.iter()
.map(|id| (id.clone(), workspace.main_view(id)))
.collect();
let selected = workspace
.active_main_id()
.and_then(|id| open.iter().position(|open_id| open_id == id))
.unwrap_or(usize::MAX);
let change_workspace = self.workspace.clone();
let close_workspace = self.workspace.clone();
let open_for_change = open.to_vec();
Some(
Tabs::new("signed-repo-tabs")
.variant(TabsVariant::Titlebar)
.overflow_scroll(true)
.selected(selected)
.tabs(move |_, cx| {
tabs.iter()
.map(|(id, view)| match view {
Some(view) => view.tab(id.clone().into(), cx).closeable(true),
None => Tab::new(id.clone(), id.clone()).closeable(true),
})
.collect()
})
.on_change(move |index, _, cx| {
let Some(id) = open_for_change.get(index).cloned() else {
return;
};
log_dropped(change_workspace.update(cx, |workspace, cx| {
workspace.activate_main(&id, cx);
}));
})
.on_close(move |index, _, cx| {
log_dropped(close_workspace.update(cx, |workspace, cx| {
workspace.close_main_at(index, cx);
}));
}),
)
}
pub(crate) fn activate_shortcut(
&mut self,
index: usize,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.repository_switcher
.update(cx, |switcher, cx| switcher.close(cx));
self.activate(index, window, cx);
}
pub(crate) fn create_repository(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.repository_switcher
.update(cx, |switcher, cx| switcher.close(cx));
self.open_create(window, cx);
}
fn open_settings(&mut self, cx: &mut Context<Self>) {
self.settings = Some(SettingsDialog::new(cx));
cx.notify();
}
fn open_exit(&mut self, cx: &mut Context<Self>) {
self.exit = Some(ExitDialog::new(cx));
cx.notify();
}
fn open_create(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let view = dialogs::create::CreateRepoDialog::new(self.workspace.clone(), window, cx);
self.create = Some(view);
cx.notify();
}
/// The dialogs this titlebar opens, rendered at the window root.
pub fn dialogs(&self) -> Vec<AnyView> {
[
self.settings.clone().map(Into::into),
self.exit.clone().map(Into::into),
self.create.clone().map(Into::into),
]
.into_iter()
.flatten()
.collect()
}
fn activate(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
if let Some(announcement) = self.announcements.get(index) {
let addr = announcement.addr();
actions::open_repo_panel(&self.workspace, &addr, Some(announcement), window, cx);
return;
}
let Some(entry) = index
.checked_sub(self.announcements.len())
.and_then(|local| self.local_repos.get(local))
.cloned()
else {
return;
};
self.open_local_entry(entry, window, cx);
}
/// A local repository opens as the announced repository when its binding matches one.
fn open_local_entry(
&mut self,
entry: ResolvedLocalRepo,
window: &mut Window,
cx: &mut Context<Self>,
) {
let ResolvedLocalRepo {
path,
nip34,
announcement,
} = entry;
if let Some(announcement) = announcement {
let id = SharedString::from(format!("repo:{}", announcement.addr()));
let workspace = self.workspace.clone();
let workspace_for_build = workspace.clone();
panels::open_primary(
&workspace,
id,
move |window, cx| {
cx.new(|cx| {
RepoDetailView::new_local_announced(
workspace_for_build.clone(),
announcement.clone(),
path.clone(),
window,
cx,
)
})
},
window,
cx,
);
return;
}
let id = SharedString::from(format!("repo-local:{}", path.display()));
let workspace = self.workspace.clone();
let workspace_for_build = workspace.clone();
panels::open_primary(
&workspace,
id,
move |window, cx| {
cx.new(|cx| {
RepoDetailView::new_local(
workspace_for_build.clone(),
path.clone(),
nip34.clone(),
window,
cx,
)
})
},
window,
cx,
);
}
pub fn render_user_menu(&self, cx: &App) -> Option<AnyElement> {
let profile = Backend::global(cx)
.read(cx)
.current_user()
.map(|public_key| self.directory.read(cx).profile(&public_key, cx))?;
Some(self.render_user(&profile, cx).into_any_element())
}
pub fn render_explore(&self) -> AnyElement {
let workspace = self.workspace.clone();
Button::new("open-explore")
.icon(IconRole::Grid)
.variant(ButtonVariant::Ghost)
.fully_rounded(true)
.tooltip(Tooltip::text("Explore repositories"))
.on_click(move |_, window, cx| {
ExploreView::open(&workspace, window, cx);
})
.into_any_element()
}
pub fn render_new_repository(&self) -> AnyElement {
let weak = self.weak.clone();
Button::new("add-repo")
.icon(IconRole::Plus)
.variant(ButtonVariant::Ghost)
.fully_rounded(true)
.tooltip(Tooltip::text("Create repository"))
.on_click(move |_, window, cx| {
log_dropped(weak.update(cx, |this, cx| this.open_create(window, cx)));
})
.into_any_element()
}
fn render_user(&self, profile: &Profile, _cx: &App) -> impl IntoElement {
let name = profile.name();
let picture = profile.picture();
let public_key = profile.public_key();
let weak = self.weak.clone();
Menu::new("user-menu")
.open(self.user_menu_open)
.on_change({
let weak = weak.clone();
move |open, _, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.user_menu_open = open;
cx.notify();
}));
}
})
.trigger({
let name = name.clone();
let picture = picture.clone();
move |_, _| {
Button::new("user-menu-trigger")
.variant(ButtonVariant::Ghost)
.fully_rounded(true)
.padded(false)
.accessibility_label(name.clone())
.child(
Avatar::new(public_key)
.name(name.clone())
.picture(picture.clone())
.fully_rounded(true),
)
.into_any_element()
}
})
.items(move |_, _| {
vec![
MenuItem::new("Settings").handler({
let weak = weak.clone();
move |_, cx| {
log_dropped(weak.update(cx, |this, cx| this.open_settings(cx)));
}
}),
MenuItem::separator(),
MenuItem::new("Exit").destructive(true).handler({
let weak = weak.clone();
move |_, cx| {
log_dropped(weak.update(cx, |this, cx| this.open_exit(cx)));
}
}),
]
})
}
}
fn announcement_key(announcement: &Announcement) -> SharedString {
SharedString::from(format!("repo:{}", announcement.addr()))
}
fn local_key(entry: &ResolvedLocalRepo) -> SharedString {
match entry.announcement.as_ref() {
Some(announcement) => announcement_key(announcement),
None => SharedString::from(format!("repo-local:{}", entry.path.display())),
}
}
@@ -0,0 +1,288 @@
use std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, Role,
SharedString, StatefulInteractiveElement as _, Styled as _, UniformListScrollHandle, Window,
div, px, uniform_list,
};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
use ui::avatar::Avatar;
use ui::button::{Button, ButtonSide, ButtonVariant};
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::kbd::Kbd;
use ui::popover::Popover;
use ui::separator::Separator;
use ui::theme::{ActiveTheme as _, TextRole, Typeset};
use ui::tooltip::Tooltip;
use super::{CreateRepository, REPOSITORY_KEY_CONTEXT, SwitchRepository};
use crate::shared::log_dropped;
type OpenHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
type CreateHandler = Rc<dyn Fn(&mut Window, &mut App)>;
type RescanHandler = Rc<dyn Fn(&mut App)>;
/// One row of the repository switcher.
#[derive(Clone)]
pub(super) struct RepositoryEntry {
pub(super) index: usize,
pub(super) key: SharedString,
pub(super) label: SharedString,
pub(super) owner: Option<PublicKey>,
}
impl RepositoryEntry {
pub(super) fn avatar(&self, directory: &Entity<ProfileDirectory>, cx: &App) -> Avatar {
let mut avatar = Avatar::new(self.key.clone());
if let Some(owner) = self.owner {
let profile = directory.read(cx).profile(&owner, cx);
avatar = avatar.name(profile.name()).picture(profile.picture());
}
avatar.small()
}
}
/// The titlebar repository launcher: a static trigger and a searchable list.
pub(crate) struct RepositorySwitcher {
search: Entity<InputState>,
directory: Entity<ProfileDirectory>,
entries: Vec<RepositoryEntry>,
open: bool,
on_open: OpenHandler,
on_create: CreateHandler,
on_rescan: RescanHandler,
scroll_handle: UniformListScrollHandle,
}
impl RepositorySwitcher {
pub(super) fn new(
directory: Entity<ProfileDirectory>,
on_open: impl Fn(usize, &mut Window, &mut App) + 'static,
on_create: impl Fn(&mut Window, &mut App) + 'static,
on_rescan: impl Fn(&mut App) + 'static,
cx: &mut Context<Self>,
) -> Self {
let search = InputState::new(cx);
Self {
search,
directory,
entries: Vec::new(),
open: false,
on_open: Rc::new(on_open),
on_create: Rc::new(on_create),
on_rescan: Rc::new(on_rescan),
scroll_handle: UniformListScrollHandle::new(),
}
}
pub(super) fn set_entries(&mut self, entries: Vec<RepositoryEntry>, cx: &mut Context<Self>) {
self.entries = entries;
cx.notify();
}
pub(super) fn close(&mut self, cx: &mut Context<Self>) {
if self.open {
self.open = false;
cx.notify();
}
}
}
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 search = self.search.clone();
let directory = self.directory.clone();
let on_open = self.on_open.clone();
let on_create = self.on_create.clone();
let on_rescan = self.on_rescan.clone();
let row_weak = weak.clone();
let create_weak = weak.clone();
let rescan_weak = weak.clone();
let content_search = search.clone();
let scroll_handle = self.scroll_handle.clone();
let change_search = search.clone();
let change_weak = weak.clone();
Popover::new("repo-switcher-popover")
.open(self.open)
.on_change(move |open, window, cx| {
let search = change_search.clone();
log_dropped(change_weak.update(cx, |this, cx| {
this.open = open;
if open {
search.update(cx, |state, cx| {
state.set_value_silent("", window, cx);
});
}
cx.notify();
}));
})
.trigger(move |_window: &mut Window, _cx: &mut App| {
Button::new("repo-switcher")
.icon(Icon::named(IconRole::Stack))
.variant(ButtonVariant::Ghost)
.fully_rounded(true)
.tooltip(Tooltip::text("Repositories"))
.accessibility_label("Repositories")
.into_any_element()
})
.content(move |window: &mut Window, cx: &mut App| {
let focus = content_search.read(cx).focus_handle();
let query = content_search.read(cx).value().to_lowercase();
window.defer(cx, move |window, cx| {
if !focus.is_focused(window) {
window.focus(&focus, cx);
}
});
let visible: Vec<RepositoryEntry> = entries
.iter()
.filter(|entry| query.is_empty() || entry.label.to_lowercase().contains(&query))
.cloned()
.collect();
let row_height = theme.sizes.medium.menu_item_height + px(2.);
let list_height = (row_height * visible.len() as f32).min(px(280.));
let list_entries = visible.clone();
let list_directory = directory.clone();
let list_weak = row_weak.clone();
let list_on_open = on_open.clone();
let list_scroll_handle = scroll_handle.clone();
let create_hint = Kbd::binding_for_action(
&CreateRepository,
Some(REPOSITORY_KEY_CONTEXT),
window,
);
v_flex()
.w(px(380.))
.p_2()
.gap_2()
.child(
Input::new("repo-switcher-search", content_search.clone())
.placeholder("Filter repositories...")
.fully_rounded(true)
.prefix(
Icon::named(IconRole::Search)
.small()
.color(theme.colors.muted_foreground),
)
.bg(theme.colors.muted)
.border_color(theme.colors.muted),
)
.map(|this| {
if visible.is_empty() {
this.child(
div()
.p_3()
.text_color(theme.colors.muted_foreground)
.text_center()
.typeset(TextRole::Callout, cx)
.child("No repositories found"),
)
} else {
this.child(
uniform_list(
"repo-switcher-list",
visible.len(),
move |range, window, cx| {
range
.filter_map(|row| {
let entry = list_entries.get(row)?;
let index = entry.index;
let shortcut = Kbd::binding_for_action(
&SwitchRepository { index },
Some(REPOSITORY_KEY_CONTEXT),
window,
);
let weak = list_weak.clone();
let on_open = list_on_open.clone();
Some(
h_flex()
.id(("repo-switcher-entry", index))
.role(Role::MenuItem)
.w_full()
.h(row_height)
.px_3()
.gap_2()
.rounded(theme.radius.control)
.text_size(theme.sizes.medium.text_size)
.hover(|row| row.bg(theme.colors.muted))
.child(entry.avatar(&list_directory, cx))
.child(
div()
.flex_1()
.min_w_0()
.child(entry.label.clone()),
)
.when_some(shortcut, |row, shortcut| {
row.child(shortcut)
})
.cursor_pointer()
.on_click(move |_, window, cx| {
log_dropped(weak.update(
cx,
|this, cx| {
this.close(cx);
},
));
on_open(index, window, cx);
}),
)
})
.collect()
},
)
.track_scroll(&list_scroll_handle)
.h(list_height)
.w_full(),
)
}
})
.child(Separator::horizontal())
.child(
Button::new("repo-switcher-create")
.variant(ButtonVariant::Ghost)
.side(ButtonSide::Left)
.full_width(true)
.icon(Icon::named(IconRole::CirclePlus))
.child(div().flex_1().child("Create Repository"))
.when_some(create_hint, |button, hint| button.child(hint))
.on_click(move |_, window, cx| {
log_dropped(create_weak.update(cx, |this, cx| {
this.close(cx);
}));
on_create(window, cx);
}),
)
.child(
Button::new("repo-switcher-rescan")
.variant(ButtonVariant::Ghost)
.side(ButtonSide::Left)
.full_width(true)
.icon(Icon::named(IconRole::Refresh))
.label("Rescan Repositories")
.on_click(move |_, _, cx| {
log_dropped(rescan_weak.update(cx, |this, cx| {
this.close(cx);
}));
on_rescan(cx);
}),
)
.into_any_element()
})
}
}
+242
View File
@@ -0,0 +1,242 @@
use std::collections::HashMap;
use std::sync::Arc;
use gpui::{
App, Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div,
};
use ui::common::v_flex;
use ui::layout::panel::{Panel, PanelView};
use ui::tabs::{Tab, Tabs, TabsVariant};
use crate::shared::log_dropped;
/// The repository shown in the main panel and the detail panels opened beside it.
#[derive(Default)]
pub struct Workspace {
main: Option<SharedString>,
main_order: Vec<SharedString>,
main_views: HashMap<SharedString, Arc<dyn PanelView>>,
details: Vec<SharedString>,
detail_views: HashMap<SharedString, Arc<dyn PanelView>>,
active_detail: Option<SharedString>,
}
impl Workspace {
pub fn new() -> Self {
Self::default()
}
pub fn active_main(&self) -> Option<Arc<dyn PanelView>> {
self.main
.as_ref()
.and_then(|id| self.main_views.get(id))
.cloned()
}
pub fn active_main_id(&self) -> Option<&SharedString> {
self.main.as_ref()
}
pub fn open_mains(&self) -> &[SharedString] {
&self.main_order
}
/// The open main panel with this id.
pub fn main_view(&self, id: &SharedString) -> Option<Arc<dyn PanelView>> {
self.main_views.get(id).cloned()
}
pub fn active_detail(&self) -> Option<Arc<dyn PanelView>> {
self.active_detail
.as_ref()
.and_then(|id| self.detail_views.get(id))
.cloned()
}
pub fn has_main(&self, id: &SharedString) -> bool {
self.main_views.contains_key(id)
}
pub fn has_details(&self) -> bool {
!self.details.is_empty()
}
pub fn has_detail(&self, id: &SharedString) -> bool {
self.detail_views.contains_key(id)
}
pub fn show_main(
&mut self,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut Context<Self>,
) {
if self.main.as_ref() != Some(&id) {
self.clear_details();
}
if !self.main_views.contains_key(&id) {
self.main_order.push(id.clone());
}
self.main_views.insert(id.clone(), view);
self.main = Some(id);
cx.notify();
}
pub fn activate_main(&mut self, id: &SharedString, cx: &mut Context<Self>) {
if self.main.as_ref() != Some(id) {
self.clear_details();
}
self.main = Some(id.clone());
cx.notify();
}
pub fn activate_detail(&mut self, id: &SharedString, cx: &mut Context<Self>) {
if self.detail_views.contains_key(id) {
self.active_detail = Some(id.clone());
cx.notify();
}
}
pub fn show_detail(
&mut self,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut Context<Self>,
) {
if !self.details.contains(&id) {
self.details.push(id.clone());
}
self.detail_views.insert(id.clone(), view);
self.active_detail = Some(id);
cx.notify();
}
pub fn close_detail(&mut self, id: &SharedString, cx: &mut Context<Self>) {
let Some(index) = self.details.iter().position(|open| open == id) else {
return;
};
self.close_detail_at(index, cx);
}
pub fn close_main_at(&mut self, index: usize, cx: &mut Context<Self>) {
if index >= self.main_order.len() {
return;
}
let id = self.main_order.remove(index);
self.main_views.remove(&id);
if self.main.as_ref() == Some(&id) {
self.main = self
.main_order
.get(index)
.or_else(|| {
index
.checked_sub(1)
.and_then(|prev| self.main_order.get(prev))
})
.cloned();
self.clear_details();
}
cx.notify();
}
pub fn clear(&mut self, cx: &mut Context<Self>) {
self.main = None;
self.main_order.clear();
self.main_views.clear();
self.clear_details();
cx.notify();
}
fn clear_details(&mut self) {
self.details.clear();
self.detail_views.clear();
self.active_detail = None;
}
fn close_detail_at(&mut self, index: usize, cx: &mut Context<Self>) {
if index >= self.details.len() {
return;
}
let id = self.details.remove(index);
self.detail_views.remove(&id);
if self.active_detail.as_ref() == Some(&id) {
self.active_detail = self
.details
.get(index)
.or_else(|| index.checked_sub(1).and_then(|prev| self.details.get(prev)))
.cloned();
}
cx.notify();
}
fn activate_detail_at(&mut self, index: usize, cx: &mut Context<Self>) {
let Some(id) = self.details.get(index) else {
return;
};
self.active_detail = Some(id.clone());
cx.notify();
}
}
impl Panel for Workspace {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Workspace")
}
}
impl Render for Workspace {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let selected = self
.active_detail
.as_ref()
.and_then(|active| self.details.iter().position(|id| id == active))
.unwrap_or(usize::MAX);
let details: Vec<_> = self
.details
.iter()
.map(|id| (id.clone(), self.detail_views.get(id).cloned()))
.collect();
let weak = cx.entity().downgrade();
let close_weak = weak.clone();
let tabs = Tabs::new("signed-detail-tabs")
.variant(TabsVariant::Pill)
.overflow_scroll(true)
.selected(selected)
.tabs(move |_, cx| {
details
.iter()
.map(|(id, view)| match view {
Some(view) => view.tab(id.clone().into(), cx).closeable(true),
None => Tab::new(id.clone(), id.clone()).closeable(true),
})
.collect()
})
.on_change(move |index, _, cx| {
log_dropped(weak.update(cx, |workspace, cx| {
workspace.activate_detail_at(index, cx);
}));
})
.on_close(move |index, _, cx| {
log_dropped(close_weak.update(cx, |workspace, cx| {
workspace.close_detail_at(index, cx);
}));
});
let body = self.active_detail().map(|view| view.view());
v_flex()
.size_full()
.gap_2()
.child(tabs)
.child(div().flex_1().min_h_0().w_full().children(body))
}
}