Author SHA1 Message Date
reya b6bfc3fc15 fix(ui): fully round buttons and menu rows by default
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run
2026-11-20 09:31:29 +07:00
reya 8153e5c28a feat: add fixed width support to dialog
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run
2026-11-20 09:02:16 +07:00
reya 7962c2c50e refactor(ui): use v_flex/h_flex helpers in components
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run
2026-11-20 08:43:28 +07:00
reya 01c3ced1c7 chore: enforce clippy lints across workspace
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run
2026-11-20 08:14:03 +07:00
89 changed files with 2824 additions and 2058 deletions
+5
View File
@@ -50,3 +50,8 @@ panic = "unwind"
[profile.profiling] [profile.profiling]
inherits = "release" inherits = "release"
debug = true debug = true
[workspace.lints.clippy]
all = "deny"
perf = "deny"
unwrap_used = "deny"
+1
View File
@@ -0,0 +1 @@
allow-unwrap-in-tests = true
+3
View File
@@ -14,3 +14,6 @@ futures.workspace = true
anyhow.workspace = true anyhow.workspace = true
gpui.workspace = true gpui.workspace = true
log.workspace = true log.workspace = true
[lints]
workspace = true
+3
View File
@@ -6,3 +6,6 @@ publish.workspace = true
[dependencies] [dependencies]
dirs = "6" dirs = "6"
[lints]
workspace = true
+3
View File
@@ -13,3 +13,6 @@ serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
anyhow.workspace = true anyhow.workspace = true
log.workspace = true log.workspace = true
[lints]
workspace = true
+3
View File
@@ -20,3 +20,6 @@ nostr.workspace = true
anyhow.workspace = true anyhow.workspace = true
futures.workspace = true futures.workspace = true
log.workspace = true log.workspace = true
[lints]
workspace = true
+1 -1
View File
@@ -131,7 +131,7 @@ impl Render for AppRoot {
div() div()
.relative() .relative()
.size_full() .size_full()
.font_family(".SystemUIFont") .font_family(cx.theme().ui_font())
.text_color(cx.theme().colors.foreground) .text_color(cx.theme().colors.foreground)
.key_context(REPOSITORY_KEY_CONTEXT) .key_context(REPOSITORY_KEY_CONTEXT)
.on_action(cx.listener(|this, action: &SwitchRepository, window, cx| { .on_action(cx.listener(|this, action: &SwitchRepository, window, cx| {
+2 -5
View File
@@ -13,6 +13,7 @@ use ui::theme::ActiveTheme as _;
use utils::relative_time; use utils::relative_time;
use crate::repo::actions::open_repo_panel; use crate::repo::actions::open_repo_panel;
use crate::repo::helpers::announcement_display_name;
use crate::workspace::Workspace; use crate::workspace::Workspace;
const RECENT_COUNT: usize = 10; const RECENT_COUNT: usize = 10;
@@ -62,11 +63,7 @@ pub(super) fn render_card(
let workspace = workspace.clone(); let workspace = workspace.clone();
let announcement = announcement.clone(); let announcement = announcement.clone();
let name = announcement let name = announcement_display_name(&announcement);
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()));
let description = announcement let description = announcement
.description .description
+22 -33
View File
@@ -14,7 +14,6 @@ use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent}; use ui::input::{Input, InputState, InputStateEvent};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption}; use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
@@ -22,6 +21,7 @@ use crate::shared::panels;
use crate::workspace::Workspace; use crate::workspace::Workspace;
const COLUMNS: usize = 2; const COLUMNS: usize = 2;
// Name row, avatar strip, meta row, and their borders and gaps, in px.
const CARD_HEIGHT: f32 = 40. + 64. + 48. + 2. + 6.; const CARD_HEIGHT: f32 = 40. + 64. + 48. + 2. + 6.;
pub struct ExploreView { pub struct ExploreView {
@@ -153,29 +153,23 @@ impl ExploreView {
), ),
) )
.child( .child(
div() div().absolute().left_0().bottom_0().pl_4().pb_4().child(
.absolute() Segmented::new("explore-filter", filter)
.left_0() .options(vec![
.bottom_0() SegmentedOption::new(RepoFilter::All, "All")
.pl_4() .icon(Icon::named(IconRole::Grid).small().color(muted)),
.pb_4() SegmentedOption::new(RepoFilter::Recent, "Recent")
.child( .icon(Icon::named(IconRole::Clock).small().color(muted)),
Segmented::new("explore-filter", filter) ])
.options(vec![ .on_change(move |filter, _, cx| {
SegmentedOption::new(RepoFilter::All, "All") if let Err(error) = weak.update(cx, |this, cx| {
.icon(Icon::named(IconRole::Grid).small().color(muted)), this.filter = filter;
SegmentedOption::new(RepoFilter::Recent, "Recent") this.rebuild_rows(cx);
.icon(Icon::named(IconRole::Clock).small().color(muted)), }) {
]) log::warn!("failed to change explore filter: {error}");
.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() .into_any_element()
} }
@@ -262,14 +256,9 @@ impl Render for ExploreView {
}) })
.size_full(), .size_full(),
) )
.child( .child(crate::shared::widgets::scroll_overlay(
div() "explore-scroll",
.absolute() scroll_handle,
.top_0() ))
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical("explore-scroll", scroll_handle)),
)
} }
} }
+9 -9
View File
@@ -11,7 +11,7 @@ use ui::field::Field;
use ui::input::{Input, InputState, InputStateEvent}; use ui::input::{Input, InputState, InputStateEvent};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use crate::shared::progress::{DialogProgress, error_row}; use crate::shared::progress::{DialogProgress, error_row, run_dialog_task_with};
#[derive(Clone, Copy, Default, PartialEq, Eq)] #[derive(Clone, Copy, Default, PartialEq, Eq)]
enum Stage { enum Stage {
@@ -347,17 +347,17 @@ fn finish_import<T: 'static>(
handle: &DialogHandle, handle: &DialogHandle,
cx: &mut App, cx: &mut App,
) { ) {
let state = state.clone();
let handle = handle.clone(); let handle = handle.clone();
let state = state.clone();
cx.spawn(async move |cx| match task.await { run_dialog_task_with(
Ok(_) => cx.update(|cx| handle.close(cx)), task,
Err(error) => { cx,
move |_, cx| cx.update(|cx| handle.close(cx)),
move |error, cx| {
state.update(cx, |state, cx| { state.update(cx, |state, cx| {
state.progress.fail(error.to_string()); state.progress.fail(error.to_string());
cx.notify(); cx.notify();
}); });
} },
}) );
.detach();
} }
+2 -14
View File
@@ -11,7 +11,7 @@ use ui::field::Field;
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use crate::shared::progress::{DialogProgress, error_row}; use crate::shared::progress::{DialogProgress, error_row, run_dialog_task};
pub struct OnboardingDialog { pub struct OnboardingDialog {
handle: DialogHandle, handle: DialogHandle,
@@ -61,19 +61,7 @@ impl OnboardingDialog {
let backend = Backend::global(cx); let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| backend.create_identity(&name, &pass, cx)); let task = backend.update(cx, |backend, cx| backend.create_identity(&name, &pass, cx));
let state = self.state.clone(); run_dialog_task(task, &self.state, &self.handle, cx);
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();
} }
} }
+2 -14
View File
@@ -11,7 +11,7 @@ use ui::field::Field;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent}; use ui::input::{Input, InputState, InputStateEvent};
use crate::shared::progress::{DialogProgress, error_row, push_steps_row}; use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task};
pub struct PassphraseDialog { pub struct PassphraseDialog {
handle: DialogHandle, handle: DialogHandle,
@@ -64,19 +64,7 @@ impl PassphraseDialog {
let backend = Backend::global(cx); let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| backend.restore_with_passphrase(&pass, cx)); let task = backend.update(cx, |backend, cx| backend.restore_with_passphrase(&pass, cx));
let state = self.state.clone(); run_dialog_task(task, &self.state, &self.handle, cx);
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();
} }
} }
+3 -29
View File
@@ -1,7 +1,7 @@
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, Div, Entity, InteractiveElement as _, IntoElement, ParentElement as _, AnyElement, App, Div, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
SharedString, Stateful, Styled as _, div, px, SharedString, Stateful, Styled as _, div,
}; };
use metadata::ProfileDirectory; use metadata::ProfileDirectory;
use nostr::prelude::{Event, Kind, PublicKey}; use nostr::prelude::{Event, Kind, PublicKey};
@@ -101,11 +101,8 @@ pub fn thread(
.child(div().flex_1()) .child(div().flex_1())
.when(unread, |this| { .when(unread, |this| {
this.child( this.child(
div() ui::status_dot::StatusDot::new(("inbox-unread", ix))
.flex_shrink_0() .variant(ui::status_dot::StatusDotVariant::Accent),
.size_2()
.rounded_full()
.bg(cx.theme().colors.primary),
) )
}), }),
) )
@@ -167,26 +164,3 @@ fn activity_phrase(kind: Kind) -> &'static str {
_ => "did something", _ => "did something",
} }
} }
pub fn empty_state(message: &'static str, cx: &App) -> AnyElement {
v_flex()
.w_full()
.flex_1()
.min_h_0()
.items_center()
.justify_center()
.gap_2()
.py_8()
.child(
Icon::named(IconRole::Inbox)
.size(px(24.))
.color(cx.theme().colors.muted_foreground),
)
.child(
div()
.text_base()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(message)),
)
.into_any_element()
}
+41 -11
View File
@@ -2,6 +2,7 @@ use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use anyhow::Error; use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity,
@@ -11,6 +12,7 @@ use metadata::ProfileDirectory;
use nostr::prelude::{Event, EventId, Kind, PublicKey, Timestamp}; use nostr::prelude::{Event, EventId, Kind, PublicKey, Timestamp};
use signed_core::{InboxItem, InboxReadState, RepoAddr}; use signed_core::{InboxItem, InboxReadState, RepoAddr};
use signed_state::{Backend, BackendEvent, Inbox, RefreshGate, RefreshRequest, RepoListStore}; use signed_state::{Backend, BackendEvent, Inbox, RefreshGate, RefreshRequest, RepoListStore};
use ui::alert::{Alert, AlertSeverity, AlertStyle};
use ui::button::Button; use ui::button::Button;
use ui::common::{StyledExt as _, h_flex, v_flex}; use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
@@ -19,9 +21,11 @@ use ui::scroll_area::ScrollArea;
mod helpers; mod helpers;
use helpers::{empty_section_row, empty_state, repo_header, thread}; use helpers::{empty_section_row, repo_header, thread};
use crate::repo::actions::{RepoItem, open_repo_item}; use crate::repo::actions::{RepoItem, open_repo_item};
use crate::repo::helpers::announcement_display_name;
use crate::shared::widgets::empty_state;
use crate::workspace::Workspace; use crate::workspace::Workspace;
const MAX_SUB_ACTIVITIES: usize = 5; const MAX_SUB_ACTIVITIES: usize = 5;
@@ -50,6 +54,8 @@ pub struct InboxView {
refresh: RefreshGate, refresh: RefreshGate,
tasks: Vec<Task<Result<(), Error>>>, tasks: Vec<Task<Result<(), Error>>>,
directory: Entity<ProfileDirectory>, directory: Entity<ProfileDirectory>,
/// The last refresh failure, shown inline until the next refresh succeeds.
error: Option<SharedString>,
_subscriptions: Vec<Subscription>, _subscriptions: Vec<Subscription>,
} }
@@ -92,6 +98,7 @@ impl InboxView {
refresh: RefreshGate::default(), refresh: RefreshGate::default(),
tasks: vec![], tasks: vec![],
directory: ProfileDirectory::new(cx), directory: ProfileDirectory::new(cx),
error: None,
_subscriptions: subscriptions, _subscriptions: subscriptions,
} }
} }
@@ -164,6 +171,12 @@ impl InboxView {
self.run_refresh(cx); self.run_refresh(cx);
} }
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn run_refresh(&mut self, cx: &mut Context<Self>) { fn run_refresh(&mut self, cx: &mut Context<Self>) {
self.refresh.begin(); self.refresh.begin();
let backend = Backend::global(cx); let backend = Backend::global(cx);
@@ -178,12 +191,16 @@ impl InboxView {
let state = self.state.clone(); let state = self.state.clone();
let work = cx.background_spawn(async move { Inbox::query(&client, me, &state).await }); let work = cx.background_spawn(async move { Inbox::query(&client, me, &state).await });
self.tasks.push(cx.spawn(async move |this, cx| { self.push_task(cx.spawn(async move |this, cx| {
let (threads, _unread_count) = match work.await { let (threads, _unread_count) = match work.await {
Ok(results) => results, Ok(results) => results,
Err(error) => { Err(error) => {
log::warn!("inbox refresh failed: {error}"); log::warn!("inbox refresh failed: {error}");
return this.update(cx, |this, _cx| this.refresh.abort()); return this.update(cx, |this, cx| {
this.error = Some(error.to_string().into());
this.refresh.abort();
cx.notify();
});
} }
}; };
@@ -193,6 +210,7 @@ impl InboxView {
return false; return false;
} }
this.threads = Arc::new(threads); this.threads = Arc::new(threads);
this.error = None;
this.rebuild(cx); this.rebuild(cx);
cx.notify(); cx.notify();
this.refresh.finish() this.refresh.finish()
@@ -427,6 +445,24 @@ impl Render for InboxView {
.on_click(cx.listener(|this, _, _, cx| this.mark_all_read(cx))), .on_click(cx.listener(|this, _, _, cx| this.mark_all_read(cx))),
), ),
) )
.when_some(self.error.clone(), |this, error| {
let weak = cx.entity().downgrade();
this.child(
Alert::new("inbox-error")
.severity(AlertSeverity::Danger)
.title("Inbox")
.message(error)
.style(AlertStyle::Inline)
.on_dismiss(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.error = None;
cx.notify();
}) {
log::warn!("failed to dismiss inbox error: {error}");
}
}),
)
})
.child( .child(
div() div()
.relative() .relative()
@@ -434,7 +470,7 @@ impl Render for InboxView {
.min_h_0() .min_h_0()
.px_4() .px_4()
.child(if rows.is_empty() { .child(if rows.is_empty() {
empty_state("You're all caught up.", cx) empty_state("You're all caught up.")
} else { } else {
ScrollArea::new("inbox-scroll") ScrollArea::new("inbox-scroll")
.flex_1() .flex_1()
@@ -455,12 +491,6 @@ fn repo_name(addr: Option<&RepoAddr>, cx: &App) -> SharedString {
.announcements .announcements
.iter() .iter()
.find(|announcement| announcement.addr() == *addr) .find(|announcement| announcement.addr() == *addr)
.map(|announcement| { .map(announcement_display_name)
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()))
})
.unwrap_or_else(|| SharedString::from("Untitled")) .unwrap_or_else(|| SharedString::from("Untitled"))
} }
+17 -27
View File
@@ -3,12 +3,11 @@ use gpui::{
ScrollHandle, SharedString, Styled as _, Subscription, Window, div, ScrollHandle, SharedString, Styled as _, Subscription, Window, div,
}; };
use metadata::ProfileDirectory; use metadata::ProfileDirectory;
use nostr::prelude::{EventId, PublicKey}; use nostr::prelude::EventId;
use signed_core::GitEvent; use signed_core::GitEvent;
use signed_state::RepoStore; use signed_state::RepoStore;
use ui::avatar::Avatar; use ui::avatar::Avatar;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::input::InputState; use ui::input::InputState;
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea; use ui::scroll_area::ScrollArea;
@@ -56,27 +55,23 @@ impl IssueDetailView {
/// Track the issue author, everyone who commented and the repository owner. /// Track the issue author, everyone who commented and the repository owner.
fn track_participants(&mut self, cx: &mut Context<Self>) { fn track_participants(&mut self, cx: &mut Context<Self>) {
let store = self.store.read(cx); let store = self.store.read(cx);
let mut keys: Vec<PublicKey> = store let author = store
.issues .issues
.iter() .iter()
.find(|issue| issue.id == self.issue_id) .find(|issue| issue.id == self.issue_id)
.map(|issue| issue.pubkey) .map(|issue| issue.pubkey);
.into_iter() let owner = store.announcement.as_ref().map(|a| a.owner);
let comments: Vec<_> = store
.comments_of(&self.issue_id)
.map(|comment| comment.pubkey)
.collect(); .collect();
crate::shared::track_event_participants(
keys.extend( author,
store owner,
.comments_of(&self.issue_id) comments.into_iter(),
.map(|comment| comment.pubkey), &self.directory,
cx,
); );
if let Some(owner) = store.announcement.as_ref().map(|a| a.owner) {
keys.push(owner);
}
self.directory.update(cx, |directory, cx| {
directory.track(keys, cx);
});
} }
} }
@@ -97,17 +92,12 @@ impl Render for IssueDetailView {
let store = self.store.read(cx); let store = self.store.read(cx);
let Some(issue) = store.issues.iter().find(|issue| issue.id == self.issue_id) else { let Some(issue) = store.issues.iter().find(|issue| issue.id == self.issue_id) else {
let message = if store.loaded { // A not-yet-loaded store is not the same as a missing issue.
"Issue not found" return if store.loaded {
crate::shared::widgets::empty_state("Issue not found")
} else { } else {
"Loading issue..." crate::shared::widgets::centered_spinner("issue-loading")
}; };
return v_flex()
.size_full()
.items_center()
.justify_center()
.child(EmptyState::new(message))
.into_any_element();
}; };
let (title, author, status, age, issue_id, content, pubkey) = { let (title, author, status, age, issue_id, content, pubkey) = {
+72 -157
View File
@@ -1,36 +1,33 @@
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, SharedString, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div,
Subscription, UniformListScrollHandle, WeakEntity, Window, div, px, uniform_list,
}; };
use helpers::{IssueFilter, StatusCounts, filter_by_status}; use helpers::{IssueFilter, StatusCounts, filter_by_status};
use metadata::ProfileDirectory; use metadata::ProfileDirectory;
use nostr::prelude::PublicKey; use nostr::prelude::PublicKey;
use signed_core::GitEvent; use signed_core::GitEvent;
use signed_state::RepoStore; use signed_state::RepoStore;
use ui::avatar::Avatar;
use ui::button::Button; use ui::button::Button;
use ui::common::{Sizable as _, h_flex, v_flex}; use ui::common::v_flex;
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption}; use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use utils::relative_time; use utils::relative_time;
use std::rc::Rc;
use self::detail::IssueDetailView; use self::detail::IssueDetailView;
use crate::repo::helpers::short_id;
use crate::shared::event_list::{EventList, EventRow};
use crate::shared::panels; use crate::shared::panels;
use crate::shared::widgets::status_badge;
use crate::workspace::Workspace; use crate::workspace::Workspace;
pub mod detail; pub mod detail;
pub(crate) mod helpers; pub(crate) mod helpers;
pub mod new_issue; pub mod new_issue;
const ISSUE_ROW_HEIGHT: f32 = 73.;
pub struct IssuesView { pub struct IssuesView {
workspace: WeakEntity<Workspace>, workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>, store: Entity<RepoStore>,
@@ -131,14 +128,9 @@ impl IssuesView {
let muted = cx.theme().colors.muted_foreground; let muted = cx.theme().colors.muted_foreground;
let weak = cx.entity().downgrade(); let weak = cx.entity().downgrade();
h_flex() crate::shared::event_list::filter_toolbar(
.px_4() cx,
.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) Segmented::new("issue-filter", self.filter)
.options(vec![ .options(vec![
SegmentedOption::new(IssueFilter::All, format!("All ({})", counts.total)) SegmentedOption::new(IssueFilter::All, format!("All ({})", counts.total))
@@ -158,18 +150,18 @@ impl IssuesView {
}) { }) {
log::warn!("failed to switch issue filter: {error}"); log::warn!("failed to switch issue filter: {error}");
} }
}), })
) .into_any_element(),
.child(div().flex_1()) div().flex_1().into_any_element(),
.child(
Button::new("new-issue") Button::new("new-issue")
.label("New issue") .label("New issue")
.icon(Icon::named(IconRole::CirclePlus)) .icon(Icon::named(IconRole::CirclePlus))
.on_click(cx.listener(|this, _, _, cx| { .on_click(cx.listener(|this, _, _, cx| {
this.open_new_issue(cx); this.open_new_issue(cx);
})), }))
) .into_any_element(),
.into_any_element() ],
)
} }
} }
@@ -182,147 +174,70 @@ impl Panel for IssuesView {
impl Render for IssuesView { impl Render for IssuesView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let filter = self.filter; let filter = self.filter;
let count = self.visible_issues.len();
let visible_issues = self.visible_issues.clone(); let visible_issues = self.visible_issues.clone();
let directory = self.directory.clone(); let directory = self.directory.clone();
let store = self.store.clone(); let store = self.store.clone();
let workspace = self.workspace.clone(); let workspace = self.workspace.clone();
let rows = visible_issues
.iter()
.enumerate()
.filter_map(|(ix, &issue_ix)| {
// The store re-read per frame can shrink below a captured index.
let issue = store.read(cx).issues.get(issue_ix)?;
let profile = directory.read(cx).profile(&issue.pubkey, cx);
let issue_id = issue.id;
let id_hex = issue.id.to_hex();
let status = store.read(cx).status_of(issue);
let on_click: crate::shared::event_list::EventHandler = {
let workspace = workspace.clone();
let store = store.clone();
Rc::new(move |_, window, cx| {
let id = SharedString::from(format!("issue:{issue_id}"));
let store = store.clone();
panels::open_detail(
&workspace,
id,
move |_, cx| {
cx.new(|cx| IssueDetailView::new(store.clone(), issue_id, cx))
},
window,
cx,
);
})
};
Some(EventRow {
id: ix.into(),
status,
title: issue.activity_subject().into(),
author: profile.name(),
picture: profile.picture(),
pubkey: issue.pubkey,
short_id: short_id(&id_hex),
age: SharedString::from(relative_time(issue.created_at)),
on_click,
})
})
.collect();
let empty_message = match filter {
IssueFilter::All => "No issues",
IssueFilter::Open => "No open issues",
IssueFilter::Closed => "No closed issues",
};
v_flex() v_flex()
.size_full() .size_full()
.child(self.render_header(cx))
.when_some(self.new_issue.clone(), |el, view| el.child(view)) .when_some(self.new_issue.clone(), |el, view| el.child(view))
.child( .child(
v_flex() EventList::new("issues")
.relative() .toolbar(self.render_header(cx))
.flex_1() .scroll_handle(self.scroll_handle.clone())
.min_h_0() .rows(rows)
.w_full() .empty_message(empty_message)
.when(count > 0, |this| { .render(cx),
this.child(
uniform_list("issues", count, move |range, _, cx| {
range
.map(|ix| {
let issue_ix = visible_issues[ix];
let issue = &store.read(cx).issues[issue_ix];
let title = issue.activity_subject();
let id_hex = issue.id.to_hex();
let profile = directory.read(cx).profile(&issue.pubkey, cx);
let author = profile.name();
let age = relative_time(issue.created_at);
let status = store.read(cx).status_of(issue);
let issue_id = issue.id;
let workspace = workspace.clone();
let store = store.clone();
h_flex()
.id(ix)
.w_full()
.h(px(ISSUE_ROW_HEIGHT))
.gap_4()
.px_4()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.on_click(move |_, window, cx| {
let id =
SharedString::from(format!("issue:{issue_id}"));
let store = store.clone();
panels::open_detail(
&workspace,
id,
move |_, cx| {
cx.new(|cx| {
IssueDetailView::new(
store.clone(),
issue_id,
cx,
)
})
},
window,
cx,
);
})
.child(status_badge(status))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(
div()
.text_base()
.text_ellipsis()
.whitespace_nowrap()
.child(title),
)
.child(
h_flex()
.gap_2()
.text_xs()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(issue.pubkey)
.name(author.clone())
.picture(
profile.picture(),
)
.small(),
)
.child(div().child(author)),
)
.child(SharedString::from("opened"))
.child(
div()
.text_color(
cx.theme()
.colors
.muted_foreground,
)
.child(SharedString::from(
&id_hex[..8],
)),
)
.child(SharedString::from(age)),
),
)
.into_any_element()
})
.collect()
})
.track_scroll(&self.scroll_handle)
.size_full(),
)
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(
"issues-scroll",
self.scroll_handle.clone(),
)),
)
})
.when(count == 0, |this| {
let message = match filter {
IssueFilter::All => "No issues",
IssueFilter::Open => "No open issues",
IssueFilter::Closed => "No closed issues",
};
this.child(
v_flex()
.size_full()
.items_center()
.justify_center()
.child(EmptyState::new(message)),
)
}),
) )
.into_any_element() .into_any_element()
} }
+15 -1
View File
@@ -10,31 +10,41 @@ use ui::field::Field;
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use crate::shared::progress::DialogProgress;
pub struct NewIssueDialog { pub struct NewIssueDialog {
handle: DialogHandle, handle: DialogHandle,
store: Entity<RepoStore>, store: Entity<RepoStore>,
subject: Entity<InputState>, subject: Entity<InputState>,
content: Entity<InputState>, content: Entity<InputState>,
state: Entity<DialogProgress>,
} }
impl NewIssueDialog { impl NewIssueDialog {
pub fn new(store: Entity<RepoStore>, cx: &mut App) -> Entity<Self> { pub fn new(store: Entity<RepoStore>, cx: &mut App) -> Entity<Self> {
let subject = InputState::new(cx); let subject = InputState::new(cx);
let content = InputState::builder().multiline().build(cx); let content = InputState::builder().multiline().build(cx);
let state = cx.new(|_| DialogProgress::default());
cx.new(|_| Self { cx.new(|_| Self {
handle: DialogHandle::new(true), handle: DialogHandle::new(true),
store, store,
subject, subject,
content, content,
state,
}) })
} }
fn submit(&mut self, cx: &mut Context<Self>) { fn submit(&mut self, cx: &mut Context<Self>) {
// The publish runs detached in the store; one submission per dialog.
if self.state.read(cx).busy {
return;
}
let subject = self.subject.read(cx).value().to_string(); let subject = self.subject.read(cx).value().to_string();
let content = self.content.read(cx).value().to_string(); let content = self.content.read(cx).value().to_string();
let subject = (!subject.trim().is_empty()).then_some(subject); let subject = (!subject.trim().is_empty()).then_some(subject);
self.state.update(cx, |state, _| state.begin());
self.store.update(cx, |store, cx| { self.store.update(cx, |store, cx| {
store.open_issue(subject, content, cx); store.open_issue(subject, content, cx);
}); });
@@ -48,6 +58,7 @@ impl Render for NewIssueDialog {
let subject = self.subject.clone(); let subject = self.subject.clone();
let content = self.content.clone(); let content = self.content.clone();
let this = cx.entity().downgrade(); let this = cx.entity().downgrade();
let action_state = self.state.clone();
Dialog::new("new-issue-dialog") Dialog::new("new-issue-dialog")
.handle(self.handle.clone()) .handle(self.handle.clone())
@@ -72,11 +83,14 @@ impl Render for NewIssueDialog {
) )
.into_any_element() .into_any_element()
}) })
.actions(move |_, _| { .actions(move |_, cx| {
let this = this.clone(); let this = this.clone();
let busy = action_state.read(cx).busy;
vec![ vec![
Button::new("create-issue") Button::new("create-issue")
.label("Create issue") .label("Create issue")
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| { .on_click(move |_, _, cx| {
crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx))); crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx)));
}) })
+46 -69
View File
@@ -1,13 +1,15 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle, ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle,
WeakEntity, Window, div, uniform_list, WeakEntity, Window, div,
}; };
use metadata::ProfileDirectory; use metadata::ProfileDirectory;
use nostr::prelude::{EventId, Kind, PublicKey, Url}; use nostr::prelude::{EventId, Kind, Url};
use signed_core::{GitEvent, PullRequest, RepoAddr}; use signed_core::{GitEvent, PullRequest, RepoAddr};
use signed_git::{FileCommit, PatchParser}; use signed_git::{FileCommit, PatchParser};
use signed_state::{Backend, Mirrors, RepoStore}; use signed_state::{Backend, Mirrors, RepoStore};
@@ -19,8 +21,6 @@ use ui::icons::{Icon, IconRole};
use ui::input::InputState; use ui::input::InputState;
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea; use ui::scroll_area::ScrollArea;
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::tabs::{Tab, Tabs}; use ui::tabs::{Tab, Tabs};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use utils::relative_time; use utils::relative_time;
@@ -28,7 +28,6 @@ use utils::relative_time;
use super::dialogs; use super::dialogs;
use crate::issues::helpers::{comment_form, comments_section, pr_roots, sidebar_section}; use crate::issues::helpers::{comment_form, comments_section, pr_roots, sidebar_section};
use crate::repo::commit_diff::{CommitDiffView, DiffPane}; use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::repo::helpers::commit_row;
use crate::shared::widgets::{empty_state, status_badge}; use crate::shared::widgets::{empty_state, status_badge};
use crate::workspace::Workspace; use crate::workspace::Workspace;
@@ -54,7 +53,7 @@ pub struct PullRequestDetailView {
worktree: Option<PathBuf>, worktree: Option<PathBuf>,
description: SharedString, description: SharedString,
current_commit: Option<SharedString>, current_commit: Option<SharedString>,
commits: Vec<FileCommit>, commits: Arc<Vec<FileCommit>>,
loading: bool, loading: bool,
error: Option<SharedString>, error: Option<SharedString>,
bound: Option<PrBinding>, bound: Option<PrBinding>,
@@ -96,7 +95,7 @@ impl PullRequestDetailView {
worktree: None, worktree: None,
description: SharedString::default(), description: SharedString::default(),
current_commit: None, current_commit: None,
commits: Vec::new(), commits: Arc::new(Vec::new()),
loading: true, loading: true,
error: None, error: None,
bound: None, bound: None,
@@ -112,18 +111,23 @@ impl PullRequestDetailView {
fn track_participants(&mut self, cx: &mut Context<Self>) { fn track_participants(&mut self, cx: &mut Context<Self>) {
let store = self.store.read(cx); let store = self.store.read(cx);
let mut keys: Vec<PublicKey> = store let author = store
.pull_requests .pull_requests
.iter() .iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest) .find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
.map(|root| vec![root.pubkey]) .map(|root| root.pubkey);
.unwrap_or_default(); let owner = store.announcement.as_ref().map(|a| a.owner);
keys.extend(store.comments_of(&self.pr_id).map(|comment| comment.pubkey)); let comments: Vec<_> = store
if let Some(owner) = store.announcement.as_ref().map(|a| a.owner) { .comments_of(&self.pr_id)
keys.push(owner); .map(|comment| comment.pubkey)
} .collect();
self.directory crate::shared::track_event_participants(
.update(cx, |directory, cx| directory.track(keys, cx)); author,
owner,
comments.into_iter(),
&self.directory,
cx,
);
} }
fn sync(&mut self, cx: &mut Context<Self>) { fn sync(&mut self, cx: &mut Context<Self>) {
@@ -181,6 +185,12 @@ impl PullRequestDetailView {
self.load_diff(binding, cx); self.load_diff(binding, cx);
} }
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: gpui::Task<Result<(), anyhow::Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn load_diff(&mut self, binding: PrBinding, cx: &mut Context<Self>) { fn load_diff(&mut self, binding: PrBinding, cx: &mut Context<Self>) {
self.loading = true; self.loading = true;
self.error = None; self.error = None;
@@ -266,7 +276,7 @@ impl PullRequestDetailView {
} }
this.loading = false; this.loading = false;
this.worktree = worktree; this.worktree = worktree;
this.commits = commits; this.commits = Arc::new(commits);
match diff { match diff {
Ok(diff) => this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx)), Ok(diff) => this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx)),
Err(error) => this.error = Some(error.to_string().into()), Err(error) => this.error = Some(error.to_string().into()),
@@ -275,7 +285,7 @@ impl PullRequestDetailView {
})?; })?;
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
fn open_commit_diff( fn open_commit_diff(
@@ -443,54 +453,26 @@ impl PullRequestDetailView {
if self.commits.is_empty() { if self.commits.is_empty() {
return empty_state("No commits found"); return empty_state("No commits found");
} }
let commits = self.commits.clone(); let commits = Arc::clone(&self.commits);
let worktree = self.worktree.clone(); let worktree = self.worktree.clone();
let view = cx.entity().downgrade(); let view = cx.entity().downgrade();
v_flex() crate::shared::event_list::commit_list(
.relative() "pr-commits",
.flex_1() "pr-commits-scroll",
.min_h_0() commits,
.child( self.commit_scroll_handle.clone(),
uniform_list("pr-commits", commits.len(), move |range, _, cx| { |_, _, _| None,
range move |commit, window, cx| {
.map(|ix| { if let Some(worktree) = worktree.clone() {
let commit = commits[ix].clone(); let id = commit.id.clone();
let id = commit.id.clone(); crate::shared::log_dropped(view.update(cx, |this, cx| {
let worktree = worktree.clone(); this.open_commit_diff(worktree, &id, window, cx);
let view = view.clone(); }));
commit_row( }
ix, },
&commit, cx,
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 { fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
@@ -614,10 +596,5 @@ impl Render for PullRequestDetailView {
} }
fn centered_spinner() -> AnyElement { fn centered_spinner() -> AnyElement {
v_flex() crate::shared::widgets::centered_spinner("pr-loading")
.size_full()
.items_center()
.justify_center()
.child(Spinner::new("pr-loading"))
.into_any_element()
} }
@@ -11,29 +11,39 @@ use ui::field::Field;
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use crate::shared::progress::DialogProgress;
pub struct UpdatePrDialog { pub struct UpdatePrDialog {
handle: DialogHandle, handle: DialogHandle,
store: Entity<RepoStore>, store: Entity<RepoStore>,
root: Event, root: Event,
patch: Entity<InputState>, patch: Entity<InputState>,
state: Entity<DialogProgress>,
} }
impl UpdatePrDialog { impl UpdatePrDialog {
pub fn new(store: Entity<RepoStore>, root: Event, cx: &mut App) -> Entity<Self> { pub fn new(store: Entity<RepoStore>, root: Event, cx: &mut App) -> Entity<Self> {
let patch = InputState::builder().multiline().build(cx); let patch = InputState::builder().multiline().build(cx);
let state = cx.new(|_| DialogProgress::default());
cx.new(|_| Self { cx.new(|_| Self {
handle: DialogHandle::new(true), handle: DialogHandle::new(true),
store, store,
root, root,
patch, patch,
state,
}) })
} }
fn submit(&mut self, cx: &mut Context<Self>) { fn submit(&mut self, cx: &mut Context<Self>) {
// The publish runs detached in the store; one submission per dialog.
if self.state.read(cx).busy {
return;
}
let patch = self.patch.read(cx).value().to_string(); let patch = self.patch.read(cx).value().to_string();
if patch.trim().is_empty() { if patch.trim().is_empty() {
return; return;
} }
self.state.update(cx, |state, _| state.begin());
self.store.update(cx, |store, cx| { self.store.update(cx, |store, cx| {
store.update_pull_request(&self.root, patch, cx); store.update_pull_request(&self.root, patch, cx);
}); });
@@ -45,6 +55,7 @@ impl Render for UpdatePrDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let patch = self.patch.clone(); let patch = self.patch.clone();
let this = cx.entity().downgrade(); let this = cx.entity().downgrade();
let action_state = self.state.clone();
Dialog::new("update-pr-dialog") Dialog::new("update-pr-dialog")
.handle(self.handle.clone()) .handle(self.handle.clone())
@@ -65,11 +76,14 @@ impl Render for UpdatePrDialog {
) )
.into_any_element() .into_any_element()
}) })
.actions(move |_, _| { .actions(move |_, cx| {
let this = this.clone(); let this = this.clone();
let busy = action_state.read(cx).busy;
vec![ vec![
Button::new("submit-update") Button::new("submit-update")
.label("Update pull request") .label("Update pull request")
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| { .on_click(move |_, _, cx| {
crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx))); crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx)));
}) })
@@ -55,14 +55,6 @@ impl ForkCompare {
} }
} }
pub fn fork_display_name(announcement: &Announcement) -> SharedString {
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()))
}
pub fn shorten_owner(owner: &PublicKey) -> String { pub fn shorten_owner(owner: &PublicKey) -> String {
owner.to_hex().chars().take(10).collect() owner.to_hex().chars().take(10).collect()
} }
@@ -121,7 +113,11 @@ pub fn source_menu_items(
} else { } else {
SharedString::from(format!("by {}", shorten_owner(&candidate.owner))) SharedString::from(format!("by {}", shorten_owner(&candidate.owner)))
}; };
let title = format!("{} — {}", fork_display_name(&candidate), subtitle); let title = format!(
"{} — {}",
crate::repo::helpers::announcement_display_name(&candidate),
subtitle
);
let target = view.clone(); let target = view.clone();
let checked = active_fork == Some(candidate.addr()); let checked = active_fork == Some(candidate.addr());
let announcement = candidate; let announcement = candidate;
+74 -147
View File
@@ -1,21 +1,19 @@
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, SharedString, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div,
Subscription, UniformListScrollHandle, WeakEntity, Window, div, px, uniform_list,
}; };
use metadata::ProfileDirectory; use metadata::ProfileDirectory;
use nostr::prelude::{Kind, PublicKey}; use nostr::prelude::{Kind, PublicKey};
use signed_core::GitEvent; use signed_core::GitEvent;
use signed_state::RepoStore; use signed_state::RepoStore;
use std::rc::Rc;
use ui::alert::{Alert, AlertSeverity}; use ui::alert::{Alert, AlertSeverity};
use ui::avatar::Avatar; use ui::common::v_flex;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::dropdown_menu::DropdownMenu; use ui::dropdown_menu::DropdownMenu;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::menu::MenuItem; use ui::menu::MenuItem;
use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption}; use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use utils::relative_time; use utils::relative_time;
@@ -32,11 +30,10 @@ pub use new::NewPullRequestView;
pub use send_patch::SendPatchView; pub use send_patch::SendPatchView;
use crate::issues::helpers::{StatusCounts, filter_by_status}; use crate::issues::helpers::{StatusCounts, filter_by_status};
use crate::shared::widgets::{empty_state, status_badge}; use crate::repo::helpers::short_id;
use crate::shared::event_list::{EventList, EventRow};
use crate::workspace::Workspace; use crate::workspace::Workspace;
const ROW_HEIGHT: f32 = 73.;
pub struct PullRequestsView { pub struct PullRequestsView {
workspace: WeakEntity<Workspace>, workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>, store: Entity<RepoStore>,
@@ -198,14 +195,9 @@ impl PullRequestsView {
let menu_open_weak = cx.entity().downgrade(); let menu_open_weak = cx.entity().downgrade();
let patch_weak = cx.entity().downgrade(); let patch_weak = cx.entity().downgrade();
h_flex() crate::shared::event_list::filter_toolbar(
.px_4() cx,
.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) Segmented::new("pr-filter", self.filter)
.options(vec![ .options(vec![
SegmentedOption::new( SegmentedOption::new(
@@ -241,10 +233,9 @@ impl PullRequestsView {
}) { }) {
log::warn!("failed to switch PR filter: {error}"); log::warn!("failed to switch PR filter: {error}");
} }
}), })
) .into_any_element(),
.child(div().flex_1()) div().flex_1().into_any_element(),
.child(
DropdownMenu::new("new-pr-actions") DropdownMenu::new("new-pr-actions")
.label("New") .label("New")
.icon(Icon::named(IconRole::GitPullRequest)) .icon(Icon::named(IconRole::GitPullRequest))
@@ -271,9 +262,10 @@ impl PullRequestsView {
})); }));
} }
})] })]
}), })
) .into_any_element(),
.into_any_element() ],
)
} }
} }
@@ -286,7 +278,6 @@ impl Panel for PullRequestsView {
impl Render for PullRequestsView { impl Render for PullRequestsView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let filter = self.filter; let filter = self.filter;
let count = self.visible_prs.len();
let visible = self.visible_prs.clone(); let visible = self.visible_prs.clone();
let directory = self.directory.clone(); let directory = self.directory.clone();
let store = self.store.clone(); let store = self.store.clone();
@@ -300,9 +291,60 @@ impl Render for PullRequestsView {
let dismiss_warning_store = self.store.clone(); let dismiss_warning_store = self.store.clone();
let dismiss_error_store = self.store.clone(); let dismiss_error_store = self.store.clone();
let rows = visible
.iter()
.enumerate()
.filter_map(|(ix, &pr_ix)| {
// The store re-read per frame can shrink below a captured index.
let pr = store.read(cx).pull_requests.get(pr_ix)?;
let profile = directory.read(cx).profile(&pr.pubkey, cx);
let pr_id = pr.id;
let id_hex = pr.id.to_hex();
let status = store.read(cx).status_of(pr);
let on_click: crate::shared::event_list::EventHandler = {
let workspace = workspace.clone();
let store = store.clone();
Rc::new(move |_, window, cx| {
let id = SharedString::from(format!("pr:{pr_id}"));
let workspace_for_build = workspace.clone();
let store = store.clone();
crate::shared::panels::open_detail(
&workspace,
id,
move |window, cx| {
cx.new(|cx| {
PullRequestDetailView::new(
workspace_for_build.clone(),
store.clone(),
pr_id,
window,
cx,
)
})
},
window,
cx,
);
})
};
Some(EventRow {
id: ix.into(),
status,
title: pr.activity_subject().into(),
author: profile.name(),
picture: profile.picture(),
pubkey: pr.pubkey,
short_id: short_id(&id_hex),
age: SharedString::from(relative_time(pr.created_at)),
on_click,
})
})
.collect();
v_flex() v_flex()
.size_full() .size_full()
.child(self.render_header(cx))
.when_some(last_warning, |this, warning| { .when_some(last_warning, |this, warning| {
this.child( this.child(
Alert::new("pr-warning") Alert::new("pr-warning")
@@ -326,127 +368,12 @@ impl Render for PullRequestsView {
) )
}) })
.child( .child(
v_flex() EventList::new("prl")
.relative() .toolbar(self.render_header(cx))
.flex_1() .scroll_handle(self.scroll_handle.clone())
.min_h_0() .rows(rows)
.w_full() .empty_message(filter.empty_message())
.when(count > 0, |this| { .render(cx),
this.child(
uniform_list("prl", count, move |range, _, cx| {
range
.map(|ix| {
let pr_ix = visible[ix];
let pr = &store.read(cx).pull_requests[pr_ix];
let pr_id = pr.id;
let title = pr.activity_subject();
let id_hex = pr.id.to_hex();
let age = relative_time(pr.created_at);
let status = store.read(cx).status_of(pr);
let profile = directory.read(cx).profile(&pr.pubkey, cx);
let author = profile.name();
let workspace = workspace.clone();
let store = store.clone();
h_flex()
.id(ix)
.w_full()
.h(px(ROW_HEIGHT))
.gap_4()
.px_4()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.on_click(move |_, window, cx| {
let id = SharedString::from(format!("pr:{pr_id}"));
let workspace_for_build = workspace.clone();
let store = store.clone();
crate::shared::panels::open_detail(
&workspace,
id,
move |window, cx| {
cx.new(|cx| {
PullRequestDetailView::new(
workspace_for_build.clone(),
store.clone(),
pr_id,
window,
cx,
)
})
},
window,
cx,
);
})
.child(status_badge(status))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(
div()
.text_base()
.text_ellipsis()
.whitespace_nowrap()
.child(title),
)
.child(
h_flex()
.gap_2()
.text_xs()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(pr.pubkey)
.name(author.clone())
.picture(
profile.picture(),
)
.small(),
)
.child(div().child(author)),
)
.child(SharedString::from("opened"))
.child(
div()
.text_color(
cx.theme()
.colors
.muted_foreground,
)
.child(SharedString::from(
&id_hex[..8],
)),
)
.child(SharedString::from(age)),
),
)
.into_any_element()
})
.collect()
})
.track_scroll(&self.scroll_handle)
.size_full(),
)
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(
"prl-scroll",
self.scroll_handle.clone(),
)),
)
})
.when(count == 0, |this| {
this.child(empty_state(filter.empty_message()))
}),
) )
.into_any_element() .into_any_element()
} }
+33 -65
View File
@@ -1,10 +1,12 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle, ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle,
WeakEntity, Window, div, px, uniform_list, WeakEntity, Window, div, px,
}; };
use signed_state::{CheckoutsStore, RepoStore}; use signed_state::{CheckoutsStore, RepoStore};
use ui::button::Button; use ui::button::Button;
@@ -14,14 +16,11 @@ use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::menu::Menu; use ui::menu::Menu;
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::tabs::{Tab, Tabs}; use ui::tabs::{Tab, Tabs};
use ui::theme::ActiveTheme as _;
use super::helpers::{ForkCompare, fork_display_name, truncate_label}; use super::helpers::{ForkCompare, truncate_label};
use crate::repo::commit_diff::{CommitDiffView, DiffPane}; use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::repo::helpers::commit_row; use crate::shared::progress::error_row;
use crate::shared::widgets::empty_state; use crate::shared::widgets::empty_state;
use crate::workspace::Workspace; use crate::workspace::Workspace;
@@ -41,7 +40,7 @@ pub struct NewPullRequestView {
subject: Entity<InputState>, subject: Entity<InputState>,
description: Entity<InputState>, description: Entity<InputState>,
pub(super) merge_base: Option<String>, pub(super) merge_base: Option<String>,
pub(super) commits: Option<Vec<signed_git::FileCommit>>, pub(super) commits: Option<Arc<Vec<signed_git::FileCommit>>>,
pub(super) loading: bool, pub(super) loading: bool,
pub(super) error: Option<SharedString>, pub(super) error: Option<SharedString>,
submitting: bool, submitting: bool,
@@ -159,6 +158,12 @@ impl NewPullRequestView {
} }
} }
/// Reaps finished tasks, then queues another.
pub(super) fn push_task(&mut self, task: gpui::Task<Result<(), anyhow::Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn submit(&mut self, _window: &mut Window, cx: &mut Context<Self>) { fn submit(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
if self.submitting || self.loading { if self.submitting || self.loading {
return; return;
@@ -210,7 +215,7 @@ impl NewPullRequestView {
); );
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
fn open_commit_diff(&mut self, commit_id: &str, window: &mut Window, cx: &mut Context<Self>) { fn open_commit_diff(&mut self, commit_id: &str, window: &mut Window, cx: &mut Context<Self>) {
@@ -264,7 +269,9 @@ impl NewPullRequestView {
let active_fork = self.fork.as_ref().map(|fork| fork.announcement.addr()); let active_fork = self.fork.as_ref().map(|fork| fork.announcement.addr());
let can_submit = self.submit_enabled(cx); let can_submit = self.submit_enabled(cx);
let source_label = match &self.fork { let source_label = match &self.fork {
Some(fork) => truncate_label(&fork_display_name(&fork.announcement)), Some(fork) => truncate_label(&crate::repo::helpers::announcement_display_name(
&fork.announcement,
)),
None => self.repo_path.as_ref().map_or_else( None => self.repo_path.as_ref().map_or_else(
|| SharedString::from("No source"), || SharedString::from("No source"),
|path| truncate_label(&path.display().to_string()), |path| truncate_label(&path.display().to_string()),
@@ -368,12 +375,7 @@ impl NewPullRequestView {
fn render_content(&self, cx: &mut Context<Self>) -> AnyElement { fn render_content(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading { if self.loading {
return v_flex() return crate::shared::widgets::centered_spinner("new-pr-loading");
.size_full()
.items_center()
.justify_center()
.child(Spinner::new("new-pr-loading"))
.into_any_element();
} }
if !self.has_source() { if !self.has_source() {
return empty_state("Choose a local checkout or an announced fork to compare"); return empty_state("Choose a local checkout or an announced fork to compare");
@@ -394,50 +396,23 @@ impl NewPullRequestView {
if commits.is_empty() { if commits.is_empty() {
return empty_state("No commits between the branches"); return empty_state("No commits between the branches");
} }
let commits = commits.clone(); let commits = Arc::clone(commits);
let view = cx.entity().downgrade(); let view = cx.entity().downgrade();
v_flex() crate::shared::event_list::commit_list(
.relative() "new-pr-commits",
.flex_1() "new-pr-commits-scroll",
.min_h_0() commits,
.child( self.scroll_handle.clone(),
uniform_list("new-pr-commits", commits.len(), move |range, _, cx| { |_, _, _| None,
range move |commit, window, cx| {
.map(|ix| { let id = commit.id.clone();
let commit = commits[ix].clone(); crate::shared::log_dropped(view.update(cx, |this, cx| {
let id = commit.id.clone(); this.open_commit_diff(&id, window, cx);
let view = view.clone(); }));
commit_row( },
ix, cx,
&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()
} }
} }
@@ -472,14 +447,7 @@ impl Render for NewPullRequestView {
.rows(3) .rows(3)
.placeholder("Describe..."), .placeholder("Describe..."),
) )
.when_some(self.error.clone(), |this, error| { .when_some(error_row(&self.error, cx), |this, error| this.child(error)),
this.child(
div()
.text_xs()
.text_color(cx.theme().ramps.destructive.base)
.child(error),
)
}),
) )
.child(self.render_tabs(cx)), .child(self.render_tabs(cx)),
) )
@@ -1,4 +1,5 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc;
use gpui::{App, AppContext as _, Context, PathPromptOptions, SharedString, Window}; use gpui::{App, AppContext as _, Context, PathPromptOptions, SharedString, Window};
use nostr::prelude::Url; use nostr::prelude::Url;
@@ -9,6 +10,19 @@ use signed_state::{Backend, CheckoutsStore, Mirrors, RepoListStore};
use super::NewPullRequestView; use super::NewPullRequestView;
use crate::pull_requests::helpers::ForkCompare; use crate::pull_requests::helpers::ForkCompare;
/// The announced head when listed, else `main`, else the first branch.
fn preferred_branch(branches: &[String], announced: Option<String>) -> String {
announced
.filter(|branch| branches.contains(branch))
.or_else(|| {
branches
.iter()
.find(|branch| branch.as_str() == "main")
.cloned()
})
.unwrap_or_else(|| branches[0].clone())
}
impl NewPullRequestView { impl NewPullRequestView {
pub(super) fn has_source(&self) -> bool { pub(super) fn has_source(&self) -> bool {
self.repo_path.is_some() || self.fork.is_some() self.repo_path.is_some() || self.fork.is_some()
@@ -56,7 +70,7 @@ impl NewPullRequestView {
})?; })?;
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
pub(crate) fn apply_folder_path( pub(crate) fn apply_folder_path(
@@ -93,7 +107,7 @@ impl NewPullRequestView {
})?; })?;
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
fn apply_checkout( fn apply_checkout(
@@ -126,12 +140,7 @@ impl NewPullRequestView {
} }
let announced = self.store.read(cx).head.clone(); let announced = self.store.read(cx).head.clone();
let base = announced let base = preferred_branch(&branches, 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 let compare = current
.filter(|branch| branches.contains(branch)) .filter(|branch| branches.contains(branch))
.unwrap_or_else(|| base.clone()); .unwrap_or_else(|| base.clone());
@@ -266,7 +275,7 @@ impl NewPullRequestView {
} }
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
fn apply_fork( fn apply_fork(
@@ -299,16 +308,7 @@ impl NewPullRequestView {
} }
let announced = self.store.read(cx).head.clone(); let announced = self.store.read(cx).head.clone();
let base = announced let base = preferred_branch(&base_branches, 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 let compare = compare_branches
.iter() .iter()
.find(|branch| branch.as_str() == "main") .find(|branch| branch.as_str() == "main")
@@ -321,7 +321,7 @@ impl NewPullRequestView {
mirror_path, mirror_path,
}); });
self.error = None; self.error = None;
self.base = base; self.base = SharedString::from(base);
self.compare = compare; self.compare = compare;
self.branches = base_branches.into_iter().map(SharedString::from).collect(); self.branches = base_branches.into_iter().map(SharedString::from).collect();
self.sync_selectors(window, cx); self.sync_selectors(window, cx);
@@ -378,7 +378,7 @@ impl NewPullRequestView {
match result { match result {
Ok((merge_base, commits, diff)) => { Ok((merge_base, commits, diff)) => {
this.merge_base = Some(merge_base); this.merge_base = Some(merge_base);
this.commits = Some(commits); this.commits = Some(Arc::new(commits));
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx)); this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
} }
Err(error) => { Err(error) => {
@@ -392,6 +392,6 @@ impl NewPullRequestView {
})?; })?;
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
} }
@@ -5,12 +5,13 @@ use gpui::{
}; };
use signed_state::RepoStore; use signed_state::RepoStore;
use ui::button::Button; use ui::button::Button;
use ui::common::{h_flex, v_flex}; use ui::common::{ResultLogErr as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use crate::shared::progress::error_row;
use crate::workspace::Workspace; use crate::workspace::Workspace;
pub struct SendPatchView { pub struct SendPatchView {
@@ -65,7 +66,7 @@ impl SendPatchView {
self.error = None; self.error = None;
cx.notify(); cx.notify();
let sync_error = self.store.update(cx, |store, cx| { let task = self.store.update(cx, |store, cx| {
store.open_pull_request( store.open_pull_request(
(!subject.is_empty()).then_some(subject), (!subject.is_empty()).then_some(subject),
description, description,
@@ -75,22 +76,30 @@ impl SendPatchView {
None, None,
None, None,
cx, cx,
); )
store.last_error.clone()
}); });
if let Some(error) = sync_error { cx.spawn(async move |this, cx| match task.await {
self.submitting = false; Ok(()) => {
self.error = Some(error.into()); this.update(cx, |this, cx| {
cx.notify(); let panel_id = this.panel_id.clone();
return; crate::shared::log_dropped(
} this.workspace
.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)),
let panel_id = self.panel_id.clone(); );
crate::shared::log_dropped( })
self.workspace .log_err();
.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)), }
); Err(error) => {
this.update(cx, |this, cx| {
this.submitting = false;
this.error = Some(error.to_string().into());
cx.notify();
})
.log_err();
}
})
.detach();
} }
fn render_footer(&self, cx: &Context<Self>) -> AnyElement { fn render_footer(&self, cx: &Context<Self>) -> AnyElement {
@@ -159,14 +168,7 @@ impl Render for SendPatchView {
.rows(12) .rows(12)
.placeholder("diff --git a/file.txt b/file.txt"), .placeholder("diff --git a/file.txt b/file.txt"),
) )
.when_some(self.error.clone(), |this, error| { .when_some(error_row(&self.error, cx), |this, error| this.child(error)),
this.child(
div()
.text_xs()
.text_color(cx.theme().ramps.destructive.base)
.child(error),
)
}),
) )
.child(self.render_footer(cx)) .child(self.render_footer(cx))
} }
+2 -1
View File
@@ -88,6 +88,7 @@ pub fn open_repo_item(
cx, cx,
); );
} }
RepoItem::Patch => {} // Opening a patch series directly is not a feature.
_ => {}
} }
} }
+16 -27
View File
@@ -14,8 +14,6 @@ use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::layout::resizable::{Resizable, ResizableState}; use ui::layout::resizable::{Resizable, ResizableState};
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use ui::tree::{Tree, TreeItem}; use ui::tree::{Tree, TreeItem};
use utils::relative_time_secs; use utils::relative_time_secs;
@@ -257,18 +255,10 @@ impl DiffPane {
.track_scroll(&self.scroll_handle) .track_scroll(&self.scroll_handle)
.size_full(), .size_full(),
) )
.child( .child(crate::shared::widgets::scroll_overlay(
div() "commit-diff-scroll",
.absolute() self.scroll_handle.clone(),
.top_0() ))
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(
"commit-diff-scroll",
self.scroll_handle.clone(),
)),
)
.into_any_element() .into_any_element()
}; };
@@ -304,14 +294,12 @@ impl DiffPane {
.gap_2() .gap_2()
.text_xs() .text_xs()
.child( .child(
div() Badge::new("file-insertions", format!("+ {}", file.insertions))
.text_color(cx.theme().ramps.success.base) .variant(BadgeVariant::Success),
.child(format!("+{}", file.insertions)),
) )
.child( .child(
div() Badge::new("file-deletions", format!("- {}", file.deletions))
.text_color(cx.theme().ramps.destructive.base) .variant(BadgeVariant::Danger),
.child(format!("-{}", file.deletions)),
), ),
) )
}), }),
@@ -381,6 +369,12 @@ impl CommitDiffView {
} }
} }
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), anyhow::Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn load(&mut self, window: &mut Window, cx: &mut Context<Self>) { fn load(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.loading = true; self.loading = true;
self.error = None; self.error = None;
@@ -424,7 +418,7 @@ impl CommitDiffView {
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement { fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
@@ -513,12 +507,7 @@ impl Panel for CommitDiffView {
impl Render for CommitDiffView { impl Render for CommitDiffView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let body: AnyElement = if self.loading { let body: AnyElement = if self.loading {
v_flex() crate::shared::widgets::centered_spinner("commit-diff-loading")
.size_full()
.items_center()
.justify_center()
.child(Spinner::new("commit-diff-loading"))
.into_any_element()
} else if let Some(error) = self.error.clone() { } else if let Some(error) = self.error.clone() {
empty_state(error) empty_state(error)
} else { } else {
+23 -20
View File
@@ -8,7 +8,7 @@ use gpui::{
use settings::SettingsStore; use settings::SettingsStore;
use signed_state::{Backend, CheckoutsStore}; use signed_state::{Backend, CheckoutsStore};
use ui::button::{Button, ButtonVariant}; use ui::button::{Button, ButtonVariant};
use ui::common::{h_flex, v_flex}; use ui::common::{ResultLogErr as _, h_flex, v_flex};
use ui::dialog::{Dialog, DialogHandle}; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
@@ -17,7 +17,7 @@ use ui::tooltip::Tooltip;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::repo::actions::open_repo_panel; use crate::repo::actions::open_repo_panel;
use crate::shared::progress::{DialogProgress, error_row, push_steps_row}; use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with};
use crate::workspace::Workspace; use crate::workspace::Workspace;
/// Progress of the create-repository flow, so async results can be rendered. /// Progress of the create-repository flow, so async results can be rendered.
@@ -94,17 +94,26 @@ impl CreateRepoDialog {
let servers = self.grasp_state.read(cx).grasp_servers.clone(); let servers = self.grasp_state.read(cx).grasp_servers.clone();
if name.is_empty() { if name.is_empty() {
self.fail("Repository name is required", cx); self.state.update(cx, |state, cx| {
state.fail("Repository name is required");
cx.notify();
});
return; return;
} }
if servers.is_empty() { if servers.is_empty() {
self.fail("Add at least one grasp server", cx); self.state.update(cx, |state, cx| {
state.fail("Add at least one grasp server");
cx.notify();
});
return; return;
} }
let backend = Backend::global(cx); let backend = Backend::global(cx);
let Some(user) = backend.read(cx).current_user() else { let Some(user) = backend.read(cx).current_user() else {
self.fail("Sign in to create a repository", cx); self.state.update(cx, |state, cx| {
state.fail("Sign in to create a repository");
cx.notify();
});
return; return;
}; };
@@ -123,8 +132,10 @@ impl CreateRepoDialog {
let close = self.handle.clone(); let close = self.handle.clone();
let handle = window.window_handle(); let handle = window.window_handle();
cx.spawn(async move |_this, cx| match task.await { run_dialog_task_with(
Ok((announcement, local_path)) => { task,
cx,
move |(announcement, local_path), cx| {
cx.update_window(handle, |_, window, cx| { cx.update_window(handle, |_, window, cx| {
let checkouts = CheckoutsStore::global(cx); let checkouts = CheckoutsStore::global(cx);
checkouts.update(cx, |store, cx| { checkouts.update(cx, |store, cx| {
@@ -140,23 +151,15 @@ impl CreateRepoDialog {
); );
close.close(cx); close.close(cx);
}) })
.ok(); .log_err();
} },
Err(error) => { move |error, cx| {
state.update(cx, |state, cx| { state.update(cx, |state, cx| {
state.fail(error.to_string()); state.fail(error.to_string());
cx.notify(); cx.notify();
}); });
} },
}) );
.detach();
}
fn fail(&mut self, message: impl Into<gpui::SharedString>, cx: &mut Context<Self>) {
self.state.update(cx, |state, cx| {
state.fail(message);
cx.notify();
});
} }
} }
@@ -13,6 +13,8 @@ use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip; use ui::tooltip::Tooltip;
use crate::shared::progress::error_row;
/// State of the grasp-server section of a publish dialog, so async results can be rendered. /// State of the grasp-server section of a publish dialog, so async results can be rendered.
#[derive(Default)] #[derive(Default)]
pub struct GraspServersState { pub struct GraspServersState {
@@ -137,14 +139,7 @@ pub fn grasp_servers_field(
.child("Loading your grasp servers..."), .child("Loading your grasp servers..."),
) )
}) })
.when_some(error, |section, error| { .when_some(error_row(&error, cx), |section, error| section.child(error))
section.child(
div()
.text_xs()
.text_color(cx.theme().ramps.destructive.base)
.child(error),
)
})
}) })
.into_any_element() .into_any_element()
} }
@@ -155,6 +150,7 @@ fn render_server_row(
state: Entity<GraspServersState>, state: Entity<GraspServersState>,
cx: &App, cx: &App,
) -> AnyElement { ) -> AnyElement {
let relay = relay.clone();
h_flex() h_flex()
.w_full() .w_full()
.gap_1() .gap_1()
@@ -168,7 +164,7 @@ fn render_server_row(
.text_color(cx.theme().colors.muted_foreground) .text_color(cx.theme().colors.muted_foreground)
.text_xs() .text_xs()
.rounded(cx.theme().radius.control) .rounded(cx.theme().radius.control)
.child(server_host(relay)), .child(server_host(&relay)),
) )
.child( .child(
Button::new(SharedString::from(format!("remove-relay:{ix}"))) Button::new(SharedString::from(format!("remove-relay:{ix}")))
@@ -176,9 +172,12 @@ fn render_server_row(
.variant(ButtonVariant::Ghost) .variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove")) .tooltip(Tooltip::text("Remove"))
.on_click(move |_, _, cx| { .on_click(move |_, _, cx| {
// A row's index can desync after a prior removal; match by value.
state.update(cx, |state, cx| { state.update(cx, |state, cx| {
if ix < state.grasp_servers.len() { if let Some(at) =
state.grasp_servers.remove(ix); state.grasp_servers.iter().position(|known| known == &relay)
{
state.grasp_servers.remove(at);
cx.notify(); cx.notify();
} }
}); });
+35 -23
View File
@@ -10,7 +10,7 @@ use signed_core::RepoAddr;
use signed_git::Repo; use signed_git::Repo;
use signed_state::Backend; use signed_state::Backend;
use ui::button::Button; use ui::button::Button;
use ui::common::v_flex; use ui::common::{ResultLogErr as _, v_flex};
use ui::dialog::{Dialog, DialogHandle}; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
@@ -20,7 +20,7 @@ use ui::theme::ActiveTheme as _;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::repo::RepoDetailView; use crate::repo::RepoDetailView;
use crate::shared::progress::{DialogProgress, error_row, push_steps_row}; use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with};
pub struct InitRepoDialog { pub struct InitRepoDialog {
handle: DialogHandle, handle: DialogHandle,
@@ -105,17 +105,26 @@ impl InitRepoDialog {
.filter(|branch| !branch.is_empty()); .filter(|branch| !branch.is_empty());
if name.is_empty() { if name.is_empty() {
self.fail("Repository name is required", cx); self.state.update(cx, |state, cx| {
state.fail("Repository name is required");
cx.notify();
});
return; return;
} }
if servers.is_empty() { if servers.is_empty() {
self.fail("Add at least one grasp server", cx); self.state.update(cx, |state, cx| {
state.fail("Add at least one grasp server");
cx.notify();
});
return; return;
} }
let backend = Backend::global(cx); let backend = Backend::global(cx);
let Some(user) = backend.read(cx).current_user() else { let Some(user) = backend.read(cx).current_user() else {
self.fail("Sign in to publish a repository", cx); self.state.update(cx, |state, cx| {
state.fail("Sign in to publish a repository");
cx.notify();
});
return; return;
}; };
@@ -134,31 +143,25 @@ impl InitRepoDialog {
let close = self.handle.clone(); let close = self.handle.clone();
let handle = window.window_handle(); let handle = window.window_handle();
cx.spawn(async move |_this, cx| match task.await { run_dialog_task_with(
Ok(announcement) => { task,
cx,
move |announcement, cx| {
cx.update_window(handle, |_, _window, cx| { cx.update_window(handle, |_, _window, cx| {
close.close(cx); close.close(cx);
if let Some(view) = view.upgrade() { if let Some(view) = view.upgrade() {
view.update(cx, |this, cx| this.apply_announcement(announcement, cx)); view.update(cx, |this, cx| this.apply_announcement(announcement, cx));
} }
}) })
.ok(); .log_err();
} },
Err(error) => { move |error, cx| {
state.update(cx, |state, cx| { state.update(cx, |state, cx| {
state.fail(error.to_string()); state.fail(error.to_string());
cx.notify(); cx.notify();
}); });
} },
}) );
.detach();
}
fn fail(&mut self, message: impl Into<SharedString>, cx: &mut Context<Self>) {
self.state.update(cx, |state, cx| {
state.fail(message);
cx.notify();
});
} }
} }
@@ -271,9 +274,18 @@ fn load_branches(dialog: Entity<InitRepoDialog>, cx: &mut App) {
}) })
.await; .await;
let Ok((branches, current)) = loaded else { let (branches, current) = match loaded {
log::warn!("failed to list branches for the default branch selector"); Ok(loaded) => loaded,
return; Err(error) => {
log::warn!("failed to list branches for the default branch selector: {error}");
dialog.update(cx, |dialog, cx| {
dialog.state.update(cx, |state, cx| {
state.fail("Could not list the repository's branches");
cx.notify();
});
});
return;
}
}; };
dialog.update(cx, |dialog, cx| { dialog.update(cx, |dialog, cx| {
+31 -7
View File
@@ -1,25 +1,31 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div, px, Styled as _, Window, div, px,
}; };
use signed_state::RepoStore; use signed_state::RepoStore;
use ui::button::{Button, ButtonVariant}; use ui::button::{Button, ButtonVariant};
use ui::common::v_flex; use ui::common::{ResultLogErr as _, v_flex};
use ui::dialog::{Dialog, DialogHandle}; use ui::dialog::{Dialog, DialogHandle};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use crate::shared::progress::{DialogProgress, error_row};
pub struct ResetRemoteDialog { pub struct ResetRemoteDialog {
handle: DialogHandle, handle: DialogHandle,
store: Entity<RepoStore>, store: Entity<RepoStore>,
deleted: Vec<String>, deleted: Vec<String>,
state: Entity<DialogProgress>,
} }
impl ResetRemoteDialog { impl ResetRemoteDialog {
pub fn new(store: Entity<RepoStore>, deleted: Vec<String>, cx: &mut App) -> Entity<Self> { pub fn new(store: Entity<RepoStore>, deleted: Vec<String>, cx: &mut App) -> Entity<Self> {
let state = cx.new(|_| DialogProgress::default());
cx.new(|_| Self { cx.new(|_| Self {
handle: DialogHandle::new(true), handle: DialogHandle::new(true),
store, store,
deleted, deleted,
state,
}) })
} }
} }
@@ -30,12 +36,16 @@ impl Render for ResetRemoteDialog {
let store = self.store.clone(); let store = self.store.clone();
let cancel_close = self.handle.clone(); let cancel_close = self.handle.clone();
let confirm_close = self.handle.clone(); let confirm_close = self.handle.clone();
let content_state = self.state.clone();
let action_state = self.state.clone();
Dialog::new("reset-remote-dialog") Dialog::new("reset-remote-dialog")
.handle(self.handle.clone()) .handle(self.handle.clone())
.min_width(px(480.)) .min_width(px(480.))
.title("Reset remote to local") .title("Reset remote to local")
.content(move |_, cx| { .content(move |_, cx| {
let progress = content_state.read(cx);
v_flex() v_flex()
.gap_2() .gap_2()
.child( .child(
@@ -60,12 +70,15 @@ impl Render for ResetRemoteDialog {
})) }))
.into_any_element() .into_any_element()
}) })
.when_some(error_row(&progress.error, cx), |el, error| el.child(error))
.into_any_element() .into_any_element()
}) })
.actions(move |_, _| { .actions(move |_, cx| {
let busy = action_state.read(cx).busy;
let store = store.clone(); let store = store.clone();
let cancel_close = cancel_close.clone(); let cancel_close = cancel_close.clone();
let confirm_close = confirm_close.clone(); let confirm_close = confirm_close.clone();
let confirm_state = action_state.clone();
let cancel: AnyElement = Button::new("cancel-reset-remote") let cancel: AnyElement = Button::new("cancel-reset-remote")
.label("Cancel") .label("Cancel")
@@ -76,15 +89,26 @@ impl Render for ResetRemoteDialog {
let confirm: AnyElement = Button::new("confirm-reset-remote") let confirm: AnyElement = Button::new("confirm-reset-remote")
.label("Reset remote") .label("Reset remote")
.variant(ButtonVariant::Destructive) .variant(ButtonVariant::Destructive)
.on_click(move |_, _, cx| { .loading(busy)
.disabled(busy)
.on_click(move |_, window, cx| {
let task = store.update(cx, |store, cx| store.reset_repository(cx)); let task = store.update(cx, |store, cx| store.reset_repository(cx));
cx.spawn(async move |_cx| { let state = confirm_state.clone();
if let Err(error) = task.await { let close = confirm_close.clone();
log::error!("failed to reset remote: {error:#}"); let handle = window.window_handle();
cx.spawn(async move |cx| match task.await {
Ok(()) => {
cx.update_window(handle, |_, _, cx| close.close(cx))
.log_err();
}
Err(error) => {
state.update(cx, |state, cx| {
state.fail(error.to_string());
cx.notify();
});
} }
}) })
.detach(); .detach();
confirm_close.close(cx);
}) })
.into_any_element(); .into_any_element();
+15 -2
View File
@@ -493,6 +493,12 @@ impl RepoFilesView {
.into_any_element() .into_any_element()
} }
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn open_file(&mut self, path: &str, window: &mut Window, cx: &mut Context<Self>) { fn open_file(&mut self, path: &str, window: &mut Window, cx: &mut Context<Self>) {
self.selected_file = Some(path.into()); self.selected_file = Some(path.into());
@@ -528,7 +534,14 @@ impl RepoFilesView {
return; return;
}; };
// Tree paths originate from git, so symlink escapes are accepted; only
// crafted components are rejected, and visibly.
if unsafe_path { if unsafe_path {
self.files.insert(
path.to_string(),
FileContent::Failed("Cannot open file".into()),
);
cx.notify();
return; return;
} }
@@ -600,7 +613,7 @@ impl RepoFilesView {
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
fn drop_preview_of(&mut self, path: &str) { fn drop_preview_of(&mut self, path: &str) {
@@ -705,6 +718,6 @@ impl RepoFilesView {
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
} }
+2 -3
View File
@@ -17,10 +17,9 @@ use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip; use ui::tooltip::Tooltip;
use utils::relative_time_secs; use utils::relative_time_secs;
use super::helpers::{ use super::helpers::{bound_repo_label, clone_group, fork_row, nostr_clone_url, repo_display_name};
bound_repo_label, clone_group, clone_row, fork_row, nostr_clone_url, repo_display_name,
};
use super::{RepoDetailView, actions, dialogs}; use super::{RepoDetailView, actions, dialogs};
use crate::shared::widgets::clone_row;
impl RepoDetailView { impl RepoDetailView {
pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context<Self>) { pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+34 -43
View File
@@ -9,10 +9,9 @@ use gpui::{
use metadata::ProfileDirectory; use metadata::ProfileDirectory;
use nostr::prelude::{RelayUrl, ToBech32}; use nostr::prelude::{RelayUrl, ToBech32};
use signed_core::Announcement; use signed_core::Announcement;
use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo}; use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo, WorktreeSnapshot};
use signed_state::{Nip34Binding, RepoListStore, RepoStore}; use signed_state::{Nip34Binding, RepoListStore, RepoStore};
use ui::avatar::Avatar; use ui::avatar::Avatar;
use ui::clipboard::ClipboardButton;
use ui::combobox::ComboboxState; use ui::combobox::ComboboxState;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
@@ -20,12 +19,36 @@ use ui::theme::ActiveTheme as _;
use utils::relative_time_secs; use utils::relative_time_secs;
use super::RepoDetailView; use super::RepoDetailView;
use crate::shared::tree::{TreeItemSeed, build_tree_items}; use crate::shared::tree::{TreeItemSeed, build_tree_items, sorted_worktree_paths};
const GUTTER_WIDTH: f32 = 44.; const GUTTER_WIDTH: f32 = 44.;
pub const DIFF_ROW_HEIGHT: f32 = 20.; pub const DIFF_ROW_HEIGHT: f32 = 20.;
pub const COMMIT_ROW_HEIGHT: f32 = 56.; pub const COMMIT_ROW_HEIGHT: f32 = 56.;
/// The announcement's name, falling back to its id.
pub fn announcement_display_name(announcement: &Announcement) -> SharedString {
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()))
}
/// The first eight hex characters of an object id, for row labels.
pub fn short_id(hex: &str) -> SharedString {
SharedString::from(hex.get(..8).unwrap_or(hex).to_owned())
}
/// Snapshots the worktree and derives the explorer's tree rows and paths.
pub(super) fn snapshot_worktree(
worktree: PathBuf,
) -> Result<(WorktreeSnapshot, Vec<TreeItemSeed>, Vec<String>), Error> {
let snapshot = Repo::open(&worktree)?.snapshot()?;
let tree = build_tree_items(&snapshot.entries);
let paths = sorted_worktree_paths(&snapshot.entries);
Ok((snapshot, tree, paths))
}
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub(super) enum DiffRow { pub(super) enum DiffRow {
Hunk { Hunk {
@@ -67,32 +90,7 @@ pub(super) fn clone_group(
.font_semibold() .font_semibold()
.child(SharedString::from(label)), .child(SharedString::from(label)),
) )
.child(clone_row(id, command.clone(), cx)) .child(crate::shared::widgets::clone_row(id, command.clone(), cx))
.into_any_element()
}
/// One copyable clone command with its text visible next to the copy icon.
pub(super) fn clone_row(id: SharedString, command: SharedString, cx: &App) -> AnyElement {
h_flex()
.h_8()
.px_2()
.gap_2()
.min_w_0()
.bg(cx.theme().colors.secondary)
.rounded(cx.theme().radius.control)
.text_color(cx.theme().colors.secondary_foreground)
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.font_family(cx.theme().mono_font)
.text_xs()
.child(command.clone()),
)
.child(ClipboardButton::new(id, command).xsmall())
.into_any_element() .into_any_element()
} }
@@ -193,13 +191,7 @@ pub fn repo_display_name(store: &RepoStore) -> SharedString {
store store
.announcement .announcement
.as_ref() .as_ref()
.map(|announcement| { .map(announcement_display_name)
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()))
})
.unwrap_or_default() .unwrap_or_default()
} }
@@ -253,12 +245,7 @@ pub(super) fn source_hash(text: &str) -> u64 {
} }
pub(super) fn preview_spinner() -> AnyElement { pub(super) fn preview_spinner() -> AnyElement {
v_flex() crate::shared::widgets::centered_spinner("repo-preview-spinner")
.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. /// The kit grammar for a path; only four languages are supported.
@@ -330,7 +317,11 @@ pub(super) fn render_diff_row(hunks: &[DiffHunk], row: DiffRow, cx: &App) -> Any
old_start, old_lines, new_start, new_lines old_start, old_lines, new_start, new_lines
))) )))
.into_any_element(), .into_any_element(),
DiffRow::Line { hunk, line } => render_diff_line(&hunks[hunk].lines[line], cx), DiffRow::Line { hunk, line } => match hunks.get(hunk).and_then(|h| h.lines.get(line)) {
Some(line) => render_diff_line(line, cx),
// A stale row index renders as a blank row rather than panicking.
None => div().w_full().h(px(DIFF_ROW_HEIGHT)).into_any_element(),
},
} }
} }
+95 -83
View File
@@ -1,24 +1,24 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::Error; use anyhow::Error;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString,
Styled as _, Task, UniformListScrollHandle, WeakEntity, Window, div, uniform_list, Styled as _, Task, UniformListScrollHandle, WeakEntity, Window, div,
}; };
use signed_git::{CommitList, Repo}; use signed_git::{CommitList, FileCommit, Repo};
use signed_state::{Backend, RepoStore, SyncStatusDirectory}; use signed_state::{Backend, RepoStore, SyncStatusDirectory};
use ui::alert::{Alert, AlertSeverity, AlertStyle};
use ui::button::{Button, ButtonVariant}; use ui::button::{Button, ButtonVariant};
use ui::common::{Sizable as _, v_flex}; use ui::common::{Sizable as _, v_flex};
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip; use ui::tooltip::Tooltip;
use super::RepoDetailView; use super::RepoDetailView;
use super::commit_diff::CommitDiffView; use super::commit_diff::CommitDiffView;
use super::helpers::commit_row; use crate::shared::event_list::commit_list;
use crate::shared::panels; use crate::shared::panels;
use crate::workspace::Workspace; use crate::workspace::Workspace;
@@ -28,8 +28,12 @@ pub struct RepoHistoryView {
detail: WeakEntity<RepoDetailView>, detail: WeakEntity<RepoDetailView>,
sync_directory: Entity<SyncStatusDirectory>, sync_directory: Entity<SyncStatusDirectory>,
worktree: Option<PathBuf>, worktree: Option<PathBuf>,
all_commits: Option<CommitList>, all_commits: Option<Arc<CommitList>>,
loading_all_commits: bool, loading_all_commits: bool,
/// The loaded commit list, shared with the render without a per-frame copy.
commits: Arc<Vec<FileCommit>>,
/// The last load failure, shown instead of the empty list.
error: Option<SharedString>,
scroll_handle: UniformListScrollHandle, scroll_handle: UniformListScrollHandle,
tasks: Vec<Task<Result<(), Error>>>, tasks: Vec<Task<Result<(), Error>>>,
} }
@@ -49,6 +53,8 @@ impl RepoHistoryView {
worktree: None, worktree: None,
all_commits: None, all_commits: None,
loading_all_commits: false, loading_all_commits: false,
commits: Arc::new(Vec::new()),
error: None,
scroll_handle: UniformListScrollHandle::new(), scroll_handle: UniformListScrollHandle::new(),
tasks: Vec::new(), tasks: Vec::new(),
} }
@@ -74,6 +80,12 @@ impl RepoHistoryView {
self.load(cx); self.load(cx);
} }
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn load(&mut self, cx: &mut Context<Self>) { fn load(&mut self, cx: &mut Context<Self>) {
if self.loading_all_commits || self.all_commits.is_some() { if self.loading_all_commits || self.all_commits.is_some() {
return; return;
@@ -93,8 +105,13 @@ impl RepoHistoryView {
.await; .await;
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
if let Ok(list) = result { match result {
this.all_commits = Some(list); Ok(list) => {
this.commits = Arc::new(list.commits.clone());
this.all_commits = Some(Arc::new(list));
this.error = None;
}
Err(error) => this.error = Some(error.to_string().into()),
} }
this.loading_all_commits = false; this.loading_all_commits = false;
cx.notify(); cx.notify();
@@ -103,7 +120,7 @@ impl RepoHistoryView {
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
pub fn open_commit_diff( pub fn open_commit_diff(
@@ -140,22 +157,39 @@ impl Render for RepoHistoryView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(list) = self.all_commits.as_ref() else { let Some(list) = self.all_commits.as_ref() else {
return if self.loading_all_commits { return if self.loading_all_commits {
crate::shared::widgets::centered_spinner("commits-loading")
} else if let Some(error) = self.error.clone() {
let weak = cx.entity().downgrade();
v_flex() v_flex()
.size_full() .size_full()
.items_center() .items_center()
.justify_center() .justify_center()
.child(Spinner::new("commits-loading")) .child(
Alert::new("commits-error")
.severity(AlertSeverity::Danger)
.title("Failed to load commits")
.message(error)
.style(AlertStyle::Inline)
.on_dismiss(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.error = None;
cx.notify();
}) {
log::warn!("failed to dismiss commits error: {error}");
}
}),
)
.into_any_element() .into_any_element()
} else { } else {
crate::shared::widgets::empty_state("Failed to load commits") crate::shared::widgets::empty_state("Failed to load commits")
}; };
}; };
if list.commits.is_empty() { if self.commits.is_empty() {
return crate::shared::widgets::empty_state("No commits found"); return crate::shared::widgets::empty_state("No commits found");
} }
let commits = list.commits.clone(); let commits = Arc::clone(&self.commits);
let shown = commits.len(); let shown = commits.len();
let total = list.total; let total = list.total;
let view = cx.entity().downgrade(); let view = cx.entity().downgrade();
@@ -180,70 +214,60 @@ impl Render for RepoHistoryView {
let pushing = self.store.read(cx).pushing; let pushing = self.store.read(cx).pushing;
let list = commit_list(
"commits",
"commits-scroll",
commits,
self.scroll_handle.clone(),
move |ix, commit, _| {
ahead
.iter()
.find(|(id, _)| id.starts_with(commit.id.as_str()))
.map(|(ahead_id, path)| {
let detail = detail.clone();
let path = path.clone();
let target = ahead_id.clone();
let short = commit.id.clone();
Button::new(("sync-commit", ix))
.label("Sync")
.icon(Icon::named(IconRole::ArrowUp))
.variant(ButtonVariant::Secondary)
.small()
.disabled(pushing)
.tooltip(Tooltip::text(format!("Sync up to {short}")))
.on_click(move |_, window, cx| {
cx.stop_propagation();
if let Some(detail) = detail.upgrade() {
detail.update(cx, |this, cx| {
this.sync_checkout_commit(
path.clone(),
target.clone(),
window,
cx,
);
});
}
})
.into_any_element()
})
},
move |commit, window, cx| {
if let Err(error) = view.update(cx, |this, cx| {
this.open_commit_diff(&commit.id, window, cx);
}) {
log::warn!("failed to open commit diff: {error}");
}
},
cx,
);
v_flex() v_flex()
.relative() .relative()
.flex_1() .flex_1()
.w_full() .w_full()
.min_h_0() .min_h_0()
.child( .child(list)
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| { .when(shown < total, |this| {
this.child( this.child(
div() div()
@@ -254,18 +278,6 @@ impl Render for RepoHistoryView {
.child(format!("Showing {shown} of {total} commits")), .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() .into_any_element()
} }
} }
+6 -20
View File
@@ -38,14 +38,14 @@ pub mod history;
pub mod refs; pub mod refs;
use files::RepoFilesView; use files::RepoFilesView;
use helpers::{RepoData, load_repo_data}; use helpers::{RepoData, announcement_display_name, load_repo_data, snapshot_worktree};
use history::RepoHistoryView; use history::RepoHistoryView;
use refs::RefSwitcher; use refs::RefSwitcher;
use crate::issues::IssuesView; use crate::issues::IssuesView;
use crate::pull_requests::PullRequestsView; use crate::pull_requests::PullRequestsView;
use crate::shared::log_dropped; use crate::shared::log_dropped;
use crate::shared::tree::{build_tree_items, sorted_worktree_paths}; use crate::shared::tree::sorted_worktree_paths;
use crate::workspace::Workspace; use crate::workspace::Workspace;
#[derive(Clone, Copy, PartialEq, Eq)] #[derive(Clone, Copy, PartialEq, Eq)]
@@ -685,12 +685,7 @@ impl RepoDetailView {
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| { let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let result = cx let result = cx
.background_spawn(async move { .background_spawn(async move { snapshot_worktree(worktree) })
let snapshot = Repo::open(&worktree)?.snapshot()?;
let tree = build_tree_items(&snapshot.entries);
let paths = sorted_worktree_paths(&snapshot.entries);
Ok::<_, Error>((snapshot, tree, paths))
})
.await; .await;
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
@@ -734,12 +729,7 @@ impl RepoDetailView {
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| { let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let result = cx let result = cx
.background_spawn(async move { .background_spawn(async move { snapshot_worktree(worktree) })
let snapshot = Repo::open(&worktree)?.snapshot()?;
let tree = build_tree_items(&snapshot.entries);
let paths = sorted_worktree_paths(&snapshot.entries);
Ok::<_, Error>((snapshot, tree, paths))
})
.await; .await;
this.update(cx, |this, cx| match result { this.update(cx, |this, cx| match result {
@@ -838,7 +828,7 @@ impl RepoDetailView {
match result { match result {
Ok(()) => { Ok(()) => {
if let Some(tag) = &tag { if let Some(tag) = &tag {
let short = commit.chars().take(7).collect::<String>(); let short = crate::repo::helpers::short_id(&commit);
let (title, body) = match store.read(cx).last_push_warning.clone() { let (title, body) = match store.read(cx).last_push_warning.clone() {
Some(warning) => ("Sync partially failed", warning), Some(warning) => ("Sync partially failed", warning),
None => ("Sync complete", format!("Synced up to {short}")), None => ("Sync complete", format!("Synced up to {short}")),
@@ -1047,11 +1037,7 @@ impl Panel for RepoDetailView {
return SharedString::from(name.to_string_lossy().into_owned()); return SharedString::from(name.to_string_lossy().into_owned());
} }
if let Some(announcement) = store.announcement.as_ref() { if let Some(announcement) = store.announcement.as_ref() {
return announcement return announcement_display_name(announcement);
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()));
} }
SharedString::from("Repository") SharedString::from("Repository")
} }
+23 -3
View File
@@ -118,6 +118,7 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
v_flex() v_flex()
.gap_2() .gap_2()
.children(servers.iter().enumerate().map(|(ix, server)| { .children(servers.iter().enumerate().map(|(ix, server)| {
let server = server.clone();
h_flex() h_flex()
.gap_1() .gap_1()
.child( .child(
@@ -129,7 +130,7 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
.text_color(cx.theme().colors.muted_foreground) .text_color(cx.theme().colors.muted_foreground)
.text_xs() .text_xs()
.rounded(cx.theme().radius.control) .rounded(cx.theme().radius.control)
.child(display_server(server)), .child(display_server(&server)),
) )
.child( .child(
Button::new(format!("settings-remove-server:{ix}")) Button::new(format!("settings-remove-server:{ix}"))
@@ -142,7 +143,16 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
store.update(cx, |store, cx| { store.update(cx, |store, cx| {
store.edit( store.edit(
|settings| { |settings| {
settings.grasp_servers.default_servers.remove(ix); // A row's index can desync after a prior
// removal; match by value.
if let Some(at) = settings
.grasp_servers
.default_servers
.iter()
.position(|known| known == &server)
{
settings.grasp_servers.default_servers.remove(at);
}
}, },
cx, cx,
); );
@@ -218,6 +228,7 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement {
v_flex() v_flex()
.gap_2() .gap_2()
.children(scan_paths.iter().enumerate().map(|(ix, path)| { .children(scan_paths.iter().enumerate().map(|(ix, path)| {
let path = path.clone();
h_flex() h_flex()
.gap_1() .gap_1()
.child( .child(
@@ -241,7 +252,16 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement {
store.update(cx, |store, cx| { store.update(cx, |store, cx| {
store.edit( store.edit(
|settings| { |settings| {
settings.local_repos.scan_paths.remove(ix); // A row's index can desync after a prior
// removal; match by value.
if let Some(at) = settings
.local_repos
.scan_paths
.iter()
.position(|known| known == &path)
{
settings.local_repos.scan_paths.remove(at);
}
}, },
cx, cx,
); );
+1
View File
@@ -60,6 +60,7 @@ impl Render for SettingsDialog {
Dialog::new("settings-dialog") Dialog::new("settings-dialog")
.handle(self.handle.clone()) .handle(self.handle.clone())
.width(px(600.))
.height(px(560.)) .height(px(560.))
.title("Settings") .title("Settings")
.content(move |_, cx| { .content(move |_, cx| {
+239
View File
@@ -0,0 +1,239 @@
//! The shared issue and pull-request lists: toolbar, uniform rows, scrollbar
//! overlay, and empty state, plus the scrollable commit list.
use std::rc::Rc;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, ClickEvent, ElementId, InteractiveElement as _, IntoElement,
ParentElement as _, Pixels, SharedString, StatefulInteractiveElement as _, Styled as _,
UniformListScrollHandle, Window, div, px, uniform_list,
};
use nostr::prelude::PublicKey;
use signed_core::RepoStatus;
use signed_git::FileCommit;
use ui::avatar::Avatar;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::theme::ActiveTheme as _;
use crate::repo::helpers::commit_row;
use crate::shared::widgets::{empty_state, scroll_overlay, status_badge};
/// The height of one issue or pull-request row.
pub const ROW_HEIGHT: f32 = 73.;
/// A row's activation handler.
pub type EventHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
/// The toolbar above the issue and pull-request lists: a filter and its actions.
pub fn filter_toolbar(cx: &App, children: impl IntoIterator<Item = AnyElement>) -> AnyElement {
h_flex()
.px_4()
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.bg(cx.theme().colors.muted)
.children(children)
.into_any_element()
}
/// One issue or pull-request row's display data and click handler.
pub struct EventRow {
pub id: ElementId,
pub status: RepoStatus,
pub title: SharedString,
pub author: SharedString,
pub picture: Option<SharedString>,
pub pubkey: PublicKey,
pub short_id: SharedString,
pub age: SharedString,
pub on_click: EventHandler,
}
/// The shared issue and pull-request list: toolbar, uniform rows, scrollbar
/// overlay, and empty state.
pub struct EventList {
id: ElementId,
toolbar: Option<AnyElement>,
rows: Vec<EventRow>,
scroll_handle: UniformListScrollHandle,
empty_message: SharedString,
}
impl EventList {
/// Builds a list rendering `rows` under `toolbar`.
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
toolbar: None,
rows: Vec::new(),
scroll_handle: UniformListScrollHandle::new(),
empty_message: "Nothing here".into(),
}
}
/// Replaces the list's scroll handle with the caller's.
pub fn scroll_handle(mut self, handle: UniformListScrollHandle) -> Self {
self.scroll_handle = handle;
self
}
/// Sets the toolbar above the rows.
pub fn toolbar(mut self, toolbar: AnyElement) -> Self {
self.toolbar = Some(toolbar);
self
}
/// Sets the rendered rows.
pub fn rows(mut self, rows: Vec<EventRow>) -> Self {
self.rows = rows;
self
}
/// Sets the empty-state message shown when no rows match.
pub fn empty_message(mut self, message: impl Into<SharedString>) -> Self {
self.empty_message = message.into();
self
}
/// Renders the list.
pub fn render(self, _cx: &App) -> AnyElement {
let count = self.rows.len();
let rows = self.rows;
let row_height = px(ROW_HEIGHT);
v_flex()
.relative()
.flex_1()
.min_h_0()
.w_full()
.children(self.toolbar)
.when(count > 0, |this| {
this.child(
uniform_list((self.id.clone(), "rows"), count, move |range, _, cx| {
range
.map(|ix| {
let Some(row) = rows.get(ix) else {
return div().into_any_element();
};
event_row(row, row_height, cx)
})
.collect()
})
.track_scroll(&self.scroll_handle)
.size_full(),
)
.child(scroll_overlay(
(self.id.clone(), "scroll"),
self.scroll_handle.clone(),
))
})
.when(count == 0, |this| {
this.child(empty_state(self.empty_message))
})
.into_any_element()
}
}
/// Renders one issue or pull-request row.
pub fn event_row(row: &EventRow, row_height: Pixels, cx: &App) -> AnyElement {
h_flex()
.id(row.id.clone())
.w_full()
.h(row_height)
.gap_4()
.px_4()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.on_click({
let on_click = row.on_click.clone();
move |event, window, cx| on_click(event, window, cx)
})
.child(status_badge(row.status))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(
div()
.text_base()
.text_ellipsis()
.whitespace_nowrap()
.child(row.title.clone()),
)
.child(event_meta_row(row, cx)),
)
.into_any_element()
}
/// The author, age, and id line under a row's title.
pub fn event_meta_row(row: &EventRow, cx: &App) -> AnyElement {
h_flex()
.gap_2()
.text_xs()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(row.pubkey)
.name(row.author.clone())
.picture(row.picture.clone())
.small(),
)
.child(div().child(row.author.clone())),
)
.child(SharedString::from("opened"))
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(row.short_id.clone()),
)
.child(row.age.clone())
.into_any_element()
}
/// A scrollable commit list: uniform `commit_row`s under a scrollbar overlay.
#[allow(clippy::too_many_arguments)]
pub fn commit_list(
id: &'static str,
scroll_id: &'static str,
commits: Arc<Vec<FileCommit>>,
scroll_handle: UniformListScrollHandle,
action: impl Fn(usize, &FileCommit, &App) -> Option<AnyElement> + 'static,
on_click: impl Fn(&FileCommit, &mut Window, &mut App) + Clone + 'static,
_cx: &App,
) -> AnyElement {
let count = commits.len();
v_flex()
.relative()
.flex_1()
.min_h_0()
.child(
uniform_list(id, count, move |range, _, cx| {
range
.map(|ix| {
let commit = commits[ix].clone();
let action = action(ix, &commit, cx);
let on_click = on_click.clone();
let row_commit = commit.clone();
commit_row(
ix,
&commit,
action,
move |window, cx| on_click(&row_commit, window, cx),
cx,
)
})
.collect()
})
.track_scroll(&scroll_handle)
.size_full(),
)
.child(scroll_overlay(scroll_id, scroll_handle))
.into_any_element()
}
+20
View File
@@ -1,3 +1,8 @@
use gpui::{App, Entity};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
pub mod event_list;
pub mod panels; pub mod panels;
pub mod progress; pub mod progress;
pub mod tree; pub mod tree;
@@ -15,3 +20,18 @@ pub fn log_dropped<T>(result: Result<T, anyhow::Error>) {
); );
} }
} }
/// Tracks a detail view's author, commenters, and repository owner for
/// profile prefetch.
pub fn track_event_participants(
author: Option<PublicKey>,
owner: Option<PublicKey>,
comments: impl Iterator<Item = PublicKey>,
directory: &Entity<ProfileDirectory>,
cx: &mut App,
) {
let mut keys: Vec<PublicKey> = author.into_iter().collect();
keys.extend(comments);
keys.extend(owner);
directory.update(cx, |directory, cx| directory.track(keys, cx));
}
+40 -2
View File
@@ -1,10 +1,11 @@
use gpui::{ use gpui::{
AnyElement, App, Context, IntoElement as _, ParentElement as _, SharedString, Styled as _, AnyElement, App, AsyncApp, Context, Entity, IntoElement as _, ParentElement as _, SharedString,
Subscription, div, Styled as _, Subscription, Task, div,
}; };
use signed_core::RepoAddr; use signed_core::RepoAddr;
use signed_state::{Backend, BackendEvent, PushStepStatus}; use signed_state::{Backend, BackendEvent, PushStepStatus};
use ui::common::{h_flex, v_flex}; use ui::common::{h_flex, v_flex};
use ui::dialog::DialogHandle;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::spinner::Spinner; use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
@@ -126,3 +127,40 @@ pub fn push_steps_row(steps: &[PushStepStatus], cx: &App) -> Option<AnyElement>
Some(v_flex().gap_1().children(rows).into_any_element()) Some(v_flex().gap_1().children(rows).into_any_element())
} }
/// Runs a dialog task to completion.
pub fn run_dialog_task<T: 'static>(
task: Task<Result<T, anyhow::Error>>,
state: &Entity<DialogProgress>,
handle: &DialogHandle,
cx: &mut App,
) {
let state = state.clone();
let handle = handle.clone();
run_dialog_task_with(
task,
cx,
move |_, cx| cx.update(|cx| handle.close(cx)),
move |error, cx| {
state.update(cx, |state, cx| {
state.fail(error.to_string());
cx.notify();
});
},
);
}
/// Runs a dialog task to completion, with explicit success and failure sinks.
pub fn run_dialog_task_with<T: 'static>(
task: Task<Result<T, anyhow::Error>>,
cx: &mut App,
on_success: impl FnOnce(T, &mut AsyncApp) + 'static,
on_error: impl FnOnce(anyhow::Error, &mut AsyncApp) + 'static,
) {
cx.spawn(async move |cx| match task.await {
Ok(value) => on_success(value, cx),
Err(error) => on_error(error, cx),
})
.detach();
}
+59 -3
View File
@@ -1,9 +1,14 @@
use gpui::{AnyElement, App, IntoElement, ParentElement as _, SharedString, Styled as _, div}; use gpui::{
AnyElement, App, ElementId, IntoElement, ParentElement as _, SharedString, Styled as _, div,
};
use signed_core::RepoStatus; use signed_core::RepoStatus;
use ui::badge::{Badge, BadgeVariant}; use ui::badge::{Badge, BadgeVariant};
use ui::common::StyledExt as _; use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState; use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::scrollbar::{Scrollbar, ScrollbarHandle};
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip; use ui::tooltip::Tooltip;
@@ -25,7 +30,7 @@ pub fn status_badge(status: RepoStatus) -> Badge {
/// A centered empty-state message filling the available space. /// A centered empty-state message filling the available space.
pub fn empty_state(message: impl Into<SharedString>) -> AnyElement { pub fn empty_state(message: impl Into<SharedString>) -> AnyElement {
let message = message.into(); let message = message.into();
ui::common::v_flex() v_flex()
.size_full() .size_full()
.items_center() .items_center()
.justify_center() .justify_center()
@@ -33,6 +38,57 @@ pub fn empty_state(message: impl Into<SharedString>) -> AnyElement {
.into_any_element() .into_any_element()
} }
/// A centered spinner filling the available space.
pub fn centered_spinner(id: impl Into<ElementId>) -> AnyElement {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new(id))
.into_any_element()
}
/// The vertical scrollbar pinned over a uniform list's full extent.
pub fn scroll_overlay<I, H>(id: I, handle: H) -> AnyElement
where
I: Into<ElementId>,
H: ScrollbarHandle,
{
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(id, handle))
.into_any_element()
}
/// One copyable clone command with its text visible next to the copy icon.
pub fn clone_row(id: SharedString, command: SharedString, cx: &App) -> AnyElement {
h_flex()
.h_8()
.px_2()
.gap_2()
.min_w_0()
.bg(cx.theme().colors.secondary)
.rounded(cx.theme().radius.control)
.text_color(cx.theme().colors.secondary_foreground)
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.font_family(cx.theme().mono_font)
.text_xs()
.child(command.clone()),
)
.child(ClipboardButton::new(id, command).xsmall())
.into_any_element()
}
/// A one-line muted label used by section headers. /// A one-line muted label used by section headers.
pub fn section_label(text: impl Into<SharedString>, cx: &App) -> AnyElement { pub fn section_label(text: impl Into<SharedString>, cx: &App) -> AnyElement {
div() div()
@@ -1,4 +1,5 @@
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
@@ -50,7 +51,7 @@ impl RepositoryEntry {
pub(crate) struct RepositorySwitcher { pub(crate) struct RepositorySwitcher {
search: Entity<InputState>, search: Entity<InputState>,
directory: Entity<ProfileDirectory>, directory: Entity<ProfileDirectory>,
entries: Vec<RepositoryEntry>, entries: Arc<Vec<RepositoryEntry>>,
open: bool, open: bool,
on_open: OpenHandler, on_open: OpenHandler,
on_create: CreateHandler, on_create: CreateHandler,
@@ -71,7 +72,7 @@ impl RepositorySwitcher {
Self { Self {
search, search,
directory, directory,
entries: Vec::new(), entries: Arc::new(Vec::new()),
open: false, open: false,
on_open: Rc::new(on_open), on_open: Rc::new(on_open),
on_create: Rc::new(on_create), on_create: Rc::new(on_create),
@@ -81,7 +82,7 @@ impl RepositorySwitcher {
} }
pub(super) fn set_entries(&mut self, entries: Vec<RepositoryEntry>, cx: &mut Context<Self>) { pub(super) fn set_entries(&mut self, entries: Vec<RepositoryEntry>, cx: &mut Context<Self>) {
self.entries = entries; self.entries = Arc::new(entries);
cx.notify(); cx.notify();
} }
@@ -97,7 +98,7 @@ impl Render for RepositorySwitcher {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = *cx.theme(); let theme = *cx.theme();
let weak = cx.entity().downgrade(); let weak = cx.entity().downgrade();
let entries = self.entries.clone(); let entries = Arc::clone(&self.entries);
let search = self.search.clone(); let search = self.search.clone();
let directory = self.directory.clone(); let directory = self.directory.clone();
@@ -147,15 +148,19 @@ impl Render for RepositorySwitcher {
} }
}); });
let visible: Vec<RepositoryEntry> = entries let visible: Arc<Vec<RepositoryEntry>> = Arc::new(
.iter() entries
.filter(|entry| query.is_empty() || entry.label.to_lowercase().contains(&query)) .iter()
.cloned() .filter(|entry| {
.collect(); query.is_empty() || entry.label.to_lowercase().contains(&query)
})
.cloned()
.collect(),
);
let row_height = rems(2.0).to_pixels(window.rem_size()) + px(2.); let row_height = rems(2.0).to_pixels(window.rem_size()) + px(2.);
let list_height = (row_height * visible.len() as f32).min(px(280.)); let list_height = (row_height * visible.len() as f32).min(px(280.));
let list_entries = visible.clone(); let list_entries = Arc::clone(&visible);
let list_directory = directory.clone(); let list_directory = directory.clone();
let list_weak = row_weak.clone(); let list_weak = row_weak.clone();
let list_on_open = on_open.clone(); let list_on_open = on_open.clone();
@@ -218,7 +223,7 @@ impl Render for RepositorySwitcher {
.h(row_height) .h(row_height)
.px_3() .px_3()
.gap_2() .gap_2()
.rounded(theme.radius.control) .rounded(theme.radius.full)
.text_sm() .text_sm()
.hover(|row| row.bg(theme.colors.muted)) .hover(|row| row.bg(theme.colors.muted))
.child(entry.avatar(&list_directory, cx)) .child(entry.avatar(&list_directory, cx))
+3
View File
@@ -8,3 +8,6 @@ publish.workspace = true
nostr.workspace = true nostr.workspace = true
serde.workspace = true serde.workspace = true
utils = { path = "../utils" } utils = { path = "../utils" }
[lints]
workspace = true
+6 -7
View File
@@ -34,8 +34,9 @@ impl<'a> PullRequest<'a> {
}; };
let mut series = vec![last]; let mut series = vec![last];
let mut tail = last;
loop { loop {
let Some(prev_id) = series.last().unwrap().tags.event_ids().next() else { let Some(prev_id) = tail.tags.event_ids().next() else {
break; break;
}; };
let Some(prev) = patches let Some(prev) = patches
@@ -46,6 +47,7 @@ impl<'a> PullRequest<'a> {
break; break;
}; };
series.push(prev); series.push(prev);
tail = prev;
} }
series.reverse(); series.reverse();
series series
@@ -86,21 +88,18 @@ impl<'a> PullRequest<'a> {
/// Walks reply links outward from the root patch, taking the newest child first. /// Walks reply links outward from the root patch, taking the newest child first.
fn forward_series(root: &'a Event, patches: &[&'a Event]) -> Vec<&'a Event> { fn forward_series(root: &'a Event, patches: &[&'a Event]) -> Vec<&'a Event> {
let mut series = vec![root]; let mut series = vec![root];
let mut tail = root;
loop { loop {
let next = patches let next = patches
.iter() .iter()
.filter(|patch| !series.contains(patch)) .filter(|patch| !series.contains(patch))
.filter(|patch| { .filter(|patch| patch.tags.event_ids().any(|id| id == tail.id))
patch
.tags
.event_ids()
.any(|id| id == series.last().unwrap().id)
})
.max_by_key(|patch| patch.created_at); .max_by_key(|patch| patch.created_at);
let Some(next) = next else { let Some(next) = next else {
break; break;
}; };
series.push(next); series.push(next);
tail = next;
} }
series series
} }
+3
View File
@@ -20,3 +20,6 @@ ignore = "0.4"
[dev-dependencies] [dev-dependencies]
tempfile = "3" tempfile = "3"
[lints]
workspace = true
+7 -2
View File
@@ -502,8 +502,13 @@ fn publishing_a_commit_advances_the_remote_tip() {
assert!(status.ahead_commits.contains(&third)); assert!(status.ahead_commits.contains(&third));
let second_refspec = format!("+{second}:{refname}"); let second_refspec = format!("+{second}:{refname}");
repo.push_refspecs(&base_url, "npub1test", "my-repo", &[second_refspec.as_str()]) repo.push_refspecs(
.expect("publish second"); &base_url,
"npub1test",
"my-repo",
&[second_refspec.as_str()],
)
.expect("publish second");
assert_eq!( assert_eq!(
git_in(&server_repo, &["rev-parse", refname.as_str()]).expect("server tip"), git_in(&server_repo, &["rev-parse", refname.as_str()]).expect("server tip"),
second second
+3
View File
@@ -12,3 +12,6 @@ nostr-lmdb.workspace = true
anyhow.workspace = true anyhow.workspace = true
webbrowser.workspace = true webbrowser.workspace = true
[lints]
workspace = true
+3
View File
@@ -30,3 +30,6 @@ rustls = "0.23"
[dev-dependencies] [dev-dependencies]
tempfile = "3" tempfile = "3"
[lints]
workspace = true
+7 -4
View File
@@ -418,19 +418,22 @@ impl Backend {
let relays: Vec<(RelayUrl, Option<RelayMetadata>)> = [ let relays: Vec<(RelayUrl, Option<RelayMetadata>)> = [
( (
RelayUrl::parse("wss://relay.primal.net").unwrap(), RelayUrl::parse("wss://relay.primal.net")
.expect("hardcoded relay URL parses"),
Some(RelayMetadata::Read), Some(RelayMetadata::Read),
), ),
( (
RelayUrl::parse("wss://relay.ditto.pub").unwrap(), RelayUrl::parse("wss://relay.ditto.pub")
.expect("hardcoded relay URL parses"),
Some(RelayMetadata::Read), Some(RelayMetadata::Read),
), ),
( (
RelayUrl::parse("wss://relay.nostr.net").unwrap(), RelayUrl::parse("wss://relay.nostr.net")
.expect("hardcoded relay URL parses"),
Some(RelayMetadata::Write), Some(RelayMetadata::Write),
), ),
( (
RelayUrl::parse("wss://nos.lol").unwrap(), RelayUrl::parse("wss://nos.lol").expect("hardcoded relay URL parses"),
Some(RelayMetadata::Write), Some(RelayMetadata::Write),
), ),
] ]
+19 -15
View File
@@ -663,34 +663,37 @@ impl RepoStore {
merge_base: Option<String>, merge_base: Option<String>,
push_from: Option<PathBuf>, push_from: Option<PathBuf>,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) -> Task<Result<(), Error>> {
self.last_error = None; self.last_error = None;
self.last_warning = None; self.last_warning = None;
let Some(addr) = self.addr.clone() else { let Some(addr) = self.addr.clone() else {
self.not_announced(cx); self.not_announced(cx);
return; return Task::ready(Err(Error::msg(
"This repository is not published to Nostr yet",
)));
}; };
let series = PatchSeries::parse(&patch); let series = PatchSeries::parse(&patch);
if let Some(oversized) = series.oversized_length() { if let Some(oversized) = series.oversized_length() {
self.last_error = Some(format!( let message = format!(
"patch too large ({} bytes; NIP-34 suggests keeping each patch under {} bytes)", "patch too large ({} bytes; NIP-34 suggests keeping each patch under {} bytes)",
oversized, MAX_PATCH_EVENT_BYTES oversized, MAX_PATCH_EVENT_BYTES
)); );
self.last_error = Some(message.clone());
cx.notify(); cx.notify();
return; return Task::ready(Err(Error::msg(message)));
} }
// The tip of the series is its last commit; `git format-patch` orders // The tip of the series is its last commit; `git format-patch` orders
// patches oldest first. // patches oldest first.
let Some(current_commit) = series.tip_commit() else { let Some(current_commit) = series.tip_commit() else {
self.last_error = Some( let message =
"Patch must be `git format-patch` output with a `From <commit-id>` header".into(), "Patch must be `git format-patch` output with a `From <commit-id>` header";
); self.last_error = Some(message.into());
cx.notify(); cx.notify();
return; return Task::ready(Err(Error::msg(message)));
}; };
let backend = Backend::global(cx); let backend = Backend::global(cx);
@@ -700,9 +703,10 @@ impl RepoStore {
}; };
let Some(user) = user else { let Some(user) = user else {
self.last_error = Some("Sign in to open a pull request".into()); let message = "Sign in to open a pull request";
self.last_error = Some(message.into());
cx.notify(); cx.notify();
return; return Task::ready(Err(Error::msg(message)));
}; };
let author_npub = user.to_bech32().unwrap(); let author_npub = user.to_bech32().unwrap();
@@ -733,7 +737,7 @@ impl RepoStore {
.collect() .collect()
}; };
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
let root_patch = match publish_patch_series( let root_patch = match publish_patch_series(
&client, &client,
&signer, &signer,
@@ -919,8 +923,7 @@ impl RepoStore {
} }
Ok(()) Ok(())
}); })
self.tasks.push(task);
} }
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
@@ -956,7 +959,7 @@ impl RepoStore {
}; };
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.open_pull_request( let task = this.open_pull_request(
subject, subject,
description, description,
branch_name, branch_name,
@@ -966,6 +969,7 @@ impl RepoStore {
Some(repo_path), Some(repo_path),
cx, cx,
); );
this.tasks.push(task);
}) })
}) })
} }
+3
View File
@@ -69,3 +69,6 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = [
[dev-dependencies] [dev-dependencies]
gpui = { workspace = true, features = ["test-support"] } gpui = { workspace = true, features = ["test-support"] }
[lints]
workspace = true
+22 -28
View File
@@ -28,7 +28,8 @@ use gpui::{
use crate::components::button::{Button, ButtonVariant}; use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{ use crate::components::common::{
DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, v_flex, DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, floating_panel,
v_flex,
}; };
use crate::icons::{Icon, IconRole}; use crate::icons::{Icon, IconRole};
use crate::theme::{ALERT_EDGE_WIDTH, ALERT_STACK_WIDTH, ActiveTheme as _, ENTER_SLIDE_DISTANCE}; use crate::theme::{ALERT_EDGE_WIDTH, ALERT_STACK_WIDTH, ActiveTheme as _, ENTER_SLIDE_DISTANCE};
@@ -194,10 +195,9 @@ impl RenderOnce for Alert {
}); });
match self.presentation { match self.presentation {
AlertStyle::Overlay => { AlertStyle::Overlay => floating_panel(
let surface = theme.colors.surface; cx,
let border = theme.colors.border; theme.radius.overlay,
div() div()
.id(self.id.clone()) .id(self.id.clone())
.role(Role::Alert) .role(Role::Alert)
@@ -206,26 +206,22 @@ impl RenderOnce for Alert {
.items_start() .items_start()
.gap_2() .gap_2()
.px_3() .px_3()
.py_2() .py_2(),
.rounded(theme.radius.overlay) theme.elevations.popover.shadows(),
.bg(surface) )
.border_1() .refine_style(&self.style)
.border_color(border) .when_some(self.icon.clone(), |alert, icon_glyph| {
.shadow(theme.elevations.popover.shadows()) alert.child(
.refine_style(&self.style) div()
.when_some(self.icon.clone(), |alert, icon_glyph| { .flex_none()
alert.child( .flex()
div() .items_center()
.flex_none() .h(window.line_height())
.flex() .child(icon_glyph.size(rems(1.0)).color(ramp.base)),
.items_center() )
.h(window.line_height()) })
.child(icon_glyph.size(rems(1.0)).color(ramp.base)), .child(content)
) .when_some(dismiss, |alert, dismiss| alert.child(dismiss)),
})
.child(content)
.when_some(dismiss, |alert, dismiss| alert.child(dismiss))
}
AlertStyle::Inline => div() AlertStyle::Inline => div()
.id(self.id.clone()) .id(self.id.clone())
.role(Role::Alert) .role(Role::Alert)
@@ -381,14 +377,12 @@ impl RenderOnce for AlertsView {
let entries = self.alerts.read(cx).entries(); let entries = self.alerts.read(cx).entries();
deferred( deferred(
div() v_flex()
.id(self.id) .id(self.id)
.absolute() .absolute()
.top_4() .top_4()
.right_4() .right_4()
.w(ALERT_STACK_WIDTH) .w(ALERT_STACK_WIDTH)
.flex()
.flex_col()
.items_end() .items_end()
.gap_2() .gap_2()
.children(entries.iter().rev().map(|entry| { .children(entries.iter().rev().map(|entry| {
+17
View File
@@ -11,6 +11,7 @@
//! .picture(Some("https://example.com/ada.png")); //! .picture(Some("https://example.com/ada.png"));
//! ``` //! ```
use std::collections::HashMap;
use std::fmt::Display; use std::fmt::Display;
use gpui::{ use gpui::{
@@ -211,7 +212,23 @@ impl RenderOnce for PixelAvatar {
} }
} }
// Computed identicon patterns per seed, so avatars do not reroll their PRNG every frame.
thread_local! {
static PATTERN_CACHE: std::cell::RefCell<HashMap<u64, [u8; GRID_SIZE * GRID_SIZE]>> =
std::cell::RefCell::new(HashMap::new());
}
fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] { fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
let cached = PATTERN_CACHE.with(|cache| cache.borrow().get(&seed).copied());
if let Some(cached) = cached {
return cached;
}
let computed = compute_pattern(seed);
PATTERN_CACHE.with(|cache| cache.borrow_mut().insert(seed, computed));
computed
}
fn compute_pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
let mut rng = PixelRng::new(seed); let mut rng = PixelRng::new(seed);
let mut pattern = [0u8; GRID_SIZE * GRID_SIZE]; let mut pattern = [0u8; GRID_SIZE * GRID_SIZE];
let mut filled = 0usize; let mut filled = 0usize;
+75 -53
View File
@@ -15,7 +15,7 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, AnyView, App, ClickEvent, ElementId, InteractiveElement as _, IntoElement, AnyElement, AnyView, App, ClickEvent, ElementId, Hsla, InteractiveElement as _, IntoElement,
ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, canvas, relative, transparent_black, StyleRefinement, Styled as _, Window, canvas, relative, transparent_black,
}; };
@@ -47,6 +47,65 @@ pub enum ButtonVariant {
Destructive, Destructive,
} }
/// The variant colors a button paints with, resolved from the active theme.
pub struct ButtonChrome {
/// The resting background, `None` for unpainted variants like `Ghost`.
pub background: Option<Hsla>,
pub foreground: Hsla,
pub hover: Hsla,
pub pressed: Hsla,
pub border: Hsla,
pub hover_border: Hsla,
pub pressed_border: Hsla,
}
impl ButtonVariant {
/// The variant's colors from the active theme.
pub fn chrome(&self, cx: &App) -> ButtonChrome {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
match self {
Self::Primary => ButtonChrome {
background: Some(ramps.primary.base),
foreground: colors.primary_foreground,
hover: ramps.primary.hover,
pressed: ramps.primary.pressed,
border: ramps.primary.base,
hover_border: ramps.primary.hover,
pressed_border: ramps.primary.pressed,
},
Self::Secondary => ButtonChrome {
background: Some(colors.surface),
foreground: colors.foreground,
hover: colors.muted,
pressed: colors.muted_hover,
border: colors.border,
hover_border: colors.border,
pressed_border: colors.border,
},
Self::Ghost => ButtonChrome {
background: None,
foreground: colors.foreground,
hover: colors.muted_hover,
pressed: ramps.secondary.pressed,
border: transparent_black(),
hover_border: transparent_black(),
pressed_border: transparent_black(),
},
Self::Destructive => ButtonChrome {
background: Some(ramps.destructive.base),
foreground: colors.destructive_foreground,
hover: ramps.destructive.hover,
pressed: ramps.destructive.pressed,
border: ramps.destructive.base,
hover_border: ramps.destructive.hover,
pressed_border: ramps.destructive.pressed,
},
}
}
}
/// Which edge the button's content aligns to. /// Which edge the button's content aligns to.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ButtonSide { pub enum ButtonSide {
@@ -100,7 +159,7 @@ impl Button {
disabled: false, disabled: false,
loading: false, loading: false,
padded: true, padded: true,
fully_rounded: false, fully_rounded: true,
full_width: false, full_width: false,
side: ButtonSide::default(), side: ButtonSide::default(),
tab_stop: true, tab_stop: true,
@@ -179,7 +238,7 @@ impl Button {
self self
} }
/// Renders the button as a circle instead of the control radius. /// Overrides the pill shape; buttons are fully rounded by default.
pub fn fully_rounded(mut self, fully_rounded: bool) -> Self { pub fn fully_rounded(mut self, fully_rounded: bool) -> Self {
self.fully_rounded = fully_rounded; self.fully_rounded = fully_rounded;
self self
@@ -236,13 +295,21 @@ impl Sizable for Button {
impl RenderOnce for Button { impl RenderOnce for Button {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme(); let ButtonChrome {
let colors = theme.colors; background,
let ramps = theme.ramps; foreground,
hover,
pressed,
border,
hover_border,
pressed_border,
} = self.variant.chrome(cx);
let radius = if self.fully_rounded { let radius = if self.fully_rounded {
let theme = cx.theme();
theme.radius.full theme.radius.full
} else { } else {
let theme = cx.theme();
theme.radius.control theme.radius.control
}; };
@@ -256,52 +323,7 @@ impl RenderOnce for Button {
let is_round_child = is_child_only && self.fully_rounded; let is_round_child = is_child_only && self.fully_rounded;
let icon_trailing = self.side == ButtonSide::Right; let icon_trailing = self.side == ButtonSide::Right;
let ring = cx.theme().colors.ring;
let (background, foreground, hover, pressed) = match self.variant {
ButtonVariant::Primary => (
Some(ramps.primary.base),
colors.primary_foreground,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (
Some(colors.surface),
colors.foreground,
colors.muted,
colors.muted_hover,
),
ButtonVariant::Ghost => (
None,
colors.foreground,
colors.muted_hover,
ramps.secondary.pressed,
),
ButtonVariant::Destructive => (
Some(ramps.destructive.base),
colors.destructive_foreground,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
let (border, hover_border, pressed_border) = match self.variant {
ButtonVariant::Primary => (
ramps.primary.base,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (colors.border, colors.border, colors.border),
ButtonVariant::Ghost => (
transparent_black(),
transparent_black(),
transparent_black(),
),
ButtonVariant::Destructive => (
ramps.destructive.base,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
h_flex() h_flex()
.id(self.id.clone()) .id(self.id.clone())
@@ -381,7 +403,7 @@ impl RenderOnce for Button {
.tab_stop(self.tab_stop) .tab_stop(self.tab_stop)
.hover(move |style| style.bg(hover).border_color(hover_border)) .hover(move |style| style.bg(hover).border_color(hover_border))
.active(move |style| style.bg(pressed).border_color(pressed_border)) .active(move |style| style.bg(pressed).border_color(pressed_border))
.focus_visible(|style| style.shadow(focus_ring(colors.ring))) .focus_visible(|style| style.shadow(focus_ring(ring)))
.when_some(on_click, |button, on_click| { .when_some(on_click, |button, on_click| {
button.on_click(move |event, window, cx| on_click(event, window, cx)) button.on_click(move |event, window, cx| on_click(event, window, cx))
}) })
+47 -24
View File
@@ -84,6 +84,12 @@ impl SelectionPoint {
} }
} }
/// The source-derived part of one rendered line, cached between frames.
struct CodeLineLayout {
text: String,
roles: Vec<Role>,
}
/// Retained state for a code view. /// Retained state for a code view.
/// ///
/// Build one in a [`gpui::Entity`], render the entity, and call its setters /// Build one in a [`gpui::Entity`], render the entity, and call its setters
@@ -93,6 +99,8 @@ pub struct CodeViewState {
source: SharedString, source: SharedString,
language: Language, language: Language,
code: HighlightedCode, code: HighlightedCode,
/// Per-line layout cache, rebuilt whenever the source changes.
line_layouts: Vec<CodeLineLayout>,
handle: UniformListScrollHandle, handle: UniformListScrollHandle,
/// The hovered line, driving the active-line wash and number emphasis. /// The hovered line, driving the active-line wash and number emphasis.
active_line: Option<usize>, active_line: Option<usize>,
@@ -113,12 +121,14 @@ impl CodeViewState {
{ {
let source = source.into(); let source = source.into();
let code = highlight(&source, language); let code = highlight(&source, language);
let line_layouts = Self::layout(&code);
Self { Self {
id: id.into(), id: id.into(),
source, source,
language, language,
code, code,
line_layouts,
handle: UniformListScrollHandle::new(), handle: UniformListScrollHandle::new(),
active_line: None, active_line: None,
selection: None, selection: None,
@@ -137,6 +147,7 @@ impl CodeViewState {
let source = source.into(); let source = source.into();
self.code = highlight(&source, language); self.code = highlight(&source, language);
self.line_layouts = Self::layout(&self.code);
self.source = source; self.source = source;
self.language = language; self.language = language;
self.selection = None; self.selection = None;
@@ -145,17 +156,16 @@ impl CodeViewState {
cx.notify(); cx.notify();
} }
/// Replaces one line's text and re-highlights the file. `line_ix` past /// Replaces one line's text and re-highlights the file.
/// the end clamps to the last line, and the replacement may span
/// multiple lines.
///
/// # Panics
///
/// Panics if the source is empty, which leaves no line to replace.
pub fn update_line<T>(&mut self, line_ix: usize, text: T, cx: &mut Context<Self>) pub fn update_line<T>(&mut self, line_ix: usize, text: T, cx: &mut Context<Self>)
where where
T: AsRef<str>, T: AsRef<str>,
{ {
// An empty source has no line to replace.
if self.source.is_empty() {
return;
}
let trailing_newline = self.source.ends_with('\n'); let trailing_newline = self.source.ends_with('\n');
let mut lines: Vec<String> = self.source.lines().map(str::to_string).collect(); let mut lines: Vec<String> = self.source.lines().map(str::to_string).collect();
let line_ix = line_ix.min(lines.len().saturating_sub(1)); let line_ix = line_ix.min(lines.len().saturating_sub(1));
@@ -170,10 +180,37 @@ impl CodeViewState {
self.source = (lines.join("\n") + if trailing_newline { "\n" } else { "" }).into(); self.source = (lines.join("\n") + if trailing_newline { "\n" } else { "" }).into();
self.code = highlight(&self.source, self.language); self.code = highlight(&self.source, self.language);
self.line_layouts = Self::layout(&self.code);
self.selection = None; self.selection = None;
cx.notify(); cx.notify();
} }
/// The cached per-line text and roles for the highlighted source.
fn layout(code: &HighlightedCode) -> Vec<CodeLineLayout> {
code.lines
.iter()
.map(|line| {
let mut text = String::new();
for span in &line.spans {
text.push_str(&span.text);
}
let char_count = text.chars().count();
let mut roles = vec![Role::Text; char_count];
let mut offset = 0usize;
for span in &line.spans {
let chars = span.text.chars().count();
for slot in &mut roles[offset..offset + chars] {
*slot = span.role;
}
offset += chars;
}
CodeLineLayout { text, roles }
})
.collect()
}
/// The source text the view renders. /// The source text the view renders.
pub fn source(&self) -> &str { pub fn source(&self) -> &str {
&self.source &self.source
@@ -500,24 +537,10 @@ fn render_row(
line_height: Pixels, line_height: Pixels,
cx: &App, cx: &App,
) -> gpui::AnyElement { ) -> gpui::AnyElement {
let line = code.code().lines.get(line_ix); let layout = code.line_layouts.get(line_ix);
let text = layout.map_or("", |layout| layout.text.as_str());
let mut text = String::new(); let roles = layout.map_or(&[][..], |layout| layout.roles.as_slice());
for span in line.map_or(&[][..], |line| line.spans.as_slice()) {
text.push_str(&span.text);
}
let char_count = text.chars().count(); let char_count = text.chars().count();
let mut roles = vec![Role::Text; char_count];
let mut offset = 0usize;
for span in line.map_or(&[][..], |line| line.spans.as_slice()) {
let chars = span.text.chars().count();
for slot in &mut roles[offset..offset + chars] {
*slot = span.role;
}
offset += chars;
}
let mut selected = vec![false; char_count]; let mut selected = vec![false; char_count];
+166 -173
View File
@@ -31,16 +31,18 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding,
MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, ScrollHandle, MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, SharedString,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task, StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task,
Window, actions, anchored, canvas, deferred, div, point, px, UniformListScrollHandle, Window, actions, anchored, canvas, deferred, div, point, px,
uniform_list,
}; };
use crate::components::common::{ use crate::components::common::{
ControlSizing, OVERLAY_LAYER, ResultLogErr as _, Sizable, StyledExt as _, h_flex, v_flex, ControlSizing, OVERLAY_LAYER, ResultLogErr as _, Sizable, StyledExt as _, floating_panel,
h_flex, paint_highlighted_row, v_flex, wrapping_adjacent_selectable,
}; };
use crate::components::empty_state::EmptyState;
use crate::components::input::{Input, InputState, InputStateEvent}; use crate::components::input::{Input, InputState, InputStateEvent};
use crate::components::scroll_area::ScrollArea;
use crate::icons::{IconRole, icon}; use crate::icons::{IconRole, icon};
use crate::theme::{ActiveTheme as _, COMBOBOX_MIN_WIDTH, COMBOBOX_WIDTH, POPUP_MAX_HEIGHT, Size}; use crate::theme::{ActiveTheme as _, COMBOBOX_MIN_WIDTH, COMBOBOX_WIDTH, POPUP_MAX_HEIGHT, Size};
@@ -245,8 +247,10 @@ where
size: Size, size: Size,
/// Width refinements from the builder, applied to the wrapper each render. /// Width refinements from the builder, applied to the wrapper each render.
style: StyleRefinement, style: StyleRefinement,
/// Handler reports in flight; held so they die with the state. /// The row list's scroll, kept across frames while the popup is open.
tasks: Vec<Task<()>>, rows_scroll: UniformListScrollHandle,
/// The most recent handler report in flight; a newer report replaces it.
task: Option<Task<()>>,
/// Keeps the query-event subscription tied to the state's lifetime. /// Keeps the query-event subscription tied to the state's lifetime.
_subscription: Subscription, _subscription: Subscription,
} }
@@ -304,7 +308,8 @@ where
unmatched: combobox.unmatched, unmatched: combobox.unmatched,
size: combobox.size, size: combobox.size,
style: combobox.style, style: combobox.style,
tasks: Vec::new(), rows_scroll: UniformListScrollHandle::new(),
task: None,
_subscription: subscription, _subscription: subscription,
} }
} }
@@ -385,7 +390,7 @@ where
cx.update(|window, cx| on_change(value, window, cx)) cx.update(|window, cx| on_change(value, window, cx))
.log_err(); .log_err();
}); });
self.tasks.push(task); self.task.replace(task);
} }
cx.notify(); cx.notify();
} }
@@ -453,36 +458,22 @@ where
cx.update(|window, cx| on_create(text, window, cx)) cx.update(|window, cx| on_create(text, window, cx))
.log_err(); .log_err();
}); });
self.tasks.push(task); self.task.replace(task);
} }
} }
} }
cx.notify(); cx.notify();
} }
/// Down and Up over the visible rows. /// Down and Up over the visible rows, wrapping at the ends.
fn move_highlight(&mut self, delta: i32, cx: &mut Context<Self>) { fn move_highlight(&mut self, delta: i32, cx: &mut Context<Self>) {
if self.visible.is_empty() { if self.visible.is_empty() {
return; return;
} }
let current = self.highlight.filter(|row| *row < self.visible.len());
let count = self.visible.len(); let rows: Vec<usize> = (0..self.visible.len()).collect();
let current = self.highlight.filter(|row| *row < count); let next = wrapping_adjacent_selectable(&rows, current, delta > 0);
let next = match current { self.highlight = next;
Some(row) => match row.checked_add_signed(isize::try_from(delta).unwrap_or(0)) {
Some(next) if next < count => next,
Some(_) => 0,
None => count - 1,
},
None => {
if delta > 0 {
0
} else {
count - 1
}
}
};
self.highlight = Some(next);
cx.notify(); cx.notify();
} }
@@ -511,13 +502,12 @@ where
T: Clone + PartialEq + 'static, T: Clone + PartialEq + 'static,
{ {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (colors, radius, panel_border, shadows) = { let (colors, radius, shadows) = {
let theme = cx.theme(); let theme = cx.theme();
( (
theme.colors, theme.colors,
theme.radius, theme.radius,
theme.colors.border,
theme.elevations.popover.shadows(), theme.elevations.popover.shadows(),
) )
}; };
@@ -620,96 +610,101 @@ where
.child(chevron), .child(chevron),
) )
.when(open, |wrapper| { .when(open, |wrapper| {
let rows: Vec<gpui::AnyElement> = self let visible = self.visible.clone();
.visible let options = self.options.clone();
.iter() let highlight = self.highlight;
.enumerate() let selected = self.selected.clone();
.map(|(row, option_index)| { let size = self.size;
let Some((value, label)) = self.options.get(*option_index) else { let list_state = state.clone();
return div().into_any_element(); let rows_id = id.clone();
}; let radius_sm = radius.sm;
let foreground = colors.foreground;
let highlighted = self.highlight == Some(row); // Rows are `control_height`, so the row height follows the size.
let checked = self.selected.as_ref() == Some(value); let row_height = size.control_height_rems().to_pixels(window.rem_size());
let state = state.clone(); let count = visible.len();
let row_index = row;
div() let list_height = (row_height * count as f32)
.id(("option", *option_index)) .max(row_height)
.debug_selector({ .min(POPUP_MAX_HEIGHT);
let id = id.clone();
move || format!("{id}-option-{row}")
})
.role(Role::ListBoxOption)
.aria_label(label.clone())
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.control_height(self.size)
.control_text(self.size)
.rounded(radius.sm)
.when(highlighted, |row| row.bg(colors.muted))
.when(!highlighted, |row| row.hover(|row| row.bg(colors.muted)))
.on_mouse_move({
let state = state.clone();
move |_, _window, cx| {
if state.read(cx).highlight != Some(row_index) {
state.update(cx, |state, cx| {
state.highlight = Some(row_index);
cx.notify();
});
}
}
})
.on_click({
let state = state.clone();
move |_, window, cx| {
state.update(cx, |state, cx| {
state.choose_row(row_index, window, cx)
});
}
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label.clone()),
)
.when(checked, |row| {
row.child(
icon(IconRole::Check)
.size(self.size.dense_icon_rems())
.color(colors.foreground),
)
})
.into_any_element()
})
.collect();
let rows: gpui::AnyElement = if rows.is_empty() { let rows: gpui::AnyElement = if count == 0 {
div() EmptyState::compact("No matches", cx).into_any_element()
.px_2()
.py_1()
.control_caption_text(self.size)
.text_color(colors.muted_foreground)
.child("No matches")
.into_any_element()
} else { } else {
let scroll = window.use_keyed_state((id.clone(), "rows-scroll"), cx, |_, _| { uniform_list((rows_id.clone(), "rows"), count, move |range, _, cx| {
ScrollHandle::new() range
}); .map(|row| {
let Some(option_index) = visible.get(row).copied() else {
return div().into_any_element();
};
let Some((value, label)) = options.get(option_index) else {
return div().into_any_element();
};
ScrollArea::new((id.clone(), "rows")) let highlighted = highlight == Some(row);
.handle(scroll.read(cx).clone()) let checked = selected.as_ref() == Some(value);
.axes(crate::components::scroll_area::ScrollAxes::Vertical) let state = list_state.clone();
.max_h(POPUP_MAX_HEIGHT) let row_index = row;
.children(rows)
.into_any_element() div()
.id(("option", option_index))
.debug_selector({
let id = rows_id.clone();
move || format!("{id}-option-{row}")
})
.role(Role::ListBoxOption)
.aria_label(label.clone())
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.h(row_height)
.control_text(size)
.rounded(radius_sm)
.map(|row| paint_highlighted_row(cx, row, highlighted, false))
.on_mouse_move({
let state = state.clone();
move |_, _window, cx| {
if state.read(cx).highlight != Some(row_index) {
state.update(cx, |state, cx| {
state.highlight = Some(row_index);
cx.notify();
});
}
}
})
.on_click({
let state = state.clone();
move |_, window, cx| {
state.update(cx, |state, cx| {
state.choose_row(row_index, window, cx)
});
}
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label.clone()),
)
.when(checked, |row| {
row.child(
icon(IconRole::Check)
.size(size.dense_icon_rems())
.color(foreground),
)
})
.into_any_element()
})
.collect()
})
.track_scroll(&self.rows_scroll)
.h(list_height)
.into_any_element()
}; };
let panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>> = Rc::new(RefCell::new(None)); let panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>> = Rc::new(RefCell::new(None));
@@ -719,64 +714,62 @@ where
.map(|bounds| bounds.size.width) .map(|bounds| bounds.size.width)
.unwrap_or(COMBOBOX_WIDTH); .unwrap_or(COMBOBOX_WIDTH);
let panel = v_flex() let panel = floating_panel(
.id((id.clone(), "panel")) cx,
.debug_selector({ radius.overlay,
let id = id.clone(); v_flex()
move || format!("{id}-panel") .id((id.clone(), "panel"))
}) .debug_selector({
.w(popup_width) let id = id.clone();
.p_1() move || format!("{id}-panel")
.bg(colors.surface) })
.text_color(colors.foreground) .w(popup_width)
.rounded(radius.overlay) .p_1()
.border_1() .text_color(colors.foreground),
.border_color(panel_border) shadows,
.shadow(shadows) )
.overflow_hidden() .overflow_hidden()
.child(rows) .child(rows)
.child( .child(
canvas( canvas(
{ {
let cell = panel_bounds.clone(); let cell = panel_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
}, },
{ {
let state = state.clone(); let state = state.clone();
let panel_bounds = panel_bounds.clone(); let panel_bounds = panel_bounds.clone();
let wrapper_bounds = wrapper_bounds.clone(); let wrapper_bounds = wrapper_bounds.clone();
move |_, _, window, _cx| { move |_, _, window, _cx| {
window.on_mouse_event({ window.on_mouse_event({
let state = state.clone(); let state = state.clone();
let panel_bounds = panel_bounds.clone(); let panel_bounds = panel_bounds.clone();
let wrapper_bounds = wrapper_bounds.clone(); let wrapper_bounds = wrapper_bounds.clone();
move |event: &MouseDownEvent, phase, _window, cx| { move |event: &MouseDownEvent, phase, _window, cx| {
if phase != gpui::DispatchPhase::Bubble { if phase != gpui::DispatchPhase::Bubble {
return; return;
}
let on_panel =
panel_bounds.borrow().is_some_and(|bounds| {
bounds.contains(&event.position)
});
let on_wrapper =
wrapper_bounds.borrow().is_some_and(|bounds| {
bounds.contains(&event.position)
});
if on_panel || on_wrapper {
return;
}
state.update(cx, |state, cx| {
state.highlight = None;
cx.notify();
});
} }
}); let on_panel = panel_bounds
} .borrow()
}, .is_some_and(|bounds| bounds.contains(&event.position));
) let on_wrapper = wrapper_bounds
.absolute() .borrow()
.inset_0(), .is_some_and(|bounds| bounds.contains(&event.position));
); if on_panel || on_wrapper {
return;
}
state.update(cx, |state, cx| {
state.highlight = None;
cx.notify();
});
}
});
}
},
)
.absolute()
.inset_0(),
);
wrapper.child( wrapper.child(
deferred(anchored().offset(point(px(0.), px(4.))).child(panel)) deferred(anchored().offset(point(px(0.), px(4.))).child(panel))
+164 -164
View File
@@ -29,14 +29,17 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding,
MouseButton, ParentElement as _, Render, Role, ScrollHandle, SharedString, MouseButton, ParentElement as _, Render, Role, SharedString, StatefulInteractiveElement as _,
StatefulInteractiveElement as _, StyleRefinement, Styled as _, Subscription, Window, actions, StyleRefinement, Styled as _, Subscription, UniformListScrollHandle, Window, actions, canvas,
canvas, deferred, div, relative, rems, deferred, div, relative, rems, uniform_list,
}; };
use crate::components::common::{DIALOG_LAYER, StyledExt as _, h_flex, v_flex}; use crate::components::common::{
DIALOG_LAYER, StyledExt as _, floating_panel, h_flex, paint_highlighted_row, v_flex,
wrapping_adjacent_selectable,
};
use crate::components::empty_state::EmptyState;
use crate::components::input::{Input, InputState, InputStateEvent}; use crate::components::input::{Input, InputState, InputStateEvent};
use crate::components::scroll_area::{ScrollArea, ScrollAxes};
use crate::icons::Icon; use crate::icons::Icon;
use crate::theme::{ActiveTheme as _, POPUP_MAX_HEIGHT}; use crate::theme::{ActiveTheme as _, POPUP_MAX_HEIGHT};
@@ -211,6 +214,8 @@ pub struct CommandPaletteState {
/// The highlighted row, when the palette is open. /// The highlighted row, when the palette is open.
highlight: Option<usize>, highlight: Option<usize>,
open: bool, open: bool,
/// The row list's scroll, kept across frames while the palette is open.
rows_scroll: UniformListScrollHandle,
/// Keeps the query-event subscription tied to the state's lifetime. /// Keeps the query-event subscription tied to the state's lifetime.
_subscription: Subscription, _subscription: Subscription,
} }
@@ -239,6 +244,7 @@ impl CommandPaletteState {
matches, matches,
highlight: None, highlight: None,
open: false, open: false,
rows_scroll: UniformListScrollHandle::new(),
_subscription: subscription, _subscription: subscription,
} }
} }
@@ -320,17 +326,9 @@ impl CommandPaletteState {
if self.matches.is_empty() { if self.matches.is_empty() {
return; return;
} }
let count = self.matches.len(); let rows: Vec<usize> = (0..self.matches.len()).collect();
let next = match self.highlight { let next = wrapping_adjacent_selectable(&rows, self.highlight, delta > 0);
Some(row) => match row.checked_add_signed(isize::try_from(delta).unwrap_or(0)) { self.highlight = next;
Some(next) if next < count => next,
Some(_) => 0,
None => count - 1,
},
None if delta > 0 => 0,
None => count - 1,
};
self.highlight = Some(next);
cx.notify(); cx.notify();
} }
@@ -371,12 +369,11 @@ impl Render for CommandPaletteState {
return div().into_any_element(); return div().into_any_element();
} }
let (colors, radius, panel_border, shadows, titlebar_height) = { let (colors, radius, shadows, titlebar_height) = {
let theme = cx.theme(); let theme = cx.theme();
( (
theme.colors, theme.colors,
theme.radius, theme.radius,
theme.colors.border,
theme.elevations.dialog.shadows(), theme.elevations.dialog.shadows(),
theme.titlebar_height, theme.titlebar_height,
) )
@@ -386,157 +383,160 @@ impl Render for CommandPaletteState {
let state = cx.entity(); let state = cx.entity();
let query_focus = self.query.read(cx).focus_handle(); let query_focus = self.query.read(cx).focus_handle();
let rows: Vec<AnyElement> = self let rows: AnyElement = if self.matches.is_empty() {
.matches EmptyState::compact("No matches", cx).into_any_element()
.iter()
.enumerate()
.map(|(row, command)| {
let highlighted = self.highlight == Some(row);
let state = state.clone();
let row_index = row;
h_flex()
.id((ElementId::from(command.id.clone()), "command"))
.debug_selector({
let id = id.clone();
move || format!("{id}-command-{row}")
})
.role(Role::ListBoxOption)
.aria_label(command.label.clone())
.gap_2()
.px_2()
.py_1()
.min_h_8()
.text_sm()
.line_height(relative(1.0))
.rounded(radius.sm)
.when(highlighted, |row| row.bg(colors.muted))
.when(!highlighted, |row| row.hover(|row| row.bg(colors.muted)))
.on_mouse_move({
let state = state.clone();
move |_, _window, cx| {
if state.read(cx).highlight != Some(row_index) {
state.update(cx, |state, cx| {
state.highlight = Some(row_index);
cx.notify();
});
}
}
})
.on_click({
let state = state.clone();
move |_, window, cx| {
state.update(cx, |state, cx| state.choose_row(row_index, window, cx));
}
})
.when_some(command.icon.clone(), |row, icon| {
row.child(icon.size(rems(1.0)).color(colors.foreground))
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(command.label.clone()),
)
.when_some(command.hint.clone(), |row, hint| {
row.child(
div()
.flex_shrink_0()
.text_xs()
.text_color(colors.muted_foreground)
.child(hint),
)
})
.into_any_element()
})
.collect();
let rows: AnyElement = if rows.is_empty() {
div()
.px_2()
.py_1()
.text_xs()
.text_color(colors.muted_foreground)
.child("No matches")
.into_any_element()
} else { } else {
let scroll = let matches = self.matches.clone();
window.use_keyed_state((id.clone(), "rows-scroll"), cx, |_, _| ScrollHandle::new()); let highlight = self.highlight;
let state = state.clone();
let rows_id = id.clone();
let radius_sm = radius.sm;
let foreground = colors.foreground;
let muted_foreground = colors.muted_foreground;
ScrollArea::new((id.clone(), "rows")) // Rows are `min_h_8`, so the uniform row height is two rems.
.handle(scroll.read(cx).clone()) let row_height = rems(2.0).to_pixels(window.rem_size());
.axes(ScrollAxes::Vertical) let count = matches.len();
.max_h(POPUP_MAX_HEIGHT) let list_height = (row_height * count as f32).min(POPUP_MAX_HEIGHT);
.children(rows)
.into_any_element() uniform_list((rows_id.clone(), "rows"), count, move |range, _, cx| {
range
.map(|row| {
let Some(command) = matches.get(row) else {
return div().into_any_element();
};
let highlighted = highlight == Some(row);
let row_index = row;
h_flex()
.id((ElementId::from(command.id.clone()), "command"))
.debug_selector({
let id = rows_id.clone();
move || format!("{id}-command-{row}")
})
.role(Role::ListBoxOption)
.aria_label(command.label.clone())
.gap_2()
.px_2()
.py_1()
.min_h_8()
.text_sm()
.line_height(relative(1.0))
.rounded(radius_sm)
.map(|row| paint_highlighted_row(cx, row, highlighted, false))
.on_mouse_move({
let state = state.clone();
move |_, _window, cx| {
if state.read(cx).highlight != Some(row_index) {
state.update(cx, |state, cx| {
state.highlight = Some(row_index);
cx.notify();
});
}
}
})
.on_click({
let state = state.clone();
move |_, window, cx| {
state.update(cx, |state, cx| {
state.choose_row(row_index, window, cx)
});
}
})
.when_some(command.icon.clone(), |row, icon| {
row.child(icon.size(rems(1.0)).color(foreground))
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(command.label.clone()),
)
.when_some(command.hint.clone(), |row, hint| {
row.child(
div()
.flex_shrink_0()
.text_xs()
.text_color(muted_foreground)
.child(hint),
)
})
.into_any_element()
})
.collect()
})
.track_scroll(&self.rows_scroll)
.h(list_height)
.into_any_element()
}; };
let panel = v_flex() let panel = floating_panel(
.id((id.clone(), "panel")) cx,
.debug_selector({ radius.overlay,
let id = id.clone(); v_flex()
move || format!("{id}-panel") .id((id.clone(), "panel"))
}) .debug_selector({
.key_context(COMMAND_PALETTE_CONTEXT) let id = id.clone();
.role(Role::Dialog) move || format!("{id}-panel")
.aria_label(self.name.clone())
.w_full()
.max_w(relative(0.6))
.p_2()
.gap_2()
.bg(colors.surface)
.text_color(colors.foreground)
.rounded(radius.overlay)
.border_1()
.border_color(panel_border)
.shadow(shadows)
.overflow_hidden()
.refine_style(&self.style)
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_action({
let state = state.clone();
move |_: &HighlightNext, _window, cx| {
state.update(cx, |state, cx| state.move_highlight(1, cx));
}
})
.on_action({
let state = state.clone();
move |_: &HighlightPrevious, _window, cx| {
state.update(cx, |state, cx| state.move_highlight(-1, cx));
}
})
.on_action({
let state = state.clone();
move |_: &Choose, window, cx| {
state.update(cx, |state, cx| state.choose(window, cx));
}
})
.on_action({
let state = state.clone();
move |_: &Dismiss, window, cx| {
state.update(cx, |state, cx| state.dismiss(window, cx));
}
})
.child(
Input::new((id.clone(), "query"), self.query.clone())
.placeholder(self.placeholder.clone()),
)
.child(rows)
.child(
canvas(|_, _, _| {}, {
let focus = query_focus.clone();
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
}) })
.absolute() .key_context(COMMAND_PALETTE_CONTEXT)
.inset_0(), .role(Role::Dialog)
); .aria_label(self.name.clone())
.w_full()
.max_w(relative(0.6))
.p_2()
.gap_2()
.text_color(colors.foreground),
shadows,
)
.overflow_hidden()
.refine_style(&self.style)
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_action({
let state = state.clone();
move |_: &HighlightNext, _window, cx| {
state.update(cx, |state, cx| state.move_highlight(1, cx));
}
})
.on_action({
let state = state.clone();
move |_: &HighlightPrevious, _window, cx| {
state.update(cx, |state, cx| state.move_highlight(-1, cx));
}
})
.on_action({
let state = state.clone();
move |_: &Choose, window, cx| {
state.update(cx, |state, cx| state.choose(window, cx));
}
})
.on_action({
let state = state.clone();
move |_: &Dismiss, window, cx| {
state.update(cx, |state, cx| state.dismiss(window, cx));
}
})
.child(
Input::new((id.clone(), "query"), self.query.clone())
.placeholder(self.placeholder.clone()),
)
.child(rows)
.child(
canvas(|_, _, _| {}, {
let focus = query_focus.clone();
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
let scrim = div() let scrim = div()
.absolute() .absolute()
+51
View File
@@ -129,6 +129,38 @@ pub fn focus_ring(color: Hsla) -> Vec<BoxShadow> {
] ]
} }
/// The shared floating-panel stack.
#[must_use]
pub fn floating_panel<R>(cx: &App, radius: Pixels, panel: R, shadows: Vec<BoxShadow>) -> R
where
R: Styled + IntoElement,
{
let theme = cx.theme();
panel.map(|panel| {
panel
.bg(theme.colors.surface)
.rounded(radius)
.border_1()
.border_color(theme.colors.border)
.shadow(shadows)
})
}
/// The next selectable row in the direction.
pub fn wrapping_adjacent_selectable(
selectable: &[usize],
selected: Option<usize>,
forward: bool,
) -> Option<usize> {
if selectable.is_empty() {
return None;
}
adjacent_selectable(selectable, selected, forward)
.or_else(|| forward.then(|| selectable.first().copied()).flatten())
.or_else(|| (!forward).then(|| selectable.last().copied()).flatten())
}
/// The next selectable row in the direction, or `None` at the ends. /// The next selectable row in the direction, or `None` at the ends.
pub fn adjacent_selectable( pub fn adjacent_selectable(
selectable: &[usize], selectable: &[usize],
@@ -199,6 +231,25 @@ where
}) })
} }
/// A row that highlights under the pointer, for lists driven by mouse move
/// instead of selection.
#[must_use]
pub fn paint_highlighted_row<R>(cx: &App, row: R, highlighted: bool, disabled: bool) -> R
where
R: IntoElement + Styled + StatefulInteractiveElement,
{
let theme = cx.theme();
row.map(|row| {
if disabled {
row
} else if highlighted {
row.bg(theme.colors.muted)
} else {
row.hover(|row| row.bg(theme.colors.muted))
}
})
}
/// A handler told to clean up after a dismissed surface. /// A handler told to clean up after a dismissed surface.
pub type DismissHandler = std::rc::Rc<dyn Fn(&mut gpui::App)>; pub type DismissHandler = std::rc::Rc<dyn Fn(&mut gpui::App)>;
+122 -107
View File
@@ -33,11 +33,12 @@ use gpui::{
}; };
use crate::components::button::{Button, ButtonVariant}; use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{DIALOG_LAYER, Sizable, StyledExt as _, v_flex}; use crate::components::common::{
DIALOG_LAYER, Sizable, StyledExt as _, floating_panel, h_flex, v_flex,
};
use crate::components::grain::grain; use crate::components::grain::grain;
use crate::components::scroll_area::ScrollArea; use crate::components::scroll_area::ScrollArea;
use crate::icons::IconRole; use crate::icons::IconRole;
use crate::layout::h_flex;
use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH}; use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH};
/// Requests the dialog's close: `false` closes. /// Requests the dialog's close: `false` closes.
@@ -98,6 +99,7 @@ pub struct Dialog {
content: Option<ContentFn>, content: Option<ContentFn>,
actions: Option<ActionsFn>, actions: Option<ActionsFn>,
min_width: Option<DefiniteLength>, min_width: Option<DefiniteLength>,
width: Option<DefiniteLength>,
height: Option<DefiniteLength>, height: Option<DefiniteLength>,
style: StyleRefinement, style: StyleRefinement,
} }
@@ -122,6 +124,7 @@ impl Dialog {
content: None, content: None,
actions: None, actions: None,
min_width: None, min_width: None,
width: None,
height: None, height: None,
style: StyleRefinement::default(), style: StyleRefinement::default(),
} }
@@ -217,6 +220,15 @@ impl Dialog {
self self
} }
/// Sets the panel's fixed width, capped at 90% of the window.
pub fn width<W>(mut self, width: W) -> Self
where
W: Into<DefiniteLength>,
{
self.width = Some(width.into());
self
}
/// Sets the panel's height, body content taller than the panel scrolls. /// Sets the panel's height, body content taller than the panel scrolls.
pub fn height<H>(mut self, height: H) -> Self pub fn height<H>(mut self, height: H) -> Self
where where
@@ -255,13 +267,12 @@ impl RenderOnce for Dialog {
}) })
}); });
let (scrim_color, border, foreground, surface, radius, shadows, enter_duration) = { let (scrim_color, foreground, background, radius, shadows, enter_duration) = {
let theme = cx.theme(); let theme = cx.theme();
( (
theme.colors.overlay, theme.colors.overlay,
theme.colors.border,
theme.colors.foreground, theme.colors.foreground,
theme.colors.surface, theme.colors.background,
theme.radius.overlay, theme.radius.overlay,
theme.elevations.dialog.shadows(), theme.elevations.dialog.shadows(),
theme.motion.overlay, theme.motion.overlay,
@@ -297,112 +308,116 @@ impl RenderOnce for Dialog {
.read(cx) .read(cx)
.clone(); .clone();
let panel = v_flex() let panel = floating_panel(
.id("dialog-panel") cx,
.track_focus(&focus) radius,
.role(role) v_flex()
.aria_label(label) .id("dialog-panel")
.when_some(self.min_width, |panel, width| panel.min_w(width)) .track_focus(&focus)
.when(self.min_width.is_none(), |panel| { .role(role)
panel.min_w(DIALOG_MIN_WIDTH) .aria_label(label)
}) .when_some(self.width, |panel, width| panel.w(width))
.max_w(relative(0.9)) .when(self.width.is_none() && self.min_width.is_none(), |panel| {
.when_some(height, |panel, height| panel.h(height)) panel.min_w(DIALOG_MIN_WIDTH)
.bg(surface) })
.text_color(foreground) .when_some(self.min_width, |panel, width| panel.min_w(width))
.rounded(radius) .max_w(relative(0.9))
.border_1() .when_some(height, |panel, height| panel.h(height))
.border_color(border) .text_color(foreground),
.shadow(shadows) shadows,
.overflow_hidden() )
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) // The panel behind the dialog is `background` (pure white/black), so
.on_key_down({ // the dialog matches it instead of the muted `surface` tint.
let on_change = on_change.clone(); .bg(background)
move |event: &KeyDownEvent, window, cx| { .overflow_hidden()
if event.keystroke.key == "escape" .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
&& !alert .on_key_down({
&& close_on_escape let on_change = on_change.clone();
&& let Some(on_change) = &on_change move |event: &KeyDownEvent, window, cx| {
{ if event.keystroke.key == "escape"
on_change(false, window, cx); && !alert
} && close_on_escape
cx.stop_propagation(); && let Some(on_change) = &on_change
{
on_change(false, window, cx);
}
cx.stop_propagation();
}
})
.when(self.title.is_some() || show_close, |panel| {
panel.child(
h_flex()
.h_12()
.px_2()
.gap_2()
.justify_between()
.when(show_close, |row| row.child(div().w_7()))
.when_some(self.title.clone(), |row, title| {
row.child(
div()
.flex_1()
.text_center()
.text_sm()
.font_semibold()
.child(title),
)
})
.when(show_close, |row| {
row.child(
Button::new("dialog-close")
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.small()
.debug_selector(|| "dialog-close".to_string())
.accessibility_label("Close")
.on_click({
let on_change = on_change.clone();
move |_, window, cx| {
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
}
}),
)
}),
)
})
.when_some(content, |panel, content| {
panel.map(|this| {
if height.is_some() {
this.child(
ScrollArea::new("dialog-content")
.handle(scroll)
.flex_1()
.min_h_0()
.child(div().p_2().child(content)),
)
} else {
this.child(div().p_2().child(content))
} }
}) })
.when(self.title.is_some() || show_close, |panel| { })
panel.child( .when_some(actions, |panel, actions| {
h_flex() panel.child(
.h_12() h_flex()
.px_2() .px_2()
.gap_2() .h_12()
.justify_between() .justify_end()
.when(show_close, |row| row.child(div().w_7())) .gap_2()
.when_some(self.title.clone(), |row, title| { .children(actions),
row.child( )
div() })
.flex_1() .child(
.text_center() canvas(|_, _, _| {}, {
.text_sm() move |_, _, window, cx| {
.font_semibold() if !focus.contains_focused(window, cx) {
.child(title), window.focus(&focus, cx);
)
})
.when(show_close, |row| {
row.child(
Button::new("dialog-close")
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.small()
.debug_selector(|| "dialog-close".to_string())
.accessibility_label("Close")
.on_click({
let on_change = on_change.clone();
move |_, window, cx| {
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
}
}),
)
}),
)
})
.when_some(content, |panel, content| {
panel.map(|this| {
if height.is_some() {
this.child(
ScrollArea::new("dialog-content")
.handle(scroll)
.flex_1()
.min_h_0()
.child(div().p_2().child(content)),
)
} else {
this.child(div().p_2().child(content))
} }
}) }
}) })
.when_some(actions, |panel, actions| { .absolute()
panel.child( .inset_0(),
h_flex() );
.px_2()
.h_12()
.justify_end()
.gap_2()
.children(actions),
)
})
.child(
canvas(|_, _, _| {}, {
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
let scrim = div() let scrim = div()
.absolute() .absolute()
+9 -8
View File
@@ -33,14 +33,17 @@ use gpui::{
App, Context, ElementId, HighlightStyle, InteractiveElement as _, IntoElement, App, Context, ElementId, HighlightStyle, InteractiveElement as _, IntoElement,
ListHorizontalSizingBehavior, ParentElement as _, Pixels, Render, ScrollStrategy, SharedString, ListHorizontalSizingBehavior, ParentElement as _, Pixels, Render, ScrollStrategy, SharedString,
StatefulInteractiveElement as _, Styled as _, TextStyle, UniformListScrollHandle, Window, div, StatefulInteractiveElement as _, Styled as _, TextStyle, UniformListScrollHandle, Window, div,
point, rems, uniform_list, point, px, rems, uniform_list,
}; };
use similar::{Change, ChangeTag, TextDiff}; use similar::{Change, ChangeTag, TextDiff};
use crate::components::highlight::{HighlightedCode, Language, Line, Role, highlight}; use crate::components::highlight::{HighlightedCode, Language, Line, Role, highlight};
use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility}; use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility};
use crate::components::utils::{gutter_cell, wash, wash_gutter, wash_strong}; use crate::components::utils::{gutter_cell, wash, wash_gutter, wash_strong};
use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CODE_GUTTER_WIDTH, MONO_ADVANCE_RATIO}; use crate::theme::{ActiveTheme as _, CODE_GUTTER_WIDTH, CODE_LINE_HEIGHT, MONO_ADVANCE_RATIO};
/// The left change-indicator bar's width, four hairlines.
const CHANGE_BAR_WIDTH: Pixels = px(4.0);
/// What a diff row did to the file. /// What a diff row did to the file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -525,7 +528,7 @@ fn render_row(
let mono_font = theme.mono_font; let mono_font = theme.mono_font;
let colors = theme.colors; let colors = theme.colors;
let ramps = theme.ramps; let ramps = theme.ramps;
let line_height = text_size * 1.5; let line_height = text_size * CODE_LINE_HEIGHT;
let char_width = text_size * MONO_ADVANCE_RATIO; let char_width = text_size * MONO_ADVANCE_RATIO;
let frame = div() let frame = div()
@@ -563,7 +566,7 @@ fn render_row(
row_element.child( row_element.child(
div() div()
.flex_none() .flex_none()
.border_l(BORDER_WIDTH * 4.0) .border_l(CHANGE_BAR_WIDTH)
.border_color(gpui::transparent_black()), .border_color(gpui::transparent_black()),
) )
}, },
@@ -689,9 +692,7 @@ fn render_row(
_ => wash_strong(change_color), _ => wash_strong(change_color),
}) })
.when(options.indicators == DiffIndicators::Bars, |number| { .when(options.indicators == DiffIndicators::Bars, |number| {
number number.border_l(CHANGE_BAR_WIDTH).border_color(change_color)
.border_l(BORDER_WIDTH * 4.0)
.border_color(change_color)
}), }),
) )
}) })
@@ -702,7 +703,7 @@ fn render_row(
div() div()
.h_full() .h_full()
.flex_none() .flex_none()
.border_l(BORDER_WIDTH * 4.0) .border_l(CHANGE_BAR_WIDTH)
.border_color(change_color), .border_color(change_color),
) )
}, },
+10 -35
View File
@@ -23,7 +23,7 @@ use gpui::{
div, relative, div, relative,
}; };
use crate::components::button::ButtonVariant; use crate::components::button::{ButtonChrome, ButtonVariant};
use crate::components::common::{ use crate::components::common::{
ControlSizing, Sizable, StyledExt as _, focus_handle, focus_ring, h_flex, ControlSizing, Sizable, StyledExt as _, focus_handle, focus_ring, h_flex,
}; };
@@ -194,45 +194,20 @@ impl RenderOnce for DropdownMenu {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme(); let theme = cx.theme();
let colors = theme.colors; let colors = theme.colors;
let ramps = theme.ramps; let radius = theme.radius.full;
let radius = theme.radius.control;
let ring = colors.ring; let ring = colors.ring;
let (panel_chrome, enter_duration) = MenuChrome::read(cx); let (panel_chrome, enter_duration) = MenuChrome::read(cx);
let (background, foreground, hover, pressed) = match self.variant {
ButtonVariant::Primary => (
Some(ramps.primary.base),
colors.primary_foreground,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (
Some(colors.surface),
colors.foreground,
colors.muted,
colors.muted_hover,
),
ButtonVariant::Ghost => (
None,
colors.foreground,
colors.muted_hover,
ramps.secondary.pressed,
),
ButtonVariant::Destructive => (
Some(ramps.destructive.base),
colors.destructive_foreground,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
let border = match self.variant { let ButtonChrome {
ButtonVariant::Primary => ramps.primary.base, background,
ButtonVariant::Secondary => colors.border, foreground,
ButtonVariant::Ghost => gpui::transparent_black(), hover,
ButtonVariant::Destructive => ramps.destructive.base, pressed,
}; border,
..
} = self.variant.chrome(cx);
let split = self.on_click.is_some(); let split = self.on_click.is_some();
let icon_only = self.icon.is_some() && self.label.is_none() && !split; let icon_only = self.icon.is_some() && self.label.is_none() && !split;
+14
View File
@@ -71,6 +71,20 @@ impl EmptyState {
self.action = Some(action.into_any_element()); self.action = Some(action.into_any_element());
self self
} }
/// A compact inline caption for popups with nothing to show.
#[must_use]
pub fn compact<L>(label: L, cx: &App) -> gpui::Div
where
L: Into<SharedString>,
{
div()
.px_2()
.py_1()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(label.into())
}
} }
impl gpui::Styled for EmptyState { impl gpui::Styled for EmptyState {
+2 -6
View File
@@ -143,9 +143,7 @@ impl RenderOnce for Field {
}; };
let content = if self.variant == FieldVariant::Row { let content = if self.variant == FieldVariant::Row {
div() v_flex()
.flex()
.flex_col()
.gap_1() .gap_1()
.child( .child(
h_flex() h_flex()
@@ -160,9 +158,7 @@ impl RenderOnce for Field {
}) })
.when_some(error, |field, error| field.child(error)) .when_some(error, |field, error| field.child(error))
} else { } else {
div() v_flex()
.flex()
.flex_col()
.gap_2() .gap_2()
.child( .child(
v_flex() v_flex()
+96 -11
View File
@@ -23,6 +23,7 @@
use std::ops::Range; use std::ops::Range;
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
@@ -353,15 +354,17 @@ impl InputBindings {
} }
/// The shaped text: one wrapped line per buffer line, plus the mask map when masking. /// The shaped text: one wrapped line per buffer line, plus the mask map when masking.
#[derive(Clone)]
struct ShapedText { struct ShapedText {
lines: Vec<ShapedLineEntry>, lines: Vec<ShapedLineEntry>,
mask_map: Option<Vec<(usize, usize)>>, mask_map: Option<Vec<(usize, usize)>>,
} }
/// One shaped source line and its first byte's offset in the display text. /// One shaped source line and its first byte's offset in the display text.
#[derive(Clone)]
struct ShapedLineEntry { struct ShapedLineEntry {
start: usize, start: usize,
line: WrappedLine, line: Arc<WrappedLine>,
} }
/// The field's inner padding. /// The field's inner padding.
@@ -550,6 +553,18 @@ pub struct InputState {
caret_epoch_started: Instant, caret_epoch_started: Instant,
/// The shaped line and element bounds, recorded during each paint. /// The shaped line and element bounds, recorded during each paint.
layout: Option<InputLayout>, layout: Option<InputLayout>,
/// The last shaped buffer, reused while no shaping input changed.
shaped_cache: std::cell::RefCell<Option<(ShapeCacheKey, ShapedText)>>,
}
/// Everything `shape_text` consumes, for cache reuse between frames.
#[derive(Clone, PartialEq)]
struct ShapeCacheKey {
text: String,
wrap_width: Option<Pixels>,
font_size: Pixels,
font: Font,
color: gpui::Hsla,
} }
impl EventEmitter<InputStateEvent> for InputState {} impl EventEmitter<InputStateEvent> for InputState {}
@@ -645,6 +660,7 @@ impl InputState {
caret_epoch: 0, caret_epoch: 0,
caret_epoch_started: Instant::now(), caret_epoch_started: Instant::now(),
layout: None, layout: None,
shaped_cache: std::cell::RefCell::new(None),
} }
} }
@@ -1024,7 +1040,8 @@ impl InputState {
} }
/// Shapes the masked or plain buffer, wrapping to `wrap_width` when set, /// Shapes the masked or plain buffer, wrapping to `wrap_width` when set,
/// with the paint-time text style. /// with the paint-time text style. Reuses the previous result while the
/// text, wrap width, and text style are unchanged.
fn shape_current_text(&self, wrap_width: Option<Pixels>, window: &Window) -> ShapedText { fn shape_current_text(&self, wrap_width: Option<Pixels>, window: &Window) -> ShapedText {
let (text, mask_map) = if self.masked() { let (text, mask_map) = if self.masked() {
masked_display(&self.text) masked_display(&self.text)
@@ -1042,6 +1059,21 @@ impl InputState {
}; };
let font_size = text_style.font_size.to_pixels(window.rem_size()); let font_size = text_style.font_size.to_pixels(window.rem_size());
let key = ShapeCacheKey {
text: text.clone(),
wrap_width,
font_size,
font: font.clone(),
color: text_style.color,
};
if let Some((cached_key, shaped)) = self.shaped_cache.borrow().as_ref()
&& *cached_key == key
{
return shaped.clone();
}
let runs = [TextRun { let runs = [TextRun {
len: text.len(), len: text.len(),
font, font,
@@ -1062,14 +1094,19 @@ impl InputState {
let mut start = 0; let mut start = 0;
for line in shaped { for line in shaped {
let end = start + line.len(); let end = start + line.len();
lines.push(ShapedLineEntry { start, line }); lines.push(ShapedLineEntry {
start,
line: Arc::new(line),
});
start = end + '\n'.len_utf8(); start = end + '\n'.len_utf8();
} }
} }
Err(err) => log::warn!("shaping input text failed: {err}"), Err(err) => log::warn!("shaping input text failed: {err}"),
} }
ShapedText { lines, mask_map } let shaped = ShapedText { lines, mask_map };
*self.shaped_cache.borrow_mut() = Some((key, shaped.clone()));
shaped
} }
/// Stores the paint geometry for hit-testing and the IME conversions. /// Stores the paint geometry for hit-testing and the IME conversions.
@@ -2210,15 +2247,12 @@ impl RenderOnce for Input {
input.child(edge_zone("input-prefix", prefix)) input.child(edge_zone("input-prefix", prefix))
}) })
.child( .child(
div() h_flex()
.relative() .relative()
.flex_1() .flex_1()
.min_w_0() .min_w_0()
.h_full() .h_full()
.overflow_hidden() .overflow_hidden()
.flex()
.flex_row()
.items_center()
.when_some(line_height, |region, line_height| { .when_some(line_height, |region, line_height| {
region.items_start().line_height(line_height) region.items_start().line_height(line_height)
}) })
@@ -2616,12 +2650,63 @@ fn utf16_to_utf8_offset(text: &str, utf16_offset: usize) -> usize {
/// Converts a UTF-8 byte range to a UTF-16 range. /// Converts a UTF-8 byte range to a UTF-16 range.
fn utf8_range_to_utf16(text: &str, range: Range<usize>) -> Range<usize> { fn utf8_range_to_utf16(text: &str, range: Range<usize>) -> Range<usize> {
let start = text[..range.start].encode_utf16().count(); // IME can supply reversed or off-boundary offsets; normalize both
let end = start + text[range.start..range.end].encode_utf16().count(); // endpoints so the slicing below cannot panic.
let start = floor_to_char_boundary(text, range.start.min(range.end));
let end = floor_to_char_boundary(text, range.start.max(range.end));
let start = text[..start].encode_utf16().count();
let end = start + text[start..end].encode_utf16().count();
start..end start..end
} }
/// Converts a UTF-16 range to a UTF-8 byte range. /// Converts a UTF-16 range to a UTF-8 byte range.
fn utf16_range_to_utf8(text: &str, range: Range<usize>) -> Range<usize> { fn utf16_range_to_utf8(text: &str, range: Range<usize>) -> Range<usize> {
utf16_to_utf8_offset(text, range.start)..utf16_to_utf8_offset(text, range.end) // IME can supply a reversed range; order the endpoints so the result
// slices cleanly.
let (start, end) = (range.start.min(range.end), range.start.max(range.end));
utf16_to_utf8_offset(text, start)..utf16_to_utf8_offset(text, end)
}
/// Floors `index` to the nearest char boundary at or below it.
fn floor_to_char_boundary(text: &str, index: usize) -> usize {
if index >= text.len() {
return text.len();
}
let mut index = index;
while !text.is_char_boundary(index) {
index -= 1;
}
index
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[allow(clippy::reversed_empty_ranges)] // The fixture is intentionally reversed.
fn utf16_range_to_utf8_orders_reversed_endpoints() {
// "héllo": h 0, é 1, l 2, l 3, o 4 in UTF-16 units.
let text = "héllo";
assert_eq!(utf16_range_to_utf8(text, 4..2), 3..5);
assert_eq!(utf16_range_to_utf8(text, 2..4), 3..5);
}
#[test]
#[allow(clippy::reversed_empty_ranges)] // The fixture is intentionally reversed.
fn utf8_range_to_utf16_floors_off_boundary_offsets() {
let text = "héllo";
// Byte 2 sits inside `é`; a reversed, off-boundary range must not panic.
let range = utf8_range_to_utf16(text, 4..2);
assert!(range.start <= range.end);
assert_eq!(range, 1..3);
}
#[test]
fn char_boundary_floor_clamps_to_len() {
// "héllo" is six bytes.
assert_eq!(floor_to_char_boundary("héllo", 7), 6);
assert_eq!(floor_to_char_boundary("héllo", 2), 1);
assert_eq!(floor_to_char_boundary("héllo", 0), 0);
}
} }
+4 -5
View File
@@ -25,8 +25,9 @@ use gpui::{
StyleRefinement, Styled as _, Window, div, rems, StyleRefinement, Styled as _, Window, div, rems,
}; };
use crate::common::focus_handle;
use crate::components::common::{ use crate::components::common::{
StyledExt as _, nav_key, paint_selectable_row, selectable_label_color, StyledExt as _, nav_key, paint_selectable_row, selectable_label_color, v_flex,
}; };
use crate::icons::Icon; use crate::icons::Icon;
use crate::theme::ActiveTheme as _; use crate::theme::ActiveTheme as _;
@@ -172,7 +173,7 @@ impl RenderOnce for List {
.map(|(index, _)| index) .map(|(index, _)| index)
.collect(); .collect();
let focus = crate::components::common::focus_handle(&self.id, window, cx); let focus = focus_handle(&self.id, window, cx);
let label = self let label = self
.a11y_label .a11y_label
@@ -194,10 +195,8 @@ impl RenderOnce for List {
}) })
.collect(); .collect();
div() v_flex()
.id(self.id) .id(self.id)
.flex()
.flex_col()
.gap_0p5() .gap_0p5()
.text_sm() .text_sm()
.refine_style(&self.style) .refine_style(&self.style)
+7 -17
View File
@@ -45,7 +45,7 @@ use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, T
use crate::components::button::{Button, ButtonVariant}; use crate::components::button::{Button, ButtonVariant};
use crate::components::checkbox::Checkbox; use crate::components::checkbox::Checkbox;
use crate::components::common::{Sizable as _, StyledExt as _}; use crate::components::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use crate::components::highlight::{HighlightedCode, Language, highlight, plain}; use crate::components::highlight::{HighlightedCode, Language, highlight, plain};
use crate::components::scrollbar::{Scrollbar, ScrollbarVisibility}; use crate::components::scrollbar::{Scrollbar, ScrollbarVisibility};
use crate::components::utils::code_line; use crate::components::utils::code_line;
@@ -853,10 +853,8 @@ pub fn bind_text_view_keys(cx: &mut App) {
fn view_container(frame: &ViewFrame) -> Div { fn view_container(frame: &ViewFrame) -> Div {
let clear_flag = frame.pressed_on_piece.clone(); let clear_flag = frame.pressed_on_piece.clone();
div() v_flex()
.w_full() .w_full()
.flex()
.flex_col()
.key_context(TEXT_VIEW_CONTEXT) .key_context(TEXT_VIEW_CONTEXT)
.track_focus(&frame.focus_handle) .track_focus(&frame.focus_handle)
.on_action({ .on_action({
@@ -1470,15 +1468,13 @@ fn render_block(
/// The shared block frame: ambient text style, spacing, quote bar. /// The shared block frame: ambient text style, spacing, quote bar.
fn block_frame(quote: bool, top: Rems, bottom: Rems, id: &ElementId, cx: &App) -> Div { fn block_frame(quote: bool, top: Rems, bottom: Rems, id: &ElementId, cx: &App) -> Div {
let theme = cx.theme(); let theme = cx.theme();
div() v_flex()
.debug_selector({ .debug_selector({
let id = id.clone(); let id = id.clone();
move || id.to_string() move || id.to_string()
}) })
.w_full() .w_full()
.flex() .font_family(theme.ui_font())
.flex_col()
.font_family(".SystemUIFont")
.text_xs() .text_xs()
.line_height(relative(BODY_LINE_HEIGHT)) .line_height(relative(BODY_LINE_HEIGHT))
.text_color(theme.colors.foreground) .text_color(theme.colors.foreground)
@@ -1714,9 +1710,7 @@ fn code_row(
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join("\n"); .join("\n");
let actions_row = div() let actions_row = h_flex()
.flex()
.items_center()
.justify_between() .justify_between()
.pb_1() .pb_1()
.when_some(language.cloned(), |row, language| { .when_some(language.cloned(), |row, language| {
@@ -1737,10 +1731,8 @@ fn code_row(
}), }),
); );
let plate = div() let plate = v_flex()
.w_full() .w_full()
.flex()
.flex_col()
.rounded(theme.radius.control) .rounded(theme.radius.control)
.bg(theme.colors.muted) .bg(theme.colors.muted)
.p_2() .p_2()
@@ -1798,10 +1790,8 @@ fn table_row(
let row_count = table.rows.len(); let row_count = table.rows.len();
let mut cell_ix = 0usize; let mut cell_ix = 0usize;
let grid = div() let grid = v_flex()
.w_full() .w_full()
.flex()
.flex_col()
.border_1() .border_1()
.border_color(colors.border) .border_color(colors.border)
.rounded(theme.radius.control) .rounded(theme.radius.control)
+117 -126
View File
@@ -25,14 +25,17 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
Animation, AnimationExt as _, AnyElement, App, Bounds, BoxShadow, DefiniteLength, Animation, AnimationExt as _, AnyElement, App, Bounds, DefiniteLength, DispatchPhase,
DispatchPhase, ElementId, Entity, FocusHandle, InteractiveElement as _, IntoElement, ElementId, Entity, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent,
KeyDownEvent, MouseButton, MouseDownEvent, ParentElement as _, Pixels, Point, RenderOnce, Role, MouseButton, MouseDownEvent, ParentElement as _, Pixels, Point, RenderOnce, Role, ScrollHandle,
ScrollHandle, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, anchored,
Window, anchored, canvas, deferred, div, ease_out_quint, point, px, relative, rems, canvas, deferred, div, ease_out_quint, point, px, relative, rems,
}; };
use crate::components::common::{OVERLAY_LAYER, StyledExt as _, focus_handle, v_flex}; use crate::components::common::{
OVERLAY_LAYER, StyledExt as _, floating_panel, focus_handle, v_flex,
wrapping_adjacent_selectable,
};
use crate::components::scroll_area::{ScrollArea, ScrollAxes}; use crate::components::scroll_area::{ScrollArea, ScrollAxes};
use crate::icons::{Icon, IconRole, icon as icon_glyph}; use crate::icons::{Icon, IconRole, icon as icon_glyph};
use crate::theme::{ActiveTheme as _, MENU_MIN_WIDTH, POPUP_MAX_HEIGHT}; use crate::theme::{ActiveTheme as _, MENU_MIN_WIDTH, POPUP_MAX_HEIGHT};
@@ -190,7 +193,6 @@ impl FluentBuilder for MenuItem {}
/// Menu chrome styles. /// Menu chrome styles.
#[derive(Clone)] #[derive(Clone)]
pub(crate) struct MenuChrome { pub(crate) struct MenuChrome {
surface: gpui::Hsla,
border: gpui::Hsla, border: gpui::Hsla,
foreground: gpui::Hsla, foreground: gpui::Hsla,
muted_foreground: gpui::Hsla, muted_foreground: gpui::Hsla,
@@ -199,9 +201,7 @@ pub(crate) struct MenuChrome {
primary_foreground: gpui::Hsla, primary_foreground: gpui::Hsla,
destructive: gpui::Hsla, destructive: gpui::Hsla,
destructive_foreground: gpui::Hsla, destructive_foreground: gpui::Hsla,
radius_overlay: Pixels, radius_full: Pixels,
radius_sm: Pixels,
shadow: Vec<BoxShadow>,
} }
/// A floating menu of [`MenuItem`] rows anchored below its trigger. /// A floating menu of [`MenuItem`] rows anchored below its trigger.
@@ -227,7 +227,6 @@ impl MenuChrome {
let theme = cx.theme(); let theme = cx.theme();
( (
Self { Self {
surface: theme.colors.surface,
border: theme.colors.border, border: theme.colors.border,
foreground: theme.colors.foreground, foreground: theme.colors.foreground,
muted_foreground: theme.colors.muted_foreground, muted_foreground: theme.colors.muted_foreground,
@@ -236,9 +235,7 @@ impl MenuChrome {
primary_foreground: theme.colors.primary_foreground, primary_foreground: theme.colors.primary_foreground,
destructive: theme.ramps.destructive.base, destructive: theme.ramps.destructive.base,
destructive_foreground: theme.colors.destructive_foreground, destructive_foreground: theme.colors.destructive_foreground,
radius_overlay: theme.radius.overlay, radius_full: theme.radius.full,
radius_sm: theme.radius.sm,
shadow: theme.elevations.popover.shadows(),
}, },
theme.motion.overlay, theme.motion.overlay,
) )
@@ -688,110 +685,110 @@ fn menu_panel(
}) })
.collect(); .collect();
v_flex() floating_panel(
.id("menu-panel") cx,
.debug_selector(move || format!("{}-panel", params.debug_prefix)) cx.theme().radius.overlay,
.occlude() v_flex()
.track_focus(focus) .id("menu-panel")
.role(Role::Menu) .debug_selector(move || format!("{}-panel", params.debug_prefix))
.aria_label(params.label) .occlude()
.when_some(params.min_width, |panel, width| panel.min_w(width)) .track_focus(focus)
.when(params.min_width.is_none(), |panel| { .role(Role::Menu)
panel.min_w(MENU_MIN_WIDTH) .aria_label(params.label)
}) .when_some(params.min_width, |panel, width| panel.min_w(width))
.p_1() .when(params.min_width.is_none(), |panel| {
.bg(params.chrome.surface) panel.min_w(MENU_MIN_WIDTH)
.text_color(params.chrome.foreground) })
.rounded(params.chrome.radius_overlay) .p_1()
.border_1() .text_color(params.chrome.foreground),
.border_color(params.chrome.border) cx.theme().elevations.popover.shadows(),
.shadow(params.chrome.shadow.clone()) )
.overflow_hidden() .overflow_hidden()
.on_mouse_down_out({ .on_mouse_down_out({
let on_dismiss = params.on_dismiss.clone(); let on_dismiss = params.on_dismiss.clone();
let dismiss_bounds = params.dismiss_bounds.clone(); let dismiss_bounds = params.dismiss_bounds.clone();
let flyout_stack = flyout_stack.clone(); let flyout_stack = flyout_stack.clone();
move |event, window, cx| { move |event, window, cx| {
if dismiss_bounds if dismiss_bounds
.borrow() .borrow()
.is_some_and(|bounds| bounds.contains(&event.position))
{
return;
}
// Clicks inside any open flyout belong to that flyout.
if flyout_stack.borrow().iter().any(|cell| {
cell.borrow()
.is_some_and(|bounds| bounds.contains(&event.position)) .is_some_and(|bounds| bounds.contains(&event.position))
{ }) {
return; return;
}
// Clicks inside any open flyout belong to that flyout.
if flyout_stack.borrow().iter().any(|cell| {
cell.borrow()
.is_some_and(|bounds| bounds.contains(&event.position))
}) {
return;
}
if let Some(on_dismiss) = &on_dismiss {
on_dismiss(false, window, cx);
}
} }
})
.on_key_down({ if let Some(on_dismiss) = &on_dismiss {
let items = params.items.clone(); on_dismiss(false, window, cx);
let selection = selection.clone();
let set_flyout = set_flyout.clone();
let on_dismiss = params.on_dismiss.clone();
let on_activate = params.on_activate.clone();
let left_dismisses = params.is_flyout;
move |event: &KeyDownEvent, window, cx| {
handle_menu_key(
event,
MenuKeyEnv {
items: &items,
selection: &selection,
set_flyout: &set_flyout,
on_dismiss: &on_dismiss,
on_activate: &on_activate,
left_dismisses,
},
window,
cx,
);
} }
}) }
.child( })
ScrollArea::new("menu-items") .on_key_down({
.handle(scroll.read(cx).clone()) let items = params.items.clone();
.axes(ScrollAxes::Vertical) let selection = selection.clone();
.max_h(POPUP_MAX_HEIGHT) let set_flyout = set_flyout.clone();
.child(v_flex().gap_0p5().children(rows)), let on_dismiss = params.on_dismiss.clone();
) let on_activate = params.on_activate.clone();
.child( let left_dismisses = params.is_flyout;
canvas( move |event: &KeyDownEvent, window, cx| {
{ handle_menu_key(
let bounds_sink = params.bounds_sink.cloned(); event,
move |bounds, _window, _cx| { MenuKeyEnv {
if let Some(cell) = &bounds_sink { items: &items,
*cell.borrow_mut() = Some(bounds); selection: &selection,
} set_flyout: &set_flyout,
} on_dismiss: &on_dismiss,
on_activate: &on_activate,
left_dismisses,
}, },
{ window,
let focus = focus.clone(); cx,
let flyout_open = flyout_open.clone(); );
move |_, _, window, cx| { }
if flyout_open.read(cx).is_none() && !focus.contains_focused(window, cx) { })
window.focus(&focus, cx); .child(
} ScrollArea::new("menu-items")
.handle(scroll.read(cx).clone())
.axes(ScrollAxes::Vertical)
.max_h(POPUP_MAX_HEIGHT)
.child(v_flex().gap_0p5().children(rows)),
)
.child(
canvas(
{
let bounds_sink = params.bounds_sink.cloned();
move |bounds, _window, _cx| {
if let Some(cell) = &bounds_sink {
*cell.borrow_mut() = Some(bounds);
} }
}, }
) },
.absolute() {
.inset_0(), let focus = focus.clone();
let flyout_open = flyout_open.clone();
move |_, _, window, cx| {
if flyout_open.read(cx).is_none() && !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
},
) )
.with_animation( .absolute()
"menu-enter", .inset_0(),
Animation::new(params.enter_duration).with_easing(ease_out_quint()), )
|panel, delta| panel.opacity(delta), .with_animation(
) "menu-enter",
.into_any_element() Animation::new(params.enter_duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
)
.into_any_element()
} }
/// Renders one menu row. /// Renders one menu row.
@@ -968,7 +965,7 @@ fn row_shell(
.px_4() .px_4()
.text_sm() .text_sm()
.line_height(relative(1.0)) .line_height(relative(1.0))
.rounded(chrome.radius_sm) .rounded(chrome.radius_full)
.map(|row| { .map(|row| {
if item.disabled { if item.disabled {
row row
@@ -1053,8 +1050,6 @@ fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, c
.collect(); .collect();
let current = *env.selection.read(cx); let current = *env.selection.read(cx);
let position =
current.and_then(|current| selectable.iter().position(|index| *index == current));
match event.keystroke.key.as_str() { match event.keystroke.key.as_str() {
"down" | "up" | "home" | "end" => { "down" | "up" | "home" | "end" => {
@@ -1062,19 +1057,15 @@ fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, c
return; return;
} }
let next = match event.keystroke.key.as_str() { let next = match event.keystroke.key.as_str() {
"down" => match position { "down" => wrapping_adjacent_selectable(&selectable, current, true),
Some(pos) => (pos + 1).min(selectable.len() - 1), "up" => wrapping_adjacent_selectable(&selectable, current, false),
None => 0, "home" => selectable.first().copied(),
}, _ => selectable.last().copied(),
"up" => match position {
Some(pos) => pos.saturating_sub(1),
None => selectable.len() - 1,
},
"home" => 0,
_ => selectable.len() - 1,
}; };
env.selection if let Some(next) = next {
.update(cx, |selection, _| *selection = Some(selectable[next])); env.selection
.update(cx, |selection, _| *selection = Some(next));
}
} }
"right" => { "right" => {
let opens = current let opens = current
+49 -50
View File
@@ -31,7 +31,7 @@ use gpui::{
px, px,
}; };
use crate::components::common::{OVERLAY_LAYER, StyledExt as _, v_flex}; use crate::components::common::{OVERLAY_LAYER, StyledExt as _, floating_panel, v_flex};
use crate::theme::{ActiveTheme as _, POPOVER_MIN_WIDTH}; use crate::theme::{ActiveTheme as _, POPOVER_MIN_WIDTH};
/// Reports the next open state of a [`Popover`]: `true` to open, `false` to close. /// Reports the next open state of a [`Popover`]: `true` to open, `false` to close.
@@ -124,14 +124,13 @@ impl gpui::Styled for Popover {
impl RenderOnce for Popover { impl RenderOnce for Popover {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let (colors, radius, shadows, enter_duration, panel_border) = { let (colors, radius, shadows, enter_duration) = {
let theme = cx.theme(); let theme = cx.theme();
( (
theme.colors, theme.colors,
theme.radius, theme.radius,
theme.elevations.popover.shadows(), theme.elevations.popover.shadows(),
theme.motion.overlay, theme.motion.overlay,
theme.colors.border,
) )
}; };
@@ -197,60 +196,60 @@ impl RenderOnce for Popover {
let focus = crate::components::common::focus_handle(&self.id, window, cx); let focus = crate::components::common::focus_handle(&self.id, window, cx);
let content = self.content.map(|content| content(window, cx)); let content = self.content.map(|content| content(window, cx));
let panel = v_flex() let panel = floating_panel(
.id("popover-panel") cx,
.debug_selector(|| "popover-panel".to_string()) radius.overlay,
.occlude() v_flex()
.track_focus(&focus) .id("popover-panel")
.role(Role::Dialog) .debug_selector(|| "popover-panel".to_string())
.aria_label(label) .occlude()
.min_w(POPOVER_MIN_WIDTH) .track_focus(&focus)
.bg(colors.surface) .role(Role::Dialog)
.text_color(colors.surface_foreground) .aria_label(label)
.rounded(radius.overlay) .min_w(POPOVER_MIN_WIDTH)
.border_1() .text_color(colors.surface_foreground),
.border_color(panel_border) shadows,
.shadow(shadows) )
.overflow_hidden() .overflow_hidden()
.on_mouse_down_out({ .on_mouse_down_out({
let on_change = on_change.clone(); let on_change = on_change.clone();
let trigger_bounds = trigger_bounds.clone(); let trigger_bounds = trigger_bounds.clone();
move |event, window, cx| { move |event, window, cx| {
if trigger_bounds if trigger_bounds
.borrow() .borrow()
.is_some_and(|bounds| bounds.contains(&event.position)) .is_some_and(|bounds| bounds.contains(&event.position))
{ {
return; return;
} }
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
}
})
.on_key_down({
let on_change = on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "escape" {
if let Some(on_change) = &on_change { if let Some(on_change) = &on_change {
on_change(false, window, cx); on_change(false, window, cx);
} }
cx.stop_propagation();
} }
}) }
.on_key_down({ })
let on_change = on_change.clone(); .when_some(content, |panel, content| panel.child(content))
move |event: &KeyDownEvent, window, cx| { .child(
if event.keystroke.key == "escape" { canvas(|_, _, _| {}, {
if let Some(on_change) = &on_change { let focus = focus;
on_change(false, window, cx); move |_, _, window, cx| {
} if !focus.contains_focused(window, cx) {
cx.stop_propagation(); window.focus(&focus, cx);
} }
} }
}) })
.when_some(content, |panel, content| panel.child(content)) .absolute()
.child( .inset_0(),
canvas(|_, _, _| {}, { );
let focus = focus;
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
wrapper.child( wrapper.child(
deferred(anchored().offset(point(Pixels::ZERO, px(4.))).child( deferred(anchored().offset(point(Pixels::ZERO, px(4.))).child(
+2 -2
View File
@@ -228,8 +228,8 @@ where
}; };
h_flex() h_flex()
.id((ElementId::from("segment"), segment.label.clone())) .id(("segment", index))
.gap_2() .gap_1()
.justify_center() .justify_center()
.cursor_pointer() .cursor_pointer()
.h_full() .h_full()
+1 -2
View File
@@ -221,7 +221,6 @@ where
let open_for_items = open.clone(); let open_for_items = open.clone();
let rest_border = if is_open { ring } else { border }; let rest_border = if is_open { ring } else { border };
let hover_border = rest_border;
let selected_index = self.selected.as_ref().and_then(|value| { let selected_index = self.selected.as_ref().and_then(|value| {
self.options self.options
@@ -282,7 +281,7 @@ where
} else { } else {
muted_foreground muted_foreground
}) })
.hover(|style| style.bg(muted).border_color(hover_border)) .hover(|style| style.bg(muted).border_color(rest_border))
.child(trigger_text.clone()) .child(trigger_text.clone())
.child( .child(
icon(IconRole::ChevronDown) icon(IconRole::ChevronDown)
+1 -3
View File
@@ -378,9 +378,7 @@ impl RenderOnce for Sidebar {
.handle(scroll.read(cx).clone()) .handle(scroll.read(cx).clone())
.h_full() .h_full()
.child( .child(
div() v_flex()
.flex()
.flex_col()
.gap_0p5() .gap_0p5()
.when(padded, |content| content.p_2()) .when(padded, |content| content.p_2())
.children(children), .children(children),
+75 -47
View File
@@ -30,7 +30,7 @@ use std::time::Duration;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
App, Context, ElementId, Entity, EventEmitter, InteractiveElement as _, IntoElement, App, Context, Div, ElementId, Entity, EventEmitter, Hsla, InteractiveElement as _, IntoElement,
ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled, Subscription, Task, WeakEntity, Window, div, relative, rems, StyleRefinement, Styled, Subscription, Task, WeakEntity, Window, div, relative, rems,
}; };
@@ -719,6 +719,32 @@ impl Sizable for SpeechButton {
} }
} }
/// The waveform bar elements for a dictation control's level history.
fn waveform_bars<'a>(
levels: &'a [f32],
size: Size,
cx: &'a App,
bar_color: impl Fn(f32) -> Hsla + 'a,
) -> impl IntoIterator<Item = Div> + 'a {
let theme = cx.theme();
let bar_height = move |level: f32| {
if theme.accessibility.reduce_motion {
STILL_HEIGHT
} else {
DOT_HEIGHT + (1.0 - DOT_HEIGHT) * level
}
};
levels.iter().map(move |level| {
div()
.flex_none()
.w(rems(size.dense_icon_rems().0 / 4.0))
.h(relative(bar_height(*level)))
.rounded(theme.radius.full)
.bg(bar_color(*level))
})
}
impl RenderOnce for SpeechButton { impl RenderOnce for SpeechButton {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let unsupported = !self.speech.read(cx).has_recognizer(); let unsupported = !self.speech.read(cx).has_recognizer();
@@ -726,7 +752,7 @@ impl RenderOnce for SpeechButton {
return div().into_any_element(); return div().into_any_element();
} }
let (status, unavailable, capturing, reduce_motion, bars) = { let (status, unavailable, capturing, bars) = {
let state = self.speech.read(cx); let state = self.speech.read(cx);
let status = state.status(); let status = state.status();
let levels = state.levels(); let levels = state.levels();
@@ -735,7 +761,6 @@ impl RenderOnce for SpeechButton {
status, status,
unsupported || !state.is_available(cx), unsupported || !state.is_available(cx),
status.is_capturing(), status.is_capturing(),
cx.theme().accessibility.reduce_motion,
levels[tail_start..].to_vec(), levels[tail_start..].to_vec(),
) )
}; };
@@ -762,6 +787,7 @@ impl RenderOnce for SpeechButton {
}; };
let foreground = colors.foreground; let foreground = colors.foreground;
let bar_color = |_| theme.ramps.primary.base;
h_flex() h_flex()
.id(id.clone()) .id(id.clone())
@@ -785,26 +811,12 @@ impl RenderOnce for SpeechButton {
.color(foreground) .color(foreground)
.into_any_element() .into_any_element()
} else if capturing { } else if capturing {
let bar_height = |level: f32| {
if reduce_motion {
STILL_HEIGHT
} else {
DOT_HEIGHT + (1.0 - DOT_HEIGHT) * level
}
};
h_flex() h_flex()
.id(("speech-bars", self.speech.entity_id())) .id(("speech-bars", self.speech.entity_id()))
.h(size.icon_rems()) .h(size.icon_rems())
.items_end() .items_end()
.gap_0p5() .gap_0p5()
.children(bars.iter().map(|level| { .children(waveform_bars(&bars, size, cx, bar_color))
div()
.flex_none()
.w(rems(size.dense_icon_rems().0 / 4.0))
.h(relative(bar_height(*level)))
.rounded(theme.radius.full)
.bg(theme.ramps.primary.base)
}))
.group_hover(group.clone(), |style| style.invisible()) .group_hover(group.clone(), |style| style.invisible())
.into_any_element() .into_any_element()
} else { } else {
@@ -877,22 +889,19 @@ impl RenderOnce for SpeechWaveform {
if !self.speech.read(cx).status().is_capturing() { if !self.speech.read(cx).status().is_capturing() {
return div().into_any_element(); return div().into_any_element();
} }
let (levels, reduce_motion) = { let levels = {
let state = self.speech.read(cx); let state = self.speech.read(cx);
( state.levels().to_vec()
state.levels().to_vec(),
cx.theme().accessibility.reduce_motion,
)
}; };
let theme = cx.theme(); let theme = cx.theme();
let colors = theme.colors; let colors = theme.colors;
let size = self.size; let size = self.size;
let bar_height = |level: f32| { let bar_color = |level: f32| {
if reduce_motion { if level <= 0.0 {
STILL_HEIGHT colors.muted_foreground
} else { } else {
DOT_HEIGHT + (1.0 - DOT_HEIGHT) * level theme.ramps.primary.base
} }
}; };
@@ -904,18 +913,7 @@ impl RenderOnce for SpeechWaveform {
.h(size.icon_rems()) .h(size.icon_rems())
.w(SPEECH_WAVEFORM_WIDTH) .w(SPEECH_WAVEFORM_WIDTH)
.overflow_hidden() .overflow_hidden()
.children(levels.iter().map(|level| { .children(waveform_bars(&levels, size, cx, bar_color))
div()
.flex_none()
.w(rems(size.dense_icon_rems().0 / 4.0))
.h(relative(bar_height(*level)))
.rounded(theme.radius.full)
.bg(if *level <= 0.0 {
colors.muted_foreground
} else {
theme.ramps.primary.base
})
}))
.refine_style(&self.style) .refine_style(&self.style)
.into_any_element() .into_any_element()
} }
@@ -948,11 +946,19 @@ impl AudioInput for Microphone {
}; };
let device_channels = stream_config.channels.max(1) as usize; let device_channels = stream_config.channels.max(1) as usize;
let (sender, receiver) = flume::unbounded::<Vec<i16>>(); let (sender, receiver) = flume::unbounded::<Result<Vec<i16>, String>>();
let converter = Arc::new(Mutex::new(Resampler::new( let converter = Arc::new(Mutex::new(Resampler::new(
config.sample_rate() as f32 / format.sample_rate().max(1) as f32, config.sample_rate() as f32 / format.sample_rate().max(1) as f32,
))); )));
let error_handler = |error| log::warn!("microphone stream error: {error}"); let error_handler = {
let sender = sender.clone();
move |error: cpal::Error| {
log::warn!("microphone stream error: {error}");
if sender.send(Err(error.to_string())).is_err() {
log::debug!("speech session closed before its stream error arrived");
}
}
};
let stream = match config.sample_format() { let stream = match config.sample_format() {
cpal::SampleFormat::F32 => device.build_input_stream( cpal::SampleFormat::F32 => device.build_input_stream(
@@ -1002,8 +1008,24 @@ impl AudioInput for Microphone {
stream.play().map_err(SpeechError::input)?; stream.play().map_err(SpeechError::input)?;
let task = cx.spawn(async move |cx| { let task = cx.spawn(async move |cx| {
while let Ok(samples) = receiver.recv_async().await { while let Ok(message) = receiver.recv_async().await {
cx.update(|cx| sink.push(samples, cx)); match message {
Ok(samples) => cx.update(|cx| sink.push(samples, cx)),
Err(message) => {
let error = SpeechError::input(message);
let state = sink.state.clone();
let generation = sink.generation;
cx.update(move |cx| {
if let Some(state) = state.upgrade() {
state.update(cx, |state, cx| {
state.apply(generation, cx, |state, cx| {
state.report_error(error, cx)
})
});
}
});
}
}
} }
}); });
@@ -1021,14 +1043,20 @@ impl Microphone {
device_channels: usize, device_channels: usize,
format: AudioFormat, format: AudioFormat,
converter: Arc<Mutex<Resampler>>, converter: Arc<Mutex<Resampler>>,
sender: flume::Sender<Vec<i16>>, sender: flume::Sender<Result<Vec<i16>, String>>,
) -> impl FnMut(&[T], &cpal::InputCallbackInfo) + Send + 'static ) -> impl FnMut(&[T], &cpal::InputCallbackInfo) + Send + 'static
where where
T: Copy + 'static, T: Copy + 'static,
{ {
move |data: &[T], _: &cpal::InputCallbackInfo| { move |data: &[T], _: &cpal::InputCallbackInfo| {
let Ok(mut converter) = converter.lock() else { // A panic while resampling poisons the lock; the phase is
return; // approximate anyway, so recover and keep the stream alive.
let mut converter = match converter.lock() {
Ok(converter) => converter,
Err(poisoned) => {
log::warn!("microphone resampler lock was poisoned; recovering");
poisoned.into_inner()
}
}; };
let mut mono = Vec::with_capacity(data.len() / device_channels + 1); let mut mono = Vec::with_capacity(data.len() / device_channels + 1);
@@ -1052,7 +1080,7 @@ impl Microphone {
} }
} }
if sender.send(samples).is_err() { if sender.send(Ok(samples)).is_err() {
log::debug!("speech session closed before its audio arrived"); log::debug!("speech session closed before its audio arrived");
} }
} }
+88 -101
View File
@@ -21,11 +21,11 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Bounds, ClickEvent, Context, Div, ElementId, Global, AnyElement, App, AppContext as _, Bounds, ClickEvent, Context, Div, ElementId, Global, Hsla,
InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _, Pixels, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _, Pixels,
Point, Render, RenderOnce, Role, SharedString, Stateful, StatefulInteractiveElement as _, Point, Render, RenderOnce, Role, SharedString, Stateful, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, TextOverflow, Window, canvas, div, linear_color_stop, StyleRefinement, Styled, TextOverflow, Window, canvas, div, linear_color_stop, linear_gradient,
linear_gradient, px, rems, px, rems,
}; };
use crate::components::button::{Button, ButtonVariant}; use crate::components::button::{Button, ButtonVariant};
@@ -100,6 +100,13 @@ impl TabsMeasurements {
.tabs .tabs
.insert(tab, measure); .insert(tab, measure);
} }
/// Drops measurements for tabs no longer rendered in the strip.
fn retain_tabs(&mut self, key: &MeasureKey, rendered: &[String]) {
if let Some(strip) = self.strips.get_mut(key) {
strip.tabs.retain(|tab, _| rendered.contains(tab));
}
}
} }
/// Everything a tab needs to draw and interact, shared across a strip's slots. /// Everything a tab needs to draw and interact, shared across a strip's slots.
@@ -190,6 +197,64 @@ fn group_key(tabs_id: &ElementId, kind: &SharedString) -> ElementId {
SharedString::from(format!("{tabs_id}-tabs-group-{kind}")).into() SharedString::from(format!("{tabs_id}-tabs-group-{kind}")).into()
} }
/// The label color shared by strip tabs and group chips.
fn tab_label_color(variant: TabsVariant, active: bool, disabled: bool, cx: &App) -> Hsla {
let theme = cx.theme();
if disabled {
return theme.colors.muted_foreground;
}
match variant {
TabsVariant::Underline => {
if active {
theme.ramps.primary.base
} else {
theme.colors.foreground
}
}
TabsVariant::Pill => theme.colors.foreground,
TabsVariant::Titlebar => {
if active {
theme.colors.foreground
} else {
theme.colors.muted_foreground
}
}
}
}
/// The variant treatment shared by strip tabs and group chips.
fn apply_tab_chrome<R>(row: R, variant: TabsVariant, active: bool, cx: &App) -> R
where
R: Styled + IntoElement,
{
let theme = cx.theme();
match variant {
TabsVariant::Underline => row
.px_2()
.py_1()
.rounded_tl(theme.radius.sm)
.rounded_tr(theme.radius.sm)
.border_b_2()
.border_color(gpui::transparent_black())
.when(active, |row| row.border_color(theme.ramps.primary.base)),
TabsVariant::Pill | TabsVariant::Titlebar => row
.h_8()
.px_2()
.pr_0p5()
.rounded(match variant {
TabsVariant::Titlebar => theme.radius.full,
_ => theme.radius.control,
})
.when(variant == TabsVariant::Titlebar, |row| {
row.bg(theme.colors.muted)
})
.when(active, |row| {
row.bg(theme.colors.background)
.shadow(theme.elevations.control.shadows())
}),
}
}
/// The payload dragged when reordering a tab. /// The payload dragged when reordering a tab.
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TabDrag { pub struct TabDrag {
@@ -619,23 +684,7 @@ impl Tabs {
let theme = cx.theme(); let theme = cx.theme();
let group_key = group_key(&tabs_id, &kind); let group_key = group_key(&tabs_id, &kind);
let label_color = match ctx.variant { let label_color = tab_label_color(ctx.variant, active, false, cx);
TabsVariant::Underline => {
if active {
theme.ramps.primary.base
} else {
theme.colors.foreground
}
}
TabsVariant::Pill => theme.colors.foreground,
TabsVariant::Titlebar => {
if active {
theme.colors.foreground
} else {
theme.colors.muted_foreground
}
}
};
let chip = div() let chip = div()
.id((group_key.clone(), "group-tab")) .id((group_key.clone(), "group-tab"))
@@ -660,31 +709,7 @@ impl Tabs {
}) })
}) })
}) })
.map(|chip| match ctx.variant { .map(|chip| apply_tab_chrome(chip, ctx.variant, active, cx))
TabsVariant::Underline => chip
.px_2()
.py_1()
.rounded_tl(theme.radius.sm)
.rounded_tr(theme.radius.sm)
.border_b_2()
.border_color(gpui::transparent_black())
.when(active, |chip| chip.border_color(theme.ramps.primary.base)),
TabsVariant::Pill | TabsVariant::Titlebar => chip
.h_8()
.px_2()
.pr_0p5()
.rounded(match ctx.variant {
TabsVariant::Titlebar => theme.radius.full,
_ => theme.radius.control,
})
.when(ctx.variant == TabsVariant::Titlebar, |chip| {
chip.bg(theme.colors.muted)
})
.when(active, |chip| {
chip.bg(theme.colors.background)
.shadow(theme.elevations.control.shadows())
}),
})
.child(SharedString::from(format!("{kind} ({count})"))) .child(SharedString::from(format!("{kind} ({count})")))
.when(ctx.variant.is_capsule(), |chip| { .when(ctx.variant.is_capsule(), |chip| {
chip.child(div().flex_none().w_4()) chip.child(div().flex_none().w_4())
@@ -826,6 +851,17 @@ impl RenderOnce for Tabs {
.unwrap_or(items.len()); .unwrap_or(items.len());
let overflow_items = items.split_off(inline_count); let overflow_items = items.split_off(inline_count);
// The strip records geometry per inline tab each frame; drop entries
// for tabs no longer rendered inline.
if cx.try_global::<TabsMeasurements>().is_some() {
let rendered: Vec<String> = items
.iter()
.map(|item| item.measure_key(&self.id))
.collect();
cx.global_mut::<TabsMeasurements>()
.retain_tabs(&measure_key, &rendered);
}
let measure_frame = self.overflow_popover.then(|| MeasureFrame { let measure_frame = self.overflow_popover.then(|| MeasureFrame {
key: measure_key.clone(), key: measure_key.clone(),
root_bounds: Rc::new(RefCell::new(None)), root_bounds: Rc::new(RefCell::new(None)),
@@ -951,6 +987,7 @@ impl RenderOnce for Tabs {
let Some(root_bounds) = measure_frame.map(|frame| frame.root_bounds) else { let Some(root_bounds) = measure_frame.map(|frame| frame.root_bounds) else {
return root.children(strip); return root.children(strip);
}; };
let container_canvas = canvas( let container_canvas = canvas(
{ {
let key = measure_key.clone(); let key = measure_key.clone();
@@ -964,6 +1001,7 @@ impl RenderOnce for Tabs {
) )
.absolute() .absolute()
.inset(shadow_bleed); .inset(shadow_bleed);
let trigger_canvas = canvas( let trigger_canvas = canvas(
{ {
let key = measure_key; let key = measure_key;
@@ -1029,32 +1067,7 @@ impl Tab {
let active = selected || self.pinned; let active = selected || self.pinned;
let theme = cx.theme(); let theme = cx.theme();
let label_color = tab_label_color(ctx.variant, active, self.disabled, cx);
let label_color = match ctx.variant {
TabsVariant::Underline => {
if self.disabled {
theme.colors.muted_foreground
} else if active {
theme.ramps.primary.base
} else {
theme.colors.foreground
}
}
TabsVariant::Pill => {
if self.disabled {
theme.colors.muted_foreground
} else {
theme.colors.foreground
}
}
TabsVariant::Titlebar => {
if self.disabled || !active {
theme.colors.muted_foreground
} else {
theme.colors.foreground
}
}
};
let titlebar = ctx.variant == TabsVariant::Titlebar; let titlebar = ctx.variant == TabsVariant::Titlebar;
let group = SharedString::from(format!("{}-tab-{}", ctx.id, self.key)); let group = SharedString::from(format!("{}-tab-{}", ctx.id, self.key));
@@ -1143,36 +1156,10 @@ impl Tab {
}) })
}) })
}) })
.map(|strip_tab| match ctx.variant { .map(|strip_tab| {
TabsVariant::Underline => strip_tab apply_tab_chrome(strip_tab, ctx.variant, active, cx).when(titlebar, |strip_tab| {
.px_2() strip_tab.min_w(TAB_MIN_WIDTH).max_w(TAB_MAX_WIDTH)
.py_1() })
.rounded_tl(theme.radius.sm)
.rounded_tr(theme.radius.sm)
.border_b_2()
.border_color(gpui::transparent_black())
.when(active, |strip_tab| {
strip_tab.border_color(theme.ramps.primary.base)
}),
TabsVariant::Pill | TabsVariant::Titlebar => strip_tab
.h_8()
.px_2()
.pr_0p5()
.rounded(match ctx.variant {
TabsVariant::Titlebar => theme.radius.full,
_ => theme.radius.control,
})
.when(titlebar, |strip_tab| {
strip_tab
.min_w(TAB_MIN_WIDTH)
.max_w(TAB_MAX_WIDTH)
.bg(theme.colors.muted)
})
.when(active, |strip_tab| {
strip_tab
.bg(theme.colors.background)
.shadow(theme.elevations.control.shadows())
}),
}) })
.when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead)) .when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead))
.child(label) .child(label)
+64 -66
View File
@@ -25,7 +25,8 @@ use gpui::{
use crate::components::button::{Button, ButtonVariant}; use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{ use crate::components::common::{
DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, floating_panel,
v_flex,
}; };
use crate::icons::{Icon, IconRole}; use crate::icons::{Icon, IconRole};
use crate::theme::{ActiveTheme as _, TOAST_MAX_WIDTH}; use crate::theme::{ActiveTheme as _, TOAST_MAX_WIDTH};
@@ -132,8 +133,10 @@ pub struct Toasts {
current: Option<ToastEntry>, current: Option<ToastEntry>,
exiting: Option<ToastEntry>, exiting: Option<ToastEntry>,
next_id: usize, next_id: usize,
/// Pending dismiss and fade timers; held so they die with the store. /// The pending auto-dismiss timer, replaced on each push.
tasks: Vec<Task<()>>, dismiss_task: Option<Task<()>>,
/// The pending fade timer, replaced on each exit.
fade_task: Option<Task<()>>,
} }
impl Toasts { impl Toasts {
@@ -157,7 +160,7 @@ impl Toasts {
this.update(cx, |toasts, cx| toasts.dismiss(id, cx)) this.update(cx, |toasts, cx| toasts.dismiss(id, cx))
.log_err(); .log_err();
}); });
self.tasks.push(task); self.dismiss_task.replace(task);
} }
id id
@@ -210,7 +213,7 @@ impl Toasts {
this.update(cx, |toasts, cx| toasts.finish_exit(cx)) this.update(cx, |toasts, cx| toasts.finish_exit(cx))
.log_err(); .log_err();
}); });
self.tasks.push(task); self.fade_task.replace(task);
} }
fn finish_exit(&mut self, cx: &mut Context<Self>) { fn finish_exit(&mut self, cx: &mut Context<Self>) {
@@ -252,14 +255,12 @@ impl RenderOnce for ToastsView {
let current = self.toasts.read(cx).current.clone(); let current = self.toasts.read(cx).current.clone();
deferred( deferred(
div() v_flex()
.id(self.id) .id(self.id)
.absolute() .absolute()
.left_0() .left_0()
.bottom_4() .bottom_4()
.w_full() .w_full()
.flex()
.flex_col()
.items_center() .items_center()
.when_some(exiting, |column, entry| { .when_some(exiting, |column, entry| {
let id = entry.id; let id = entry.id;
@@ -286,80 +287,77 @@ impl ToastEntry {
/// The rendered pill for this toast. /// The rendered pill for this toast.
fn pill(&self, toasts: &Entity<Toasts>, cx: &App) -> gpui::Stateful<gpui::Div> { fn pill(&self, toasts: &Entity<Toasts>, cx: &App) -> gpui::Stateful<gpui::Div> {
let theme = cx.theme(); let theme = cx.theme();
let surface = theme.colors.surface;
let border = theme.colors.border;
let foreground = theme.colors.foreground; let foreground = theme.colors.foreground;
let radius = theme.radius.full; let radius = theme.radius.full;
let shadows = theme.elevations.popover.shadows();
let toast = &self.toast; let toast = &self.toast;
let toasts = toasts.clone(); let toasts = toasts.clone();
let id = self.id; let id = self.id;
div() floating_panel(
.id(("toast", id)) cx,
.debug_selector(|| "toast-pill".to_string()) radius,
.role(Role::Alert) div()
.aria_label(toast.message.clone()) .id(("toast", id))
.max_w(TOAST_MAX_WIDTH) .debug_selector(|| "toast-pill".to_string())
.flex() .role(Role::Alert)
.items_center() .aria_label(toast.message.clone())
.gap_2() .max_w(TOAST_MAX_WIDTH)
.py_1p5() .flex()
.px_3() .items_center()
.bg(surface) .gap_2()
.border_1() .py_1p5()
.border_color(border) .px_3(),
.rounded(radius) theme.elevations.popover.shadows(),
.shadow(shadows.clone()) )
.refine_style(&toast.style) .refine_style(&toast.style)
.when_some(toast.icon.clone(), |pill, icon| { .when_some(toast.icon.clone(), |pill, icon| {
pill.child( pill.child(
div()
.flex_none()
.flex()
.items_center()
.child(icon.size(rems(1.0)).color(foreground)),
)
})
.child(
div() div()
.flex_1() .flex_none()
.min_w(px(0.)) .flex()
.truncate() .items_center()
.text_sm() .child(icon.size(rems(1.0)).color(foreground)),
.text_color(foreground)
.child(toast.message.clone()),
) )
.when_some(toast.action.clone(), |pill, action| { })
let toasts = toasts.clone(); .child(
pill.child( div()
div().flex_none().child( .flex_1()
Button::new(("toast-action", id)) .min_w(px(0.))
.label(action.label.clone()) .truncate()
.variant(ButtonVariant::Primary) .text_sm()
.small() .text_color(foreground)
.on_click(move |_, _window, cx| { .child(toast.message.clone()),
(action.handler)(cx); )
toasts.update(cx, |toasts, cx| { .when_some(toast.action.clone(), |pill, action| {
toasts.dismiss(id, cx); let toasts = toasts.clone();
}); pill.child(
}),
),
)
})
.child(
div().flex_none().child( div().flex_none().child(
Button::new(("toast-close", id)) Button::new(("toast-action", id))
.icon(IconRole::Close) .label(action.label.clone())
.variant(ButtonVariant::Ghost) .variant(ButtonVariant::Primary)
.small() .small()
.accessibility_label("Dismiss")
.on_click(move |_, _window, cx| { .on_click(move |_, _window, cx| {
(action.handler)(cx);
toasts.update(cx, |toasts, cx| { toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx); toasts.dismiss(id, cx);
}); });
}), }),
), ),
) )
})
.child(
div().flex_none().child(
Button::new(("toast-close", id))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.small()
.accessibility_label("Dismiss")
.on_click(move |_, _window, cx| {
toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx);
});
}),
),
)
} }
} }
+23 -24
View File
@@ -19,8 +19,10 @@ use gpui::{
StatefulInteractiveElement as _, Styled as _, Window, canvas, div, point, px, StatefulInteractiveElement as _, Styled as _, Window, canvas, div, point, px,
}; };
use crate::components::common::{anchor_bounds, record_anchor_bounds}; use crate::components::common::{anchor_bounds, floating_panel, record_anchor_bounds};
use crate::theme::{ActiveTheme as _, BORDER_WIDTH, TOOLTIP_MAX_WIDTH, TOOLTIP_OFFSET}; use crate::theme::{
ActiveTheme as _, BORDER_WIDTH, TOOLTIP_ANCHOR_GAP, TOOLTIP_MAX_WIDTH, TOOLTIP_OFFSET,
};
const PANEL_BOUNDS_ID: &str = "tooltip-panel-bounds"; const PANEL_BOUNDS_ID: &str = "tooltip-panel-bounds";
@@ -80,29 +82,26 @@ impl Render for Tooltip {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// Copied out: the mutable reads below need `cx` free of this borrow. // Copied out: the mutable reads below need `cx` free of this borrow.
let theme = cx.theme(); let theme = cx.theme();
let surface = theme.colors.surface;
let surface_foreground = theme.colors.surface_foreground; let surface_foreground = theme.colors.surface_foreground;
let radius_sm = theme.radius.sm; let radius_sm = theme.radius.sm;
let shadows = theme.elevations.popover.shadows(); let shadows = theme.elevations.popover.shadows();
let border = theme.colors.border;
let build_panel = || { let build_panel = || {
div() floating_panel(
.id("tooltip-panel") cx,
.role(Role::Tooltip) radius_sm,
.debug_selector(|| "tooltip-panel".to_string()) div()
.px_2() .id("tooltip-panel")
.py_1() .role(Role::Tooltip)
.max_w(TOOLTIP_MAX_WIDTH) .debug_selector(|| "tooltip-panel".to_string())
.bg(surface) .px_2()
.border_1() .py_1()
.border_color(border) .max_w(TOOLTIP_MAX_WIDTH)
.rounded(radius_sm) .text_sm()
.shadow(shadows.clone()) .text_color(surface_foreground)
.text_sm() .child(self.text.clone()),
.text_color(surface_foreground) shadows.clone(),
.child(self.text.clone()) )
}; };
let (wrapper, panel) = match self.anchor { let (wrapper, panel) = match self.anchor {
@@ -118,16 +117,16 @@ impl Render for Tooltip {
.map(|bounds| bounds.size.height) .map(|bounds| bounds.size.height)
.unwrap_or_else(|| window.line_height() + px(8.) + BORDER_WIDTH * 2.0); .unwrap_or_else(|| window.line_height() + px(8.) + BORDER_WIDTH * 2.0);
let below = viewport_height - px(4.) - parent.bottom(); let below = viewport_height - TOOLTIP_ANCHOR_GAP - parent.bottom();
let above = parent.top() - px(4.); let above = parent.top() - TOOLTIP_ANCHOR_GAP;
let hang_below = below >= height || below >= above; let hang_below = below >= height || below >= above;
let panel = build_panel() let panel = build_panel()
.ml(parent.left() - origin.x) .ml(parent.left() - origin.x)
.mt(if hang_below { .mt(if hang_below {
parent.bottom() + px(4.) - origin.y parent.bottom() + TOOLTIP_ANCHOR_GAP - origin.y
} else { } else {
parent.top() - px(4.) - height - origin.y parent.top() - TOOLTIP_ANCHOR_GAP - height - origin.y
}) })
.child( .child(
canvas( canvas(
+8 -7
View File
@@ -25,7 +25,7 @@ use gpui::{
}; };
use crate::components::common::{ use crate::components::common::{
StyledExt as _, nav_key, paint_selectable_row, selectable_label_color, StyledExt as _, nav_key, paint_selectable_row, selectable_label_color, v_flex,
}; };
use crate::icons::{Icon, IconRole, icon}; use crate::icons::{Icon, IconRole, icon};
use crate::theme::ActiveTheme as _; use crate::theme::ActiveTheme as _;
@@ -37,6 +37,9 @@ type DisclosureHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
/// The visible row builder, run during render. /// The visible row builder, run during render.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<TreeItem>>; type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<TreeItem>>;
/// The deepest indent the tree paints, bounding misbuilt item trees.
const TREE_MAX_DEPTH: usize = 16;
/// One row of a [`Tree`]. /// One row of a [`Tree`].
#[derive(Clone)] #[derive(Clone)]
#[must_use] #[must_use]
@@ -280,10 +283,8 @@ impl RenderOnce for Tree {
}) })
.collect(); .collect();
div() v_flex()
.id(self.id) .id(self.id)
.flex()
.flex_col()
.gap_0p5() .gap_0p5()
.text_sm() .text_sm()
.refine_style(&self.style) .refine_style(&self.style)
@@ -362,7 +363,7 @@ impl TreeItem {
let label_color = selectable_label_color(cx, selected, self.disabled); let label_color = selectable_label_color(cx, selected, self.disabled);
let disabled = self.disabled; let disabled = self.disabled;
let depth = u32::try_from(self.depth).unwrap_or(u32::MAX) as f32; let depth = self.depth.min(TREE_MAX_DEPTH) as f32;
let indent = rems(0.75 * if self.depth == 0 { 0.5 } else { depth + 1.0 }); let indent = rems(0.75 * if self.depth == 0 { 0.5 } else { depth + 1.0 });
div() div()
@@ -402,8 +403,8 @@ impl TreeItem {
} }
}) })
}) })
.children((0..self.depth).map(|level| { .children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| {
let step = u32::try_from(level).unwrap_or(u32::MAX) as f32; let step = level as f32;
div() div()
.absolute() .absolute()
.left(rems(0.75 * (step + 0.5))) .left(rems(0.75 * (step + 0.5)))
+4 -47
View File
@@ -1,11 +1,9 @@
//! Application window layout: a titlebar over a panel row. //! Application window layout: a titlebar over a panel row.
//!
//! The shared flex and focus helpers live in [`crate::components::common`];
//! they are re-exported here for the `ui::layout::…` paths.
use gpui::{ pub use crate::components::common::{StyledExt, focus_handle, focus_ring, h_flex, v_flex};
App, BoxShadow, Div, ElementId, FocusHandle, Hsla, Refineable as _, StyleRefinement, Styled,
Window, div, px,
};
use crate::theme::{FOCUS_RING_ALPHA, FOCUS_RING_SPREAD};
pub mod panel; pub mod panel;
pub mod resizable; pub mod resizable;
@@ -15,44 +13,3 @@ pub mod titlebar;
pub mod window_controls; pub mod window_controls;
mod window_frame; mod window_frame;
/// A row whose children center on the cross axis.
#[must_use]
pub fn h_flex() -> Div {
div().flex().flex_row().items_center()
}
/// A column whose children stack on the main axis.
#[must_use]
pub fn v_flex() -> Div {
div().flex().flex_col()
}
/// Extensions over [`Styled`], shared by the layout views.
pub trait StyledExt: Styled + Sized {
#[must_use]
fn refine_style(mut self, style: &StyleRefinement) -> Self {
self.style().refine(style);
self
}
}
impl<E: Styled> StyledExt for E {}
/// Returns a focus handle for the given element ID.
pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusHandle {
window
.with_element_namespace(id.clone(), |window| {
window.use_keyed_state("focus-handle", cx, |_, cx| cx.focus_handle())
})
.read(cx)
.clone()
}
/// Returns a focus ring shadow with the given color at half ink.
pub fn focus_ring(color: Hsla) -> Vec<BoxShadow> {
vec![
BoxShadow::new(px(0.), px(0.), color.alpha(FOCUS_RING_ALPHA))
.spread_radius(FOCUS_RING_SPREAD),
]
}
+3 -3
View File
@@ -7,13 +7,13 @@ use std::sync::Arc;
use gpui::{ use gpui::{
AnyElement, AnyView, App, Axis, Div, ElementId, Entity, IntoElement, ParentElement as _, AnyElement, AnyView, App, Axis, Div, ElementId, Entity, IntoElement, ParentElement as _,
Render, RenderOnce, SharedString, StyleRefinement, Styled as _, Window, div, px, Render, RenderOnce, SharedString, StyleRefinement, Styled as _, Window, div,
}; };
use crate::components::tabs::Tab; use crate::components::tabs::Tab;
use crate::layout::StyledExt as _; use crate::layout::StyledExt as _;
use crate::layout::resizable::{Resizable, ResizableState}; use crate::layout::resizable::{Resizable, ResizableState};
use crate::theme::ActiveTheme as _; use crate::theme::{ActiveTheme as _, RESIZE_HANDLE_WIDTH};
/// A user-defined panel the row can show. /// A user-defined panel the row can show.
#[allow(unused_variables)] #[allow(unused_variables)]
@@ -186,7 +186,7 @@ impl gpui::Styled for PanelRow {
impl RenderOnce for PanelRow { impl RenderOnce for PanelRow {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone(); let id = self.id.clone();
let gutter = px(8.); let gutter = RESIZE_HANDLE_WIDTH;
let main = island( let main = island(
div() div()
+32 -1
View File
@@ -86,7 +86,9 @@ impl ResizableState {
.filter(|(j, _)| *j != ix) .filter(|(j, _)| *j != ix)
.fold(px(0.), |sum, (_, min)| sum + *min); .fold(px(0.), |sum, (_, min)| sum + *min);
let ceiling = extent - floors; let ceiling = extent - floors;
size = size.min(ceiling); // When the window is smaller than the other panes' floors, keep
// the floor rather than shrinking this pane below it.
size = size.min(ceiling.max(floor));
} }
// Earlier panes hold the equal split they already render at, // Earlier panes hold the equal split they already render at,
@@ -107,6 +109,8 @@ impl ResizableState {
/// Sets pane `ix`'s width, backfilling earlier panes. /// Sets pane `ix`'s width, backfilling earlier panes.
pub fn set_pane_width(&mut self, ix: usize, width: Pixels, cx: &mut Context<Self>) { pub fn set_pane_width(&mut self, ix: usize, width: Pixels, cx: &mut Context<Self>) {
// Persisted layouts can carry negative sizes.
let width = width.max(PANE_MIN_SIZE);
while self.sizes.len() <= ix { while self.sizes.len() <= ix {
self.sizes.push(width); self.sizes.push(width);
} }
@@ -310,3 +314,30 @@ impl RenderOnce for Resizable {
}) })
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use gpui::TestAppContext;
#[gpui::test]
fn resize_never_stores_sub_floor_size(cx: &mut TestAppContext) {
let state = cx.new(|_| ResizableState::default());
state.update(cx, |state, cx| {
// The measured extent is smaller than the other pane's floor.
state.set_measured(px(100.), cx);
state.resize(0, px(500.), &[px(48.), px(150.)], cx);
assert_eq!(state.sizes[0], px(48.));
});
}
#[gpui::test]
fn set_pane_width_clamps_negative_values(cx: &mut TestAppContext) {
let state = cx.new(|_| ResizableState::default());
state.update(cx, |state, cx| {
// Persisted layouts can carry negative sizes.
state.set_pane_width(0, px(-20.), cx);
assert_eq!(state.pane_size(0, 1), PANE_MIN_SIZE);
});
}
}
+3 -2
View File
@@ -14,7 +14,8 @@ use gpui::{
use crate::layout::{StyledExt as _, focus_handle, focus_ring}; use crate::layout::{StyledExt as _, focus_handle, focus_ring};
use crate::theme::{ use crate::theme::{
ActiveTheme as _, BORDER_WIDTH, DISABLED_OPACITY, HAIRLINE_WIDTH, RESIZE_KEYBOARD_STEP, ActiveTheme as _, BORDER_WIDTH, DISABLED_OPACITY, HAIRLINE_WIDTH, RESIZE_HANDLE_WIDTH,
RESIZE_KEYBOARD_STEP,
}; };
/// How far one keyboard arrow step moves the seam. /// How far one keyboard arrow step moves the seam.
@@ -111,7 +112,7 @@ impl RenderOnce for ResizeHandle {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme(); let theme = cx.theme();
let ring = theme.colors.ring; let ring = theme.colors.ring;
let thickness = px(8.); let thickness = RESIZE_HANDLE_WIDTH;
let label = self let label = self
.accessibility_label .accessibility_label
+6 -6
View File
@@ -19,6 +19,8 @@ use gpui::{
Stateful, StatefulInteractiveElement as _, Window, WindowControlArea, div, Stateful, StatefulInteractiveElement as _, Window, WindowControlArea, div,
}; };
#[cfg(any(target_os = "windows", target_os = "linux"))]
use crate::components::common::h_flex;
#[cfg(any(target_os = "windows", target_os = "linux"))] #[cfg(any(target_os = "windows", target_os = "linux"))]
use crate::icons::{IconRole, icon}; use crate::icons::{IconRole, icon};
#[cfg(any(target_os = "windows", target_os = "linux"))] #[cfg(any(target_os = "windows", target_os = "linux"))]
@@ -106,11 +108,9 @@ impl RenderOnce for WindowControls {
let client_decorated = let client_decorated =
matches!(window.window_decorations(), Decorations::Client { .. }); matches!(window.window_decorations(), Decorations::Client { .. });
div() h_flex()
.flex_none() .flex_none()
.flex() .h_full()
.flex_row()
.items_center()
.gap_1() .gap_1()
.when(client_decorated && controls.minimize, |row| { .when(client_decorated && controls.minimize, |row| {
row.child(circle_button( row.child(circle_button(
@@ -274,7 +274,7 @@ fn caption_button(
.text_color(theme.colors.foreground) .text_color(theme.colors.foreground)
}) })
}) })
.child(icon(role).size(rems(0.75))) .child(icon(role).size(crate::theme::OVERLAY_ICON_SIZE))
.into_any_element() .into_any_element()
} }
@@ -309,6 +309,6 @@ where
action(window, cx); action(window, cx);
}) })
}) })
.child(icon(role).size(rems(0.75))) .child(icon(role).size(crate::theme::OVERLAY_ICON_SIZE))
.into_any_element() .into_any_element()
} }
+7
View File
@@ -164,3 +164,10 @@ impl MaterialTokens {
} }
} }
} }
/// Windows paints its caption close-button hover red in every theme.
pub const WINDOWS_CLOSE_HOVER: Hsla = hsla(0.986043, 0.863406, 0.488235, 1.0);
/// The close-button hover dimmed while pressed.
pub const WINDOWS_CLOSE_PRESSED: Hsla = hsla(0.986043, 0.863406, 0.488235, 0.8);
/// The close glyph's color over the red hover.
pub const WINDOWS_CLOSE_FOREGROUND: Hsla = gpui::white();
+23
View File
@@ -187,6 +187,10 @@ impl ThemeDefinition {
/// Parses `#rgb` or `#rrggbb` into an opaque color. /// Parses `#rgb` or `#rrggbb` into an opaque color.
pub(crate) fn parse_hex(value: &str) -> Option<Hsla> { pub(crate) fn parse_hex(value: &str) -> Option<Hsla> {
let digits = value.strip_prefix('#')?; let digits = value.strip_prefix('#')?;
// Lengths are byte lengths; non-ASCII input would panic the slicing below.
if !digits.is_ascii() {
return None;
}
let expand = |channels: [f32; 3]| Some(expand_rgb([channels[0], channels[1], channels[2]])); let expand = |channels: [f32; 3]| Some(expand_rgb([channels[0], channels[1], channels[2]]));
match digits.len() { match digits.len() {
@@ -219,3 +223,22 @@ pub(crate) fn parse_hex(value: &str) -> Option<Hsla> {
fn expand_rgb([r, g, b]: [f32; 3]) -> Hsla { fn expand_rgb([r, g, b]: [f32; 3]) -> Hsla {
Hsla::from(Rgba { r, g, b, a: 1.0 }) Hsla::from(Rgba { r, g, b, a: 1.0 })
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_hex_rejects_non_ascii_digits() {
assert_eq!(parse_hex("#éa"), None);
assert_eq!(parse_hex("#éaabbcc"), None);
}
#[test]
fn parse_hex_resolves_three_and_six_digits() {
assert!(parse_hex("#abc").is_some());
assert!(parse_hex("#aabbcc").is_some());
assert_eq!(parse_hex("abc"), None);
assert_eq!(parse_hex("#ab"), None);
}
}
+17 -8
View File
@@ -16,10 +16,14 @@ mod system;
use std::time::Duration; use std::time::Duration;
pub use colors::{ColorTokens, MaterialTokens}; pub use colors::{
ColorTokens, MaterialTokens, WINDOWS_CLOSE_FOREGROUND, WINDOWS_CLOSE_HOVER,
WINDOWS_CLOSE_PRESSED,
};
pub use definition::ThemeDefinition; pub use definition::ThemeDefinition;
use gpui::{ use gpui::{
App, Global, Hsla, Pixels, SpringConfig, WindowAppearance, WindowBackgroundAppearance, hsla, px, App, Global, Hsla, Pixels, Rems, SpringConfig, WindowAppearance, WindowBackgroundAppearance,
px, rems,
}; };
pub use ramps::{AccentShades, Oklch}; pub use ramps::{AccentShades, Oklch};
pub use resolve::{Ramps, ResolvedTheme}; pub use resolve::{Ramps, ResolvedTheme};
@@ -27,6 +31,12 @@ pub use system::{AccessibilityPreferences, SourceKind, SystemTheme};
/// The hairline width of the control border every button and field paints. /// The hairline width of the control border every button and field paints.
pub const BORDER_WIDTH: Pixels = px(1.0); pub const BORDER_WIDTH: Pixels = px(1.0);
/// The side of glyphs inside titlebar overlay controls.
pub const OVERLAY_ICON_SIZE: Rems = rems(0.75);
/// The draggable width of a resize seam and its panel-row gutter.
pub const RESIZE_HANDLE_WIDTH: Pixels = px(8.0);
/// The gap between an anchored tooltip and its anchor.
pub const TOOLTIP_ANCHOR_GAP: Pixels = px(4.0);
/// The widest a titlebar tab grows before its label fades. /// The widest a titlebar tab grows before its label fades.
pub const TAB_MAX_WIDTH: Pixels = px(240.0); pub const TAB_MAX_WIDTH: Pixels = px(240.0);
/// The narrowest a titlebar tab shrinks, keeping short labels clear of the fade. /// The narrowest a titlebar tab shrinks, keeping short labels clear of the fade.
@@ -75,12 +85,6 @@ pub const WINDOW_RESIZE_INSET: Pixels = px(4.0);
pub const TRAFFIC_LIGHT_PAD: Pixels = px(88.0); pub const TRAFFIC_LIGHT_PAD: Pixels = px(88.0);
/// The width of a Windows caption button. /// The width of a Windows caption button.
pub const WINDOWS_CAPTION_WIDTH: Pixels = px(36.0); pub const WINDOWS_CAPTION_WIDTH: Pixels = px(36.0);
/// Windows paints its caption close-button hover red in every theme.
pub const WINDOWS_CLOSE_HOVER: Hsla = hsla(0.986043, 0.863406, 0.488235, 1.0);
/// The close-button hover dimmed while pressed.
pub const WINDOWS_CLOSE_PRESSED: Hsla = hsla(0.986043, 0.863406, 0.488235, 0.8);
/// The close glyph's color over the red hover.
pub const WINDOWS_CLOSE_FOREGROUND: Hsla = gpui::white();
/// The width a sidebar opens at. /// The width a sidebar opens at.
pub const SIDEBAR_DEFAULT_WIDTH: Pixels = px(240.0); pub const SIDEBAR_DEFAULT_WIDTH: Pixels = px(240.0);
/// The narrowest a sidebar may be dragged. /// The narrowest a sidebar may be dragged.
@@ -210,6 +214,11 @@ impl Theme {
cx.global::<Self>() cx.global::<Self>()
} }
/// The system UI family, for chrome surfaces.
pub fn ui_font(&self) -> &'static str {
".SystemUIFont"
}
fn from_resolved(resolved: ResolvedTheme) -> Self { fn from_resolved(resolved: ResolvedTheme) -> Self {
Self { Self {
variant: resolved.variant, variant: resolved.variant,
+83 -7
View File
@@ -10,7 +10,8 @@ use objc2_app_kit::{
}; };
use objc2_foundation::{ use objc2_foundation::{
NSDictionary, NSDistributedNotificationCenter, NSKeyValueObservingOptions, NSNotification, NSDictionary, NSDistributedNotificationCenter, NSKeyValueObservingOptions, NSNotification,
NSNotificationName, NSObjectNSKeyValueObserverRegistration, NSString, NSUserDefaults, NSNotificationCenter, NSNotificationName, NSObjectNSKeyValueObserverRegistration, NSString,
NSUserDefaults,
}; };
use super::signal::ReapplySignal; use super::signal::ReapplySignal;
@@ -46,14 +47,37 @@ define_class!(
impl ThemeObserver { impl ThemeObserver {
fn new(reapply: async_channel::Sender<()>) -> Retained<Self> { fn new(reapply: async_channel::Sender<()>) -> Retained<Self> {
let this = Self::alloc().set_ivars(reapply); let this = Self::alloc().set_ivars(reapply);
// SAFETY: `this` is freshly allocated with ivars set and not yet
// initialized, which is exactly the receiver `init` requires.
unsafe { msg_send![super(this), init] } unsafe { msg_send![super(this), init] }
} }
} }
/// One watcher registration, kept so [`Drop`] can undo it.
enum Watcher {
/// A distributed notification, registered by name.
Distributed {
center: Retained<NSDistributedNotificationCenter>,
name: Retained<NSNotificationName>,
},
/// A defaults key path observed via KVO, which does not retain observers.
Defaults {
defaults: Retained<NSUserDefaults>,
key: Retained<NSString>,
},
/// A workspace notification, registered by name.
Workspace {
center: Retained<NSNotificationCenter>,
name: &'static NSNotificationName,
},
}
#[derive(Default)] #[derive(Default)]
pub(crate) struct MacosSource { pub(crate) struct MacosSource {
/// The notification centers track, but do not retain, the observer. /// The observer, retained until `Drop` has removed every registration.
_observer: Option<Retained<ThemeObserver>>, observer: Option<Retained<ThemeObserver>>,
/// Registrations to undo, in the order they were installed.
watchers: Vec<Watcher>,
/// Keeps the reapply loop alive. /// Keeps the reapply loop alive.
_signal: Option<ReapplySignal>, _signal: Option<ReapplySignal>,
} }
@@ -96,6 +120,7 @@ impl ThemeSource for MacosSource {
fn install_watchers(&mut self, async_cx: gpui::AsyncApp) { fn install_watchers(&mut self, async_cx: gpui::AsyncApp) {
let signal = ReapplySignal::install(&async_cx); let signal = ReapplySignal::install(&async_cx);
let observer = ThemeObserver::new(signal.sender()); let observer = ThemeObserver::new(signal.sender());
let mut watchers = Vec::new();
let center = NSDistributedNotificationCenter::defaultCenter(); let center = NSDistributedNotificationCenter::defaultCenter();
for name in [ for name in [
@@ -103,7 +128,9 @@ impl ThemeSource for MacosSource {
"AppleInterfaceThemeChangedNotification", "AppleInterfaceThemeChangedNotification",
] { ] {
let name = NSNotificationName::from_str(name); let name = NSNotificationName::from_str(name);
// SAFETY: the observer is retained past every delivery. // SAFETY: the center tracks this exact registration until `Drop`
// removes it, and the observer is retained by `MacosSource` until
// after that removal.
unsafe { unsafe {
center.addObserver_selector_name_object( center.addObserver_selector_name_object(
&observer, &observer,
@@ -112,6 +139,10 @@ impl ThemeSource for MacosSource {
None, None,
); );
} }
watchers.push(Watcher::Distributed {
center: center.clone(),
name,
});
} }
let defaults = NSUserDefaults::standardUserDefaults(); let defaults = NSUserDefaults::standardUserDefaults();
@@ -121,7 +152,9 @@ impl ThemeSource for MacosSource {
"AppleInterfaceStyle", "AppleInterfaceStyle",
] { ] {
let key = NSString::from_str(key); let key = NSString::from_str(key);
// SAFETY: as above // SAFETY: KVO does not retain the observer, so the registration is
// only valid while `MacosSource` keeps the observer alive and
// `Drop` unregisters the key path before releasing it.
unsafe { unsafe {
defaults.addObserver_forKeyPath_options_context( defaults.addObserver_forKeyPath_options_context(
&observer, &observer,
@@ -130,13 +163,18 @@ impl ThemeSource for MacosSource {
core::ptr::null_mut(), core::ptr::null_mut(),
); );
} }
watchers.push(Watcher::Defaults {
defaults: defaults.clone(),
key,
});
} }
let workspace_center = NSWorkspace::sharedWorkspace().notificationCenter(); let workspace_center = NSWorkspace::sharedWorkspace().notificationCenter();
let accessibility_name = let accessibility_name =
unsafe { NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification }; unsafe { NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification };
// SAFETY: as above. // SAFETY: the workspace center retains the observer for the
// registration's lifetime, and `Drop` removes the registration.
unsafe { unsafe {
workspace_center.addObserver_selector_name_object( workspace_center.addObserver_selector_name_object(
&observer, &observer,
@@ -145,8 +183,13 @@ impl ThemeSource for MacosSource {
None, None,
); );
} }
watchers.push(Watcher::Workspace {
center: workspace_center,
name: accessibility_name,
});
self._observer = Some(observer); self.observer = Some(observer);
self.watchers = watchers;
self._signal = Some(signal); self._signal = Some(signal);
} }
@@ -154,3 +197,36 @@ impl ThemeSource for MacosSource {
SourceKind::Macos.label() SourceKind::Macos.label()
} }
} }
impl Drop for MacosSource {
fn drop(&mut self) {
let Some(observer) = self.observer.take() else {
return;
};
for watcher in self.watchers.drain(..) {
match watcher {
Watcher::Distributed { center, name } => {
// SAFETY: the observer is registered with this center
// under this name and object.
unsafe {
center.removeObserver_name_object(&observer, Some(&name), None);
}
}
Watcher::Defaults { defaults, key } => {
// SAFETY: the observer is registered for this key path
// with no context.
unsafe {
defaults.removeObserver_forKeyPath(&observer, &key);
}
}
Watcher::Workspace { center, name } => {
// SAFETY: the observer is registered with this center
// under this name and object.
unsafe {
center.removeObserver_name_object(&observer, Some(name), None);
}
}
}
}
}
}
+62
View File
@@ -62,6 +62,68 @@ fn strip_window(
cx cx
} }
struct CloseHarness {
closed: Rc<RefCell<Vec<usize>>>,
}
impl Render for CloseHarness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let closed = self.closed.clone();
div().size_full().child(
Tabs::new("strip")
.variant(TabsVariant::Pill)
.tabs(move |_, _| {
vec![
Tab::new("a", "Alpha").closeable(true),
Tab::new("b", "Beta").closeable(true),
]
})
.on_close(move |index, _, _| closed.borrow_mut().push(index)),
)
}
}
#[gpui::test]
fn a_pinned_tab_draws_inline_and_selects_itself(cx: &mut TestAppContext) {
let changed = Rc::new(RefCell::new(Vec::new()));
let mut cx = strip_window(cx, changed.clone(), Rc::new(RefCell::new(Vec::new())), true);
let delta = cx
.debug_bounds("strip-tab-Delta")
.expect("a pinned tab draws itself");
cx.simulate_click(delta.center(), Modifiers::none());
cx.run_until_parked();
assert_eq!(
changed.borrow().as_slice(),
&[3],
"clicking the pinned tab reports its index"
);
}
#[gpui::test]
fn a_closeable_tab_reports_its_close(cx: &mut TestAppContext) {
cx.update(Theme::init);
let closed = Rc::new(RefCell::new(Vec::new()));
let window = cx.open_window(size(px(800.), px(600.)), |_, _| CloseHarness {
closed: closed.clone(),
});
let mut cx = VisualTestContext::from_window(window.into(), cx);
cx.run_until_parked();
let close = cx
.debug_bounds("strip-close-Alpha")
.expect("a closeable tab draws its close control");
cx.simulate_click(close.center(), Modifiers::none());
cx.run_until_parked();
assert_eq!(
closed.borrow().as_slice(),
&[0],
"the close control reports the tab's index"
);
}
#[gpui::test] #[gpui::test]
fn same_kind_tabs_collapse_into_one_group(cx: &mut TestAppContext) { fn same_kind_tabs_collapse_into_one_group(cx: &mut TestAppContext) {
let mut cx = strip_window( let mut cx = strip_window(
+3
View File
@@ -6,3 +6,6 @@ publish.workspace = true
[dependencies] [dependencies]
nostr.workspace = true nostr.workspace = true
[lints]
workspace = true
+3
View File
@@ -39,3 +39,6 @@ ui = { path = "../crates/ui" }
reqwest_client.workspace = true reqwest_client.workspace = true
tracing.workspace = true tracing.workspace = true
tracing-subscriber.workspace = true tracing-subscriber.workspace = true
[lints]
workspace = true
+198
View File
@@ -0,0 +1,198 @@
# UI + app audit — November 2026
Audit of `crates/ui` (~15k lines) and `crates/signed_app` (~23k lines) against soundness,
panics/bounds, concurrency/async, input boundaries, and idiom categories, plus the standing
ask to migrate duplicated elements into shared components. Every finding below was verified
at its cited line before fixing; line numbers refer to the tree at audit time and have
shifted since. All fixes are in the tree; the full gate (`cargo fmt --all`,
`cargo check --workspace`, `cargo clippy --workspace --all-targets -- -D warnings`,
`cargo test --workspace`) is green.
## Fixed findings
### A. Soundness and panics
| ID | Severity | File | Finding and fix |
|----|----------|------|-----------------|
| A1 | High | `ui/src/theme/source/macos.rs` | `MacosSource` never unregistered its NSDistributedNotificationCenter, KVO, and NSWorkspace observers, so a dropped source left observers delivering into freed memory. Added `impl Drop` that removes both distributed names, the three defaults key paths, and the workspace-center registration; registrations are recorded in a `Watcher` enum during `install_watchers`. Also added the missing `// SAFETY:` on `msg_send![super(this), init]` and replaced the three "as above" comments with per-block justifications. |
| A2 | Medium | `ui/src/theme/definition.rs` | `parse_hex` sliced `digits[i..i+1]` by byte length, panicking on non-char-boundary input such as `#éa` from a malformed omarchy theme. Added an `is_ascii` guard after `strip_prefix('#')`; `color()` already logs and falls back. |
| A3 | Medium | `ui/src/components/input.rs` | IME-supplied reversed `range_utf16` produced `start > end` byte offsets and sliced out of order in `text_for_range` and the UTF-16/UTF-8 converters. Both helpers now order endpoints; `utf8_range_to_utf16` additionally floors each endpoint to a char boundary (`floor_to_char_boundary`). |
| A4 | Medium | `ui/src/components/code.rs` | `CodeViewState::update_line` spliced `0..1` on an empty source, a documented panic. It now early-returns when the source is empty; the `# Panics` section is gone. No in-workspace callers existed, so early-return is safe. |
| A5 | Medium | `ui/src/layout/resizable.rs` | A drag clamped `size.min(ceiling)` without honoring `floor`, so a window smaller than the other panes' mins rendered a pane below its floor; `set_pane_width` accepted negative persisted sizes. Fixed both: `size.min(ceiling.max(floor))` and `width.max(PANE_MIN_SIZE)`. |
| A6 | High | `signed_app/src/repo/helpers.rs` | `render_diff_row` indexed `hunks[hunk].lines[line]` with a stale captured index. Absent indices render a blank row of `DIFF_ROW_HEIGHT` instead of panicking. |
| A7 | High | `signed_app/src/pull_requests/mod.rs`, `signed_app/src/issues/mod.rs` | List rows indexed `pull_requests[pr_ix]` / `issues[issue_ix]` with indices captured at rebuild while the store is re-read each frame. Both now use `.get()` and render an empty row when the entry is gone. |
| A8 | High | `signed_app/src/repo/dialogs/reset.rs` | The destructive remote reset detached its task and closed the dialog immediately; failures were invisible. It now uses the stored-progress pattern (busy gate, `DialogProgress.fail`, close only on success, `update_window` result logged instead of `.ok()`-swallowed). The same `.ok()` swallows in `create.rs` and `init.rs` now log. |
### B. Async and task hygiene
| ID | Severity | File | Finding and fix |
|----|----------|------|-----------------|
| B1 | High | `ui/src/components/toast.rs`, `combobox.rs` | Timer/report handles accumulated in `Vec<Task<()>>` forever. Toasts now keep one `dismiss_task` and one `fade_task` slot (each new timer replaces the previous, which also fixes stale fade timers finishing the wrong toast); the combobox keeps a single `task` slot, latest report wins. |
| B2 | Medium | `ui/src/components/tabs.rs` | `TabsMeasurements.strips` grew forever. `retain_tabs` prunes per-strip tab measurements to the keys rendered inline this frame, before paint re-records them. |
| B3 | Medium | `repo/mod.rs`, `repo/files.rs`, `repo/history.rs`, `repo/commit_diff.rs`, `pull_requests/detail.rs`, `pull_requests/new.rs` (+ `new/source.rs`), `inbox/mod.rs` | Task vecs were never reaped. Each owner struct got a private `push_task` that retains unfinished tasks before pushing; every `tasks.push` site routes through it. `new/source.rs` sites were in the same category as the plan list and are covered. |
| B4 | Medium | `repo/dialogs/grasp_servers.rs`, `settings/helpers.rs` | Remove buttons used an index captured at render, which desyncs after a prior removal (removing the wrong row or silently nothing). All three editors now capture the value and remove with `iter().position()` + `remove`. |
| B5 | Medium | `pull_requests/dialogs/update.rs`, `issues/new_issue.rs` | Submit had no busy gate; a double-click published twice. Both dialogs hold a `DialogProgress`, `begin()` on submit, and disable the button while busy. The store publishes detached and reports through `last_error` (surfaced by the parent view's Alert), so the dialog closes after firing, as before. |
| B6 | Medium | `ui/src/components/speech.rs` | (1) The mic stream loop discarded the dead-app `cx.update` error and kept spinning; this gpui's `AsyncApp::update` returns the value directly and panics on a dead app, ending the loop, so the loop was simplified instead. (2) A poisoned `Mutex<Resampler>` silently dropped all audio; it now recovers via `into_inner()` with a `log::warn!`. (3) `error_handler` only logged; stream errors are now sent as `Err(String)` over the same flume channel as samples and reported on the UI thread through the generation-guarded state, firing `SpeechEvent::Error`. |
| B7 | Medium | `pull_requests/send_patch.rs`, `signed_state/src/repo.rs` | The panel closed immediately after firing the publish; failures were invisible until some other view read `last_error`. `RepoStore::open_pull_request` now returns its publish `Task<Result<(), Error>>` (early failures as `Task::ready(Err)`, `last_error` still set; `open_pull_request_from_refs` pushes the task into the store's vec), and `SendPatchView::submit` awaits it: stays open with `submitting` set, `fail(message)` on error, closes on success. |
### C. Error surfacing
| ID | Severity | File | Finding and fix |
|----|----------|------|-----------------|
| C1 | Medium | `inbox/mod.rs` | `Inbox::query` failures only logged. The app-level `Toasts` entity lives in `AppRoot` and is not addressable from the inbox entity, so the plan's stated fallback applies: an inline dismissible `Alert` bound to a new `error` field, cleared on the next successful refresh. |
| C2 | Medium | `repo/dialogs/init.rs` | Branch-load failure only logged, rendering an empty dropdown. `load_branches` now calls `DialogProgress::fail` so `error_row` renders inside the dialog. |
| C3 | Low | `repo/history.rs` | "Failed to load commits" conflated a load error with an empty list. The load records `error`, and the render shows an inline `Alert` with the message (dismiss clears it). |
| C4 | Low | `repo/files.rs` | The traversal-guard rejection returned silently. It now inserts `FileContent::Failed("Cannot open file")` so the content pane renders the shared empty state; a comment documents that tree paths originate from git, so only crafted components are rejected (symlink escapes are accepted). |
## Shared infrastructure added to `crates/ui` (D) and migrations (E)
- **D1** `layout/mod.rs` duplicated `h_flex`, `v_flex`, `StyledExt`, `focus_handle`, `focus_ring`
from `components/common.rs`. The copies are deleted; `layout/mod.rs` re-exports the
canonical ones so external `ui::layout::…` paths keep working. The one component-internal
importer (`dialog.rs`) now imports from `components::common`.
- **D2** New shared builders in `components/common.rs` and `empty_state.rs`:
`floating_panel(cx, radius, panel, shadows)` (generic over `Styled`, so it slots into
existing chains), `paint_highlighted_row` (mouse-move-driven rows),
`wrapping_adjacent_selectable`, and `EmptyState::compact`. Each had 3+ verified call sites
and no equivalent.
- **D3** `ButtonVariant::chrome(cx)` returns a `ButtonChrome` (background, foreground, hover,
pressed, and the three border states); `Button::render` consumes it.
- **D4** `tabs.rs` gained `tab_label_color` and `apply_tab_chrome`, shared by `render_tab`
and `render_group_tab`.
- **D5** Theme tokens for recurring literals: `Theme::ui_font()`,
`WINDOWS_CLOSE_*` moved into `colors.rs` (the only color-literal home),
`CODE_LINE_HEIGHT` (diff line height), `CHANGE_BAR_WIDTH` (diff change bar),
`RESIZE_HANDLE_WIDTH` (resize seam + panel gutter), `OVERLAY_ICON_SIZE` (window controls),
`TOOLTIP_ANCHOR_GAP` (tooltip placement).
- **E1** All eight floating-panel stacks (toast pill, overlay alert, popover, dialog,
combobox popup, command palette, menu panel via `MenuChrome`, tooltip) render through
`floating_panel`; `MenuChrome` shed its `surface`/`radius_overlay`/`shadow` fields.
Command palette and dialog pass their dialog-elevation shadows to keep visuals identical.
- **E2** Combobox and command-palette rows use `paint_highlighted_row`. Menu `row_shell`
kept its hand-rolled three-way painting: its selected state uses ramp colors plus a
destructive variant and a flyout distinction the shared helpers do not express; migrating
it would have moved the code rather than deduplicated it.
- **E3** Combobox, command palette, and `handle_menu_key` navigate via
`wrapping_adjacent_selectable`. Note: menu `down`/`up` previously clamped at the ends;
they now wrap, per the plan.
- **E4** `dropdown_menu` consumes `ButtonVariant::chrome` for trigger colors and borders.
- **E5** Combobox and command-palette popups render `uniform_list` sized
`rows * row_height` capped at `POPUP_MAX_HEIGHT`, per the AGENTS.md convention. Scroll
positions persist through `rows_scroll: UniformListScrollHandle` fields on both states.
- **E6** Both "No matches" captions use `EmptyState::compact`.
- **E7** `waveform_bars(levels, size, cx, bar_color)` replaces the duplicated bar geometry
and reduce-motion height logic in `SpeechButton` and `SpeechWaveform`; the bar color is a
closure because the waveform paints silent levels muted and the button does not.
- **E8** Render-path caches: (1) `CodeViewState` caches per-line text and syntax roles
(`CodeLineLayout`) rebuilt on `set_source`/`update_line`; selection-dependent highlight
runs are still computed per visible row, since they cannot be derived at source-change
time. (2) `InputState::shape_current_text` reuses the previous `ShapedText` while the
text, wrap width, font, size, and color are unchanged (`ShapeCacheKey`, `RefCell` so the
paint-phase caller needs no entity update); `ShapedLineEntry.line` is `Arc<WrappedLine>`
to make the cache cloneable.
- **E9** Nits: inlined the single-use border alias in `select.rs`; identicon patterns are
cached per seed in a thread-local (PRNG no longer reruns each frame); tree indent depth is
clamped at `TREE_MAX_DEPTH = 16` instead of `u32::MAX as f32`; segmented ids are
`("segment", index)` so same-label segments cannot collide.
## App de-duplication (F)
- **F1** `shared/widgets.rs` gained `centered_spinner` (five pure copies migrated; the
`repo/mod.rs` variant that pairs a spinner with a status label stays inline — different
shape), `scroll_overlay` (all seven scrollbar overlays), and `clone_row` (moved from
`repo/helpers.rs`; `header.rs` imports it). `error_row` is the single inline-error
convention (`new.rs`, `send_patch.rs`, `grasp_servers.rs` migrated); the two banner-level
`Alert` uses remain Alerts. The inbox unread dot is `ui::status_dot::StatusDot`; the
inbox-local `empty_state` and the hand-centered wrapper in `issues/mod.rs` are gone in
favor of `shared::widgets::empty_state`; the issues detail "Loading…" pseudo-empty-state
is `centered_spinner` (the PR detail equivalent was already a spinner).
- **F2** File-level `+/−` counts in `commit_diff.rs` are `Badge`s (`Success`/`Danger`),
matching the commit-row counts.
- **F3** New `shared/event_list.rs`: `EventList` (toolbar + `uniform_list` +
`scroll_overlay` + empty state), `EventRow` + `event_row`/`event_meta_row` (badge, title,
author avatar, "opened", short id, age, click handler), `filter_toolbar` (the shared
`px_4 border_b_1 bg(muted)` skeleton), and `ROW_HEIGHT = 73`. `issues/mod.rs` and
`pull_requests/mod.rs` render through it; both headers build via `filter_toolbar`.
The detail-view meta rows were inspected and left alone: they render state verbs,
merged-at labels, and multi-author lines that do not match the row meta shape.
- **F4** `commit_list` in `shared/event_list.rs` is the uniform commit-list scaffold
(rows + optional per-row action + scrollbar overlay), migrated `repo/history.rs`,
`pull_requests/detail.rs`, and `pull_requests/new.rs`.
- **F5** `shared/progress.rs` gained `run_dialog_task` (close on success, fail on error)
and `run_dialog_task_with` (explicit success/error sinks). Onboarding, passphrase, and
create/init dialogs use them; `init.rs`/`create.rs` private `fail` wrappers are deleted
in favor of direct `DialogProgress` calls. `identity/import.rs` keeps a thin
`finish_import` because `ImportState` wraps `DialogProgress` rather than being one.
- **F6** `announcement_display_name` (five hand-rolled copies in `repo/helpers.rs`,
`repo/mod.rs` title, `explore/helpers.rs`, `pull_requests/helpers.rs` — whose
`fork_display_name` is deleted — and `inbox/mod.rs`), `short_id` (`..8`, now also used by
the history sync tooltip, which took 7), `snapshot_worktree` (the duplicated worktree
snapshot + tree + paths block in `reload_worktree`/`catch_up_worktree`),
`preferred_branch` (the announced → `main` → first fallback in `new/source.rs`),
`track_event_participants` (the duplicated author/commenter/owner tracking in the two
detail views).
- **F7** Render-path clones: commit lists store `Arc<Vec<FileCommit>>` (history also keeps
`Arc<CommitList>`), assigned once per load and cloned per frame as an Arc;
`RepositorySwitcher.entries` and its filtered `visible` rows are Arc'd.
- **F8** The no-op `RepoItem::Patch` arm in `open_repo_item` collapsed into `_ => {}` with
a comment; `RepoItem` keeps the variant.
- **F9** `issues/mod.rs` `ISSUE_ROW_HEIGHT` and the PR `ROW_HEIGHT` unified into
`event_list::ROW_HEIGHT`; `explore` `CARD_HEIGHT` decomposition documented. Per-dialog
widths (440/520/500/480/420) are intentional — see report-only items.
## Tests and lints (G)
- **G1** New regression tests: `theme::definition::tests` (`#éa` → `None`; `#abc`,
`#aabbcc` resolve), `input.rs` (reversed UTF-16 ranges order instead of panic;
off-boundary byte offsets floor; `floor_to_char_boundary` clamps), `resizable.rs`
(sub-floor resize clamps to the floor; negative `set_pane_width` clamps to
`PANE_MIN_SIZE`), `tests/tabs.rs` (`pinned=true` draws inline and selects; `closeable`
close control reports the tab index).
- **G2** Root `[workspace.lints.clippy]`: `all`, `perf`, `unwrap_used` — all `deny`, with
`clippy.toml` `allow-unwrap-in-tests = true`; every crate opts in via
`[lints] workspace = true`. `cargo clippy --workspace --all-targets -- -D warnings` is
clean. Fixes en route: the two `series.last().unwrap()` loop invariants in
`signed_core/src/pull_request.rs` now track the tail explicitly, and the four hardcoded
relay parses in `signed_state/src/backend.rs` use `expect`.
- **G4** Full gate green: `cargo fmt --all` (clean under `--check`), `cargo check
--workspace`, `cargo clippy --workspace --all-targets -- -D warnings`,
`cargo test --workspace` (all suites pass, including the panel/sizing/tabs suites that
exercise `Theme::init` and the macOS Drop path).
## Report-only items (need a product call)
- **Unlinked `inbox` module** (`signed_app/src/inbox`): `InboxView` has no reference from
any navigation surface today — the module compiles but nothing opens it. Left in place
per the plan. Note: this audit still hardened it (C1, B3), so enabling it later starts
from sound ground.
- **11 zero-consumer `crates/ui` components**: left in place as library stockpile; the
components participate in the shared refactors above, so nothing dead was deleted.
- **`DefaultHasher` in-session caveat** (`repo/helpers.rs` stable-hash helper): SipHash
keys are not stable across process restarts, so anything persisted from it would change.
Currently only used for in-session identity — safe today, do not persist its output.
- **Per-dialog widths** (440/520/500/480/420): deliberate distinct sizes, left alone.
- **`AnyThread` main-thread caveat** (`ui/src/theme/source/macos.rs:7`): theme reads use
`AnyThread` accessors on the main thread by convention; nothing enforces it.
## Verified-clean inventory
From the three audit passes, checked and deliberately unchanged:
- macOS/Windows unsafe blocks outside `theme/source/macos.rs` (`window_controls.rs`
caption-button cfg blocks, `windows.rs` theme reads): bounds-correct, correctly gated.
- Speech audio path beyond B6: sink/generation guards, stop-timeout handling, and the
recognizer handoff are generation-guarded; no unguarded shared state found.
- Command construction (`EventBuilder` paths in `signed_state`): tag parsing uses
`expect` on statically valid tags; no user-controlled panics found.
- Deserialization paths: `Settings` serde falls back per-field with defaults; theme
definitions log-and-fall back (hardened further by A2); announcement parsing drops
malformed clone/relay/maintainer values (covered by existing tests).
- Clean files across all passes: `layout/panel.rs`, `layout/shell.rs`,
`layout/titlebar.rs`, `components/segmented.rs`, `components/slider.rs`,
`components/switch.rs`, `components/toggle.rs`, `components/status_dot.rs`,
`components/tooltip.rs`, `components/grain.rs`, `shared/tree.rs`,
`shared/panels.rs`, `explore/helpers.rs`, `issues/helpers.rs` (post-F1),
`titlebar/repository_switcher.rs` (post-F7), `settings/*` (post-G2).
- Bounded-growth notes: `AnchorBoundsRegistry` (`common.rs`) never evicts but is bounded
by live windows × element ids (documented in-code); `TabsMeasurements.strips` is keyed
by window + strip id, now with per-strip tab pruning (B2).