diff --git a/Cargo.toml b/Cargo.toml index d181039..d5c189a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,3 +50,8 @@ panic = "unwind" [profile.profiling] inherits = "release" debug = true + +[workspace.lints.clippy] +all = "deny" +perf = "deny" +unwrap_used = "deny" diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 0000000..154626e --- /dev/null +++ b/clippy.toml @@ -0,0 +1 @@ +allow-unwrap-in-tests = true diff --git a/crates/metadata/Cargo.toml b/crates/metadata/Cargo.toml index a2d3c6d..b9f776f 100644 --- a/crates/metadata/Cargo.toml +++ b/crates/metadata/Cargo.toml @@ -14,3 +14,6 @@ futures.workspace = true anyhow.workspace = true gpui.workspace = true log.workspace = true + +[lints] +workspace = true diff --git a/crates/paths/Cargo.toml b/crates/paths/Cargo.toml index da558cc..d0c2a55 100644 --- a/crates/paths/Cargo.toml +++ b/crates/paths/Cargo.toml @@ -6,3 +6,6 @@ publish.workspace = true [dependencies] dirs = "6" + +[lints] +workspace = true diff --git a/crates/settings/Cargo.toml b/crates/settings/Cargo.toml index 2a41458..9b511bd 100644 --- a/crates/settings/Cargo.toml +++ b/crates/settings/Cargo.toml @@ -13,3 +13,6 @@ serde.workspace = true serde_json.workspace = true anyhow.workspace = true log.workspace = true + +[lints] +workspace = true diff --git a/crates/signed_app/Cargo.toml b/crates/signed_app/Cargo.toml index 645a5aa..2d32dad 100644 --- a/crates/signed_app/Cargo.toml +++ b/crates/signed_app/Cargo.toml @@ -20,3 +20,6 @@ nostr.workspace = true anyhow.workspace = true futures.workspace = true log.workspace = true + +[lints] +workspace = true diff --git a/crates/signed_app/src/app/mod.rs b/crates/signed_app/src/app/mod.rs index 22ce429..2a287d9 100644 --- a/crates/signed_app/src/app/mod.rs +++ b/crates/signed_app/src/app/mod.rs @@ -131,7 +131,7 @@ impl Render for AppRoot { div() .relative() .size_full() - .font_family(".SystemUIFont") + .font_family(cx.theme().ui_font()) .text_color(cx.theme().colors.foreground) .key_context(REPOSITORY_KEY_CONTEXT) .on_action(cx.listener(|this, action: &SwitchRepository, window, cx| { diff --git a/crates/signed_app/src/explore/helpers.rs b/crates/signed_app/src/explore/helpers.rs index b3fedba..140c43b 100644 --- a/crates/signed_app/src/explore/helpers.rs +++ b/crates/signed_app/src/explore/helpers.rs @@ -13,6 +13,7 @@ use ui::theme::ActiveTheme as _; use utils::relative_time; use crate::repo::actions::open_repo_panel; +use crate::repo::helpers::announcement_display_name; use crate::workspace::Workspace; const RECENT_COUNT: usize = 10; @@ -62,11 +63,7 @@ pub(super) fn render_card( let workspace = workspace.clone(); let announcement = announcement.clone(); - let name = announcement - .name - .as_deref() - .map(SharedString::from) - .unwrap_or_else(|| SharedString::from(announcement.id.clone())); + let name = announcement_display_name(&announcement); let description = announcement .description diff --git a/crates/signed_app/src/explore/mod.rs b/crates/signed_app/src/explore/mod.rs index 27e68c4..1ae7bf0 100644 --- a/crates/signed_app/src/explore/mod.rs +++ b/crates/signed_app/src/explore/mod.rs @@ -14,7 +14,6 @@ use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState, InputStateEvent}; use ui::layout::panel::Panel; -use ui::scrollbar::Scrollbar; use ui::segmented::{Segmented, SegmentedOption}; use ui::theme::ActiveTheme as _; @@ -22,6 +21,7 @@ use crate::shared::panels; use crate::workspace::Workspace; const COLUMNS: usize = 2; +// Name row, avatar strip, meta row, and their borders and gaps, in px. const CARD_HEIGHT: f32 = 40. + 64. + 48. + 2. + 6.; pub struct ExploreView { @@ -153,29 +153,23 @@ impl ExploreView { ), ) .child( - div() - .absolute() - .left_0() - .bottom_0() - .pl_4() - .pb_4() - .child( - Segmented::new("explore-filter", filter) - .options(vec![ - SegmentedOption::new(RepoFilter::All, "All") - .icon(Icon::named(IconRole::Grid).small().color(muted)), - SegmentedOption::new(RepoFilter::Recent, "Recent") - .icon(Icon::named(IconRole::Clock).small().color(muted)), - ]) - .on_change(move |filter, _, cx| { - if let Err(error) = weak.update(cx, |this, cx| { - this.filter = filter; - this.rebuild_rows(cx); - }) { - log::warn!("failed to change explore filter: {error}"); - } - }), - ), + div().absolute().left_0().bottom_0().pl_4().pb_4().child( + Segmented::new("explore-filter", filter) + .options(vec![ + SegmentedOption::new(RepoFilter::All, "All") + .icon(Icon::named(IconRole::Grid).small().color(muted)), + SegmentedOption::new(RepoFilter::Recent, "Recent") + .icon(Icon::named(IconRole::Clock).small().color(muted)), + ]) + .on_change(move |filter, _, cx| { + if let Err(error) = weak.update(cx, |this, cx| { + this.filter = filter; + this.rebuild_rows(cx); + }) { + log::warn!("failed to change explore filter: {error}"); + } + }), + ), ) .into_any_element() } @@ -262,14 +256,9 @@ impl Render for ExploreView { }) .size_full(), ) - .child( - div() - .absolute() - .top_0() - .left_0() - .right_0() - .bottom_0() - .child(Scrollbar::vertical("explore-scroll", scroll_handle)), - ) + .child(crate::shared::widgets::scroll_overlay( + "explore-scroll", + scroll_handle, + )) } } diff --git a/crates/signed_app/src/identity/import.rs b/crates/signed_app/src/identity/import.rs index e2b1c50..1e6f287 100644 --- a/crates/signed_app/src/identity/import.rs +++ b/crates/signed_app/src/identity/import.rs @@ -11,7 +11,7 @@ use ui::field::Field; use ui::input::{Input, InputState, InputStateEvent}; use ui::theme::ActiveTheme as _; -use crate::shared::progress::{DialogProgress, error_row}; +use crate::shared::progress::{DialogProgress, error_row, run_dialog_task_with}; #[derive(Clone, Copy, Default, PartialEq, Eq)] enum Stage { @@ -347,17 +347,17 @@ fn finish_import( handle: &DialogHandle, cx: &mut App, ) { - let state = state.clone(); let handle = handle.clone(); - - cx.spawn(async move |cx| match task.await { - Ok(_) => cx.update(|cx| handle.close(cx)), - Err(error) => { + let state = state.clone(); + run_dialog_task_with( + task, + cx, + move |_, cx| cx.update(|cx| handle.close(cx)), + move |error, cx| { state.update(cx, |state, cx| { state.progress.fail(error.to_string()); cx.notify(); }); - } - }) - .detach(); + }, + ); } diff --git a/crates/signed_app/src/identity/onboarding.rs b/crates/signed_app/src/identity/onboarding.rs index e96bfe5..c8ba544 100644 --- a/crates/signed_app/src/identity/onboarding.rs +++ b/crates/signed_app/src/identity/onboarding.rs @@ -11,7 +11,7 @@ use ui::field::Field; use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; -use crate::shared::progress::{DialogProgress, error_row}; +use crate::shared::progress::{DialogProgress, error_row, run_dialog_task}; pub struct OnboardingDialog { handle: DialogHandle, @@ -61,19 +61,7 @@ impl OnboardingDialog { let backend = Backend::global(cx); let task = backend.update(cx, |backend, cx| backend.create_identity(&name, &pass, cx)); - let state = self.state.clone(); - let handle = self.handle.clone(); - - cx.spawn(async move |_this, cx| match task.await { - Ok(_) => cx.update(|cx| handle.close(cx)), - Err(error) => { - state.update(cx, |state, cx| { - state.fail(error.to_string()); - cx.notify(); - }); - } - }) - .detach(); + run_dialog_task(task, &self.state, &self.handle, cx); } } diff --git a/crates/signed_app/src/identity/passphrase.rs b/crates/signed_app/src/identity/passphrase.rs index 6f2cd5c..91947f9 100644 --- a/crates/signed_app/src/identity/passphrase.rs +++ b/crates/signed_app/src/identity/passphrase.rs @@ -11,7 +11,7 @@ use ui::field::Field; use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState, InputStateEvent}; -use crate::shared::progress::{DialogProgress, error_row, push_steps_row}; +use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task}; pub struct PassphraseDialog { handle: DialogHandle, @@ -64,19 +64,7 @@ impl PassphraseDialog { let backend = Backend::global(cx); let task = backend.update(cx, |backend, cx| backend.restore_with_passphrase(&pass, cx)); - let state = self.state.clone(); - let handle = self.handle.clone(); - - cx.spawn(async move |_this, cx| match task.await { - Ok(_) => cx.update(|cx| handle.close(cx)), - Err(error) => { - state.update(cx, |state, cx| { - state.fail(error.to_string()); - cx.notify(); - }); - } - }) - .detach(); + run_dialog_task(task, &self.state, &self.handle, cx); } } diff --git a/crates/signed_app/src/inbox/helpers.rs b/crates/signed_app/src/inbox/helpers.rs index 365ac96..dcffbe7 100644 --- a/crates/signed_app/src/inbox/helpers.rs +++ b/crates/signed_app/src/inbox/helpers.rs @@ -1,7 +1,7 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, Div, Entity, InteractiveElement as _, IntoElement, ParentElement as _, - SharedString, Stateful, Styled as _, div, px, + SharedString, Stateful, Styled as _, div, }; use metadata::ProfileDirectory; use nostr::prelude::{Event, Kind, PublicKey}; @@ -101,11 +101,8 @@ pub fn thread( .child(div().flex_1()) .when(unread, |this| { this.child( - div() - .flex_shrink_0() - .size_2() - .rounded_full() - .bg(cx.theme().colors.primary), + ui::status_dot::StatusDot::new(("inbox-unread", ix)) + .variant(ui::status_dot::StatusDotVariant::Accent), ) }), ) @@ -167,26 +164,3 @@ fn activity_phrase(kind: Kind) -> &'static str { _ => "did something", } } - -pub fn empty_state(message: &'static str, cx: &App) -> AnyElement { - v_flex() - .w_full() - .flex_1() - .min_h_0() - .items_center() - .justify_center() - .gap_2() - .py_8() - .child( - Icon::named(IconRole::Inbox) - .size(px(24.)) - .color(cx.theme().colors.muted_foreground), - ) - .child( - div() - .text_base() - .text_color(cx.theme().colors.muted_foreground) - .child(SharedString::from(message)), - ) - .into_any_element() -} diff --git a/crates/signed_app/src/inbox/mod.rs b/crates/signed_app/src/inbox/mod.rs index 28365cf..dbeb362 100644 --- a/crates/signed_app/src/inbox/mod.rs +++ b/crates/signed_app/src/inbox/mod.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use std::sync::Arc; use anyhow::Error; +use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity, @@ -11,6 +12,7 @@ use metadata::ProfileDirectory; use nostr::prelude::{Event, EventId, Kind, PublicKey, Timestamp}; use signed_core::{InboxItem, InboxReadState, RepoAddr}; use signed_state::{Backend, BackendEvent, Inbox, RefreshGate, RefreshRequest, RepoListStore}; +use ui::alert::{Alert, AlertSeverity, AlertStyle}; use ui::button::Button; use ui::common::{StyledExt as _, h_flex, v_flex}; use ui::icons::{Icon, IconRole}; @@ -19,9 +21,11 @@ use ui::scroll_area::ScrollArea; mod helpers; -use helpers::{empty_section_row, empty_state, repo_header, thread}; +use helpers::{empty_section_row, repo_header, thread}; use crate::repo::actions::{RepoItem, open_repo_item}; +use crate::repo::helpers::announcement_display_name; +use crate::shared::widgets::empty_state; use crate::workspace::Workspace; const MAX_SUB_ACTIVITIES: usize = 5; @@ -50,6 +54,8 @@ pub struct InboxView { refresh: RefreshGate, tasks: Vec>>, directory: Entity, + /// The last refresh failure, shown inline until the next refresh succeeds. + error: Option, _subscriptions: Vec, } @@ -92,6 +98,7 @@ impl InboxView { refresh: RefreshGate::default(), tasks: vec![], directory: ProfileDirectory::new(cx), + error: None, _subscriptions: subscriptions, } } @@ -164,6 +171,12 @@ impl InboxView { self.run_refresh(cx); } + /// Reaps finished tasks, then queues another. + fn push_task(&mut self, task: Task>) { + self.tasks.retain(|task| !task.is_ready()); + self.tasks.push(task); + } + fn run_refresh(&mut self, cx: &mut Context) { self.refresh.begin(); let backend = Backend::global(cx); @@ -178,12 +191,16 @@ impl InboxView { let state = self.state.clone(); let work = cx.background_spawn(async move { Inbox::query(&client, me, &state).await }); - self.tasks.push(cx.spawn(async move |this, cx| { + self.push_task(cx.spawn(async move |this, cx| { let (threads, _unread_count) = match work.await { Ok(results) => results, Err(error) => { log::warn!("inbox refresh failed: {error}"); - return this.update(cx, |this, _cx| this.refresh.abort()); + return this.update(cx, |this, cx| { + this.error = Some(error.to_string().into()); + this.refresh.abort(); + cx.notify(); + }); } }; @@ -193,6 +210,7 @@ impl InboxView { return false; } this.threads = Arc::new(threads); + this.error = None; this.rebuild(cx); cx.notify(); this.refresh.finish() @@ -427,6 +445,24 @@ impl Render for InboxView { .on_click(cx.listener(|this, _, _, cx| this.mark_all_read(cx))), ), ) + .when_some(self.error.clone(), |this, error| { + let weak = cx.entity().downgrade(); + this.child( + Alert::new("inbox-error") + .severity(AlertSeverity::Danger) + .title("Inbox") + .message(error) + .style(AlertStyle::Inline) + .on_dismiss(move |cx| { + if let Err(error) = weak.update(cx, |this, cx| { + this.error = None; + cx.notify(); + }) { + log::warn!("failed to dismiss inbox error: {error}"); + } + }), + ) + }) .child( div() .relative() @@ -434,7 +470,7 @@ impl Render for InboxView { .min_h_0() .px_4() .child(if rows.is_empty() { - empty_state("You're all caught up.", cx) + empty_state("You're all caught up.") } else { ScrollArea::new("inbox-scroll") .flex_1() @@ -455,12 +491,6 @@ fn repo_name(addr: Option<&RepoAddr>, cx: &App) -> SharedString { .announcements .iter() .find(|announcement| announcement.addr() == *addr) - .map(|announcement| { - announcement - .name - .as_deref() - .map(SharedString::from) - .unwrap_or_else(|| SharedString::from(announcement.id.clone())) - }) + .map(announcement_display_name) .unwrap_or_else(|| SharedString::from("Untitled")) } diff --git a/crates/signed_app/src/issues/detail.rs b/crates/signed_app/src/issues/detail.rs index 99553f8..71115a9 100644 --- a/crates/signed_app/src/issues/detail.rs +++ b/crates/signed_app/src/issues/detail.rs @@ -3,12 +3,11 @@ use gpui::{ ScrollHandle, SharedString, Styled as _, Subscription, Window, div, }; use metadata::ProfileDirectory; -use nostr::prelude::{EventId, PublicKey}; +use nostr::prelude::EventId; use signed_core::GitEvent; use signed_state::RepoStore; use ui::avatar::Avatar; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; -use ui::empty_state::EmptyState; use ui::input::InputState; use ui::layout::panel::Panel; use ui::scroll_area::ScrollArea; @@ -56,27 +55,23 @@ impl IssueDetailView { /// Track the issue author, everyone who commented and the repository owner. fn track_participants(&mut self, cx: &mut Context) { let store = self.store.read(cx); - let mut keys: Vec = store + let author = store .issues .iter() .find(|issue| issue.id == self.issue_id) - .map(|issue| issue.pubkey) - .into_iter() + .map(|issue| issue.pubkey); + let owner = store.announcement.as_ref().map(|a| a.owner); + let comments: Vec<_> = store + .comments_of(&self.issue_id) + .map(|comment| comment.pubkey) .collect(); - - keys.extend( - store - .comments_of(&self.issue_id) - .map(|comment| comment.pubkey), + crate::shared::track_event_participants( + author, + owner, + comments.into_iter(), + &self.directory, + cx, ); - - if let Some(owner) = store.announcement.as_ref().map(|a| a.owner) { - keys.push(owner); - } - - self.directory.update(cx, |directory, cx| { - directory.track(keys, cx); - }); } } @@ -97,17 +92,12 @@ impl Render for IssueDetailView { let store = self.store.read(cx); let Some(issue) = store.issues.iter().find(|issue| issue.id == self.issue_id) else { - let message = if store.loaded { - "Issue not found" + // A not-yet-loaded store is not the same as a missing issue. + return if store.loaded { + crate::shared::widgets::empty_state("Issue not found") } else { - "Loading issue..." + crate::shared::widgets::centered_spinner("issue-loading") }; - return v_flex() - .size_full() - .items_center() - .justify_center() - .child(EmptyState::new(message)) - .into_any_element(); }; let (title, author, status, age, issue_id, content, pubkey) = { diff --git a/crates/signed_app/src/issues/mod.rs b/crates/signed_app/src/issues/mod.rs index fc763fb..7169421 100644 --- a/crates/signed_app/src/issues/mod.rs +++ b/crates/signed_app/src/issues/mod.rs @@ -1,36 +1,33 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, - ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, - Subscription, UniformListScrollHandle, WeakEntity, Window, div, px, uniform_list, + AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, + SharedString, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div, }; use helpers::{IssueFilter, StatusCounts, filter_by_status}; use metadata::ProfileDirectory; use nostr::prelude::PublicKey; use signed_core::GitEvent; use signed_state::RepoStore; -use ui::avatar::Avatar; use ui::button::Button; -use ui::common::{Sizable as _, h_flex, v_flex}; -use ui::empty_state::EmptyState; +use ui::common::v_flex; use ui::icons::{Icon, IconRole}; use ui::layout::panel::Panel; -use ui::scrollbar::Scrollbar; use ui::segmented::{Segmented, SegmentedOption}; use ui::theme::ActiveTheme as _; use utils::relative_time; +use std::rc::Rc; + use self::detail::IssueDetailView; +use crate::repo::helpers::short_id; +use crate::shared::event_list::{EventList, EventRow}; use crate::shared::panels; -use crate::shared::widgets::status_badge; use crate::workspace::Workspace; pub mod detail; pub(crate) mod helpers; pub mod new_issue; -const ISSUE_ROW_HEIGHT: f32 = 73.; - pub struct IssuesView { workspace: WeakEntity, store: Entity, @@ -131,14 +128,9 @@ impl IssuesView { let muted = cx.theme().colors.muted_foreground; let weak = cx.entity().downgrade(); - h_flex() - .px_4() - .w_full() - .gap_3() - .border_b_1() - .border_color(cx.theme().colors.border) - .bg(cx.theme().colors.muted) - .child( + crate::shared::event_list::filter_toolbar( + cx, + [ Segmented::new("issue-filter", self.filter) .options(vec![ SegmentedOption::new(IssueFilter::All, format!("All ({})", counts.total)) @@ -158,18 +150,18 @@ impl IssuesView { }) { log::warn!("failed to switch issue filter: {error}"); } - }), - ) - .child(div().flex_1()) - .child( + }) + .into_any_element(), + div().flex_1().into_any_element(), Button::new("new-issue") .label("New issue") .icon(Icon::named(IconRole::CirclePlus)) .on_click(cx.listener(|this, _, _, cx| { this.open_new_issue(cx); - })), - ) - .into_any_element() + })) + .into_any_element(), + ], + ) } } @@ -182,147 +174,70 @@ impl Panel for IssuesView { impl Render for IssuesView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let filter = self.filter; - let count = self.visible_issues.len(); let visible_issues = self.visible_issues.clone(); let directory = self.directory.clone(); let store = self.store.clone(); let workspace = self.workspace.clone(); + let rows = visible_issues + .iter() + .enumerate() + .filter_map(|(ix, &issue_ix)| { + // The store re-read per frame can shrink below a captured index. + let issue = store.read(cx).issues.get(issue_ix)?; + let profile = directory.read(cx).profile(&issue.pubkey, cx); + let issue_id = issue.id; + let id_hex = issue.id.to_hex(); + let status = store.read(cx).status_of(issue); + + let on_click: crate::shared::event_list::EventHandler = { + let workspace = workspace.clone(); + let store = store.clone(); + Rc::new(move |_, window, cx| { + let id = SharedString::from(format!("issue:{issue_id}")); + let store = store.clone(); + panels::open_detail( + &workspace, + id, + move |_, cx| { + cx.new(|cx| IssueDetailView::new(store.clone(), issue_id, cx)) + }, + window, + cx, + ); + }) + }; + + Some(EventRow { + id: ix.into(), + status, + title: issue.activity_subject().into(), + author: profile.name(), + picture: profile.picture(), + pubkey: issue.pubkey, + short_id: short_id(&id_hex), + age: SharedString::from(relative_time(issue.created_at)), + on_click, + }) + }) + .collect(); + + let empty_message = match filter { + IssueFilter::All => "No issues", + IssueFilter::Open => "No open issues", + IssueFilter::Closed => "No closed issues", + }; + v_flex() .size_full() - .child(self.render_header(cx)) .when_some(self.new_issue.clone(), |el, view| el.child(view)) .child( - v_flex() - .relative() - .flex_1() - .min_h_0() - .w_full() - .when(count > 0, |this| { - this.child( - uniform_list("issues", count, move |range, _, cx| { - range - .map(|ix| { - let issue_ix = visible_issues[ix]; - let issue = &store.read(cx).issues[issue_ix]; - let title = issue.activity_subject(); - let id_hex = issue.id.to_hex(); - let profile = directory.read(cx).profile(&issue.pubkey, cx); - let author = profile.name(); - let age = relative_time(issue.created_at); - let status = store.read(cx).status_of(issue); - let issue_id = issue.id; - let workspace = workspace.clone(); - let store = store.clone(); - - h_flex() - .id(ix) - .w_full() - .h(px(ISSUE_ROW_HEIGHT)) - .gap_4() - .px_4() - .border_b_1() - .border_color(cx.theme().colors.border) - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .on_click(move |_, window, cx| { - let id = - SharedString::from(format!("issue:{issue_id}")); - let store = store.clone(); - panels::open_detail( - &workspace, - id, - move |_, cx| { - cx.new(|cx| { - IssueDetailView::new( - store.clone(), - issue_id, - cx, - ) - }) - }, - window, - cx, - ); - }) - .child(status_badge(status)) - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_1() - .child( - div() - .text_base() - .text_ellipsis() - .whitespace_nowrap() - .child(title), - ) - .child( - h_flex() - .gap_2() - .text_xs() - .child( - h_flex() - .gap_1() - .child( - Avatar::new(issue.pubkey) - .name(author.clone()) - .picture( - profile.picture(), - ) - .small(), - ) - .child(div().child(author)), - ) - .child(SharedString::from("opened")) - .child( - div() - .text_color( - cx.theme() - .colors - .muted_foreground, - ) - .child(SharedString::from( - &id_hex[..8], - )), - ) - .child(SharedString::from(age)), - ), - ) - .into_any_element() - }) - .collect() - }) - .track_scroll(&self.scroll_handle) - .size_full(), - ) - .child( - div() - .absolute() - .top_0() - .left_0() - .right_0() - .bottom_0() - .child(Scrollbar::vertical( - "issues-scroll", - self.scroll_handle.clone(), - )), - ) - }) - .when(count == 0, |this| { - let message = match filter { - IssueFilter::All => "No issues", - IssueFilter::Open => "No open issues", - IssueFilter::Closed => "No closed issues", - }; - this.child( - v_flex() - .size_full() - .items_center() - .justify_center() - .child(EmptyState::new(message)), - ) - }), + EventList::new("issues") + .toolbar(self.render_header(cx)) + .scroll_handle(self.scroll_handle.clone()) + .rows(rows) + .empty_message(empty_message) + .render(cx), ) .into_any_element() } diff --git a/crates/signed_app/src/issues/new_issue.rs b/crates/signed_app/src/issues/new_issue.rs index 1069bd0..6c11980 100644 --- a/crates/signed_app/src/issues/new_issue.rs +++ b/crates/signed_app/src/issues/new_issue.rs @@ -10,31 +10,41 @@ use ui::field::Field; use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; +use crate::shared::progress::DialogProgress; + pub struct NewIssueDialog { handle: DialogHandle, store: Entity, subject: Entity, content: Entity, + state: Entity, } impl NewIssueDialog { pub fn new(store: Entity, cx: &mut App) -> Entity { let subject = InputState::new(cx); let content = InputState::builder().multiline().build(cx); + let state = cx.new(|_| DialogProgress::default()); cx.new(|_| Self { handle: DialogHandle::new(true), store, subject, content, + state, }) } fn submit(&mut self, cx: &mut Context) { + // The publish runs detached in the store; one submission per dialog. + if self.state.read(cx).busy { + return; + } let subject = self.subject.read(cx).value().to_string(); let content = self.content.read(cx).value().to_string(); let subject = (!subject.trim().is_empty()).then_some(subject); + self.state.update(cx, |state, _| state.begin()); self.store.update(cx, |store, cx| { store.open_issue(subject, content, cx); }); @@ -48,6 +58,7 @@ impl Render for NewIssueDialog { let subject = self.subject.clone(); let content = self.content.clone(); let this = cx.entity().downgrade(); + let action_state = self.state.clone(); Dialog::new("new-issue-dialog") .handle(self.handle.clone()) @@ -72,11 +83,14 @@ impl Render for NewIssueDialog { ) .into_any_element() }) - .actions(move |_, _| { + .actions(move |_, cx| { let this = this.clone(); + let busy = action_state.read(cx).busy; vec![ Button::new("create-issue") .label("Create issue") + .loading(busy) + .disabled(busy) .on_click(move |_, _, cx| { crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx))); }) diff --git a/crates/signed_app/src/pull_requests/detail.rs b/crates/signed_app/src/pull_requests/detail.rs index 844376c..f9c8719 100644 --- a/crates/signed_app/src/pull_requests/detail.rs +++ b/crates/signed_app/src/pull_requests/detail.rs @@ -1,13 +1,15 @@ use std::path::PathBuf; +use std::sync::Arc; + use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle, - WeakEntity, Window, div, uniform_list, + WeakEntity, Window, div, }; use metadata::ProfileDirectory; -use nostr::prelude::{EventId, Kind, PublicKey, Url}; +use nostr::prelude::{EventId, Kind, Url}; use signed_core::{GitEvent, PullRequest, RepoAddr}; use signed_git::{FileCommit, PatchParser}; use signed_state::{Backend, Mirrors, RepoStore}; @@ -19,8 +21,6 @@ use ui::icons::{Icon, IconRole}; use ui::input::InputState; use ui::layout::panel::Panel; use ui::scroll_area::ScrollArea; -use ui::scrollbar::Scrollbar; -use ui::spinner::Spinner; use ui::tabs::{Tab, Tabs}; use ui::theme::ActiveTheme as _; use utils::relative_time; @@ -28,7 +28,6 @@ use utils::relative_time; use super::dialogs; use crate::issues::helpers::{comment_form, comments_section, pr_roots, sidebar_section}; use crate::repo::commit_diff::{CommitDiffView, DiffPane}; -use crate::repo::helpers::commit_row; use crate::shared::widgets::{empty_state, status_badge}; use crate::workspace::Workspace; @@ -54,7 +53,7 @@ pub struct PullRequestDetailView { worktree: Option, description: SharedString, current_commit: Option, - commits: Vec, + commits: Arc>, loading: bool, error: Option, bound: Option, @@ -96,7 +95,7 @@ impl PullRequestDetailView { worktree: None, description: SharedString::default(), current_commit: None, - commits: Vec::new(), + commits: Arc::new(Vec::new()), loading: true, error: None, bound: None, @@ -112,18 +111,23 @@ impl PullRequestDetailView { fn track_participants(&mut self, cx: &mut Context) { let store = self.store.read(cx); - let mut keys: Vec = store + let author = store .pull_requests .iter() .find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest) - .map(|root| vec![root.pubkey]) - .unwrap_or_default(); - keys.extend(store.comments_of(&self.pr_id).map(|comment| comment.pubkey)); - if let Some(owner) = store.announcement.as_ref().map(|a| a.owner) { - keys.push(owner); - } - self.directory - .update(cx, |directory, cx| directory.track(keys, cx)); + .map(|root| root.pubkey); + let owner = store.announcement.as_ref().map(|a| a.owner); + let comments: Vec<_> = store + .comments_of(&self.pr_id) + .map(|comment| comment.pubkey) + .collect(); + crate::shared::track_event_participants( + author, + owner, + comments.into_iter(), + &self.directory, + cx, + ); } fn sync(&mut self, cx: &mut Context) { @@ -181,6 +185,12 @@ impl PullRequestDetailView { self.load_diff(binding, cx); } + /// Reaps finished tasks, then queues another. + fn push_task(&mut self, task: gpui::Task>) { + self.tasks.retain(|task| !task.is_ready()); + self.tasks.push(task); + } + fn load_diff(&mut self, binding: PrBinding, cx: &mut Context) { self.loading = true; self.error = None; @@ -266,7 +276,7 @@ impl PullRequestDetailView { } this.loading = false; this.worktree = worktree; - this.commits = commits; + this.commits = Arc::new(commits); match diff { Ok(diff) => this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx)), Err(error) => this.error = Some(error.to_string().into()), @@ -275,7 +285,7 @@ impl PullRequestDetailView { })?; Ok(()) }); - self.tasks.push(task); + self.push_task(task); } fn open_commit_diff( @@ -443,54 +453,26 @@ impl PullRequestDetailView { if self.commits.is_empty() { return empty_state("No commits found"); } - let commits = self.commits.clone(); + let commits = Arc::clone(&self.commits); let worktree = self.worktree.clone(); let view = cx.entity().downgrade(); - v_flex() - .relative() - .flex_1() - .min_h_0() - .child( - uniform_list("pr-commits", commits.len(), move |range, _, cx| { - range - .map(|ix| { - let commit = commits[ix].clone(); - let id = commit.id.clone(); - let worktree = worktree.clone(); - let view = view.clone(); - commit_row( - ix, - &commit, - None, - move |window, cx| { - if let Some(worktree) = worktree.clone() { - crate::shared::log_dropped(view.update(cx, |this, cx| { - this.open_commit_diff(worktree, &id, window, cx); - })); - } - }, - cx, - ) - }) - .collect() - }) - .track_scroll(&self.commit_scroll_handle) - .size_full(), - ) - .child( - div() - .absolute() - .top_0() - .left_0() - .right_0() - .bottom_0() - .child(Scrollbar::vertical( - "pr-commits-scroll", - self.commit_scroll_handle.clone(), - )), - ) - .into_any_element() + crate::shared::event_list::commit_list( + "pr-commits", + "pr-commits-scroll", + commits, + self.commit_scroll_handle.clone(), + |_, _, _| None, + move |commit, window, cx| { + if let Some(worktree) = worktree.clone() { + let id = commit.id.clone(); + crate::shared::log_dropped(view.update(cx, |this, cx| { + this.open_commit_diff(worktree, &id, window, cx); + })); + } + }, + cx, + ) } fn render_header(&self, cx: &mut Context) -> AnyElement { @@ -614,10 +596,5 @@ impl Render for PullRequestDetailView { } fn centered_spinner() -> AnyElement { - v_flex() - .size_full() - .items_center() - .justify_center() - .child(Spinner::new("pr-loading")) - .into_any_element() + crate::shared::widgets::centered_spinner("pr-loading") } diff --git a/crates/signed_app/src/pull_requests/dialogs/update.rs b/crates/signed_app/src/pull_requests/dialogs/update.rs index 675d7b7..388d6f6 100644 --- a/crates/signed_app/src/pull_requests/dialogs/update.rs +++ b/crates/signed_app/src/pull_requests/dialogs/update.rs @@ -11,29 +11,39 @@ use ui::field::Field; use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; +use crate::shared::progress::DialogProgress; + pub struct UpdatePrDialog { handle: DialogHandle, store: Entity, root: Event, patch: Entity, + state: Entity, } impl UpdatePrDialog { pub fn new(store: Entity, root: Event, cx: &mut App) -> Entity { let patch = InputState::builder().multiline().build(cx); + let state = cx.new(|_| DialogProgress::default()); cx.new(|_| Self { handle: DialogHandle::new(true), store, root, patch, + state, }) } fn submit(&mut self, cx: &mut Context) { + // The publish runs detached in the store; one submission per dialog. + if self.state.read(cx).busy { + return; + } let patch = self.patch.read(cx).value().to_string(); if patch.trim().is_empty() { return; } + self.state.update(cx, |state, _| state.begin()); self.store.update(cx, |store, cx| { store.update_pull_request(&self.root, patch, cx); }); @@ -45,6 +55,7 @@ impl Render for UpdatePrDialog { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let patch = self.patch.clone(); let this = cx.entity().downgrade(); + let action_state = self.state.clone(); Dialog::new("update-pr-dialog") .handle(self.handle.clone()) @@ -65,11 +76,14 @@ impl Render for UpdatePrDialog { ) .into_any_element() }) - .actions(move |_, _| { + .actions(move |_, cx| { let this = this.clone(); + let busy = action_state.read(cx).busy; vec![ Button::new("submit-update") .label("Update pull request") + .loading(busy) + .disabled(busy) .on_click(move |_, _, cx| { crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx))); }) diff --git a/crates/signed_app/src/pull_requests/helpers.rs b/crates/signed_app/src/pull_requests/helpers.rs index b39b227..c484503 100644 --- a/crates/signed_app/src/pull_requests/helpers.rs +++ b/crates/signed_app/src/pull_requests/helpers.rs @@ -55,14 +55,6 @@ impl ForkCompare { } } -pub fn fork_display_name(announcement: &Announcement) -> SharedString { - announcement - .name - .as_deref() - .map(SharedString::from) - .unwrap_or_else(|| SharedString::from(announcement.id.clone())) -} - pub fn shorten_owner(owner: &PublicKey) -> String { owner.to_hex().chars().take(10).collect() } @@ -121,7 +113,11 @@ pub fn source_menu_items( } else { SharedString::from(format!("by {}", shorten_owner(&candidate.owner))) }; - let title = format!("{} — {}", fork_display_name(&candidate), subtitle); + let title = format!( + "{} — {}", + crate::repo::helpers::announcement_display_name(&candidate), + subtitle + ); let target = view.clone(); let checked = active_fork == Some(candidate.addr()); let announcement = candidate; diff --git a/crates/signed_app/src/pull_requests/mod.rs b/crates/signed_app/src/pull_requests/mod.rs index bc4107a..fd7c7a8 100644 --- a/crates/signed_app/src/pull_requests/mod.rs +++ b/crates/signed_app/src/pull_requests/mod.rs @@ -1,21 +1,19 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, - ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, - Subscription, UniformListScrollHandle, WeakEntity, Window, div, px, uniform_list, + AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, + SharedString, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div, }; use metadata::ProfileDirectory; use nostr::prelude::{Kind, PublicKey}; use signed_core::GitEvent; use signed_state::RepoStore; +use std::rc::Rc; use ui::alert::{Alert, AlertSeverity}; -use ui::avatar::Avatar; -use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::common::v_flex; use ui::dropdown_menu::DropdownMenu; use ui::icons::{Icon, IconRole}; use ui::layout::panel::Panel; use ui::menu::MenuItem; -use ui::scrollbar::Scrollbar; use ui::segmented::{Segmented, SegmentedOption}; use ui::theme::ActiveTheme as _; use utils::relative_time; @@ -32,11 +30,10 @@ pub use new::NewPullRequestView; pub use send_patch::SendPatchView; use crate::issues::helpers::{StatusCounts, filter_by_status}; -use crate::shared::widgets::{empty_state, status_badge}; +use crate::repo::helpers::short_id; +use crate::shared::event_list::{EventList, EventRow}; use crate::workspace::Workspace; -const ROW_HEIGHT: f32 = 73.; - pub struct PullRequestsView { workspace: WeakEntity, store: Entity, @@ -198,14 +195,9 @@ impl PullRequestsView { let menu_open_weak = cx.entity().downgrade(); let patch_weak = cx.entity().downgrade(); - h_flex() - .px_4() - .w_full() - .gap_3() - .border_b_1() - .border_color(cx.theme().colors.border) - .bg(cx.theme().colors.muted) - .child( + crate::shared::event_list::filter_toolbar( + cx, + [ Segmented::new("pr-filter", self.filter) .options(vec![ SegmentedOption::new( @@ -241,10 +233,9 @@ impl PullRequestsView { }) { log::warn!("failed to switch PR filter: {error}"); } - }), - ) - .child(div().flex_1()) - .child( + }) + .into_any_element(), + div().flex_1().into_any_element(), DropdownMenu::new("new-pr-actions") .label("New") .icon(Icon::named(IconRole::GitPullRequest)) @@ -271,9 +262,10 @@ impl PullRequestsView { })); } })] - }), - ) - .into_any_element() + }) + .into_any_element(), + ], + ) } } @@ -286,7 +278,6 @@ impl Panel for PullRequestsView { impl Render for PullRequestsView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let filter = self.filter; - let count = self.visible_prs.len(); let visible = self.visible_prs.clone(); let directory = self.directory.clone(); let store = self.store.clone(); @@ -300,9 +291,60 @@ impl Render for PullRequestsView { let dismiss_warning_store = self.store.clone(); let dismiss_error_store = self.store.clone(); + let rows = visible + .iter() + .enumerate() + .filter_map(|(ix, &pr_ix)| { + // The store re-read per frame can shrink below a captured index. + let pr = store.read(cx).pull_requests.get(pr_ix)?; + let profile = directory.read(cx).profile(&pr.pubkey, cx); + let pr_id = pr.id; + let id_hex = pr.id.to_hex(); + let status = store.read(cx).status_of(pr); + + let on_click: crate::shared::event_list::EventHandler = { + let workspace = workspace.clone(); + let store = store.clone(); + Rc::new(move |_, window, cx| { + let id = SharedString::from(format!("pr:{pr_id}")); + let workspace_for_build = workspace.clone(); + let store = store.clone(); + crate::shared::panels::open_detail( + &workspace, + id, + move |window, cx| { + cx.new(|cx| { + PullRequestDetailView::new( + workspace_for_build.clone(), + store.clone(), + pr_id, + window, + cx, + ) + }) + }, + window, + cx, + ); + }) + }; + + Some(EventRow { + id: ix.into(), + status, + title: pr.activity_subject().into(), + author: profile.name(), + picture: profile.picture(), + pubkey: pr.pubkey, + short_id: short_id(&id_hex), + age: SharedString::from(relative_time(pr.created_at)), + on_click, + }) + }) + .collect(); + v_flex() .size_full() - .child(self.render_header(cx)) .when_some(last_warning, |this, warning| { this.child( Alert::new("pr-warning") @@ -326,127 +368,12 @@ impl Render for PullRequestsView { ) }) .child( - v_flex() - .relative() - .flex_1() - .min_h_0() - .w_full() - .when(count > 0, |this| { - this.child( - uniform_list("prl", count, move |range, _, cx| { - range - .map(|ix| { - let pr_ix = visible[ix]; - let pr = &store.read(cx).pull_requests[pr_ix]; - let pr_id = pr.id; - let title = pr.activity_subject(); - let id_hex = pr.id.to_hex(); - let age = relative_time(pr.created_at); - let status = store.read(cx).status_of(pr); - let profile = directory.read(cx).profile(&pr.pubkey, cx); - let author = profile.name(); - let workspace = workspace.clone(); - let store = store.clone(); - - h_flex() - .id(ix) - .w_full() - .h(px(ROW_HEIGHT)) - .gap_4() - .px_4() - .border_b_1() - .border_color(cx.theme().colors.border) - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .on_click(move |_, window, cx| { - let id = SharedString::from(format!("pr:{pr_id}")); - let workspace_for_build = workspace.clone(); - let store = store.clone(); - crate::shared::panels::open_detail( - &workspace, - id, - move |window, cx| { - cx.new(|cx| { - PullRequestDetailView::new( - workspace_for_build.clone(), - store.clone(), - pr_id, - window, - cx, - ) - }) - }, - window, - cx, - ); - }) - .child(status_badge(status)) - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_1() - .child( - div() - .text_base() - .text_ellipsis() - .whitespace_nowrap() - .child(title), - ) - .child( - h_flex() - .gap_2() - .text_xs() - .child( - h_flex() - .gap_1() - .child( - Avatar::new(pr.pubkey) - .name(author.clone()) - .picture( - profile.picture(), - ) - .small(), - ) - .child(div().child(author)), - ) - .child(SharedString::from("opened")) - .child( - div() - .text_color( - cx.theme() - .colors - .muted_foreground, - ) - .child(SharedString::from( - &id_hex[..8], - )), - ) - .child(SharedString::from(age)), - ), - ) - .into_any_element() - }) - .collect() - }) - .track_scroll(&self.scroll_handle) - .size_full(), - ) - .child( - div() - .absolute() - .top_0() - .left_0() - .right_0() - .bottom_0() - .child(Scrollbar::vertical( - "prl-scroll", - self.scroll_handle.clone(), - )), - ) - }) - .when(count == 0, |this| { - this.child(empty_state(filter.empty_message())) - }), + EventList::new("prl") + .toolbar(self.render_header(cx)) + .scroll_handle(self.scroll_handle.clone()) + .rows(rows) + .empty_message(filter.empty_message()) + .render(cx), ) .into_any_element() } diff --git a/crates/signed_app/src/pull_requests/new.rs b/crates/signed_app/src/pull_requests/new.rs index 71dc3c9..e8c9371 100644 --- a/crates/signed_app/src/pull_requests/new.rs +++ b/crates/signed_app/src/pull_requests/new.rs @@ -1,10 +1,12 @@ use std::path::PathBuf; +use std::sync::Arc; + use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle, - WeakEntity, Window, div, px, uniform_list, + WeakEntity, Window, div, px, }; use signed_state::{CheckoutsStore, RepoStore}; use ui::button::Button; @@ -14,14 +16,11 @@ use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState}; use ui::layout::panel::Panel; use ui::menu::Menu; -use ui::scrollbar::Scrollbar; -use ui::spinner::Spinner; use ui::tabs::{Tab, Tabs}; -use ui::theme::ActiveTheme as _; -use super::helpers::{ForkCompare, fork_display_name, truncate_label}; +use super::helpers::{ForkCompare, truncate_label}; use crate::repo::commit_diff::{CommitDiffView, DiffPane}; -use crate::repo::helpers::commit_row; +use crate::shared::progress::error_row; use crate::shared::widgets::empty_state; use crate::workspace::Workspace; @@ -41,7 +40,7 @@ pub struct NewPullRequestView { subject: Entity, description: Entity, pub(super) merge_base: Option, - pub(super) commits: Option>, + pub(super) commits: Option>>, pub(super) loading: bool, pub(super) error: Option, submitting: bool, @@ -159,6 +158,12 @@ impl NewPullRequestView { } } + /// Reaps finished tasks, then queues another. + pub(super) fn push_task(&mut self, task: gpui::Task>) { + self.tasks.retain(|task| !task.is_ready()); + self.tasks.push(task); + } + fn submit(&mut self, _window: &mut Window, cx: &mut Context) { if self.submitting || self.loading { return; @@ -210,7 +215,7 @@ impl NewPullRequestView { ); Ok(()) }); - self.tasks.push(task); + self.push_task(task); } fn open_commit_diff(&mut self, commit_id: &str, window: &mut Window, cx: &mut Context) { @@ -264,7 +269,9 @@ impl NewPullRequestView { let active_fork = self.fork.as_ref().map(|fork| fork.announcement.addr()); let can_submit = self.submit_enabled(cx); let source_label = match &self.fork { - Some(fork) => truncate_label(&fork_display_name(&fork.announcement)), + Some(fork) => truncate_label(&crate::repo::helpers::announcement_display_name( + &fork.announcement, + )), None => self.repo_path.as_ref().map_or_else( || SharedString::from("No source"), |path| truncate_label(&path.display().to_string()), @@ -368,12 +375,7 @@ impl NewPullRequestView { fn render_content(&self, cx: &mut Context) -> AnyElement { if self.loading { - return v_flex() - .size_full() - .items_center() - .justify_center() - .child(Spinner::new("new-pr-loading")) - .into_any_element(); + return crate::shared::widgets::centered_spinner("new-pr-loading"); } if !self.has_source() { return empty_state("Choose a local checkout or an announced fork to compare"); @@ -394,50 +396,23 @@ impl NewPullRequestView { if commits.is_empty() { return empty_state("No commits between the branches"); } - let commits = commits.clone(); + let commits = Arc::clone(commits); let view = cx.entity().downgrade(); - v_flex() - .relative() - .flex_1() - .min_h_0() - .child( - uniform_list("new-pr-commits", commits.len(), move |range, _, cx| { - range - .map(|ix| { - let commit = commits[ix].clone(); - let id = commit.id.clone(); - let view = view.clone(); - commit_row( - ix, - &commit, - None, - move |window, cx| { - crate::shared::log_dropped(view.update(cx, |this, cx| { - this.open_commit_diff(&id, window, cx); - })); - }, - cx, - ) - }) - .collect() - }) - .track_scroll(&self.scroll_handle) - .size_full(), - ) - .child( - div() - .absolute() - .top_0() - .left_0() - .right_0() - .bottom_0() - .child(Scrollbar::vertical( - "new-pr-commits-scroll", - self.scroll_handle.clone(), - )), - ) - .into_any_element() + crate::shared::event_list::commit_list( + "new-pr-commits", + "new-pr-commits-scroll", + commits, + self.scroll_handle.clone(), + |_, _, _| None, + move |commit, window, cx| { + let id = commit.id.clone(); + crate::shared::log_dropped(view.update(cx, |this, cx| { + this.open_commit_diff(&id, window, cx); + })); + }, + cx, + ) } } @@ -472,14 +447,7 @@ impl Render for NewPullRequestView { .rows(3) .placeholder("Describe..."), ) - .when_some(self.error.clone(), |this, error| { - this.child( - div() - .text_xs() - .text_color(cx.theme().ramps.destructive.base) - .child(error), - ) - }), + .when_some(error_row(&self.error, cx), |this, error| this.child(error)), ) .child(self.render_tabs(cx)), ) diff --git a/crates/signed_app/src/pull_requests/new/source.rs b/crates/signed_app/src/pull_requests/new/source.rs index e151c36..49f3298 100644 --- a/crates/signed_app/src/pull_requests/new/source.rs +++ b/crates/signed_app/src/pull_requests/new/source.rs @@ -1,4 +1,5 @@ use std::path::{Path, PathBuf}; +use std::sync::Arc; use gpui::{App, AppContext as _, Context, PathPromptOptions, SharedString, Window}; use nostr::prelude::Url; @@ -9,6 +10,19 @@ use signed_state::{Backend, CheckoutsStore, Mirrors, RepoListStore}; use super::NewPullRequestView; use crate::pull_requests::helpers::ForkCompare; +/// The announced head when listed, else `main`, else the first branch. +fn preferred_branch(branches: &[String], announced: Option) -> String { + announced + .filter(|branch| branches.contains(branch)) + .or_else(|| { + branches + .iter() + .find(|branch| branch.as_str() == "main") + .cloned() + }) + .unwrap_or_else(|| branches[0].clone()) +} + impl NewPullRequestView { pub(super) fn has_source(&self) -> bool { self.repo_path.is_some() || self.fork.is_some() @@ -56,7 +70,7 @@ impl NewPullRequestView { })?; Ok(()) }); - self.tasks.push(task); + self.push_task(task); } pub(crate) fn apply_folder_path( @@ -93,7 +107,7 @@ impl NewPullRequestView { })?; Ok(()) }); - self.tasks.push(task); + self.push_task(task); } fn apply_checkout( @@ -126,12 +140,7 @@ impl NewPullRequestView { } let announced = self.store.read(cx).head.clone(); - let base = announced - .as_ref() - .filter(|branch| branches.contains(branch)) - .cloned() - .or_else(|| branches.iter().find(|branch| *branch == "main").cloned()) - .unwrap_or_else(|| branches[0].clone()); + let base = preferred_branch(&branches, announced); let compare = current .filter(|branch| branches.contains(branch)) .unwrap_or_else(|| base.clone()); @@ -266,7 +275,7 @@ impl NewPullRequestView { } Ok(()) }); - self.tasks.push(task); + self.push_task(task); } fn apply_fork( @@ -299,16 +308,7 @@ impl NewPullRequestView { } let announced = self.store.read(cx).head.clone(); - let base = announced - .filter(|branch| base_branches.contains(branch)) - .map(SharedString::from) - .or_else(|| { - base_branches - .iter() - .find(|branch| branch.as_str() == "main") - .map(|branch| SharedString::from(branch.clone())) - }) - .unwrap_or_else(|| SharedString::from(base_branches[0].clone())); + let base = preferred_branch(&base_branches, announced); let compare = compare_branches .iter() .find(|branch| branch.as_str() == "main") @@ -321,7 +321,7 @@ impl NewPullRequestView { mirror_path, }); self.error = None; - self.base = base; + self.base = SharedString::from(base); self.compare = compare; self.branches = base_branches.into_iter().map(SharedString::from).collect(); self.sync_selectors(window, cx); @@ -378,7 +378,7 @@ impl NewPullRequestView { match result { Ok((merge_base, commits, diff)) => { this.merge_base = Some(merge_base); - this.commits = Some(commits); + this.commits = Some(Arc::new(commits)); this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx)); } Err(error) => { @@ -392,6 +392,6 @@ impl NewPullRequestView { })?; Ok(()) }); - self.tasks.push(task); + self.push_task(task); } } diff --git a/crates/signed_app/src/pull_requests/send_patch.rs b/crates/signed_app/src/pull_requests/send_patch.rs index 5698c66..595bb0e 100644 --- a/crates/signed_app/src/pull_requests/send_patch.rs +++ b/crates/signed_app/src/pull_requests/send_patch.rs @@ -5,12 +5,13 @@ use gpui::{ }; use signed_state::RepoStore; use ui::button::Button; -use ui::common::{h_flex, v_flex}; +use ui::common::{ResultLogErr as _, h_flex, v_flex}; use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState}; use ui::layout::panel::Panel; use ui::theme::ActiveTheme as _; +use crate::shared::progress::error_row; use crate::workspace::Workspace; pub struct SendPatchView { @@ -65,7 +66,7 @@ impl SendPatchView { self.error = None; cx.notify(); - let sync_error = self.store.update(cx, |store, cx| { + let task = self.store.update(cx, |store, cx| { store.open_pull_request( (!subject.is_empty()).then_some(subject), description, @@ -75,22 +76,30 @@ impl SendPatchView { None, None, cx, - ); - store.last_error.clone() + ) }); - if let Some(error) = sync_error { - self.submitting = false; - self.error = Some(error.into()); - cx.notify(); - return; - } - - let panel_id = self.panel_id.clone(); - crate::shared::log_dropped( - self.workspace - .update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)), - ); + cx.spawn(async move |this, cx| match task.await { + Ok(()) => { + this.update(cx, |this, cx| { + let panel_id = this.panel_id.clone(); + crate::shared::log_dropped( + this.workspace + .update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)), + ); + }) + .log_err(); + } + Err(error) => { + this.update(cx, |this, cx| { + this.submitting = false; + this.error = Some(error.to_string().into()); + cx.notify(); + }) + .log_err(); + } + }) + .detach(); } fn render_footer(&self, cx: &Context) -> AnyElement { @@ -159,14 +168,7 @@ impl Render for SendPatchView { .rows(12) .placeholder("diff --git a/file.txt b/file.txt"), ) - .when_some(self.error.clone(), |this, error| { - this.child( - div() - .text_xs() - .text_color(cx.theme().ramps.destructive.base) - .child(error), - ) - }), + .when_some(error_row(&self.error, cx), |this, error| this.child(error)), ) .child(self.render_footer(cx)) } diff --git a/crates/signed_app/src/repo/actions.rs b/crates/signed_app/src/repo/actions.rs index ad13255..9794660 100644 --- a/crates/signed_app/src/repo/actions.rs +++ b/crates/signed_app/src/repo/actions.rs @@ -88,6 +88,7 @@ pub fn open_repo_item( cx, ); } - RepoItem::Patch => {} + // Opening a patch series directly is not a feature. + _ => {} } } diff --git a/crates/signed_app/src/repo/commit_diff.rs b/crates/signed_app/src/repo/commit_diff.rs index 0a6bcf5..c16c3ec 100644 --- a/crates/signed_app/src/repo/commit_diff.rs +++ b/crates/signed_app/src/repo/commit_diff.rs @@ -14,8 +14,6 @@ use ui::common::{StyledExt as _, h_flex, v_flex}; use ui::icons::{Icon, IconRole}; use ui::layout::panel::Panel; use ui::layout::resizable::{Resizable, ResizableState}; -use ui::scrollbar::Scrollbar; -use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; use ui::tree::{Tree, TreeItem}; use utils::relative_time_secs; @@ -257,18 +255,10 @@ impl DiffPane { .track_scroll(&self.scroll_handle) .size_full(), ) - .child( - div() - .absolute() - .top_0() - .left_0() - .right_0() - .bottom_0() - .child(Scrollbar::vertical( - "commit-diff-scroll", - self.scroll_handle.clone(), - )), - ) + .child(crate::shared::widgets::scroll_overlay( + "commit-diff-scroll", + self.scroll_handle.clone(), + )) .into_any_element() }; @@ -304,14 +294,12 @@ impl DiffPane { .gap_2() .text_xs() .child( - div() - .text_color(cx.theme().ramps.success.base) - .child(format!("+{}", file.insertions)), + Badge::new("file-insertions", format!("+ {}", file.insertions)) + .variant(BadgeVariant::Success), ) .child( - div() - .text_color(cx.theme().ramps.destructive.base) - .child(format!("-{}", file.deletions)), + Badge::new("file-deletions", format!("- {}", file.deletions)) + .variant(BadgeVariant::Danger), ), ) }), @@ -334,7 +322,10 @@ impl Render for DiffPane { Resizable::new("commit-diff-split", self.split.clone()) .axis(Axis::Horizontal) .pane_with_min(tree, px(120.)) - .pane_with_min(detail, px(240.)), + .pane_with_min(detail, px(240.)) + .flex_1() + .min_w_0() + .h_full(), ) } } @@ -381,6 +372,12 @@ impl CommitDiffView { } } + /// Reaps finished tasks, then queues another. + fn push_task(&mut self, task: Task>) { + self.tasks.retain(|task| !task.is_ready()); + self.tasks.push(task); + } + fn load(&mut self, window: &mut Window, cx: &mut Context) { self.loading = true; self.error = None; @@ -424,7 +421,7 @@ impl CommitDiffView { Ok(()) }); - self.tasks.push(task); + self.push_task(task); } fn render_header(&self, cx: &mut Context) -> AnyElement { @@ -513,12 +510,7 @@ impl Panel for CommitDiffView { impl Render for CommitDiffView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let body: AnyElement = if self.loading { - v_flex() - .size_full() - .items_center() - .justify_center() - .child(Spinner::new("commit-diff-loading")) - .into_any_element() + crate::shared::widgets::centered_spinner("commit-diff-loading") } else if let Some(error) = self.error.clone() { empty_state(error) } else { diff --git a/crates/signed_app/src/repo/dialogs/create.rs b/crates/signed_app/src/repo/dialogs/create.rs index cf92cf7..9598d83 100644 --- a/crates/signed_app/src/repo/dialogs/create.rs +++ b/crates/signed_app/src/repo/dialogs/create.rs @@ -8,7 +8,7 @@ use gpui::{ use settings::SettingsStore; use signed_state::{Backend, CheckoutsStore}; use ui::button::{Button, ButtonVariant}; -use ui::common::{h_flex, v_flex}; +use ui::common::{ResultLogErr as _, h_flex, v_flex}; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; use ui::icons::{Icon, IconRole}; @@ -17,7 +17,7 @@ use ui::tooltip::Tooltip; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; use crate::repo::actions::open_repo_panel; -use crate::shared::progress::{DialogProgress, error_row, push_steps_row}; +use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with}; use crate::workspace::Workspace; /// Progress of the create-repository flow, so async results can be rendered. @@ -94,17 +94,26 @@ impl CreateRepoDialog { let servers = self.grasp_state.read(cx).grasp_servers.clone(); if name.is_empty() { - self.fail("Repository name is required", cx); + self.state.update(cx, |state, cx| { + state.fail("Repository name is required"); + cx.notify(); + }); return; } if servers.is_empty() { - self.fail("Add at least one grasp server", cx); + self.state.update(cx, |state, cx| { + state.fail("Add at least one grasp server"); + cx.notify(); + }); return; } let backend = Backend::global(cx); let Some(user) = backend.read(cx).current_user() else { - self.fail("Sign in to create a repository", cx); + self.state.update(cx, |state, cx| { + state.fail("Sign in to create a repository"); + cx.notify(); + }); return; }; @@ -123,8 +132,10 @@ impl CreateRepoDialog { let close = self.handle.clone(); let handle = window.window_handle(); - cx.spawn(async move |_this, cx| match task.await { - Ok((announcement, local_path)) => { + run_dialog_task_with( + task, + cx, + move |(announcement, local_path), cx| { cx.update_window(handle, |_, window, cx| { let checkouts = CheckoutsStore::global(cx); checkouts.update(cx, |store, cx| { @@ -140,23 +151,15 @@ impl CreateRepoDialog { ); close.close(cx); }) - .ok(); - } - Err(error) => { + .log_err(); + }, + move |error, cx| { state.update(cx, |state, cx| { state.fail(error.to_string()); cx.notify(); }); - } - }) - .detach(); - } - - fn fail(&mut self, message: impl Into, cx: &mut Context) { - self.state.update(cx, |state, cx| { - state.fail(message); - cx.notify(); - }); + }, + ); } } diff --git a/crates/signed_app/src/repo/dialogs/grasp_servers.rs b/crates/signed_app/src/repo/dialogs/grasp_servers.rs index 97ce814..c36db1c 100644 --- a/crates/signed_app/src/repo/dialogs/grasp_servers.rs +++ b/crates/signed_app/src/repo/dialogs/grasp_servers.rs @@ -13,6 +13,8 @@ use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; +use crate::shared::progress::error_row; + /// State of the grasp-server section of a publish dialog, so async results can be rendered. #[derive(Default)] pub struct GraspServersState { @@ -137,14 +139,7 @@ pub fn grasp_servers_field( .child("Loading your grasp servers..."), ) }) - .when_some(error, |section, error| { - section.child( - div() - .text_xs() - .text_color(cx.theme().ramps.destructive.base) - .child(error), - ) - }) + .when_some(error_row(&error, cx), |section, error| section.child(error)) }) .into_any_element() } @@ -155,6 +150,7 @@ fn render_server_row( state: Entity, cx: &App, ) -> AnyElement { + let relay = relay.clone(); h_flex() .w_full() .gap_1() @@ -168,7 +164,7 @@ fn render_server_row( .text_color(cx.theme().colors.muted_foreground) .text_xs() .rounded(cx.theme().radius.control) - .child(server_host(relay)), + .child(server_host(&relay)), ) .child( Button::new(SharedString::from(format!("remove-relay:{ix}"))) @@ -176,9 +172,12 @@ fn render_server_row( .variant(ButtonVariant::Ghost) .tooltip(Tooltip::text("Remove")) .on_click(move |_, _, cx| { + // A row's index can desync after a prior removal; match by value. state.update(cx, |state, cx| { - if ix < state.grasp_servers.len() { - state.grasp_servers.remove(ix); + if let Some(at) = + state.grasp_servers.iter().position(|known| known == &relay) + { + state.grasp_servers.remove(at); cx.notify(); } }); diff --git a/crates/signed_app/src/repo/dialogs/init.rs b/crates/signed_app/src/repo/dialogs/init.rs index f1ea1d5..5279d6d 100644 --- a/crates/signed_app/src/repo/dialogs/init.rs +++ b/crates/signed_app/src/repo/dialogs/init.rs @@ -10,7 +10,7 @@ use signed_core::RepoAddr; use signed_git::Repo; use signed_state::Backend; use ui::button::Button; -use ui::common::v_flex; +use ui::common::{ResultLogErr as _, v_flex}; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; use ui::icons::{Icon, IconRole}; @@ -20,7 +20,7 @@ use ui::theme::ActiveTheme as _; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; use crate::repo::RepoDetailView; -use crate::shared::progress::{DialogProgress, error_row, push_steps_row}; +use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with}; pub struct InitRepoDialog { handle: DialogHandle, @@ -105,17 +105,26 @@ impl InitRepoDialog { .filter(|branch| !branch.is_empty()); if name.is_empty() { - self.fail("Repository name is required", cx); + self.state.update(cx, |state, cx| { + state.fail("Repository name is required"); + cx.notify(); + }); return; } if servers.is_empty() { - self.fail("Add at least one grasp server", cx); + self.state.update(cx, |state, cx| { + state.fail("Add at least one grasp server"); + cx.notify(); + }); return; } let backend = Backend::global(cx); let Some(user) = backend.read(cx).current_user() else { - self.fail("Sign in to publish a repository", cx); + self.state.update(cx, |state, cx| { + state.fail("Sign in to publish a repository"); + cx.notify(); + }); return; }; @@ -134,31 +143,25 @@ impl InitRepoDialog { let close = self.handle.clone(); let handle = window.window_handle(); - cx.spawn(async move |_this, cx| match task.await { - Ok(announcement) => { + run_dialog_task_with( + task, + cx, + move |announcement, cx| { cx.update_window(handle, |_, _window, cx| { close.close(cx); if let Some(view) = view.upgrade() { view.update(cx, |this, cx| this.apply_announcement(announcement, cx)); } }) - .ok(); - } - Err(error) => { + .log_err(); + }, + move |error, cx| { state.update(cx, |state, cx| { state.fail(error.to_string()); cx.notify(); }); - } - }) - .detach(); - } - - fn fail(&mut self, message: impl Into, cx: &mut Context) { - self.state.update(cx, |state, cx| { - state.fail(message); - cx.notify(); - }); + }, + ); } } @@ -271,9 +274,18 @@ fn load_branches(dialog: Entity, cx: &mut App) { }) .await; - let Ok((branches, current)) = loaded else { - log::warn!("failed to list branches for the default branch selector"); - return; + let (branches, current) = match loaded { + Ok(loaded) => loaded, + Err(error) => { + log::warn!("failed to list branches for the default branch selector: {error}"); + dialog.update(cx, |dialog, cx| { + dialog.state.update(cx, |state, cx| { + state.fail("Could not list the repository's branches"); + cx.notify(); + }); + }); + return; + } }; dialog.update(cx, |dialog, cx| { diff --git a/crates/signed_app/src/repo/dialogs/reset.rs b/crates/signed_app/src/repo/dialogs/reset.rs index 74c3625..f1d53bf 100644 --- a/crates/signed_app/src/repo/dialogs/reset.rs +++ b/crates/signed_app/src/repo/dialogs/reset.rs @@ -1,25 +1,31 @@ +use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, px, }; use signed_state::RepoStore; use ui::button::{Button, ButtonVariant}; -use ui::common::v_flex; +use ui::common::{ResultLogErr as _, v_flex}; use ui::dialog::{Dialog, DialogHandle}; use ui::theme::ActiveTheme as _; +use crate::shared::progress::{DialogProgress, error_row}; + pub struct ResetRemoteDialog { handle: DialogHandle, store: Entity, deleted: Vec, + state: Entity, } impl ResetRemoteDialog { pub fn new(store: Entity, deleted: Vec, cx: &mut App) -> Entity { + let state = cx.new(|_| DialogProgress::default()); cx.new(|_| Self { handle: DialogHandle::new(true), store, deleted, + state, }) } } @@ -30,12 +36,16 @@ impl Render for ResetRemoteDialog { let store = self.store.clone(); let cancel_close = self.handle.clone(); let confirm_close = self.handle.clone(); + let content_state = self.state.clone(); + let action_state = self.state.clone(); Dialog::new("reset-remote-dialog") .handle(self.handle.clone()) .min_width(px(480.)) .title("Reset remote to local") .content(move |_, cx| { + let progress = content_state.read(cx); + v_flex() .gap_2() .child( @@ -60,12 +70,15 @@ impl Render for ResetRemoteDialog { })) .into_any_element() }) + .when_some(error_row(&progress.error, cx), |el, error| el.child(error)) .into_any_element() }) - .actions(move |_, _| { + .actions(move |_, cx| { + let busy = action_state.read(cx).busy; let store = store.clone(); let cancel_close = cancel_close.clone(); let confirm_close = confirm_close.clone(); + let confirm_state = action_state.clone(); let cancel: AnyElement = Button::new("cancel-reset-remote") .label("Cancel") @@ -76,15 +89,26 @@ impl Render for ResetRemoteDialog { let confirm: AnyElement = Button::new("confirm-reset-remote") .label("Reset remote") .variant(ButtonVariant::Destructive) - .on_click(move |_, _, cx| { + .loading(busy) + .disabled(busy) + .on_click(move |_, window, cx| { let task = store.update(cx, |store, cx| store.reset_repository(cx)); - cx.spawn(async move |_cx| { - if let Err(error) = task.await { - log::error!("failed to reset remote: {error:#}"); + let state = confirm_state.clone(); + let close = confirm_close.clone(); + let handle = window.window_handle(); + cx.spawn(async move |cx| match task.await { + Ok(()) => { + cx.update_window(handle, |_, _, cx| close.close(cx)) + .log_err(); + } + Err(error) => { + state.update(cx, |state, cx| { + state.fail(error.to_string()); + cx.notify(); + }); } }) .detach(); - confirm_close.close(cx); }) .into_any_element(); diff --git a/crates/signed_app/src/repo/files.rs b/crates/signed_app/src/repo/files.rs index 4c79a19..1d4f856 100644 --- a/crates/signed_app/src/repo/files.rs +++ b/crates/signed_app/src/repo/files.rs @@ -493,6 +493,12 @@ impl RepoFilesView { .into_any_element() } + /// Reaps finished tasks, then queues another. + fn push_task(&mut self, task: Task>) { + 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.selected_file = Some(path.into()); @@ -528,7 +534,14 @@ impl RepoFilesView { return; }; + // Tree paths originate from git, so symlink escapes are accepted; only + // crafted components are rejected, and visibly. if unsafe_path { + self.files.insert( + path.to_string(), + FileContent::Failed("Cannot open file".into()), + ); + cx.notify(); return; } @@ -600,7 +613,7 @@ impl RepoFilesView { Ok(()) }); - self.tasks.push(task); + self.push_task(task); } fn drop_preview_of(&mut self, path: &str) { @@ -705,6 +718,6 @@ impl RepoFilesView { Ok(()) }); - self.tasks.push(task); + self.push_task(task); } } diff --git a/crates/signed_app/src/repo/header.rs b/crates/signed_app/src/repo/header.rs index 745c976..68064eb 100644 --- a/crates/signed_app/src/repo/header.rs +++ b/crates/signed_app/src/repo/header.rs @@ -17,10 +17,9 @@ use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; use utils::relative_time_secs; -use super::helpers::{ - bound_repo_label, clone_group, clone_row, fork_row, nostr_clone_url, repo_display_name, -}; +use super::helpers::{bound_repo_label, clone_group, fork_row, nostr_clone_url, repo_display_name}; use super::{RepoDetailView, actions, dialogs}; +use crate::shared::widgets::clone_row; impl RepoDetailView { pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context) { diff --git a/crates/signed_app/src/repo/helpers.rs b/crates/signed_app/src/repo/helpers.rs index ce7244d..9172f17 100644 --- a/crates/signed_app/src/repo/helpers.rs +++ b/crates/signed_app/src/repo/helpers.rs @@ -9,10 +9,9 @@ use gpui::{ use metadata::ProfileDirectory; use nostr::prelude::{RelayUrl, ToBech32}; use signed_core::Announcement; -use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo}; +use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo, WorktreeSnapshot}; use signed_state::{Nip34Binding, RepoListStore, RepoStore}; use ui::avatar::Avatar; -use ui::clipboard::ClipboardButton; use ui::combobox::ComboboxState; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::icons::{Icon, IconRole}; @@ -20,12 +19,36 @@ use ui::theme::ActiveTheme as _; use utils::relative_time_secs; use super::RepoDetailView; -use crate::shared::tree::{TreeItemSeed, build_tree_items}; +use crate::shared::tree::{TreeItemSeed, build_tree_items, sorted_worktree_paths}; const GUTTER_WIDTH: f32 = 44.; pub const DIFF_ROW_HEIGHT: f32 = 20.; pub const COMMIT_ROW_HEIGHT: f32 = 56.; +/// The announcement's name, falling back to its id. +pub fn announcement_display_name(announcement: &Announcement) -> SharedString { + announcement + .name + .as_deref() + .map(SharedString::from) + .unwrap_or_else(|| SharedString::from(announcement.id.clone())) +} + +/// The first eight hex characters of an object id, for row labels. +pub fn short_id(hex: &str) -> SharedString { + SharedString::from(hex.get(..8).unwrap_or(hex).to_owned()) +} + +/// Snapshots the worktree and derives the explorer's tree rows and paths. +pub(super) fn snapshot_worktree( + worktree: PathBuf, +) -> Result<(WorktreeSnapshot, Vec, Vec), Error> { + let snapshot = Repo::open(&worktree)?.snapshot()?; + let tree = build_tree_items(&snapshot.entries); + let paths = sorted_worktree_paths(&snapshot.entries); + Ok((snapshot, tree, paths)) +} + #[derive(Clone, Copy)] pub(super) enum DiffRow { Hunk { @@ -67,32 +90,7 @@ pub(super) fn clone_group( .font_semibold() .child(SharedString::from(label)), ) - .child(clone_row(id, command.clone(), cx)) - .into_any_element() -} - -/// One copyable clone command with its text visible next to the copy icon. -pub(super) fn clone_row(id: SharedString, command: SharedString, cx: &App) -> AnyElement { - h_flex() - .h_8() - .px_2() - .gap_2() - .min_w_0() - .bg(cx.theme().colors.secondary) - .rounded(cx.theme().radius.control) - .text_color(cx.theme().colors.secondary_foreground) - .child( - div() - .flex_1() - .min_w_0() - .overflow_hidden() - .whitespace_nowrap() - .text_ellipsis() - .font_family(cx.theme().mono_font) - .text_xs() - .child(command.clone()), - ) - .child(ClipboardButton::new(id, command).xsmall()) + .child(crate::shared::widgets::clone_row(id, command.clone(), cx)) .into_any_element() } @@ -193,13 +191,7 @@ pub fn repo_display_name(store: &RepoStore) -> SharedString { store .announcement .as_ref() - .map(|announcement| { - announcement - .name - .as_deref() - .map(SharedString::from) - .unwrap_or_else(|| SharedString::from(announcement.id.clone())) - }) + .map(announcement_display_name) .unwrap_or_default() } @@ -253,12 +245,7 @@ pub(super) fn source_hash(text: &str) -> u64 { } pub(super) fn preview_spinner() -> AnyElement { - v_flex() - .size_full() - .items_center() - .justify_center() - .child(ui::spinner::Spinner::new("repo-preview-spinner")) - .into_any_element() + crate::shared::widgets::centered_spinner("repo-preview-spinner") } /// The kit grammar for a path; only four languages are supported. @@ -330,7 +317,11 @@ pub(super) fn render_diff_row(hunks: &[DiffHunk], row: DiffRow, cx: &App) -> Any old_start, old_lines, new_start, new_lines ))) .into_any_element(), - DiffRow::Line { hunk, line } => render_diff_line(&hunks[hunk].lines[line], cx), + DiffRow::Line { hunk, line } => match hunks.get(hunk).and_then(|h| h.lines.get(line)) { + Some(line) => render_diff_line(line, cx), + // A stale row index renders as a blank row rather than panicking. + None => div().w_full().h(px(DIFF_ROW_HEIGHT)).into_any_element(), + }, } } diff --git a/crates/signed_app/src/repo/history.rs b/crates/signed_app/src/repo/history.rs index e69f5bc..71c82f6 100644 --- a/crates/signed_app/src/repo/history.rs +++ b/crates/signed_app/src/repo/history.rs @@ -1,24 +1,24 @@ use std::path::{Path, PathBuf}; +use std::sync::Arc; use anyhow::Error; use gpui::prelude::FluentBuilder as _; use gpui::{ AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, - Styled as _, Task, UniformListScrollHandle, WeakEntity, Window, div, uniform_list, + Styled as _, Task, UniformListScrollHandle, WeakEntity, Window, div, }; -use signed_git::{CommitList, Repo}; +use signed_git::{CommitList, FileCommit, Repo}; use signed_state::{Backend, RepoStore, SyncStatusDirectory}; +use ui::alert::{Alert, AlertSeverity, AlertStyle}; use ui::button::{Button, ButtonVariant}; use ui::common::{Sizable as _, v_flex}; use ui::icons::{Icon, IconRole}; -use ui::scrollbar::Scrollbar; -use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; use super::RepoDetailView; use super::commit_diff::CommitDiffView; -use super::helpers::commit_row; +use crate::shared::event_list::commit_list; use crate::shared::panels; use crate::workspace::Workspace; @@ -28,8 +28,12 @@ pub struct RepoHistoryView { detail: WeakEntity, sync_directory: Entity, worktree: Option, - all_commits: Option, + all_commits: Option>, loading_all_commits: bool, + /// The loaded commit list, shared with the render without a per-frame copy. + commits: Arc>, + /// The last load failure, shown instead of the empty list. + error: Option, scroll_handle: UniformListScrollHandle, tasks: Vec>>, } @@ -49,6 +53,8 @@ impl RepoHistoryView { worktree: None, all_commits: None, loading_all_commits: false, + commits: Arc::new(Vec::new()), + error: None, scroll_handle: UniformListScrollHandle::new(), tasks: Vec::new(), } @@ -74,6 +80,12 @@ impl RepoHistoryView { self.load(cx); } + /// Reaps finished tasks, then queues another. + fn push_task(&mut self, task: Task>) { + self.tasks.retain(|task| !task.is_ready()); + self.tasks.push(task); + } + fn load(&mut self, cx: &mut Context) { if self.loading_all_commits || self.all_commits.is_some() { return; @@ -93,8 +105,13 @@ impl RepoHistoryView { .await; this.update(cx, |this, cx| { - if let Ok(list) = result { - this.all_commits = Some(list); + match result { + Ok(list) => { + this.commits = Arc::new(list.commits.clone()); + this.all_commits = Some(Arc::new(list)); + this.error = None; + } + Err(error) => this.error = Some(error.to_string().into()), } this.loading_all_commits = false; cx.notify(); @@ -103,7 +120,7 @@ impl RepoHistoryView { Ok(()) }); - self.tasks.push(task); + self.push_task(task); } pub fn open_commit_diff( @@ -140,22 +157,39 @@ impl Render for RepoHistoryView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let Some(list) = self.all_commits.as_ref() else { return if self.loading_all_commits { + crate::shared::widgets::centered_spinner("commits-loading") + } else if let Some(error) = self.error.clone() { + let weak = cx.entity().downgrade(); v_flex() .size_full() .items_center() .justify_center() - .child(Spinner::new("commits-loading")) + .child( + Alert::new("commits-error") + .severity(AlertSeverity::Danger) + .title("Failed to load commits") + .message(error) + .style(AlertStyle::Inline) + .on_dismiss(move |cx| { + if let Err(error) = weak.update(cx, |this, cx| { + this.error = None; + cx.notify(); + }) { + log::warn!("failed to dismiss commits error: {error}"); + } + }), + ) .into_any_element() } else { crate::shared::widgets::empty_state("Failed to load commits") }; }; - if list.commits.is_empty() { + if self.commits.is_empty() { return crate::shared::widgets::empty_state("No commits found"); } - let commits = list.commits.clone(); + let commits = Arc::clone(&self.commits); let shown = commits.len(); let total = list.total; let view = cx.entity().downgrade(); @@ -180,70 +214,60 @@ impl Render for RepoHistoryView { let pushing = self.store.read(cx).pushing; + let list = commit_list( + "commits", + "commits-scroll", + commits, + self.scroll_handle.clone(), + move |ix, commit, _| { + ahead + .iter() + .find(|(id, _)| id.starts_with(commit.id.as_str())) + .map(|(ahead_id, path)| { + let detail = detail.clone(); + let path = path.clone(); + let target = ahead_id.clone(); + let short = commit.id.clone(); + + Button::new(("sync-commit", ix)) + .label("Sync") + .icon(Icon::named(IconRole::ArrowUp)) + .variant(ButtonVariant::Secondary) + .small() + .disabled(pushing) + .tooltip(Tooltip::text(format!("Sync up to {short}"))) + .on_click(move |_, window, cx| { + cx.stop_propagation(); + if let Some(detail) = detail.upgrade() { + detail.update(cx, |this, cx| { + this.sync_checkout_commit( + path.clone(), + target.clone(), + window, + cx, + ); + }); + } + }) + .into_any_element() + }) + }, + move |commit, window, cx| { + if let Err(error) = view.update(cx, |this, cx| { + this.open_commit_diff(&commit.id, window, cx); + }) { + log::warn!("failed to open commit diff: {error}"); + } + }, + cx, + ); + v_flex() .relative() .flex_1() .w_full() .min_h_0() - .child( - uniform_list("commits", shown, move |range, _, cx| { - range - .map(|ix| { - let commit = commits[ix].clone(); - let id = commit.id.clone(); - let view = view.clone(); - - let action = ahead - .iter() - .find(|(id, _)| id.starts_with(commit.id.as_str())) - .map(|(ahead, path)| { - let detail = detail.clone(); - let path = path.clone(); - let target = ahead.clone(); - let short = commit.id.clone(); - - Button::new(("sync-commit", ix)) - .label("Sync") - .icon(Icon::named(IconRole::ArrowUp)) - .variant(ButtonVariant::Secondary) - .small() - .disabled(pushing) - .tooltip(Tooltip::text(format!("Sync up to {short}"))) - .on_click(move |_, window, cx| { - cx.stop_propagation(); - if let Some(detail) = detail.upgrade() { - detail.update(cx, |this, cx| { - this.sync_checkout_commit( - path.clone(), - target.clone(), - window, - cx, - ); - }); - } - }) - .into_any_element() - }); - - commit_row( - ix, - &commit, - action, - move |window, cx| { - if let Err(error) = view.update(cx, |this, cx| { - this.open_commit_diff(&id, window, cx); - }) { - log::warn!("failed to open commit diff: {error}"); - } - }, - cx, - ) - }) - .collect() - }) - .track_scroll(&self.scroll_handle) - .size_full(), - ) + .child(list) .when(shown < total, |this| { this.child( div() @@ -254,18 +278,6 @@ impl Render for RepoHistoryView { .child(format!("Showing {shown} of {total} commits")), ) }) - .child( - div() - .absolute() - .top_0() - .left_0() - .right_0() - .bottom_0() - .child(Scrollbar::vertical( - "commits-scroll", - self.scroll_handle.clone(), - )), - ) .into_any_element() } } diff --git a/crates/signed_app/src/repo/mod.rs b/crates/signed_app/src/repo/mod.rs index 7dafa56..1654dfc 100644 --- a/crates/signed_app/src/repo/mod.rs +++ b/crates/signed_app/src/repo/mod.rs @@ -38,14 +38,14 @@ pub mod history; pub mod refs; use files::RepoFilesView; -use helpers::{RepoData, load_repo_data}; +use helpers::{RepoData, announcement_display_name, load_repo_data, snapshot_worktree}; use history::RepoHistoryView; use refs::RefSwitcher; use crate::issues::IssuesView; use crate::pull_requests::PullRequestsView; use crate::shared::log_dropped; -use crate::shared::tree::{build_tree_items, sorted_worktree_paths}; +use crate::shared::tree::sorted_worktree_paths; use crate::workspace::Workspace; #[derive(Clone, Copy, PartialEq, Eq)] @@ -685,12 +685,7 @@ impl RepoDetailView { let task: Task> = cx.spawn(async move |this, cx| { let result = cx - .background_spawn(async move { - let snapshot = Repo::open(&worktree)?.snapshot()?; - let tree = build_tree_items(&snapshot.entries); - let paths = sorted_worktree_paths(&snapshot.entries); - Ok::<_, Error>((snapshot, tree, paths)) - }) + .background_spawn(async move { snapshot_worktree(worktree) }) .await; this.update(cx, |this, cx| { @@ -734,12 +729,7 @@ impl RepoDetailView { let task: Task> = cx.spawn(async move |this, cx| { let result = cx - .background_spawn(async move { - let snapshot = Repo::open(&worktree)?.snapshot()?; - let tree = build_tree_items(&snapshot.entries); - let paths = sorted_worktree_paths(&snapshot.entries); - Ok::<_, Error>((snapshot, tree, paths)) - }) + .background_spawn(async move { snapshot_worktree(worktree) }) .await; this.update(cx, |this, cx| match result { @@ -838,7 +828,7 @@ impl RepoDetailView { match result { Ok(()) => { if let Some(tag) = &tag { - let short = commit.chars().take(7).collect::(); + let short = crate::repo::helpers::short_id(&commit); let (title, body) = match store.read(cx).last_push_warning.clone() { Some(warning) => ("Sync partially failed", warning), None => ("Sync complete", format!("Synced up to {short}")), @@ -1047,11 +1037,7 @@ impl Panel for RepoDetailView { return SharedString::from(name.to_string_lossy().into_owned()); } if let Some(announcement) = store.announcement.as_ref() { - return announcement - .name - .as_deref() - .map(SharedString::from) - .unwrap_or_else(|| SharedString::from(announcement.id.clone())); + return announcement_display_name(announcement); } SharedString::from("Repository") } diff --git a/crates/signed_app/src/repo/refs.rs b/crates/signed_app/src/repo/refs.rs index 20f0439..2b7a9f2 100644 --- a/crates/signed_app/src/repo/refs.rs +++ b/crates/signed_app/src/repo/refs.rs @@ -1,5 +1,6 @@ use gpui::{App, AppContext as _, Entity, SharedString, WeakEntity, Window}; use ui::combobox::{Combobox, ComboboxState}; +use ui::icons::{IconRole, icon}; use super::RepoDetailView; use super::helpers::sync_selector; @@ -19,6 +20,7 @@ impl RefSwitcher { ComboboxState::new( Combobox::new("branch-select", "Branch", Vec::new()) .placeholder("Branch") + .selected_icon(icon(IconRole::GitBranch)) .on_change(move |value, window, cx| { if let Some(name) = value && let Err(error) = branch_view.update(cx, |this, cx| { diff --git a/crates/signed_app/src/settings/helpers.rs b/crates/signed_app/src/settings/helpers.rs index b1e32a4..e98838d 100644 --- a/crates/signed_app/src/settings/helpers.rs +++ b/crates/signed_app/src/settings/helpers.rs @@ -118,6 +118,7 @@ pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement v_flex() .gap_2() .children(servers.iter().enumerate().map(|(ix, server)| { + let server = server.clone(); h_flex() .gap_1() .child( @@ -129,7 +130,7 @@ pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement .text_color(cx.theme().colors.muted_foreground) .text_xs() .rounded(cx.theme().radius.control) - .child(display_server(server)), + .child(display_server(&server)), ) .child( Button::new(format!("settings-remove-server:{ix}")) @@ -142,7 +143,16 @@ pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement store.update(cx, |store, cx| { store.edit( |settings| { - settings.grasp_servers.default_servers.remove(ix); + // A row's index can desync after a prior + // removal; match by value. + if let Some(at) = settings + .grasp_servers + .default_servers + .iter() + .position(|known| known == &server) + { + settings.grasp_servers.default_servers.remove(at); + } }, cx, ); @@ -218,6 +228,7 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement { v_flex() .gap_2() .children(scan_paths.iter().enumerate().map(|(ix, path)| { + let path = path.clone(); h_flex() .gap_1() .child( @@ -241,7 +252,16 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement { store.update(cx, |store, cx| { store.edit( |settings| { - settings.local_repos.scan_paths.remove(ix); + // A row's index can desync after a prior + // removal; match by value. + if let Some(at) = settings + .local_repos + .scan_paths + .iter() + .position(|known| known == &path) + { + settings.local_repos.scan_paths.remove(at); + } }, cx, ); diff --git a/crates/signed_app/src/settings/mod.rs b/crates/signed_app/src/settings/mod.rs index a229623..cdf1e69 100644 --- a/crates/signed_app/src/settings/mod.rs +++ b/crates/signed_app/src/settings/mod.rs @@ -60,6 +60,7 @@ impl Render for SettingsDialog { Dialog::new("settings-dialog") .handle(self.handle.clone()) + .width(px(600.)) .height(px(560.)) .title("Settings") .content(move |_, cx| { diff --git a/crates/signed_app/src/shared/event_list.rs b/crates/signed_app/src/shared/event_list.rs new file mode 100644 index 0000000..f602d7c --- /dev/null +++ b/crates/signed_app/src/shared/event_list.rs @@ -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; + +/// The toolbar above the issue and pull-request lists: a filter and its actions. +pub fn filter_toolbar(cx: &App, children: impl IntoIterator) -> 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, + 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, + rows: Vec, + scroll_handle: UniformListScrollHandle, + empty_message: SharedString, +} + +impl EventList { + /// Builds a list rendering `rows` under `toolbar`. + pub fn new(id: impl Into) -> 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) -> Self { + self.rows = rows; + self + } + + /// Sets the empty-state message shown when no rows match. + pub fn empty_message(mut self, message: impl Into) -> 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>, + scroll_handle: UniformListScrollHandle, + action: impl Fn(usize, &FileCommit, &App) -> Option + '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() +} diff --git a/crates/signed_app/src/shared/mod.rs b/crates/signed_app/src/shared/mod.rs index 6652509..4c39d39 100644 --- a/crates/signed_app/src/shared/mod.rs +++ b/crates/signed_app/src/shared/mod.rs @@ -1,3 +1,8 @@ +use gpui::{App, Entity}; +use metadata::ProfileDirectory; +use nostr::prelude::PublicKey; + +pub mod event_list; pub mod panels; pub mod progress; pub mod tree; @@ -15,3 +20,18 @@ pub fn log_dropped(result: Result) { ); } } + +/// Tracks a detail view's author, commenters, and repository owner for +/// profile prefetch. +pub fn track_event_participants( + author: Option, + owner: Option, + comments: impl Iterator, + directory: &Entity, + cx: &mut App, +) { + let mut keys: Vec = author.into_iter().collect(); + keys.extend(comments); + keys.extend(owner); + directory.update(cx, |directory, cx| directory.track(keys, cx)); +} diff --git a/crates/signed_app/src/shared/progress.rs b/crates/signed_app/src/shared/progress.rs index f779357..b633245 100644 --- a/crates/signed_app/src/shared/progress.rs +++ b/crates/signed_app/src/shared/progress.rs @@ -1,10 +1,11 @@ use gpui::{ - AnyElement, App, Context, IntoElement as _, ParentElement as _, SharedString, Styled as _, - Subscription, div, + AnyElement, App, AsyncApp, Context, Entity, IntoElement as _, ParentElement as _, SharedString, + Styled as _, Subscription, Task, div, }; use signed_core::RepoAddr; use signed_state::{Backend, BackendEvent, PushStepStatus}; use ui::common::{h_flex, v_flex}; +use ui::dialog::DialogHandle; use ui::icons::{Icon, IconRole}; use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; @@ -126,3 +127,40 @@ pub fn push_steps_row(steps: &[PushStepStatus], cx: &App) -> Option Some(v_flex().gap_1().children(rows).into_any_element()) } + +/// Runs a dialog task to completion. +pub fn run_dialog_task( + task: Task>, + state: &Entity, + 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( + task: Task>, + 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(); +} diff --git a/crates/signed_app/src/shared/widgets.rs b/crates/signed_app/src/shared/widgets.rs index 6b5ae54..8783a6f 100644 --- a/crates/signed_app/src/shared/widgets.rs +++ b/crates/signed_app/src/shared/widgets.rs @@ -1,9 +1,14 @@ -use gpui::{AnyElement, App, IntoElement, ParentElement as _, SharedString, Styled as _, div}; +use gpui::{ + AnyElement, App, ElementId, IntoElement, ParentElement as _, SharedString, Styled as _, div, +}; use signed_core::RepoStatus; use ui::badge::{Badge, BadgeVariant}; -use ui::common::StyledExt as _; +use ui::clipboard::ClipboardButton; +use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; +use ui::scrollbar::{Scrollbar, ScrollbarHandle}; +use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; @@ -25,7 +30,7 @@ pub fn status_badge(status: RepoStatus) -> Badge { /// A centered empty-state message filling the available space. pub fn empty_state(message: impl Into) -> AnyElement { let message = message.into(); - ui::common::v_flex() + v_flex() .size_full() .items_center() .justify_center() @@ -33,6 +38,57 @@ pub fn empty_state(message: impl Into) -> AnyElement { .into_any_element() } +/// A centered spinner filling the available space. +pub fn centered_spinner(id: impl Into) -> 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(id: I, handle: H) -> AnyElement +where + I: Into, + H: ScrollbarHandle, +{ + div() + .absolute() + .top_0() + .left_0() + .right_0() + .bottom_0() + .child(Scrollbar::vertical(id, handle)) + .into_any_element() +} + +/// One copyable clone command with its text visible next to the copy icon. +pub fn clone_row(id: SharedString, command: SharedString, cx: &App) -> AnyElement { + h_flex() + .h_8() + .px_2() + .gap_2() + .min_w_0() + .bg(cx.theme().colors.secondary) + .rounded(cx.theme().radius.control) + .text_color(cx.theme().colors.secondary_foreground) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .font_family(cx.theme().mono_font) + .text_xs() + .child(command.clone()), + ) + .child(ClipboardButton::new(id, command).xsmall()) + .into_any_element() +} + /// A one-line muted label used by section headers. pub fn section_label(text: impl Into, cx: &App) -> AnyElement { div() diff --git a/crates/signed_app/src/titlebar/repository_switcher.rs b/crates/signed_app/src/titlebar/repository_switcher.rs index c46c1e3..4190776 100644 --- a/crates/signed_app/src/titlebar/repository_switcher.rs +++ b/crates/signed_app/src/titlebar/repository_switcher.rs @@ -1,4 +1,5 @@ use std::rc::Rc; +use std::sync::Arc; use gpui::prelude::FluentBuilder as _; use gpui::{ @@ -50,7 +51,7 @@ impl RepositoryEntry { pub(crate) struct RepositorySwitcher { search: Entity, directory: Entity, - entries: Vec, + entries: Arc>, open: bool, on_open: OpenHandler, on_create: CreateHandler, @@ -71,7 +72,7 @@ impl RepositorySwitcher { Self { search, directory, - entries: Vec::new(), + entries: Arc::new(Vec::new()), open: false, on_open: Rc::new(on_open), on_create: Rc::new(on_create), @@ -81,7 +82,7 @@ impl RepositorySwitcher { } pub(super) fn set_entries(&mut self, entries: Vec, cx: &mut Context) { - self.entries = entries; + self.entries = Arc::new(entries); cx.notify(); } @@ -97,7 +98,7 @@ impl Render for RepositorySwitcher { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = *cx.theme(); let weak = cx.entity().downgrade(); - let entries = self.entries.clone(); + let entries = Arc::clone(&self.entries); let search = self.search.clone(); let directory = self.directory.clone(); @@ -147,15 +148,19 @@ impl Render for RepositorySwitcher { } }); - let visible: Vec = entries - .iter() - .filter(|entry| query.is_empty() || entry.label.to_lowercase().contains(&query)) - .cloned() - .collect(); + let visible: Arc> = Arc::new( + entries + .iter() + .filter(|entry| { + query.is_empty() || entry.label.to_lowercase().contains(&query) + }) + .cloned() + .collect(), + ); let row_height = rems(2.0).to_pixels(window.rem_size()) + px(2.); let list_height = (row_height * visible.len() as f32).min(px(280.)); - let list_entries = visible.clone(); + let list_entries = Arc::clone(&visible); let list_directory = directory.clone(); let list_weak = row_weak.clone(); let list_on_open = on_open.clone(); @@ -218,7 +223,7 @@ impl Render for RepositorySwitcher { .h(row_height) .px_3() .gap_2() - .rounded(theme.radius.control) + .rounded(theme.radius.full) .text_sm() .hover(|row| row.bg(theme.colors.muted)) .child(entry.avatar(&list_directory, cx)) diff --git a/crates/signed_core/Cargo.toml b/crates/signed_core/Cargo.toml index a6da80d..4394a0b 100644 --- a/crates/signed_core/Cargo.toml +++ b/crates/signed_core/Cargo.toml @@ -8,3 +8,6 @@ publish.workspace = true nostr.workspace = true serde.workspace = true utils = { path = "../utils" } + +[lints] +workspace = true diff --git a/crates/signed_core/src/pull_request.rs b/crates/signed_core/src/pull_request.rs index 28790aa..9660609 100644 --- a/crates/signed_core/src/pull_request.rs +++ b/crates/signed_core/src/pull_request.rs @@ -34,8 +34,9 @@ impl<'a> PullRequest<'a> { }; let mut series = vec![last]; + let mut tail = last; loop { - let Some(prev_id) = series.last().unwrap().tags.event_ids().next() else { + let Some(prev_id) = tail.tags.event_ids().next() else { break; }; let Some(prev) = patches @@ -46,6 +47,7 @@ impl<'a> PullRequest<'a> { break; }; series.push(prev); + tail = prev; } series.reverse(); series @@ -86,21 +88,18 @@ impl<'a> PullRequest<'a> { /// 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> { let mut series = vec![root]; + let mut tail = root; loop { let next = patches .iter() .filter(|patch| !series.contains(patch)) - .filter(|patch| { - patch - .tags - .event_ids() - .any(|id| id == series.last().unwrap().id) - }) + .filter(|patch| patch.tags.event_ids().any(|id| id == tail.id)) .max_by_key(|patch| patch.created_at); let Some(next) = next else { break; }; series.push(next); + tail = next; } series } diff --git a/crates/signed_git/Cargo.toml b/crates/signed_git/Cargo.toml index 75f0dfa..35869b5 100644 --- a/crates/signed_git/Cargo.toml +++ b/crates/signed_git/Cargo.toml @@ -20,3 +20,6 @@ ignore = "0.4" [dev-dependencies] tempfile = "3" + +[lints] +workspace = true diff --git a/crates/signed_git/src/tests.rs b/crates/signed_git/src/tests.rs index 6e87784..74dff0f 100644 --- a/crates/signed_git/src/tests.rs +++ b/crates/signed_git/src/tests.rs @@ -502,8 +502,13 @@ fn publishing_a_commit_advances_the_remote_tip() { assert!(status.ahead_commits.contains(&third)); let second_refspec = format!("+{second}:{refname}"); - repo.push_refspecs(&base_url, "npub1test", "my-repo", &[second_refspec.as_str()]) - .expect("publish second"); + repo.push_refspecs( + &base_url, + "npub1test", + "my-repo", + &[second_refspec.as_str()], + ) + .expect("publish second"); assert_eq!( git_in(&server_repo, &["rev-parse", refname.as_str()]).expect("server tip"), second diff --git a/crates/signed_nostr/Cargo.toml b/crates/signed_nostr/Cargo.toml index dc6b3f3..fd687d3 100644 --- a/crates/signed_nostr/Cargo.toml +++ b/crates/signed_nostr/Cargo.toml @@ -12,3 +12,6 @@ nostr-lmdb.workspace = true anyhow.workspace = true webbrowser.workspace = true + +[lints] +workspace = true diff --git a/crates/signed_state/Cargo.toml b/crates/signed_state/Cargo.toml index 7e23203..1198bc5 100644 --- a/crates/signed_state/Cargo.toml +++ b/crates/signed_state/Cargo.toml @@ -30,3 +30,6 @@ rustls = "0.23" [dev-dependencies] tempfile = "3" + +[lints] +workspace = true diff --git a/crates/signed_state/src/backend.rs b/crates/signed_state/src/backend.rs index 0ccda92..a40f48c 100644 --- a/crates/signed_state/src/backend.rs +++ b/crates/signed_state/src/backend.rs @@ -418,19 +418,22 @@ impl Backend { let relays: Vec<(RelayUrl, Option)> = [ ( - RelayUrl::parse("wss://relay.primal.net").unwrap(), + RelayUrl::parse("wss://relay.primal.net") + .expect("hardcoded relay URL parses"), Some(RelayMetadata::Read), ), ( - RelayUrl::parse("wss://relay.ditto.pub").unwrap(), + RelayUrl::parse("wss://relay.ditto.pub") + .expect("hardcoded relay URL parses"), Some(RelayMetadata::Read), ), ( - RelayUrl::parse("wss://relay.nostr.net").unwrap(), + RelayUrl::parse("wss://relay.nostr.net") + .expect("hardcoded relay URL parses"), Some(RelayMetadata::Write), ), ( - RelayUrl::parse("wss://nos.lol").unwrap(), + RelayUrl::parse("wss://nos.lol").expect("hardcoded relay URL parses"), Some(RelayMetadata::Write), ), ] diff --git a/crates/signed_state/src/repo.rs b/crates/signed_state/src/repo.rs index db943cf..837d254 100644 --- a/crates/signed_state/src/repo.rs +++ b/crates/signed_state/src/repo.rs @@ -663,34 +663,37 @@ impl RepoStore { merge_base: Option, push_from: Option, cx: &mut Context, - ) { + ) -> Task> { self.last_error = None; self.last_warning = None; let Some(addr) = self.addr.clone() else { self.not_announced(cx); - return; + return Task::ready(Err(Error::msg( + "This repository is not published to Nostr yet", + ))); }; let series = PatchSeries::parse(&patch); 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)", oversized, MAX_PATCH_EVENT_BYTES - )); + ); + self.last_error = Some(message.clone()); cx.notify(); - return; + return Task::ready(Err(Error::msg(message))); } // The tip of the series is its last commit; `git format-patch` orders // patches oldest first. let Some(current_commit) = series.tip_commit() else { - self.last_error = Some( - "Patch must be `git format-patch` output with a `From ` header".into(), - ); + let message = + "Patch must be `git format-patch` output with a `From ` header"; + self.last_error = Some(message.into()); cx.notify(); - return; + return Task::ready(Err(Error::msg(message))); }; let backend = Backend::global(cx); @@ -700,9 +703,10 @@ impl RepoStore { }; 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(); - return; + return Task::ready(Err(Error::msg(message))); }; let author_npub = user.to_bech32().unwrap(); @@ -733,7 +737,7 @@ impl RepoStore { .collect() }; - let task: Task> = cx.spawn(async move |this, cx| { + cx.spawn(async move |this, cx| { let root_patch = match publish_patch_series( &client, &signer, @@ -919,8 +923,7 @@ impl RepoStore { } Ok(()) - }); - self.tasks.push(task); + }) } #[allow(clippy::too_many_arguments)] @@ -956,7 +959,7 @@ impl RepoStore { }; this.update(cx, |this, cx| { - this.open_pull_request( + let task = this.open_pull_request( subject, description, branch_name, @@ -966,6 +969,7 @@ impl RepoStore { Some(repo_path), cx, ); + this.tasks.push(task); }) }) } diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml index 2fbb772..99af97f 100644 --- a/crates/ui/Cargo.toml +++ b/crates/ui/Cargo.toml @@ -69,3 +69,6 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = [ [dev-dependencies] gpui = { workspace = true, features = ["test-support"] } + +[lints] +workspace = true diff --git a/crates/ui/src/components/alert.rs b/crates/ui/src/components/alert.rs index 5fc9663..13af3f0 100644 --- a/crates/ui/src/components/alert.rs +++ b/crates/ui/src/components/alert.rs @@ -28,7 +28,8 @@ use gpui::{ use crate::components::button::{Button, ButtonVariant}; 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::theme::{ALERT_EDGE_WIDTH, ALERT_STACK_WIDTH, ActiveTheme as _, ENTER_SLIDE_DISTANCE}; @@ -194,10 +195,9 @@ impl RenderOnce for Alert { }); match self.presentation { - AlertStyle::Overlay => { - let surface = theme.colors.surface; - let border = theme.colors.border; - + AlertStyle::Overlay => floating_panel( + cx, + theme.radius.overlay, div() .id(self.id.clone()) .role(Role::Alert) @@ -206,26 +206,22 @@ impl RenderOnce for Alert { .items_start() .gap_2() .px_3() - .py_2() - .rounded(theme.radius.overlay) - .bg(surface) - .border_1() - .border_color(border) - .shadow(theme.elevations.popover.shadows()) - .refine_style(&self.style) - .when_some(self.icon.clone(), |alert, icon_glyph| { - alert.child( - div() - .flex_none() - .flex() - .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)) - } + .py_2(), + theme.elevations.popover.shadows(), + ) + .refine_style(&self.style) + .when_some(self.icon.clone(), |alert, icon_glyph| { + alert.child( + div() + .flex_none() + .flex() + .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)), AlertStyle::Inline => div() .id(self.id.clone()) .role(Role::Alert) @@ -381,14 +377,12 @@ impl RenderOnce for AlertsView { let entries = self.alerts.read(cx).entries(); deferred( - div() + v_flex() .id(self.id) .absolute() .top_4() .right_4() .w(ALERT_STACK_WIDTH) - .flex() - .flex_col() .items_end() .gap_2() .children(entries.iter().rev().map(|entry| { diff --git a/crates/ui/src/components/avatar.rs b/crates/ui/src/components/avatar.rs index 4834760..1c2eb80 100644 --- a/crates/ui/src/components/avatar.rs +++ b/crates/ui/src/components/avatar.rs @@ -11,6 +11,7 @@ //! .picture(Some("https://example.com/ada.png")); //! ``` +use std::collections::HashMap; use std::fmt::Display; 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> = + std::cell::RefCell::new(HashMap::new()); +} + 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 pattern = [0u8; GRID_SIZE * GRID_SIZE]; let mut filled = 0usize; diff --git a/crates/ui/src/components/button.rs b/crates/ui/src/components/button.rs index a786b11..50c70da 100644 --- a/crates/ui/src/components/button.rs +++ b/crates/ui/src/components/button.rs @@ -15,7 +15,7 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder as _; 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 _, StyleRefinement, Styled as _, Window, canvas, relative, transparent_black, }; @@ -47,6 +47,65 @@ pub enum ButtonVariant { 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, + 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. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum ButtonSide { @@ -100,7 +159,7 @@ impl Button { disabled: false, loading: false, padded: true, - fully_rounded: false, + fully_rounded: true, full_width: false, side: ButtonSide::default(), tab_stop: true, @@ -179,7 +238,7 @@ impl Button { 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 { self.fully_rounded = fully_rounded; self @@ -236,13 +295,21 @@ impl Sizable for Button { impl RenderOnce for Button { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { - let theme = cx.theme(); - let colors = theme.colors; - let ramps = theme.ramps; + let ButtonChrome { + background, + foreground, + hover, + pressed, + border, + hover_border, + pressed_border, + } = self.variant.chrome(cx); let radius = if self.fully_rounded { + let theme = cx.theme(); theme.radius.full } else { + let theme = cx.theme(); theme.radius.control }; @@ -256,52 +323,7 @@ impl RenderOnce for Button { let is_round_child = is_child_only && self.fully_rounded; let icon_trailing = self.side == ButtonSide::Right; - - 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, - ), - }; + let ring = cx.theme().colors.ring; h_flex() .id(self.id.clone()) @@ -334,7 +356,7 @@ impl RenderOnce for Button { .when_some(a11y_label, |button, label| button.aria_label(label)) .child( h_flex() - .gap_2() + .gap_1() .when(self.full_width, |content| content.flex_1()) .when(self.loading, |content| content.invisible()) .map(|content| { @@ -381,7 +403,7 @@ impl RenderOnce for Button { .tab_stop(self.tab_stop) .hover(move |style| style.bg(hover).border_color(hover_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| { button.on_click(move |event, window, cx| on_click(event, window, cx)) }) diff --git a/crates/ui/src/components/code.rs b/crates/ui/src/components/code.rs index bd5f4e9..f256639 100644 --- a/crates/ui/src/components/code.rs +++ b/crates/ui/src/components/code.rs @@ -84,6 +84,12 @@ impl SelectionPoint { } } +/// The source-derived part of one rendered line, cached between frames. +struct CodeLineLayout { + text: String, + roles: Vec, +} + /// Retained state for a code view. /// /// Build one in a [`gpui::Entity`], render the entity, and call its setters @@ -93,6 +99,8 @@ pub struct CodeViewState { source: SharedString, language: Language, code: HighlightedCode, + /// Per-line layout cache, rebuilt whenever the source changes. + line_layouts: Vec, handle: UniformListScrollHandle, /// The hovered line, driving the active-line wash and number emphasis. active_line: Option, @@ -113,12 +121,14 @@ impl CodeViewState { { let source = source.into(); let code = highlight(&source, language); + let line_layouts = Self::layout(&code); Self { id: id.into(), source, language, code, + line_layouts, handle: UniformListScrollHandle::new(), active_line: None, selection: None, @@ -137,6 +147,7 @@ impl CodeViewState { let source = source.into(); self.code = highlight(&source, language); + self.line_layouts = Self::layout(&self.code); self.source = source; self.language = language; self.selection = None; @@ -145,17 +156,16 @@ impl CodeViewState { cx.notify(); } - /// Replaces one line's text and re-highlights the file. `line_ix` past - /// 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. + /// Replaces one line's text and re-highlights the file. pub fn update_line(&mut self, line_ix: usize, text: T, cx: &mut Context) where T: AsRef, { + // An empty source has no line to replace. + if self.source.is_empty() { + return; + } + let trailing_newline = self.source.ends_with('\n'); let mut lines: Vec = self.source.lines().map(str::to_string).collect(); 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.code = highlight(&self.source, self.language); + self.line_layouts = Self::layout(&self.code); self.selection = None; cx.notify(); } + /// The cached per-line text and roles for the highlighted source. + fn layout(code: &HighlightedCode) -> Vec { + 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. pub fn source(&self) -> &str { &self.source @@ -500,24 +537,10 @@ fn render_row( line_height: Pixels, cx: &App, ) -> gpui::AnyElement { - let line = code.code().lines.get(line_ix); - - let mut text = String::new(); - for span in line.map_or(&[][..], |line| line.spans.as_slice()) { - text.push_str(&span.text); - } - + let layout = code.line_layouts.get(line_ix); + let text = layout.map_or("", |layout| layout.text.as_str()); + let roles = layout.map_or(&[][..], |layout| layout.roles.as_slice()); 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]; diff --git a/crates/ui/src/components/combobox.rs b/crates/ui/src/components/combobox.rs index b7a1667..4f9fd31 100644 --- a/crates/ui/src/components/combobox.rs +++ b/crates/ui/src/components/combobox.rs @@ -31,17 +31,19 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder; use gpui::{ App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, - MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, ScrollHandle, - SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task, - Window, actions, anchored, canvas, deferred, div, point, px, + MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, SharedString, + StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task, + UniformListScrollHandle, Window, actions, anchored, canvas, deferred, div, point, px, + uniform_list, }; 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::scroll_area::ScrollArea; -use crate::icons::{IconRole, icon}; +use crate::icons::{Icon, IconRole, icon}; use crate::theme::{ActiveTheme as _, COMBOBOX_MIN_WIDTH, COMBOBOX_WIDTH, POPUP_MAX_HEIGHT, Size}; actions!( @@ -104,6 +106,8 @@ where filter: Option>, unmatched: UnmatchedText, size: Size, + /// Icon shown at the field's leading edge while a value is selected. + selected_icon: Option, style: StyleRefinement, } @@ -127,6 +131,7 @@ where filter: None, unmatched: UnmatchedText::default(), size: Size::default(), + selected_icon: None, style: StyleRefinement::default(), } } @@ -149,6 +154,12 @@ where self } + /// Shows an icon at the field's leading edge while a value is selected. + pub fn selected_icon(mut self, icon: Icon) -> Self { + self.selected_icon = Some(icon); + self + } + /// Reports the value whenever it changes. pub fn on_change(mut self, handler: F) -> Self where @@ -245,8 +256,12 @@ where size: Size, /// Width refinements from the builder, applied to the wrapper each render. style: StyleRefinement, - /// Handler reports in flight; held so they die with the state. - tasks: Vec>, + /// Icon shown at the field's leading edge while a value is selected. + selected_icon: Option, + /// The row list's scroll, kept across frames while the popup is open. + rows_scroll: UniformListScrollHandle, + /// The most recent handler report in flight; a newer report replaces it. + task: Option>, /// Keeps the query-event subscription tied to the state's lifetime. _subscription: Subscription, } @@ -304,7 +319,9 @@ where unmatched: combobox.unmatched, size: combobox.size, style: combobox.style, - tasks: Vec::new(), + selected_icon: combobox.selected_icon, + rows_scroll: UniformListScrollHandle::new(), + task: None, _subscription: subscription, } } @@ -331,7 +348,15 @@ where /// Replaces the value; reports it when it actually changed. pub fn set_selected(&mut self, value: Option, window: &mut Window, cx: &mut Context) { + let changed = self.selected != value; self.set_value(value, window, cx); + if changed { + let label = self.selected_label().unwrap_or_default(); + self.query + .update(cx, |query, cx| query.set_value_silent(label, window, cx)); + self.refilter(""); + cx.notify(); + } } /// Replaces the choice list and re-runs the current filter. @@ -385,7 +410,7 @@ where cx.update(|window, cx| on_change(value, window, cx)) .log_err(); }); - self.tasks.push(task); + self.task.replace(task); } cx.notify(); } @@ -453,36 +478,22 @@ where cx.update(|window, cx| on_create(text, window, cx)) .log_err(); }); - self.tasks.push(task); + self.task.replace(task); } } } 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) { if self.visible.is_empty() { return; } - - let count = self.visible.len(); - let current = self.highlight.filter(|row| *row < count); - let next = match current { - 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); + let current = self.highlight.filter(|row| *row < self.visible.len()); + let rows: Vec = (0..self.visible.len()).collect(); + let next = wrapping_adjacent_selectable(&rows, current, delta > 0); + self.highlight = next; cx.notify(); } @@ -511,13 +522,12 @@ where T: Clone + PartialEq + 'static, { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { - let (colors, radius, panel_border, shadows) = { + let (colors, radius, shadows) = { let theme = cx.theme(); ( theme.colors, theme.radius, - theme.colors.border, theme.elevations.popover.shadows(), ) }; @@ -608,6 +618,12 @@ where Input::new((id.clone(), "query"), self.query.clone()) .placeholder(self.placeholder.clone()) .placeholder_when_focused(true) + .fully_rounded(true) + .when_some(self.selected_icon.clone(), |input, selected_icon| { + input.when(self.selected.is_some(), |input| { + input.prefix(selected_icon.size(self.size.icon_rems())) + }) + }) .with_size(self.size), ) .child( @@ -620,96 +636,102 @@ where .child(chevron), ) .when(open, |wrapper| { - let rows: Vec = self - .visible - .iter() - .enumerate() - .map(|(row, option_index)| { - let Some((value, label)) = self.options.get(*option_index) else { - return div().into_any_element(); - }; + let visible = self.visible.clone(); + let options = self.options.clone(); + let highlight = self.highlight; + let selected = self.selected.clone(); + let size = self.size; + let list_state = state.clone(); + let rows_id = id.clone(); + let radius_full = radius.full; + let foreground = colors.foreground; - let highlighted = self.highlight == Some(row); - let checked = self.selected.as_ref() == Some(value); - let state = state.clone(); - let row_index = row; + // Rows are `control_height`, so the row height follows the size. + let row_height = size.control_height_rems().to_pixels(window.rem_size()); + let count = visible.len(); - div() - .id(("option", *option_index)) - .debug_selector({ - 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 list_height = (row_height * count as f32) + .max(row_height) + .min(POPUP_MAX_HEIGHT); - let rows: gpui::AnyElement = if rows.is_empty() { - div() - .px_2() - .py_1() - .control_caption_text(self.size) - .text_color(colors.muted_foreground) - .child("No matches") - .into_any_element() + let rows: gpui::AnyElement = if count == 0 { + EmptyState::compact("No matches", cx).into_any_element() } else { - let scroll = window.use_keyed_state((id.clone(), "rows-scroll"), cx, |_, _| { - ScrollHandle::new() - }); + uniform_list((rows_id.clone(), "rows"), count, move |range, _, cx| { + 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")) - .handle(scroll.read(cx).clone()) - .axes(crate::components::scroll_area::ScrollAxes::Vertical) - .max_h(POPUP_MAX_HEIGHT) - .children(rows) - .into_any_element() + let highlighted = highlight == Some(row); + let checked = selected.as_ref() == Some(value); + let state = list_state.clone(); + let row_index = row; + + div() + .id(("option", option_index)) + .debug_selector({ + let id = rows_id.clone(); + move || format!("{id}-option-{row}") + }) + .role(Role::ListBoxOption) + .aria_label(label.clone()) + .w_full() + .flex() + .items_center() + .gap_2() + .px_2() + .py_1() + .h(row_height) + .control_text(size) + .rounded(radius_full) + .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>>> = Rc::new(RefCell::new(None)); @@ -719,64 +741,62 @@ where .map(|bounds| bounds.size.width) .unwrap_or(COMBOBOX_WIDTH); - let panel = v_flex() - .id((id.clone(), "panel")) - .debug_selector({ - let id = id.clone(); - move || format!("{id}-panel") - }) - .w(popup_width) - .p_1() - .bg(colors.surface) - .text_color(colors.foreground) - .rounded(radius.overlay) - .border_1() - .border_color(panel_border) - .shadow(shadows) - .overflow_hidden() - .child(rows) - .child( - canvas( - { - let cell = panel_bounds.clone(); - move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) - }, - { - let state = state.clone(); - let panel_bounds = panel_bounds.clone(); - let wrapper_bounds = wrapper_bounds.clone(); - move |_, _, window, _cx| { - window.on_mouse_event({ - let state = state.clone(); - let panel_bounds = panel_bounds.clone(); - let wrapper_bounds = wrapper_bounds.clone(); - move |event: &MouseDownEvent, phase, _window, cx| { - if phase != gpui::DispatchPhase::Bubble { - 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 panel = floating_panel( + cx, + radius.overlay, + v_flex() + .id((id.clone(), "panel")) + .debug_selector({ + let id = id.clone(); + move || format!("{id}-panel") + }) + .w(popup_width) + .p_1() + .text_color(colors.foreground), + shadows, + ) + .overflow_hidden() + .child(rows) + .child( + canvas( + { + let cell = panel_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + { + let state = state.clone(); + let panel_bounds = panel_bounds.clone(); + let wrapper_bounds = wrapper_bounds.clone(); + move |_, _, window, _cx| { + window.on_mouse_event({ + let state = state.clone(); + let panel_bounds = panel_bounds.clone(); + let wrapper_bounds = wrapper_bounds.clone(); + move |event: &MouseDownEvent, phase, _window, cx| { + if phase != gpui::DispatchPhase::Bubble { + return; } - }); - } - }, - ) - .absolute() - .inset_0(), - ); + 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(); + }); + } + }); + } + }, + ) + .absolute() + .inset_0(), + ); wrapper.child( deferred(anchored().offset(point(px(0.), px(4.))).child(panel)) diff --git a/crates/ui/src/components/command_palette.rs b/crates/ui/src/components/command_palette.rs index f8b0038..154132f 100644 --- a/crates/ui/src/components/command_palette.rs +++ b/crates/ui/src/components/command_palette.rs @@ -29,14 +29,17 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder; use gpui::{ AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, - MouseButton, ParentElement as _, Render, Role, ScrollHandle, SharedString, - StatefulInteractiveElement as _, StyleRefinement, Styled as _, Subscription, Window, actions, - canvas, deferred, div, relative, rems, + MouseButton, ParentElement as _, Render, Role, SharedString, StatefulInteractiveElement as _, + StyleRefinement, Styled as _, Subscription, UniformListScrollHandle, Window, actions, canvas, + 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::scroll_area::{ScrollArea, ScrollAxes}; use crate::icons::Icon; use crate::theme::{ActiveTheme as _, POPUP_MAX_HEIGHT}; @@ -211,6 +214,8 @@ pub struct CommandPaletteState { /// The highlighted row, when the palette is open. highlight: Option, 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. _subscription: Subscription, } @@ -239,6 +244,7 @@ impl CommandPaletteState { matches, highlight: None, open: false, + rows_scroll: UniformListScrollHandle::new(), _subscription: subscription, } } @@ -320,17 +326,9 @@ impl CommandPaletteState { if self.matches.is_empty() { return; } - let count = self.matches.len(); - let next = match self.highlight { - 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, - None => count - 1, - }; - self.highlight = Some(next); + let rows: Vec = (0..self.matches.len()).collect(); + let next = wrapping_adjacent_selectable(&rows, self.highlight, delta > 0); + self.highlight = next; cx.notify(); } @@ -371,12 +369,11 @@ impl Render for CommandPaletteState { return div().into_any_element(); } - let (colors, radius, panel_border, shadows, titlebar_height) = { + let (colors, radius, shadows, titlebar_height) = { let theme = cx.theme(); ( theme.colors, theme.radius, - theme.colors.border, theme.elevations.dialog.shadows(), theme.titlebar_height, ) @@ -386,157 +383,160 @@ impl Render for CommandPaletteState { let state = cx.entity(); let query_focus = self.query.read(cx).focus_handle(); - let rows: Vec = self - .matches - .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() + let rows: AnyElement = if self.matches.is_empty() { + EmptyState::compact("No matches", cx).into_any_element() } else { - let scroll = - window.use_keyed_state((id.clone(), "rows-scroll"), cx, |_, _| ScrollHandle::new()); + let matches = self.matches.clone(); + 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")) - .handle(scroll.read(cx).clone()) - .axes(ScrollAxes::Vertical) - .max_h(POPUP_MAX_HEIGHT) - .children(rows) - .into_any_element() + // Rows are `min_h_8`, so the uniform row height is two rems. + let row_height = rems(2.0).to_pixels(window.rem_size()); + let count = matches.len(); + let list_height = (row_height * count as f32).min(POPUP_MAX_HEIGHT); + + 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() - .id((id.clone(), "panel")) - .debug_selector({ - let id = id.clone(); - move || format!("{id}-panel") - }) - .key_context(COMMAND_PALETTE_CONTEXT) - .role(Role::Dialog) - .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); - } - } + let panel = floating_panel( + cx, + radius.overlay, + v_flex() + .id((id.clone(), "panel")) + .debug_selector({ + let id = id.clone(); + move || format!("{id}-panel") }) - .absolute() - .inset_0(), - ); + .key_context(COMMAND_PALETTE_CONTEXT) + .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() .absolute() diff --git a/crates/ui/src/components/common.rs b/crates/ui/src/components/common.rs index e108813..fa90204 100644 --- a/crates/ui/src/components/common.rs +++ b/crates/ui/src/components/common.rs @@ -129,6 +129,38 @@ pub fn focus_ring(color: Hsla) -> Vec { ] } +/// The shared floating-panel stack. +#[must_use] +pub fn floating_panel(cx: &App, radius: Pixels, panel: R, shadows: Vec) -> 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, + forward: bool, +) -> Option { + 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. pub fn adjacent_selectable( 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(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. pub type DismissHandler = std::rc::Rc; diff --git a/crates/ui/src/components/dialog.rs b/crates/ui/src/components/dialog.rs index aee3f41..9f62145 100644 --- a/crates/ui/src/components/dialog.rs +++ b/crates/ui/src/components/dialog.rs @@ -33,11 +33,12 @@ use gpui::{ }; 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::scroll_area::ScrollArea; use crate::icons::IconRole; -use crate::layout::h_flex; use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH}; /// Requests the dialog's close: `false` closes. @@ -98,6 +99,7 @@ pub struct Dialog { content: Option, actions: Option, min_width: Option, + width: Option, height: Option, style: StyleRefinement, } @@ -122,6 +124,7 @@ impl Dialog { content: None, actions: None, min_width: None, + width: None, height: None, style: StyleRefinement::default(), } @@ -217,6 +220,15 @@ impl Dialog { self } + /// Sets the panel's fixed width, capped at 90% of the window. + pub fn width(mut self, width: W) -> Self + where + W: Into, + { + self.width = Some(width.into()); + self + } + /// Sets the panel's height, body content taller than the panel scrolls. pub fn height(mut self, height: H) -> Self 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(); ( theme.colors.overlay, - theme.colors.border, theme.colors.foreground, - theme.colors.surface, + theme.colors.background, theme.radius.overlay, theme.elevations.dialog.shadows(), theme.motion.overlay, @@ -297,112 +308,116 @@ impl RenderOnce for Dialog { .read(cx) .clone(); - let panel = v_flex() - .id("dialog-panel") - .track_focus(&focus) - .role(role) - .aria_label(label) - .when_some(self.min_width, |panel, width| panel.min_w(width)) - .when(self.min_width.is_none(), |panel| { - panel.min_w(DIALOG_MIN_WIDTH) - }) - .max_w(relative(0.9)) - .when_some(height, |panel, height| panel.h(height)) - .bg(surface) - .text_color(foreground) - .rounded(radius) - .border_1() - .border_color(border) - .shadow(shadows) - .overflow_hidden() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_key_down({ - let on_change = on_change.clone(); - move |event: &KeyDownEvent, window, cx| { - if event.keystroke.key == "escape" - && !alert - && close_on_escape - && let Some(on_change) = &on_change - { - on_change(false, window, cx); - } - cx.stop_propagation(); + let panel = floating_panel( + cx, + radius, + v_flex() + .id("dialog-panel") + .track_focus(&focus) + .role(role) + .aria_label(label) + .when_some(self.width, |panel, width| panel.w(width)) + .when(self.width.is_none() && self.min_width.is_none(), |panel| { + panel.min_w(DIALOG_MIN_WIDTH) + }) + .when_some(self.min_width, |panel, width| panel.min_w(width)) + .max_w(relative(0.9)) + .when_some(height, |panel, height| panel.h(height)) + .text_color(foreground), + shadows, + ) + // The panel behind the dialog is `background` (pure white/black), so + // the dialog matches it instead of the muted `surface` tint. + .bg(background) + .overflow_hidden() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_key_down({ + let on_change = on_change.clone(); + move |event: &KeyDownEvent, window, cx| { + if event.keystroke.key == "escape" + && !alert + && close_on_escape + && 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( - 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_some(actions, |panel, actions| { + panel.child( + 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); } - }) + } }) - .when_some(actions, |panel, actions| { - panel.child( - 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(), - ); + .absolute() + .inset_0(), + ); let scrim = div() .absolute() diff --git a/crates/ui/src/components/diff.rs b/crates/ui/src/components/diff.rs index 0415deb..a7fe65c 100644 --- a/crates/ui/src/components/diff.rs +++ b/crates/ui/src/components/diff.rs @@ -33,14 +33,17 @@ use gpui::{ App, Context, ElementId, HighlightStyle, InteractiveElement as _, IntoElement, ListHorizontalSizingBehavior, ParentElement as _, Pixels, Render, ScrollStrategy, SharedString, StatefulInteractiveElement as _, Styled as _, TextStyle, UniformListScrollHandle, Window, div, - point, rems, uniform_list, + point, px, rems, uniform_list, }; use similar::{Change, ChangeTag, TextDiff}; use crate::components::highlight::{HighlightedCode, Language, Line, Role, highlight}; use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility}; 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. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -525,7 +528,7 @@ fn render_row( let mono_font = theme.mono_font; let colors = theme.colors; 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 frame = div() @@ -563,7 +566,7 @@ fn render_row( row_element.child( div() .flex_none() - .border_l(BORDER_WIDTH * 4.0) + .border_l(CHANGE_BAR_WIDTH) .border_color(gpui::transparent_black()), ) }, @@ -689,9 +692,7 @@ fn render_row( _ => wash_strong(change_color), }) .when(options.indicators == DiffIndicators::Bars, |number| { - number - .border_l(BORDER_WIDTH * 4.0) - .border_color(change_color) + number.border_l(CHANGE_BAR_WIDTH).border_color(change_color) }), ) }) @@ -702,7 +703,7 @@ fn render_row( div() .h_full() .flex_none() - .border_l(BORDER_WIDTH * 4.0) + .border_l(CHANGE_BAR_WIDTH) .border_color(change_color), ) }, diff --git a/crates/ui/src/components/dropdown_menu.rs b/crates/ui/src/components/dropdown_menu.rs index 0bf4020..7d98d12 100644 --- a/crates/ui/src/components/dropdown_menu.rs +++ b/crates/ui/src/components/dropdown_menu.rs @@ -23,7 +23,7 @@ use gpui::{ div, relative, }; -use crate::components::button::ButtonVariant; +use crate::components::button::{ButtonChrome, ButtonVariant}; use crate::components::common::{ 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 { let theme = cx.theme(); let colors = theme.colors; - let ramps = theme.ramps; - let radius = theme.radius.control; + let radius = theme.radius.full; let ring = colors.ring; 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 { - ButtonVariant::Primary => ramps.primary.base, - ButtonVariant::Secondary => colors.border, - ButtonVariant::Ghost => gpui::transparent_black(), - ButtonVariant::Destructive => ramps.destructive.base, - }; + let ButtonChrome { + background, + foreground, + hover, + pressed, + border, + .. + } = self.variant.chrome(cx); let split = self.on_click.is_some(); let icon_only = self.icon.is_some() && self.label.is_none() && !split; diff --git a/crates/ui/src/components/empty_state.rs b/crates/ui/src/components/empty_state.rs index b6a05d3..2bccb08 100644 --- a/crates/ui/src/components/empty_state.rs +++ b/crates/ui/src/components/empty_state.rs @@ -71,6 +71,20 @@ impl EmptyState { self.action = Some(action.into_any_element()); self } + + /// A compact inline caption for popups with nothing to show. + #[must_use] + pub fn compact(label: L, cx: &App) -> gpui::Div + where + L: Into, + { + div() + .px_2() + .py_1() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child(label.into()) + } } impl gpui::Styled for EmptyState { diff --git a/crates/ui/src/components/field.rs b/crates/ui/src/components/field.rs index ec8565f..77822ac 100644 --- a/crates/ui/src/components/field.rs +++ b/crates/ui/src/components/field.rs @@ -143,9 +143,7 @@ impl RenderOnce for Field { }; let content = if self.variant == FieldVariant::Row { - div() - .flex() - .flex_col() + v_flex() .gap_1() .child( h_flex() @@ -160,9 +158,7 @@ impl RenderOnce for Field { }) .when_some(error, |field, error| field.child(error)) } else { - div() - .flex() - .flex_col() + v_flex() .gap_2() .child( v_flex() diff --git a/crates/ui/src/components/input.rs b/crates/ui/src/components/input.rs index 88b4053..b5a9f40 100644 --- a/crates/ui/src/components/input.rs +++ b/crates/ui/src/components/input.rs @@ -23,6 +23,7 @@ use std::ops::Range; use std::rc::Rc; +use std::sync::Arc; use std::time::{Duration, Instant}; 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. +#[derive(Clone)] struct ShapedText { lines: Vec, mask_map: Option>, } /// One shaped source line and its first byte's offset in the display text. +#[derive(Clone)] struct ShapedLineEntry { start: usize, - line: WrappedLine, + line: Arc, } /// The field's inner padding. @@ -550,6 +553,18 @@ pub struct InputState { caret_epoch_started: Instant, /// The shaped line and element bounds, recorded during each paint. layout: Option, + /// The last shaped buffer, reused while no shaping input changed. + shaped_cache: std::cell::RefCell>, +} + +/// Everything `shape_text` consumes, for cache reuse between frames. +#[derive(Clone, PartialEq)] +struct ShapeCacheKey { + text: String, + wrap_width: Option, + font_size: Pixels, + font: Font, + color: gpui::Hsla, } impl EventEmitter for InputState {} @@ -645,6 +660,7 @@ impl InputState { caret_epoch: 0, caret_epoch_started: Instant::now(), 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, - /// 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, window: &Window) -> ShapedText { let (text, mask_map) = if self.masked() { masked_display(&self.text) @@ -1042,6 +1059,21 @@ impl InputState { }; 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 { len: text.len(), font, @@ -1062,14 +1094,19 @@ impl InputState { let mut start = 0; for line in shaped { let end = start + line.len(); - lines.push(ShapedLineEntry { start, line }); + lines.push(ShapedLineEntry { + start, + line: Arc::new(line), + }); start = end + '\n'.len_utf8(); } } 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. @@ -2210,15 +2247,12 @@ impl RenderOnce for Input { input.child(edge_zone("input-prefix", prefix)) }) .child( - div() + h_flex() .relative() .flex_1() .min_w_0() .h_full() .overflow_hidden() - .flex() - .flex_row() - .items_center() .when_some(line_height, |region, 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. fn utf8_range_to_utf16(text: &str, range: Range) -> Range { - let start = text[..range.start].encode_utf16().count(); - let end = start + text[range.start..range.end].encode_utf16().count(); + // IME can supply reversed or off-boundary offsets; normalize both + // 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 } /// Converts a UTF-16 range to a UTF-8 byte range. fn utf16_range_to_utf8(text: &str, range: Range) -> Range { - 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); + } } diff --git a/crates/ui/src/components/list.rs b/crates/ui/src/components/list.rs index aba7af7..9523ec3 100644 --- a/crates/ui/src/components/list.rs +++ b/crates/ui/src/components/list.rs @@ -25,8 +25,9 @@ use gpui::{ StyleRefinement, Styled as _, Window, div, rems, }; +use crate::common::focus_handle; 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::theme::ActiveTheme as _; @@ -172,7 +173,7 @@ impl RenderOnce for List { .map(|(index, _)| index) .collect(); - let focus = crate::components::common::focus_handle(&self.id, window, cx); + let focus = focus_handle(&self.id, window, cx); let label = self .a11y_label @@ -194,10 +195,8 @@ impl RenderOnce for List { }) .collect(); - div() + v_flex() .id(self.id) - .flex() - .flex_col() .gap_0p5() .text_sm() .refine_style(&self.style) diff --git a/crates/ui/src/components/markdown.rs b/crates/ui/src/components/markdown.rs index e2f0edd..068b502 100644 --- a/crates/ui/src/components/markdown.rs +++ b/crates/ui/src/components/markdown.rs @@ -45,7 +45,7 @@ use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, T use crate::components::button::{Button, ButtonVariant}; 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::scrollbar::{Scrollbar, ScrollbarVisibility}; 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 { let clear_flag = frame.pressed_on_piece.clone(); - div() + v_flex() .w_full() - .flex() - .flex_col() .key_context(TEXT_VIEW_CONTEXT) .track_focus(&frame.focus_handle) .on_action({ @@ -1470,15 +1468,13 @@ fn render_block( /// The shared block frame: ambient text style, spacing, quote bar. fn block_frame(quote: bool, top: Rems, bottom: Rems, id: &ElementId, cx: &App) -> Div { let theme = cx.theme(); - div() + v_flex() .debug_selector({ let id = id.clone(); move || id.to_string() }) .w_full() - .flex() - .flex_col() - .font_family(".SystemUIFont") + .font_family(theme.ui_font()) .text_xs() .line_height(relative(BODY_LINE_HEIGHT)) .text_color(theme.colors.foreground) @@ -1714,9 +1710,7 @@ fn code_row( .collect::>() .join("\n"); - let actions_row = div() - .flex() - .items_center() + let actions_row = h_flex() .justify_between() .pb_1() .when_some(language.cloned(), |row, language| { @@ -1737,10 +1731,8 @@ fn code_row( }), ); - let plate = div() + let plate = v_flex() .w_full() - .flex() - .flex_col() .rounded(theme.radius.control) .bg(theme.colors.muted) .p_2() @@ -1798,10 +1790,8 @@ fn table_row( let row_count = table.rows.len(); let mut cell_ix = 0usize; - let grid = div() + let grid = v_flex() .w_full() - .flex() - .flex_col() .border_1() .border_color(colors.border) .rounded(theme.radius.control) diff --git a/crates/ui/src/components/menu.rs b/crates/ui/src/components/menu.rs index 336ebf4..ba78c63 100644 --- a/crates/ui/src/components/menu.rs +++ b/crates/ui/src/components/menu.rs @@ -25,14 +25,17 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder; use gpui::{ - Animation, AnimationExt as _, AnyElement, App, Bounds, BoxShadow, DefiniteLength, - DispatchPhase, ElementId, Entity, FocusHandle, InteractiveElement as _, IntoElement, - KeyDownEvent, MouseButton, MouseDownEvent, ParentElement as _, Pixels, Point, RenderOnce, Role, - ScrollHandle, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, - Window, anchored, canvas, deferred, div, ease_out_quint, point, px, relative, rems, + Animation, AnimationExt as _, AnyElement, App, Bounds, DefiniteLength, DispatchPhase, + ElementId, Entity, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, + MouseButton, MouseDownEvent, ParentElement as _, Pixels, Point, RenderOnce, Role, ScrollHandle, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, anchored, + 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::icons::{Icon, IconRole, icon as icon_glyph}; use crate::theme::{ActiveTheme as _, MENU_MIN_WIDTH, POPUP_MAX_HEIGHT}; @@ -190,7 +193,6 @@ impl FluentBuilder for MenuItem {} /// Menu chrome styles. #[derive(Clone)] pub(crate) struct MenuChrome { - surface: gpui::Hsla, border: gpui::Hsla, foreground: gpui::Hsla, muted_foreground: gpui::Hsla, @@ -199,9 +201,7 @@ pub(crate) struct MenuChrome { primary_foreground: gpui::Hsla, destructive: gpui::Hsla, destructive_foreground: gpui::Hsla, - radius_overlay: Pixels, - radius_sm: Pixels, - shadow: Vec, + radius_full: Pixels, } /// A floating menu of [`MenuItem`] rows anchored below its trigger. @@ -227,7 +227,6 @@ impl MenuChrome { let theme = cx.theme(); ( Self { - surface: theme.colors.surface, border: theme.colors.border, foreground: theme.colors.foreground, muted_foreground: theme.colors.muted_foreground, @@ -236,9 +235,7 @@ impl MenuChrome { primary_foreground: theme.colors.primary_foreground, destructive: theme.ramps.destructive.base, destructive_foreground: theme.colors.destructive_foreground, - radius_overlay: theme.radius.overlay, - radius_sm: theme.radius.sm, - shadow: theme.elevations.popover.shadows(), + radius_full: theme.radius.full, }, theme.motion.overlay, ) @@ -688,110 +685,110 @@ fn menu_panel( }) .collect(); - v_flex() - .id("menu-panel") - .debug_selector(move || format!("{}-panel", params.debug_prefix)) - .occlude() - .track_focus(focus) - .role(Role::Menu) - .aria_label(params.label) - .when_some(params.min_width, |panel, width| panel.min_w(width)) - .when(params.min_width.is_none(), |panel| { - panel.min_w(MENU_MIN_WIDTH) - }) - .p_1() - .bg(params.chrome.surface) - .text_color(params.chrome.foreground) - .rounded(params.chrome.radius_overlay) - .border_1() - .border_color(params.chrome.border) - .shadow(params.chrome.shadow.clone()) - .overflow_hidden() - .on_mouse_down_out({ - let on_dismiss = params.on_dismiss.clone(); - let dismiss_bounds = params.dismiss_bounds.clone(); - let flyout_stack = flyout_stack.clone(); + floating_panel( + cx, + cx.theme().radius.overlay, + v_flex() + .id("menu-panel") + .debug_selector(move || format!("{}-panel", params.debug_prefix)) + .occlude() + .track_focus(focus) + .role(Role::Menu) + .aria_label(params.label) + .when_some(params.min_width, |panel, width| panel.min_w(width)) + .when(params.min_width.is_none(), |panel| { + panel.min_w(MENU_MIN_WIDTH) + }) + .p_1() + .text_color(params.chrome.foreground), + cx.theme().elevations.popover.shadows(), + ) + .overflow_hidden() + .on_mouse_down_out({ + let on_dismiss = params.on_dismiss.clone(); + let dismiss_bounds = params.dismiss_bounds.clone(); + let flyout_stack = flyout_stack.clone(); - move |event, window, cx| { - if dismiss_bounds - .borrow() + move |event, window, cx| { + if dismiss_bounds + .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)) - { - 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); - } + }) { + return; } - }) - .on_key_down({ - let items = params.items.clone(); - 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, - ); + + if let Some(on_dismiss) = &on_dismiss { + on_dismiss(false, window, 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); - } - } + } + }) + .on_key_down({ + let items = params.items.clone(); + 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, }, - { - 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); - } + window, + 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( - "menu-enter", - Animation::new(params.enter_duration).with_easing(ease_out_quint()), - |panel, delta| panel.opacity(delta), - ) - .into_any_element() + .absolute() + .inset_0(), + ) + .with_animation( + "menu-enter", + Animation::new(params.enter_duration).with_easing(ease_out_quint()), + |panel, delta| panel.opacity(delta), + ) + .into_any_element() } /// Renders one menu row. @@ -968,7 +965,7 @@ fn row_shell( .px_4() .text_sm() .line_height(relative(1.0)) - .rounded(chrome.radius_sm) + .rounded(chrome.radius_full) .map(|row| { if item.disabled { row @@ -1053,8 +1050,6 @@ fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, c .collect(); let current = *env.selection.read(cx); - let position = - current.and_then(|current| selectable.iter().position(|index| *index == current)); match event.keystroke.key.as_str() { "down" | "up" | "home" | "end" => { @@ -1062,19 +1057,15 @@ fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, c return; } let next = match event.keystroke.key.as_str() { - "down" => match position { - Some(pos) => (pos + 1).min(selectable.len() - 1), - None => 0, - }, - "up" => match position { - Some(pos) => pos.saturating_sub(1), - None => selectable.len() - 1, - }, - "home" => 0, - _ => selectable.len() - 1, + "down" => wrapping_adjacent_selectable(&selectable, current, true), + "up" => wrapping_adjacent_selectable(&selectable, current, false), + "home" => selectable.first().copied(), + _ => selectable.last().copied(), }; - env.selection - .update(cx, |selection, _| *selection = Some(selectable[next])); + if let Some(next) = next { + env.selection + .update(cx, |selection, _| *selection = Some(next)); + } } "right" => { let opens = current diff --git a/crates/ui/src/components/popover.rs b/crates/ui/src/components/popover.rs index e17d866..29bd36c 100644 --- a/crates/ui/src/components/popover.rs +++ b/crates/ui/src/components/popover.rs @@ -31,7 +31,7 @@ use gpui::{ 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}; /// 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 { 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(); ( theme.colors, theme.radius, theme.elevations.popover.shadows(), 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 content = self.content.map(|content| content(window, cx)); - let panel = v_flex() - .id("popover-panel") - .debug_selector(|| "popover-panel".to_string()) - .occlude() - .track_focus(&focus) - .role(Role::Dialog) - .aria_label(label) - .min_w(POPOVER_MIN_WIDTH) - .bg(colors.surface) - .text_color(colors.surface_foreground) - .rounded(radius.overlay) - .border_1() - .border_color(panel_border) - .shadow(shadows) - .overflow_hidden() - .on_mouse_down_out({ - let on_change = on_change.clone(); - let trigger_bounds = trigger_bounds.clone(); - move |event, window, cx| { - if trigger_bounds - .borrow() - .is_some_and(|bounds| bounds.contains(&event.position)) - { - return; - } + let panel = floating_panel( + cx, + radius.overlay, + v_flex() + .id("popover-panel") + .debug_selector(|| "popover-panel".to_string()) + .occlude() + .track_focus(&focus) + .role(Role::Dialog) + .aria_label(label) + .min_w(POPOVER_MIN_WIDTH) + .text_color(colors.surface_foreground), + shadows, + ) + .overflow_hidden() + .on_mouse_down_out({ + let on_change = on_change.clone(); + let trigger_bounds = trigger_bounds.clone(); + move |event, window, cx| { + if trigger_bounds + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)) + { + 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 { on_change(false, window, cx); } + cx.stop_propagation(); } - }) - .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 { - on_change(false, window, cx); - } - cx.stop_propagation(); + } + }) + .when_some(content, |panel, content| panel.child(content)) + .child( + canvas(|_, _, _| {}, { + let focus = focus; + move |_, _, window, cx| { + if !focus.contains_focused(window, cx) { + window.focus(&focus, cx); } } }) - .when_some(content, |panel, content| panel.child(content)) - .child( - canvas(|_, _, _| {}, { - let focus = focus; - move |_, _, window, cx| { - if !focus.contains_focused(window, cx) { - window.focus(&focus, cx); - } - } - }) - .absolute() - .inset_0(), - ); + .absolute() + .inset_0(), + ); wrapper.child( deferred(anchored().offset(point(Pixels::ZERO, px(4.))).child( diff --git a/crates/ui/src/components/segmented.rs b/crates/ui/src/components/segmented.rs index 3e0afa4..2ddb2ec 100644 --- a/crates/ui/src/components/segmented.rs +++ b/crates/ui/src/components/segmented.rs @@ -228,8 +228,8 @@ where }; h_flex() - .id((ElementId::from("segment"), segment.label.clone())) - .gap_2() + .id(("segment", index)) + .gap_1() .justify_center() .cursor_pointer() .h_full() diff --git a/crates/ui/src/components/select.rs b/crates/ui/src/components/select.rs index 7c9e8ec..264583b 100644 --- a/crates/ui/src/components/select.rs +++ b/crates/ui/src/components/select.rs @@ -221,7 +221,6 @@ where let open_for_items = open.clone(); let rest_border = if is_open { ring } else { border }; - let hover_border = rest_border; let selected_index = self.selected.as_ref().and_then(|value| { self.options @@ -282,7 +281,7 @@ where } else { 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( icon(IconRole::ChevronDown) diff --git a/crates/ui/src/components/sidebar.rs b/crates/ui/src/components/sidebar.rs index 973aeb5..2750bee 100644 --- a/crates/ui/src/components/sidebar.rs +++ b/crates/ui/src/components/sidebar.rs @@ -378,9 +378,7 @@ impl RenderOnce for Sidebar { .handle(scroll.read(cx).clone()) .h_full() .child( - div() - .flex() - .flex_col() + v_flex() .gap_0p5() .when(padded, |content| content.p_2()) .children(children), diff --git a/crates/ui/src/components/speech.rs b/crates/ui/src/components/speech.rs index e251b9d..d56b112 100644 --- a/crates/ui/src/components/speech.rs +++ b/crates/ui/src/components/speech.rs @@ -30,7 +30,7 @@ use std::time::Duration; use gpui::prelude::FluentBuilder as _; 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 _, 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 + '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 { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let unsupported = !self.speech.read(cx).has_recognizer(); @@ -726,7 +752,7 @@ impl RenderOnce for SpeechButton { return div().into_any_element(); } - let (status, unavailable, capturing, reduce_motion, bars) = { + let (status, unavailable, capturing, bars) = { let state = self.speech.read(cx); let status = state.status(); let levels = state.levels(); @@ -735,7 +761,6 @@ impl RenderOnce for SpeechButton { status, unsupported || !state.is_available(cx), status.is_capturing(), - cx.theme().accessibility.reduce_motion, levels[tail_start..].to_vec(), ) }; @@ -762,6 +787,7 @@ impl RenderOnce for SpeechButton { }; let foreground = colors.foreground; + let bar_color = |_| theme.ramps.primary.base; h_flex() .id(id.clone()) @@ -785,26 +811,12 @@ impl RenderOnce for SpeechButton { .color(foreground) .into_any_element() } else if capturing { - let bar_height = |level: f32| { - if reduce_motion { - STILL_HEIGHT - } else { - DOT_HEIGHT + (1.0 - DOT_HEIGHT) * level - } - }; h_flex() .id(("speech-bars", self.speech.entity_id())) .h(size.icon_rems()) .items_end() .gap_0p5() - .children(bars.iter().map(|level| { - 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) - })) + .children(waveform_bars(&bars, size, cx, bar_color)) .group_hover(group.clone(), |style| style.invisible()) .into_any_element() } else { @@ -877,22 +889,19 @@ impl RenderOnce for SpeechWaveform { if !self.speech.read(cx).status().is_capturing() { return div().into_any_element(); } - let (levels, reduce_motion) = { + let levels = { let state = self.speech.read(cx); - ( - state.levels().to_vec(), - cx.theme().accessibility.reduce_motion, - ) + state.levels().to_vec() }; let theme = cx.theme(); let colors = theme.colors; let size = self.size; - let bar_height = |level: f32| { - if reduce_motion { - STILL_HEIGHT + let bar_color = |level: f32| { + if level <= 0.0 { + colors.muted_foreground } else { - DOT_HEIGHT + (1.0 - DOT_HEIGHT) * level + theme.ramps.primary.base } }; @@ -904,18 +913,7 @@ impl RenderOnce for SpeechWaveform { .h(size.icon_rems()) .w(SPEECH_WAVEFORM_WIDTH) .overflow_hidden() - .children(levels.iter().map(|level| { - 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 - }) - })) + .children(waveform_bars(&levels, size, cx, bar_color)) .refine_style(&self.style) .into_any_element() } @@ -948,11 +946,19 @@ impl AudioInput for Microphone { }; let device_channels = stream_config.channels.max(1) as usize; - let (sender, receiver) = flume::unbounded::>(); + let (sender, receiver) = flume::unbounded::, String>>(); let converter = Arc::new(Mutex::new(Resampler::new( 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() { cpal::SampleFormat::F32 => device.build_input_stream( @@ -1002,8 +1008,24 @@ impl AudioInput for Microphone { stream.play().map_err(SpeechError::input)?; let task = cx.spawn(async move |cx| { - while let Ok(samples) = receiver.recv_async().await { - cx.update(|cx| sink.push(samples, cx)); + while let Ok(message) = receiver.recv_async().await { + 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, format: AudioFormat, converter: Arc>, - sender: flume::Sender>, + sender: flume::Sender, String>>, ) -> impl FnMut(&[T], &cpal::InputCallbackInfo) + Send + 'static where T: Copy + 'static, { move |data: &[T], _: &cpal::InputCallbackInfo| { - let Ok(mut converter) = converter.lock() else { - return; + // A panic while resampling poisons the lock; the phase is + // 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); @@ -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"); } } diff --git a/crates/ui/src/components/tabs.rs b/crates/ui/src/components/tabs.rs index cf7c00c..d8d3092 100644 --- a/crates/ui/src/components/tabs.rs +++ b/crates/ui/src/components/tabs.rs @@ -21,11 +21,11 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder; 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, Point, Render, RenderOnce, Role, SharedString, Stateful, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, TextOverflow, Window, canvas, div, linear_color_stop, - linear_gradient, px, rems, + StyleRefinement, Styled, TextOverflow, Window, canvas, div, linear_color_stop, linear_gradient, + px, rems, }; use crate::components::button::{Button, ButtonVariant}; @@ -100,6 +100,13 @@ impl TabsMeasurements { .tabs .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. @@ -190,6 +197,64 @@ fn group_key(tabs_id: &ElementId, kind: &SharedString) -> ElementId { 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(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. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TabDrag { @@ -619,23 +684,7 @@ impl Tabs { let theme = cx.theme(); let group_key = group_key(&tabs_id, &kind); - let label_color = match ctx.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 - } - } - }; + let label_color = tab_label_color(ctx.variant, active, false, cx); let chip = div() .id((group_key.clone(), "group-tab")) @@ -660,31 +709,7 @@ impl Tabs { }) }) }) - .map(|chip| match ctx.variant { - 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()) - }), - }) + .map(|chip| apply_tab_chrome(chip, ctx.variant, active, cx)) .child(SharedString::from(format!("{kind} ({count})"))) .when(ctx.variant.is_capsule(), |chip| { chip.child(div().flex_none().w_4()) @@ -826,6 +851,17 @@ impl RenderOnce for Tabs { .unwrap_or(items.len()); 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::().is_some() { + let rendered: Vec = items + .iter() + .map(|item| item.measure_key(&self.id)) + .collect(); + cx.global_mut::() + .retain_tabs(&measure_key, &rendered); + } + let measure_frame = self.overflow_popover.then(|| MeasureFrame { key: measure_key.clone(), 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 { return root.children(strip); }; + let container_canvas = canvas( { let key = measure_key.clone(); @@ -964,6 +1001,7 @@ impl RenderOnce for Tabs { ) .absolute() .inset(shadow_bleed); + let trigger_canvas = canvas( { let key = measure_key; @@ -1029,32 +1067,7 @@ impl Tab { let active = selected || self.pinned; let theme = cx.theme(); - - 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 label_color = tab_label_color(ctx.variant, active, self.disabled, cx); let titlebar = ctx.variant == TabsVariant::Titlebar; let group = SharedString::from(format!("{}-tab-{}", ctx.id, self.key)); @@ -1143,36 +1156,10 @@ impl Tab { }) }) }) - .map(|strip_tab| match ctx.variant { - TabsVariant::Underline => strip_tab - .px_2() - .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()) - }), + .map(|strip_tab| { + apply_tab_chrome(strip_tab, ctx.variant, active, cx).when(titlebar, |strip_tab| { + strip_tab.min_w(TAB_MIN_WIDTH).max_w(TAB_MAX_WIDTH) + }) }) .when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead)) .child(label) diff --git a/crates/ui/src/components/toast.rs b/crates/ui/src/components/toast.rs index 3d20391..0405678 100644 --- a/crates/ui/src/components/toast.rs +++ b/crates/ui/src/components/toast.rs @@ -25,7 +25,8 @@ use gpui::{ use crate::components::button::{Button, ButtonVariant}; 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::theme::{ActiveTheme as _, TOAST_MAX_WIDTH}; @@ -132,8 +133,10 @@ pub struct Toasts { current: Option, exiting: Option, next_id: usize, - /// Pending dismiss and fade timers; held so they die with the store. - tasks: Vec>, + /// The pending auto-dismiss timer, replaced on each push. + dismiss_task: Option>, + /// The pending fade timer, replaced on each exit. + fade_task: Option>, } impl Toasts { @@ -157,7 +160,7 @@ impl Toasts { this.update(cx, |toasts, cx| toasts.dismiss(id, cx)) .log_err(); }); - self.tasks.push(task); + self.dismiss_task.replace(task); } id @@ -210,7 +213,7 @@ impl Toasts { this.update(cx, |toasts, cx| toasts.finish_exit(cx)) .log_err(); }); - self.tasks.push(task); + self.fade_task.replace(task); } fn finish_exit(&mut self, cx: &mut Context) { @@ -252,14 +255,12 @@ impl RenderOnce for ToastsView { let current = self.toasts.read(cx).current.clone(); deferred( - div() + v_flex() .id(self.id) .absolute() .left_0() .bottom_4() .w_full() - .flex() - .flex_col() .items_center() .when_some(exiting, |column, entry| { let id = entry.id; @@ -286,80 +287,77 @@ impl ToastEntry { /// The rendered pill for this toast. fn pill(&self, toasts: &Entity, cx: &App) -> gpui::Stateful { let theme = cx.theme(); - let surface = theme.colors.surface; - let border = theme.colors.border; let foreground = theme.colors.foreground; let radius = theme.radius.full; - let shadows = theme.elevations.popover.shadows(); let toast = &self.toast; let toasts = toasts.clone(); let id = self.id; - div() - .id(("toast", id)) - .debug_selector(|| "toast-pill".to_string()) - .role(Role::Alert) - .aria_label(toast.message.clone()) - .max_w(TOAST_MAX_WIDTH) - .flex() - .items_center() - .gap_2() - .py_1p5() - .px_3() - .bg(surface) - .border_1() - .border_color(border) - .rounded(radius) - .shadow(shadows.clone()) - .refine_style(&toast.style) - .when_some(toast.icon.clone(), |pill, icon| { - pill.child( - div() - .flex_none() - .flex() - .items_center() - .child(icon.size(rems(1.0)).color(foreground)), - ) - }) - .child( + floating_panel( + cx, + radius, + div() + .id(("toast", id)) + .debug_selector(|| "toast-pill".to_string()) + .role(Role::Alert) + .aria_label(toast.message.clone()) + .max_w(TOAST_MAX_WIDTH) + .flex() + .items_center() + .gap_2() + .py_1p5() + .px_3(), + theme.elevations.popover.shadows(), + ) + .refine_style(&toast.style) + .when_some(toast.icon.clone(), |pill, icon| { + pill.child( div() - .flex_1() - .min_w(px(0.)) - .truncate() - .text_sm() - .text_color(foreground) - .child(toast.message.clone()), + .flex_none() + .flex() + .items_center() + .child(icon.size(rems(1.0)).color(foreground)), ) - .when_some(toast.action.clone(), |pill, action| { - let toasts = toasts.clone(); - pill.child( - div().flex_none().child( - Button::new(("toast-action", id)) - .label(action.label.clone()) - .variant(ButtonVariant::Primary) - .small() - .on_click(move |_, _window, cx| { - (action.handler)(cx); - toasts.update(cx, |toasts, cx| { - toasts.dismiss(id, cx); - }); - }), - ), - ) - }) - .child( + }) + .child( + div() + .flex_1() + .min_w(px(0.)) + .truncate() + .text_sm() + .text_color(foreground) + .child(toast.message.clone()), + ) + .when_some(toast.action.clone(), |pill, action| { + let toasts = toasts.clone(); + pill.child( div().flex_none().child( - Button::new(("toast-close", id)) - .icon(IconRole::Close) - .variant(ButtonVariant::Ghost) + Button::new(("toast-action", id)) + .label(action.label.clone()) + .variant(ButtonVariant::Primary) .small() - .accessibility_label("Dismiss") .on_click(move |_, _window, cx| { + (action.handler)(cx); toasts.update(cx, |toasts, 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); + }); + }), + ), + ) } } diff --git a/crates/ui/src/components/tooltip.rs b/crates/ui/src/components/tooltip.rs index 7b296c8..f3b8066 100644 --- a/crates/ui/src/components/tooltip.rs +++ b/crates/ui/src/components/tooltip.rs @@ -19,8 +19,10 @@ use gpui::{ StatefulInteractiveElement as _, Styled as _, Window, canvas, div, point, px, }; -use crate::components::common::{anchor_bounds, record_anchor_bounds}; -use crate::theme::{ActiveTheme as _, BORDER_WIDTH, TOOLTIP_MAX_WIDTH, TOOLTIP_OFFSET}; +use crate::components::common::{anchor_bounds, floating_panel, record_anchor_bounds}; +use crate::theme::{ + ActiveTheme as _, BORDER_WIDTH, TOOLTIP_ANCHOR_GAP, TOOLTIP_MAX_WIDTH, TOOLTIP_OFFSET, +}; 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) -> impl IntoElement { // Copied out: the mutable reads below need `cx` free of this borrow. let theme = cx.theme(); - let surface = theme.colors.surface; let surface_foreground = theme.colors.surface_foreground; let radius_sm = theme.radius.sm; let shadows = theme.elevations.popover.shadows(); - let border = theme.colors.border; - let build_panel = || { - div() - .id("tooltip-panel") - .role(Role::Tooltip) - .debug_selector(|| "tooltip-panel".to_string()) - .px_2() - .py_1() - .max_w(TOOLTIP_MAX_WIDTH) - .bg(surface) - .border_1() - .border_color(border) - .rounded(radius_sm) - .shadow(shadows.clone()) - .text_sm() - .text_color(surface_foreground) - .child(self.text.clone()) + floating_panel( + cx, + radius_sm, + div() + .id("tooltip-panel") + .role(Role::Tooltip) + .debug_selector(|| "tooltip-panel".to_string()) + .px_2() + .py_1() + .max_w(TOOLTIP_MAX_WIDTH) + .text_sm() + .text_color(surface_foreground) + .child(self.text.clone()), + shadows.clone(), + ) }; let (wrapper, panel) = match self.anchor { @@ -118,16 +117,16 @@ impl Render for Tooltip { .map(|bounds| bounds.size.height) .unwrap_or_else(|| window.line_height() + px(8.) + BORDER_WIDTH * 2.0); - let below = viewport_height - px(4.) - parent.bottom(); - let above = parent.top() - px(4.); + let below = viewport_height - TOOLTIP_ANCHOR_GAP - parent.bottom(); + let above = parent.top() - TOOLTIP_ANCHOR_GAP; let hang_below = below >= height || below >= above; let panel = build_panel() .ml(parent.left() - origin.x) .mt(if hang_below { - parent.bottom() + px(4.) - origin.y + parent.bottom() + TOOLTIP_ANCHOR_GAP - origin.y } else { - parent.top() - px(4.) - height - origin.y + parent.top() - TOOLTIP_ANCHOR_GAP - height - origin.y }) .child( canvas( diff --git a/crates/ui/src/components/tree.rs b/crates/ui/src/components/tree.rs index faad316..6b5cfe3 100644 --- a/crates/ui/src/components/tree.rs +++ b/crates/ui/src/components/tree.rs @@ -25,7 +25,7 @@ use gpui::{ }; 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::theme::ActiveTheme as _; @@ -37,6 +37,9 @@ type DisclosureHandler = Rc; /// The visible row builder, run during render. type ItemsFn = Box Vec>; +/// The deepest indent the tree paints, bounding misbuilt item trees. +const TREE_MAX_DEPTH: usize = 16; + /// One row of a [`Tree`]. #[derive(Clone)] #[must_use] @@ -280,10 +283,8 @@ impl RenderOnce for Tree { }) .collect(); - div() + v_flex() .id(self.id) - .flex() - .flex_col() .gap_0p5() .text_sm() .refine_style(&self.style) @@ -362,7 +363,7 @@ impl TreeItem { let label_color = selectable_label_color(cx, selected, 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 }); div() @@ -402,8 +403,8 @@ impl TreeItem { } }) }) - .children((0..self.depth).map(|level| { - let step = u32::try_from(level).unwrap_or(u32::MAX) as f32; + .children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| { + let step = level as f32; div() .absolute() .left(rems(0.75 * (step + 0.5))) diff --git a/crates/ui/src/layout/mod.rs b/crates/ui/src/layout/mod.rs index f7ea7b5..d66a3c5 100644 --- a/crates/ui/src/layout/mod.rs +++ b/crates/ui/src/layout/mod.rs @@ -1,11 +1,9 @@ //! 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::{ - App, BoxShadow, Div, ElementId, FocusHandle, Hsla, Refineable as _, StyleRefinement, Styled, - Window, div, px, -}; - -use crate::theme::{FOCUS_RING_ALPHA, FOCUS_RING_SPREAD}; +pub use crate::components::common::{StyledExt, focus_handle, focus_ring, h_flex, v_flex}; pub mod panel; pub mod resizable; @@ -15,44 +13,3 @@ pub mod titlebar; pub mod window_controls; 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 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 { - vec![ - BoxShadow::new(px(0.), px(0.), color.alpha(FOCUS_RING_ALPHA)) - .spread_radius(FOCUS_RING_SPREAD), - ] -} diff --git a/crates/ui/src/layout/panel.rs b/crates/ui/src/layout/panel.rs index 878229c..1660948 100644 --- a/crates/ui/src/layout/panel.rs +++ b/crates/ui/src/layout/panel.rs @@ -7,13 +7,13 @@ use std::sync::Arc; use gpui::{ 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::layout::StyledExt as _; 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. #[allow(unused_variables)] @@ -186,7 +186,7 @@ impl gpui::Styled for PanelRow { impl RenderOnce for PanelRow { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let id = self.id.clone(); - let gutter = px(8.); + let gutter = RESIZE_HANDLE_WIDTH; let main = island( div() diff --git a/crates/ui/src/layout/resizable.rs b/crates/ui/src/layout/resizable.rs index 8664d6d..6dbd402 100644 --- a/crates/ui/src/layout/resizable.rs +++ b/crates/ui/src/layout/resizable.rs @@ -86,7 +86,9 @@ impl ResizableState { .filter(|(j, _)| *j != ix) .fold(px(0.), |sum, (_, min)| sum + *min); 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, @@ -107,6 +109,8 @@ impl ResizableState { /// Sets pane `ix`'s width, backfilling earlier panes. pub fn set_pane_width(&mut self, ix: usize, width: Pixels, cx: &mut Context) { + // Persisted layouts can carry negative sizes. + let width = width.max(PANE_MIN_SIZE); while self.sizes.len() <= ix { 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); + }); + } +} diff --git a/crates/ui/src/layout/resize_handle.rs b/crates/ui/src/layout/resize_handle.rs index 0481593..0b874a5 100644 --- a/crates/ui/src/layout/resize_handle.rs +++ b/crates/ui/src/layout/resize_handle.rs @@ -14,7 +14,8 @@ use gpui::{ use crate::layout::{StyledExt as _, focus_handle, focus_ring}; 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. @@ -111,7 +112,7 @@ impl RenderOnce for ResizeHandle { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let ring = theme.colors.ring; - let thickness = px(8.); + let thickness = RESIZE_HANDLE_WIDTH; let label = self .accessibility_label diff --git a/crates/ui/src/layout/window_controls.rs b/crates/ui/src/layout/window_controls.rs index 1bde83c..2ed1f4f 100644 --- a/crates/ui/src/layout/window_controls.rs +++ b/crates/ui/src/layout/window_controls.rs @@ -19,6 +19,8 @@ use gpui::{ 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"))] use crate::icons::{IconRole, icon}; #[cfg(any(target_os = "windows", target_os = "linux"))] @@ -106,11 +108,9 @@ impl RenderOnce for WindowControls { let client_decorated = matches!(window.window_decorations(), Decorations::Client { .. }); - div() + h_flex() .flex_none() - .flex() - .flex_row() - .items_center() + .h_full() .gap_1() .when(client_decorated && controls.minimize, |row| { row.child(circle_button( @@ -274,7 +274,7 @@ fn caption_button( .text_color(theme.colors.foreground) }) }) - .child(icon(role).size(rems(0.75))) + .child(icon(role).size(crate::theme::OVERLAY_ICON_SIZE)) .into_any_element() } @@ -309,6 +309,6 @@ where action(window, cx); }) }) - .child(icon(role).size(rems(0.75))) + .child(icon(role).size(crate::theme::OVERLAY_ICON_SIZE)) .into_any_element() } diff --git a/crates/ui/src/theme/colors.rs b/crates/ui/src/theme/colors.rs index a90713e..3961590 100644 --- a/crates/ui/src/theme/colors.rs +++ b/crates/ui/src/theme/colors.rs @@ -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(); diff --git a/crates/ui/src/theme/definition.rs b/crates/ui/src/theme/definition.rs index 0069143..1fbf7a7 100644 --- a/crates/ui/src/theme/definition.rs +++ b/crates/ui/src/theme/definition.rs @@ -187,6 +187,10 @@ impl ThemeDefinition { /// Parses `#rgb` or `#rrggbb` into an opaque color. pub(crate) fn parse_hex(value: &str) -> Option { 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]])); match digits.len() { @@ -219,3 +223,22 @@ pub(crate) fn parse_hex(value: &str) -> Option { fn expand_rgb([r, g, b]: [f32; 3]) -> Hsla { 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); + } +} diff --git a/crates/ui/src/theme/mod.rs b/crates/ui/src/theme/mod.rs index fd796db..9296620 100644 --- a/crates/ui/src/theme/mod.rs +++ b/crates/ui/src/theme/mod.rs @@ -16,10 +16,14 @@ mod system; 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; 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 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. 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. pub const TAB_MAX_WIDTH: Pixels = px(240.0); /// 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); /// The width of a Windows caption button. 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. pub const SIDEBAR_DEFAULT_WIDTH: Pixels = px(240.0); /// The narrowest a sidebar may be dragged. @@ -210,6 +214,11 @@ impl Theme { cx.global::() } + /// The system UI family, for chrome surfaces. + pub fn ui_font(&self) -> &'static str { + ".SystemUIFont" + } + fn from_resolved(resolved: ResolvedTheme) -> Self { Self { variant: resolved.variant, diff --git a/crates/ui/src/theme/source/macos.rs b/crates/ui/src/theme/source/macos.rs index 52e489d..3ca7e2f 100644 --- a/crates/ui/src/theme/source/macos.rs +++ b/crates/ui/src/theme/source/macos.rs @@ -10,7 +10,8 @@ use objc2_app_kit::{ }; use objc2_foundation::{ NSDictionary, NSDistributedNotificationCenter, NSKeyValueObservingOptions, NSNotification, - NSNotificationName, NSObjectNSKeyValueObserverRegistration, NSString, NSUserDefaults, + NSNotificationCenter, NSNotificationName, NSObjectNSKeyValueObserverRegistration, NSString, + NSUserDefaults, }; use super::signal::ReapplySignal; @@ -46,14 +47,37 @@ define_class!( impl ThemeObserver { fn new(reapply: async_channel::Sender<()>) -> Retained { 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] } } } +/// One watcher registration, kept so [`Drop`] can undo it. +enum Watcher { + /// A distributed notification, registered by name. + Distributed { + center: Retained, + name: Retained, + }, + /// A defaults key path observed via KVO, which does not retain observers. + Defaults { + defaults: Retained, + key: Retained, + }, + /// A workspace notification, registered by name. + Workspace { + center: Retained, + name: &'static NSNotificationName, + }, +} + #[derive(Default)] pub(crate) struct MacosSource { - /// The notification centers track, but do not retain, the observer. - _observer: Option>, + /// The observer, retained until `Drop` has removed every registration. + observer: Option>, + /// Registrations to undo, in the order they were installed. + watchers: Vec, /// Keeps the reapply loop alive. _signal: Option, } @@ -96,6 +120,7 @@ impl ThemeSource for MacosSource { fn install_watchers(&mut self, async_cx: gpui::AsyncApp) { let signal = ReapplySignal::install(&async_cx); let observer = ThemeObserver::new(signal.sender()); + let mut watchers = Vec::new(); let center = NSDistributedNotificationCenter::defaultCenter(); for name in [ @@ -103,7 +128,9 @@ impl ThemeSource for MacosSource { "AppleInterfaceThemeChangedNotification", ] { 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 { center.addObserver_selector_name_object( &observer, @@ -112,6 +139,10 @@ impl ThemeSource for MacosSource { None, ); } + watchers.push(Watcher::Distributed { + center: center.clone(), + name, + }); } let defaults = NSUserDefaults::standardUserDefaults(); @@ -121,7 +152,9 @@ impl ThemeSource for MacosSource { "AppleInterfaceStyle", ] { 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 { defaults.addObserver_forKeyPath_options_context( &observer, @@ -130,13 +163,18 @@ impl ThemeSource for MacosSource { core::ptr::null_mut(), ); } + watchers.push(Watcher::Defaults { + defaults: defaults.clone(), + key, + }); } let workspace_center = NSWorkspace::sharedWorkspace().notificationCenter(); let accessibility_name = unsafe { NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification }; - // SAFETY: as above. + // SAFETY: the workspace center retains the observer for the + // registration's lifetime, and `Drop` removes the registration. unsafe { workspace_center.addObserver_selector_name_object( &observer, @@ -145,8 +183,13 @@ impl ThemeSource for MacosSource { 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); } @@ -154,3 +197,36 @@ impl ThemeSource for MacosSource { 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); + } + } + } + } + } +} diff --git a/crates/ui/tests/tabs.rs b/crates/ui/tests/tabs.rs index 2ba264c..059b6de 100644 --- a/crates/ui/tests/tabs.rs +++ b/crates/ui/tests/tabs.rs @@ -62,6 +62,68 @@ fn strip_window( cx } +struct CloseHarness { + closed: Rc>>, +} + +impl Render for CloseHarness { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> 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] fn same_kind_tabs_collapse_into_one_group(cx: &mut TestAppContext) { let mut cx = strip_window( diff --git a/crates/utils/Cargo.toml b/crates/utils/Cargo.toml index da7dbad..4ee1643 100644 --- a/crates/utils/Cargo.toml +++ b/crates/utils/Cargo.toml @@ -6,3 +6,6 @@ publish.workspace = true [dependencies] nostr.workspace = true + +[lints] +workspace = true diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml index 5f8f541..a3f969a 100644 --- a/desktop/Cargo.toml +++ b/desktop/Cargo.toml @@ -39,3 +39,6 @@ ui = { path = "../crates/ui" } reqwest_client.workspace = true tracing.workspace = true tracing-subscriber.workspace = true + +[lints] +workspace = true diff --git a/docs/audit-2026-11.md b/docs/audit-2026-11.md new file mode 100644 index 0000000..80d07cd --- /dev/null +++ b/docs/audit-2026-11.md @@ -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>` 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` 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>` (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` + 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>` (history also keeps + `Arc`), 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).