From 9daee9d54d9e468ec31aa5c0b4485328435bf36d Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Sun, 22 Nov 2026 18:23:21 +0700 Subject: [PATCH] refactor: consolidate shared ui helpers and prune unused code --- crates/signed_app/src/app/helpers.rs | 7 +- crates/signed_app/src/app/mod.rs | 4 +- crates/signed_app/src/app/sign_in.rs | 18 +- crates/signed_app/src/explore/helpers.rs | 13 +- crates/signed_app/src/explore/mod.rs | 6 +- crates/signed_app/src/identity/onboarding.rs | 25 +- crates/signed_app/src/identity/passphrase.rs | 26 +- crates/signed_app/src/inbox/helpers.rs | 4 +- crates/signed_app/src/inbox/mod.rs | 4 +- crates/signed_app/src/issues/detail.rs | 15 +- crates/signed_app/src/issues/helpers.rs | 40 +- crates/signed_app/src/issues/mod.rs | 9 +- crates/signed_app/src/issues/new_issue.rs | 23 +- crates/signed_app/src/lib.rs | 2 +- crates/signed_app/src/pull_requests/detail.rs | 48 +- .../src/pull_requests/dialogs/update.rs | 23 +- .../signed_app/src/pull_requests/helpers.rs | 3 +- crates/signed_app/src/pull_requests/mod.rs | 20 +- crates/signed_app/src/pull_requests/new.rs | 449 ++++++- .../src/pull_requests/new/source.rs | 397 ------ .../src/pull_requests/send_patch.rs | 5 +- crates/signed_app/src/repo/commit_diff.rs | 64 +- crates/signed_app/src/repo/dialogs/create.rs | 25 +- crates/signed_app/src/repo/dialogs/init.rs | 28 +- crates/signed_app/src/repo/files.rs | 67 +- crates/signed_app/src/repo/header.rs | 455 ------- crates/signed_app/src/repo/helpers.rs | 243 ++-- crates/signed_app/src/repo/history.rs | 9 +- crates/signed_app/src/repo/mod.rs | 459 ++++++- crates/signed_app/src/settings/helpers.rs | 216 ++-- crates/signed_app/src/shared/event_list.rs | 212 ++-- crates/signed_app/src/shared/mod.rs | 2 +- crates/signed_app/src/shared/panels.rs | 135 +- crates/signed_app/src/shared/progress.rs | 32 +- crates/signed_app/src/shared/tree.rs | 188 --- crates/signed_app/src/shared/widgets.rs | 81 -- crates/signed_app/src/titlebar/mod.rs | 86 +- crates/ui/src/components/alert.rs | 9 +- crates/ui/src/components/avatar.rs | 117 +- crates/ui/src/components/button.rs | 24 +- crates/ui/src/components/clipboard.rs | 76 +- crates/ui/src/components/code.rs | 306 +++-- crates/ui/src/components/combobox.rs | 156 +-- crates/ui/src/components/command_palette.rs | 56 +- crates/ui/src/components/common.rs | 56 +- crates/ui/src/components/context_menu.rs | 145 --- crates/ui/src/components/dialog.rs | 2 +- crates/ui/src/components/diff.rs | 720 ----------- crates/ui/src/components/empty_state.rs | 17 +- crates/ui/src/components/grain.rs | 10 +- crates/ui/src/components/highlight.rs | 16 +- crates/ui/src/components/input.rs | 156 +-- crates/ui/src/components/kbd.rs | 105 +- crates/ui/src/components/link.rs | 154 --- crates/ui/src/components/list.rs | 290 ----- crates/ui/src/components/markdown.rs | 290 ++--- crates/ui/src/components/menu.rs | 678 +++++----- crates/ui/src/components/mod.rs | 8 - crates/ui/src/components/popover.rs | 99 +- crates/ui/src/components/progress.rs | 132 -- crates/ui/src/components/radio.rs | 259 ---- crates/ui/src/components/scrollbar.rs | 96 +- crates/ui/src/components/select.rs | 2 +- crates/ui/src/components/sidebar.rs | 284 ++--- crates/ui/src/components/slider.rs | 341 ----- crates/ui/src/components/speech.rs | 1126 ----------------- crates/ui/src/components/spinner.rs | 20 +- crates/ui/src/components/tabs.rs | 573 +++++---- crates/ui/src/components/toast.rs | 228 +--- crates/ui/src/components/tree.rs | 413 ++++-- crates/ui/src/components/utils.rs | 31 +- crates/ui/src/icons/mod.rs | 22 +- crates/ui/src/layout/panel.rs | 26 +- crates/ui/src/lib.rs | 2 +- crates/ui/src/theme/colors.rs | 28 +- crates/ui/src/theme/mod.rs | 6 - crates/ui/src/theme/ramps.rs | 20 +- crates/ui/src/theme/source/linux.rs | 178 +-- crates/ui/src/theme/source/macos.rs | 18 +- crates/ui/src/theme/source/windows.rs | 38 +- desktop/src/main.rs | 10 +- docs/gpui-native-kit-gaps.md | 5 + 82 files changed, 3607 insertions(+), 7184 deletions(-) delete mode 100644 crates/signed_app/src/pull_requests/new/source.rs delete mode 100644 crates/signed_app/src/repo/header.rs delete mode 100644 crates/signed_app/src/shared/tree.rs delete mode 100644 crates/ui/src/components/context_menu.rs delete mode 100644 crates/ui/src/components/diff.rs delete mode 100644 crates/ui/src/components/link.rs delete mode 100644 crates/ui/src/components/list.rs delete mode 100644 crates/ui/src/components/progress.rs delete mode 100644 crates/ui/src/components/radio.rs delete mode 100644 crates/ui/src/components/slider.rs delete mode 100644 crates/ui/src/components/speech.rs diff --git a/crates/signed_app/src/app/helpers.rs b/crates/signed_app/src/app/helpers.rs index 98ff04b..224eb0b 100644 --- a/crates/signed_app/src/app/helpers.rs +++ b/crates/signed_app/src/app/helpers.rs @@ -1,12 +1,7 @@ use gpui::App; -use settings::{AppearanceMode, Settings}; +use settings::AppearanceMode; use ui::theme::{ThemeVariant, follow_system, set_mode_override}; -/// Applies the persisted light/dark/system preference to the kit theme. -pub fn apply_appearance(settings: &Settings, cx: &mut App) { - apply_appearance_mode(settings.appearance, cx); -} - /// Applies one appearance mode to the kit theme. pub fn apply_appearance_mode(mode: AppearanceMode, cx: &mut App) { match mode { diff --git a/crates/signed_app/src/app/mod.rs b/crates/signed_app/src/app/mod.rs index a1e2bfb..293c8ff 100644 --- a/crates/signed_app/src/app/mod.rs +++ b/crates/signed_app/src/app/mod.rs @@ -7,7 +7,7 @@ use gpui::{ AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, Styled as _, Subscription, Window, div, px, }; -use helpers::apply_appearance; +use helpers::apply_appearance_mode; use settings::SettingsStore; use signed_state::{Backend, BackendEvent}; use ui::common::h_flex; @@ -82,7 +82,7 @@ impl AppRoot { subscriptions.push(cx.observe(&settings, |_this, store, cx| { let settings = store.read(cx).settings().clone(); - apply_appearance(&settings, cx); + apply_appearance_mode(settings.appearance, cx); })); let app = cx.entity().downgrade(); diff --git a/crates/signed_app/src/app/sign_in.rs b/crates/signed_app/src/app/sign_in.rs index d394f7c..34245f0 100644 --- a/crates/signed_app/src/app/sign_in.rs +++ b/crates/signed_app/src/app/sign_in.rs @@ -45,15 +45,6 @@ impl Panel for SignedOutView { } } -/// One of the three banner photos, picked per process launch. -fn pick_banner() -> SharedString { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|now| now.subsec_nanos()) - .unwrap_or(0); - format!("backgrounds/banner{}.jpg", nanos % 3 + 1).into() -} - impl Render for SignedOutView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = cx.theme(); @@ -110,3 +101,12 @@ impl Render for SignedOutView { .when_some(self.import.clone(), |el, view| el.child(view)) } } + +/// One of the three banner photos, picked per process launch. +fn pick_banner() -> SharedString { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|now| now.subsec_nanos()) + .unwrap_or(0); + format!("backgrounds/banner{}.jpg", nanos % 3 + 1).into() +} diff --git a/crates/signed_app/src/explore/helpers.rs b/crates/signed_app/src/explore/helpers.rs index 140c43b..2c55db1 100644 --- a/crates/signed_app/src/explore/helpers.rs +++ b/crates/signed_app/src/explore/helpers.rs @@ -13,7 +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::repo::helpers::{announcement_display_name, upstream_display_name}; use crate::workspace::Workspace; const RECENT_COUNT: usize = 10; @@ -78,16 +78,7 @@ pub(super) fn render_card( let fork_label: Option = announcement.upstream.as_ref().and_then(|upstream| { let addr = upstream.addr.as_ref()?; - let name = announcements - .iter() - .find(|a| a.addr() == *addr) - .map(|a| { - a.name - .as_deref() - .map(SharedString::from) - .unwrap_or_else(|| SharedString::from(a.id.clone())) - }) - .unwrap_or_else(|| SharedString::from(addr.identifier().to_owned())); + let name = upstream_display_name(addr, announcements); Some(SharedString::from(format!("forked from {name}"))) }); diff --git a/crates/signed_app/src/explore/mod.rs b/crates/signed_app/src/explore/mod.rs index 1ae7bf0..5555651 100644 --- a/crates/signed_app/src/explore/mod.rs +++ b/crates/signed_app/src/explore/mod.rs @@ -14,6 +14,7 @@ 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 _; @@ -256,9 +257,6 @@ impl Render for ExploreView { }) .size_full(), ) - .child(crate::shared::widgets::scroll_overlay( - "explore-scroll", - scroll_handle, - )) + .child(Scrollbar::vertical("explore-scroll", scroll_handle)) } } diff --git a/crates/signed_app/src/identity/onboarding.rs b/crates/signed_app/src/identity/onboarding.rs index c8ba544..b2e356b 100644 --- a/crates/signed_app/src/identity/onboarding.rs +++ b/crates/signed_app/src/identity/onboarding.rs @@ -4,14 +4,13 @@ use gpui::{ Styled as _, Window, div, px, }; use signed_state::Backend; -use ui::button::Button; use ui::common::v_flex; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; -use crate::shared::progress::{DialogProgress, error_row, run_dialog_task}; +use crate::shared::progress::{DialogProgress, dialog_submit_button, error_row, run_dialog_task}; pub struct OnboardingDialog { handle: DialogHandle, @@ -108,16 +107,18 @@ impl Render for OnboardingDialog { let busy = action_state.read(cx).busy; let this = this.clone(); - let create: AnyElement = Button::new("create-identity") - .label("Create new identity") - .loading(busy) - .disabled(busy) - .on_click(move |_, _, cx| { - crate::shared::log_dropped( - this.update(cx, |this, cx| this.create_identity(cx)), - ); - }) - .into_any_element(); + let create: AnyElement = dialog_submit_button( + "create-identity", + "Create new identity", + None, + busy, + &this, + |this, _window, cx| { + this.create_identity(cx); + Ok(()) + }, + ) + .into_any_element(); vec![create] }) diff --git a/crates/signed_app/src/identity/passphrase.rs b/crates/signed_app/src/identity/passphrase.rs index 91947f9..075ad3e 100644 --- a/crates/signed_app/src/identity/passphrase.rs +++ b/crates/signed_app/src/identity/passphrase.rs @@ -4,14 +4,13 @@ use gpui::{ Styled as _, Subscription, Window, px, }; use signed_state::Backend; -use ui::button::Button; use ui::common::v_flex; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; -use ui::icons::{Icon, IconRole}; +use ui::icons::IconRole; use ui::input::{Input, InputState, InputStateEvent}; -use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task}; +use crate::shared::progress::{DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task}; pub struct PassphraseDialog { handle: DialogHandle, @@ -102,15 +101,18 @@ impl Render for PassphraseDialog { let busy = action_state.read(cx).busy; let this = this.clone(); - let unlock: AnyElement = Button::new("unlock") - .label("Unlock") - .icon(Icon::named(IconRole::Unlock)) - .loading(busy) - .disabled(busy) - .on_click(move |_, _, cx| { - crate::shared::log_dropped(this.update(cx, |this, cx| this.unlock(cx))); - }) - .into_any_element(); + let unlock: AnyElement = dialog_submit_button( + "unlock", + "Unlock", + Some(IconRole::Unlock), + busy, + &this, + |this, _window, cx| { + this.unlock(cx); + Ok(()) + }, + ) + .into_any_element(); vec![unlock] }) diff --git a/crates/signed_app/src/inbox/helpers.rs b/crates/signed_app/src/inbox/helpers.rs index dcffbe7..478e9da 100644 --- a/crates/signed_app/src/inbox/helpers.rs +++ b/crates/signed_app/src/inbox/helpers.rs @@ -9,6 +9,7 @@ use ui::avatar::Avatar; use ui::badge::Badge; use ui::common::{Sizable as _, h_flex, v_flex}; use ui::icons::{Icon, IconRole}; +use ui::status_dot::{StatusDot, StatusDotVariant}; use ui::theme::ActiveTheme as _; use utils::relative_time; @@ -101,8 +102,7 @@ pub fn thread( .child(div().flex_1()) .when(unread, |this| { this.child( - ui::status_dot::StatusDot::new(("inbox-unread", ix)) - .variant(ui::status_dot::StatusDotVariant::Accent), + StatusDot::new(("inbox-unread", ix)).variant(StatusDotVariant::Accent), ) }), ) diff --git a/crates/signed_app/src/inbox/mod.rs b/crates/signed_app/src/inbox/mod.rs index dbeb362..bedc24f 100644 --- a/crates/signed_app/src/inbox/mod.rs +++ b/crates/signed_app/src/inbox/mod.rs @@ -15,6 +15,7 @@ use signed_state::{Backend, BackendEvent, Inbox, RefreshGate, RefreshRequest, Re use ui::alert::{Alert, AlertSeverity, AlertStyle}; use ui::button::Button; use ui::common::{StyledExt as _, h_flex, v_flex}; +use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; use ui::layout::panel::Panel; use ui::scroll_area::ScrollArea; @@ -25,7 +26,6 @@ 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; @@ -470,7 +470,7 @@ impl Render for InboxView { .min_h_0() .px_4() .child(if rows.is_empty() { - empty_state("You're all caught up.") + EmptyState::centered("You're all caught up.") } else { ScrollArea::new("inbox-scroll") .flex_1() diff --git a/crates/signed_app/src/issues/detail.rs b/crates/signed_app/src/issues/detail.rs index 71115a9..d4c3e56 100644 --- a/crates/signed_app/src/issues/detail.rs +++ b/crates/signed_app/src/issues/detail.rs @@ -8,13 +8,16 @@ 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; +use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; use utils::relative_time; -use crate::issues::helpers::{comment_form, comments_section, issue_roots, sidebar_section}; +use crate::issues::helpers::{comment_form, comments_section, sidebar_section}; +use crate::shared::log_dropped; use crate::shared::widgets::status_badge; pub struct IssueDetailView { @@ -39,7 +42,7 @@ impl IssueDetailView { let directory = ProfileDirectory::new(cx); let weak = cx.entity().downgrade(); cx.defer(move |cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| this.track_participants(cx))); + log_dropped(weak.update(cx, |this, cx| this.track_participants(cx))); }); Self { @@ -94,9 +97,9 @@ impl Render for IssueDetailView { let Some(issue) = store.issues.iter().find(|issue| issue.id == self.issue_id) else { // 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") + EmptyState::centered("Issue not found") } else { - crate::shared::widgets::centered_spinner("issue-loading") + Spinner::centered("issue-loading") }; }; @@ -189,7 +192,7 @@ impl Render for IssueDetailView { .child(comment_form( &self.store, issue_id, - issue_roots, + &store.issues, &self.comment_input, "comment", cx, @@ -200,7 +203,7 @@ impl Render for IssueDetailView { .child(sidebar_section( &self.store, issue_id, - issue_roots, + &store.issues, true, &self.directory, cx, diff --git a/crates/signed_app/src/issues/helpers.rs b/crates/signed_app/src/issues/helpers.rs index 260fcfc..31258ad 100644 --- a/crates/signed_app/src/issues/helpers.rs +++ b/crates/signed_app/src/issues/helpers.rs @@ -76,24 +76,16 @@ pub(crate) fn filter_by_status<'a>( (visible, counts) } -pub(crate) fn issue_roots(store: &RepoStore) -> &[Event] { - &store.issues -} - -pub(crate) fn pr_roots(store: &RepoStore) -> &[Event] { - &store.pull_requests -} - pub(crate) fn sidebar_section( store: &Entity, id: EventId, - roots: fn(&RepoStore) -> &[Event], + roots: &[Event], top_gap: bool, directory: &Entity, cx: &App, ) -> AnyElement { let store = store.read(cx); - let Some(root) = roots(store).iter().find(|event| event.id == id) else { + let Some(root) = roots.iter().find(|event| event.id == id) else { return div().into_any_element(); }; @@ -116,7 +108,13 @@ pub(crate) fn sidebar_section( v_flex() .when(top_gap, |this| this.mt_4()) .gap_2() - .child(crate::shared::widgets::section_label("Participants", cx)) + .child( + div() + .text_xs() + .font_medium() + .text_color(cx.theme().colors.muted_foreground) + .child("Participants"), + ) .children(participants.iter().map(|pubkey| { let profile = directory.read(cx).profile(pubkey, cx); let name = profile.name(); @@ -136,7 +134,13 @@ pub(crate) fn sidebar_section( .child( v_flex() .gap_2() - .child(crate::shared::widgets::section_label("Labels", cx)) + .child( + div() + .text_xs() + .font_medium() + .text_color(cx.theme().colors.muted_foreground) + .child("Labels"), + ) .map(|this| { if labels.is_empty() { this.child( @@ -215,11 +219,14 @@ pub(crate) fn comments_section( pub(crate) fn comment_form( store: &Entity, root: EventId, - roots: fn(&RepoStore) -> &[Event], + roots: &[Event], comment_input: &Entity, button_id: &'static str, cx: &App, ) -> AnyElement { + let Some(root) = roots.iter().find(|event| event.id == root).cloned() else { + return div().into_any_element(); + }; let comment_input = comment_input.clone(); let store = store.clone(); @@ -254,13 +261,6 @@ pub(crate) fn comment_form( if content.is_empty() { return; } - let Some(root) = roots(store.read(cx)) - .iter() - .find(|event| event.id == root) - .cloned() - else { - return; - }; store.update(cx, |store, cx| { store.comment(&root, content, cx); }); diff --git a/crates/signed_app/src/issues/mod.rs b/crates/signed_app/src/issues/mod.rs index 7169421..0196b9d 100644 --- a/crates/signed_app/src/issues/mod.rs +++ b/crates/signed_app/src/issues/mod.rs @@ -20,7 +20,8 @@ use std::rc::Rc; use self::detail::IssueDetailView; use crate::repo::helpers::short_id; -use crate::shared::event_list::{EventList, EventRow}; +use crate::shared::event_list::{EventHandler, EventList, EventRow, filter_toolbar}; +use crate::shared::log_dropped; use crate::shared::panels; use crate::workspace::Workspace; @@ -54,7 +55,7 @@ impl IssuesView { }); let weak = cx.entity().downgrade(); cx.defer(move |cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| this.rebuild(cx))); + log_dropped(weak.update(cx, |this, cx| this.rebuild(cx))); }); Self { @@ -128,7 +129,7 @@ impl IssuesView { let muted = cx.theme().colors.muted_foreground; let weak = cx.entity().downgrade(); - crate::shared::event_list::filter_toolbar( + filter_toolbar( cx, [ Segmented::new("issue-filter", self.filter) @@ -190,7 +191,7 @@ impl Render for IssuesView { let id_hex = issue.id.to_hex(); let status = store.read(cx).status_of(issue); - let on_click: crate::shared::event_list::EventHandler = { + let on_click: EventHandler = { let workspace = workspace.clone(); let store = store.clone(); Rc::new(move |_, window, cx| { diff --git a/crates/signed_app/src/issues/new_issue.rs b/crates/signed_app/src/issues/new_issue.rs index 6c11980..45c20f7 100644 --- a/crates/signed_app/src/issues/new_issue.rs +++ b/crates/signed_app/src/issues/new_issue.rs @@ -3,14 +3,13 @@ use gpui::{ Styled as _, Window, div, }; use signed_state::RepoStore; -use ui::button::Button; use ui::common::v_flex; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; -use crate::shared::progress::DialogProgress; +use crate::shared::progress::{DialogProgress, dialog_submit_button}; pub struct NewIssueDialog { handle: DialogHandle, @@ -87,14 +86,18 @@ impl Render for NewIssueDialog { 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))); - }) - .into_any_element() as AnyElement, + dialog_submit_button( + "create-issue", + "Create issue", + None, + busy, + &this, + |this, _window, cx| { + this.submit(cx); + Ok(()) + }, + ) + .into_any_element() as AnyElement, ] }) } diff --git a/crates/signed_app/src/lib.rs b/crates/signed_app/src/lib.rs index 2147dfa..9e3b172 100644 --- a/crates/signed_app/src/lib.rs +++ b/crates/signed_app/src/lib.rs @@ -12,7 +12,7 @@ mod titlebar; mod workspace; pub use app::AppRoot; -pub use app::helpers::{apply_appearance, apply_appearance_mode}; +pub use app::helpers::apply_appearance_mode; use gpui::{App, AppContext as _, Entity, Window}; pub fn root(window: &mut Window, cx: &mut App) -> Entity { diff --git a/crates/signed_app/src/pull_requests/detail.rs b/crates/signed_app/src/pull_requests/detail.rs index 9d87c59..23f98fb 100644 --- a/crates/signed_app/src/pull_requests/detail.rs +++ b/crates/signed_app/src/pull_requests/detail.rs @@ -16,18 +16,23 @@ use ui::avatar::Avatar; use ui::button::Button; 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::input::InputState; use ui::layout::panel::Panel; use ui::scroll_area::ScrollArea; +use ui::spinner::Spinner; use ui::tabs::{Tab, Tabs}; use ui::theme::ActiveTheme as _; use utils::relative_time; use super::dialogs; -use crate::issues::helpers::{comment_form, comments_section, pr_roots, sidebar_section}; +use crate::issues::helpers::{comment_form, comments_section, sidebar_section}; use crate::repo::commit_diff::{CommitDiffView, DiffPane}; -use crate::shared::widgets::{empty_state, status_badge}; +use crate::shared::event_list::commit_list; +use crate::shared::log_dropped; +use crate::shared::panels::open_detail; +use crate::shared::widgets::status_badge; use crate::workspace::Workspace; const NOT_FOUND: &str = "Pull request not found"; @@ -82,7 +87,7 @@ impl PullRequestDetailView { }); cx.defer(move |cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| this.sync(cx))); + log_dropped(weak.update(cx, |this, cx| this.sync(cx))); }); Self { @@ -300,7 +305,7 @@ impl PullRequestDetailView { }; let workspace = self.workspace.clone(); let commit_id = commit_id.to_owned(); - crate::shared::panels::open_detail( + open_detail( &workspace, id, move |window, cx| { @@ -336,7 +341,7 @@ impl PullRequestDetailView { ] }) .on_change(move |index, _, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { this.active_tab = index; cx.notify(); })); @@ -346,10 +351,10 @@ impl PullRequestDetailView { fn render_discussion(&mut self, cx: &mut Context) -> AnyElement { if self.loading { - return centered_spinner(); + return Spinner::centered("pr-loading"); } if let Some(error) = self.error.clone() { - return empty_state(error); + return EmptyState::centered(error); } let (author, picture, age, root_id, pubkey) = { let store = self.store.read(cx); @@ -358,7 +363,7 @@ impl PullRequestDetailView { .iter() .find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest) else { - return empty_state(NOT_FOUND); + return EmptyState::centered(NOT_FOUND); }; let profile = self.directory.read(cx).profile(&root.pubkey, cx); ( @@ -370,6 +375,8 @@ impl PullRequestDetailView { ) }; + let store = self.store.read(cx); + h_flex() .size_full() .min_h_0() @@ -416,7 +423,7 @@ impl PullRequestDetailView { .child(comment_form( &self.store, root_id, - pr_roots, + &store.pull_requests, &self.comment_input, "pr-comment", cx, @@ -426,7 +433,7 @@ impl PullRequestDetailView { .child(sidebar_section( &self.store, root_id, - pr_roots, + &store.pull_requests, true, &self.directory, cx, @@ -436,29 +443,29 @@ impl PullRequestDetailView { fn render_files(&self, _cx: &mut Context) -> AnyElement { if self.loading { - return centered_spinner(); + return Spinner::centered("pr-loading"); } if let Some(error) = self.error.clone() { - return empty_state(error); + return EmptyState::centered(error); } self.pane.clone().into_any_element() } fn render_commits(&self, cx: &mut Context) -> AnyElement { if self.loading { - return centered_spinner(); + return Spinner::centered("pr-loading"); } if let Some(error) = self.error.clone() { - return empty_state(error); + return EmptyState::centered(error); } if self.commits.is_empty() { - return empty_state("No commits found"); + return EmptyState::centered("No commits found"); } let commits = Arc::clone(&self.commits); let worktree = self.worktree.clone(); let view = cx.entity().downgrade(); - crate::shared::event_list::commit_list( + commit_list( "pr-commits", "pr-commits-scroll", commits, @@ -467,12 +474,11 @@ impl PullRequestDetailView { move |commit, window, cx| { if let Some(worktree) = worktree.clone() { let id = commit.id.clone(); - crate::shared::log_dropped(view.update(cx, |this, cx| { + log_dropped(view.update(cx, |this, cx| { this.open_commit_diff(worktree, &id, window, cx); })); } }, - cx, ) } @@ -528,7 +534,7 @@ impl PullRequestDetailView { .when(can_update, |this| { this.child(Button::new("update-pr").label("Update").small().on_click( move |_, _, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { let root = this .store .read(cx) @@ -595,7 +601,3 @@ impl Render for PullRequestDetailView { }) } } - -fn centered_spinner() -> AnyElement { - 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 388d6f6..7684f18 100644 --- a/crates/signed_app/src/pull_requests/dialogs/update.rs +++ b/crates/signed_app/src/pull_requests/dialogs/update.rs @@ -4,14 +4,13 @@ use gpui::{ }; use nostr::prelude::Event; use signed_state::RepoStore; -use ui::button::Button; use ui::common::v_flex; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; -use crate::shared::progress::DialogProgress; +use crate::shared::progress::{DialogProgress, dialog_submit_button}; pub struct UpdatePrDialog { handle: DialogHandle, @@ -80,14 +79,18 @@ impl Render for UpdatePrDialog { 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))); - }) - .into_any_element() as AnyElement, + dialog_submit_button( + "submit-update", + "Update pull request", + None, + busy, + &this, + |this, _window, cx| { + this.submit(cx); + Ok(()) + }, + ) + .into_any_element() as AnyElement, ] }) } diff --git a/crates/signed_app/src/pull_requests/helpers.rs b/crates/signed_app/src/pull_requests/helpers.rs index c484503..63220ad 100644 --- a/crates/signed_app/src/pull_requests/helpers.rs +++ b/crates/signed_app/src/pull_requests/helpers.rs @@ -7,6 +7,7 @@ use ui::menu::MenuItem; use utils::middle_truncate; use super::NewPullRequestView; +use crate::repo::helpers::announcement_display_name; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PullRequestFilter { @@ -115,7 +116,7 @@ pub fn source_menu_items( }; let title = format!( "{} — {}", - crate::repo::helpers::announcement_display_name(&candidate), + announcement_display_name(&candidate), subtitle ); let target = view.clone(); diff --git a/crates/signed_app/src/pull_requests/mod.rs b/crates/signed_app/src/pull_requests/mod.rs index fd7c7a8..0407b0d 100644 --- a/crates/signed_app/src/pull_requests/mod.rs +++ b/crates/signed_app/src/pull_requests/mod.rs @@ -31,7 +31,9 @@ pub use send_patch::SendPatchView; use crate::issues::helpers::{StatusCounts, filter_by_status}; use crate::repo::helpers::short_id; -use crate::shared::event_list::{EventList, EventRow}; +use crate::shared::event_list::{EventHandler, EventList, EventRow, filter_toolbar}; +use crate::shared::log_dropped; +use crate::shared::panels::open_detail; use crate::workspace::Workspace; pub struct PullRequestsView { @@ -59,7 +61,7 @@ impl PullRequestsView { }); cx.defer(move |cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { this.rebuild(cx); })); }); @@ -139,7 +141,7 @@ impl PullRequestsView { let workspace_for_build = workspace.clone(); let store = self.store.clone(); - crate::shared::panels::open_detail( + open_detail( &workspace, id.clone(), move |window, cx| { @@ -168,7 +170,7 @@ impl PullRequestsView { let workspace_for_build = workspace.clone(); let store = self.store.clone(); - crate::shared::panels::open_detail( + open_detail( &workspace, id.clone(), move |window, cx| { @@ -195,7 +197,7 @@ impl PullRequestsView { let menu_open_weak = cx.entity().downgrade(); let patch_weak = cx.entity().downgrade(); - crate::shared::event_list::filter_toolbar( + filter_toolbar( cx, [ Segmented::new("pr-filter", self.filter) @@ -248,7 +250,7 @@ impl PullRequestsView { } }) .on_open_change(move |open, _, cx| { - crate::shared::log_dropped(menu_open_weak.update(cx, |this, cx| { + log_dropped(menu_open_weak.update(cx, |this, cx| { this.new_pr_menu_open = open; cx.notify(); })); @@ -257,7 +259,7 @@ impl PullRequestsView { vec![MenuItem::new("Send Patch").handler({ let weak = patch_weak.clone(); move |window, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { this.open_send_patch(window, cx); })); } @@ -302,14 +304,14 @@ impl Render for PullRequestsView { let id_hex = pr.id.to_hex(); let status = store.read(cx).status_of(pr); - let on_click: crate::shared::event_list::EventHandler = { + let on_click: 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( + open_detail( &workspace, id, move |window, cx| { diff --git a/crates/signed_app/src/pull_requests/new.rs b/crates/signed_app/src/pull_requests/new.rs index 265b4c1..29e4cea 100644 --- a/crates/signed_app/src/pull_requests/new.rs +++ b/crates/signed_app/src/pull_requests/new.rs @@ -1,30 +1,36 @@ -use std::path::PathBuf; +use std::path::{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, + ParentElement as _, PathPromptOptions, Render, SharedString, Styled as _, Subscription, + UniformListScrollHandle, WeakEntity, Window, div, px, }; -use signed_state::{CheckoutsStore, RepoStore}; -use ui::button::Button; +use nostr::prelude::Url; +use signed_core::Announcement; +use signed_git::{GitCache, Repo}; +use signed_state::{Backend, CheckoutsStore, Mirrors, RepoListStore, RepoStore}; +use ui::button::{Button, ButtonVariant}; use ui::combobox::{Combobox, ComboboxState}; use ui::common::{StyledExt as _, h_flex, v_flex}; +use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState}; use ui::layout::panel::Panel; use ui::menu::Menu; +use ui::spinner::Spinner; use ui::tabs::{Tab, Tabs}; use super::helpers::{ForkCompare, truncate_label}; use crate::repo::commit_diff::{CommitDiffView, DiffPane}; +use crate::repo::helpers::announcement_display_name; +use crate::shared::event_list::commit_list; +use crate::shared::log_dropped; +use crate::shared::panels::open_detail; use crate::shared::progress::error_row; -use crate::shared::widgets::empty_state; use crate::workspace::Workspace; -mod source; - pub struct NewPullRequestView { workspace: WeakEntity, panel_id: SharedString, @@ -73,7 +79,7 @@ impl NewPullRequestView { let weak = weak.clone(); move |value, _window, cx| { if let Some(base) = value { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { if this.base == base { return; } @@ -94,7 +100,7 @@ impl NewPullRequestView { let weak = weak.clone(); move |value, _window, cx| { if let Some(compare) = value { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { if this.compare == compare { return; } @@ -110,7 +116,7 @@ impl NewPullRequestView { }); window.defer(cx, move |window, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { let Some(addr) = this.store.read(cx).addr().cloned() else { return; }; @@ -209,7 +215,7 @@ impl NewPullRequestView { this.update(cx, |this, _cx| { this.submitting = false; })?; - crate::shared::log_dropped( + log_dropped( workspace.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)), ); Ok(()) @@ -227,7 +233,7 @@ impl NewPullRequestView { }; let workspace = self.workspace.clone(); let commit_id = commit_id.to_owned(); - crate::shared::panels::open_detail( + open_detail( &workspace, id, move |window, cx| { @@ -270,7 +276,7 @@ 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(&crate::repo::helpers::announcement_display_name( + Some(fork) => truncate_label(&announcement_display_name( &fork.announcement, )), None => self.repo_path.as_ref().map_or_else( @@ -289,21 +295,21 @@ impl NewPullRequestView { .child( v_flex() .gap_1() - .child(label("Merge Into")) + .child(div().text_xs().font_medium().child("Merge Into")) .child(div().w(px(160.)).child(self.base_select.clone())), ) .child( v_flex() .gap_1() - .child(label("Pull From")) + .child(div().text_xs().font_medium().child("Pull From")) .child(div().w(px(160.)).child(self.compare_select.clone())), ) .child( - v_flex().gap_1().child(label("Source")).child( + v_flex().gap_1().child(div().text_xs().font_medium().child("Source")).child( Menu::new("pr-source") .open(self.source_open) .on_change(move |open, _, cx| { - crate::shared::log_dropped(weak_menu.update(cx, |this, cx| { + log_dropped(weak_menu.update(cx, |this, cx| { this.source_open = open; cx.notify(); })); @@ -311,7 +317,7 @@ impl NewPullRequestView { .trigger(move |_, _| { Button::new("compare-source") .label(source_label.clone()) - .variant(ui::button::ButtonVariant::Secondary) + .variant(ButtonVariant::Secondary) .into_any_element() }) .items(move |_, _| { @@ -343,7 +349,7 @@ impl NewPullRequestView { .loading(self.submitting) .disabled(!can_submit) .on_click(move |_, window, cx| { - crate::shared::log_dropped( + log_dropped( weak.update(cx, |this, cx| this.submit(window, cx)), ); }), @@ -366,7 +372,7 @@ impl NewPullRequestView { ] }) .on_change(move |index, _, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { this.active_tab = index; cx.notify(); })); @@ -376,13 +382,15 @@ impl NewPullRequestView { fn render_content(&self, cx: &mut Context) -> AnyElement { if self.loading { - return crate::shared::widgets::centered_spinner("new-pr-loading"); + return Spinner::centered("new-pr-loading"); } if !self.has_source() { - return empty_state("Choose a local checkout or an announced fork to compare"); + return EmptyState::centered( + "Choose a local checkout or an announced fork to compare", + ); } if self.commits.is_none() && self.error.is_some() { - return empty_state("Nothing to compare"); + return EmptyState::centered("Nothing to compare"); } match self.active_tab { 0 => self.pane.clone().into_any_element(), @@ -392,15 +400,15 @@ impl NewPullRequestView { fn render_commits(&self, cx: &mut Context) -> AnyElement { let Some(commits) = self.commits.as_ref() else { - return empty_state("No commits"); + return EmptyState::centered("No commits"); }; if commits.is_empty() { - return empty_state("No commits between the branches"); + return EmptyState::centered("No commits between the branches"); } let commits = Arc::clone(commits); let view = cx.entity().downgrade(); - crate::shared::event_list::commit_list( + commit_list( "new-pr-commits", "new-pr-commits-scroll", commits, @@ -408,13 +416,383 @@ impl NewPullRequestView { |_, _, _| None, move |commit, window, cx| { let id = commit.id.clone(); - crate::shared::log_dropped(view.update(cx, |this, cx| { + log_dropped(view.update(cx, |this, cx| { this.open_commit_diff(&id, window, cx); })); }, - cx, ) } + + pub(super) fn has_source(&self) -> bool { + self.repo_path.is_some() || self.fork.is_some() + } + + pub(super) fn work_path(&self) -> Option { + match &self.fork { + Some(fork) => Some(fork.mirror_path.clone()), + None => self.repo_path.clone(), + } + } + + pub(super) fn base_ref(&self) -> String { + match &self.fork { + Some(_) => ForkCompare::base_ref(&self.base), + None => self.base.to_string(), + } + } + + pub(super) fn compare_ref(&self) -> String { + match &self.fork { + Some(fork) => fork.compare_ref(&self.compare), + None => self.compare.to_string(), + } + } + + pub(crate) fn choose_checkout(&mut self, window: &mut Window, cx: &mut Context) { + let prompt = cx.prompt_for_paths(PathPromptOptions { + files: false, + directories: true, + multiple: false, + prompt: Some("Choose local checkout".into()), + }); + let task: gpui::Task> = + cx.spawn_in(window, async move |this, cx| { + let picked = match prompt.await { + Ok(Ok(Some(mut paths))) => paths.pop(), + _ => None, + }; + let Some(path) = picked else { + return Ok(()); + }; + this.update_in(cx, |this, window, cx| { + this.apply_folder_path(path, window, cx) + })?; + Ok(()) + }); + self.push_task(task); + } + + pub(crate) fn apply_folder_path( + &mut self, + path: PathBuf, + window: &mut Window, + cx: &mut Context, + ) { + self.fork_generation = self.fork_generation.wrapping_add(1); + let generation = self.fork_generation; + let path_string = path.to_string_lossy().to_string(); + let task: gpui::Task> = + cx.spawn_in(window, async move |this, cx| { + let info = cx + .background_spawn({ + let path = path.clone(); + async move { + let repo = Repo::try_open(&path)?; + match repo.branches() { + Ok(branches) => Some((branches, repo.current_branch())), + Err(error) => { + log::warn!("failed to list branches: {error}"); + None + } + } + } + }) + .await; + this.update_in(cx, |this, window, cx| { + if generation != this.fork_generation { + return; + } + this.apply_checkout(path_string, info, window, cx); + })?; + Ok(()) + }); + self.push_task(task); + } + + fn apply_checkout( + &mut self, + path: String, + info: Option<(Vec, Option)>, + window: &mut Window, + cx: &mut Context, + ) { + self.fork = None; + let Some((branches, current)) = info else { + self.error = Some("The chosen folder is not a git repository".into()); + self.repo_path = None; + self.branches.clear(); + self.merge_base = None; + self.commits = None; + self.pane.update(cx, |pane, cx| pane.clear(cx)); + cx.notify(); + return; + }; + if branches.is_empty() { + self.error = Some("The repository has no branches yet".into()); + self.repo_path = None; + self.branches.clear(); + self.merge_base = None; + self.commits = None; + self.pane.update(cx, |pane, cx| pane.clear(cx)); + cx.notify(); + return; + } + + let announced = self.store.read(cx).head.clone(); + let base = preferred_branch(&branches, announced); + let compare = current + .filter(|branch| branches.contains(branch)) + .unwrap_or_else(|| base.clone()); + + self.repo_path = Some(PathBuf::from(&path)); + self.error = None; + self.branches = branches.into_iter().map(SharedString::from).collect(); + + if let Some(addr) = self.store.read(cx).addr().cloned() { + CheckoutsStore::global(cx).update(cx, |store, cx| { + store.record(PathBuf::from(&path), addr, cx); + }); + } + + self.base = SharedString::from(base); + self.compare = SharedString::from(compare); + self.sync_selectors(window, cx); + self.reload_compare(cx); + } + + fn sync_selectors(&mut self, window: &mut Window, cx: &mut Context) { + let options: Vec<(SharedString, SharedString)> = self + .branches + .iter() + .map(|branch| (branch.clone(), branch.clone())) + .collect(); + let base = self.base.clone(); + let compare = self.compare.clone(); + + self.base_select.update(cx, |state, cx| { + state.set_options(options.clone(), cx); + state.set_selected(Some(base), window, cx); + }); + self.compare_select.update(cx, |state, cx| { + state.set_options(options, cx); + state.set_selected(Some(compare), window, cx); + }); + } + + pub(super) fn fork_candidates(&self, cx: &App) -> Vec { + let Some(addr) = self.store.read(cx).addr().cloned() else { + return Vec::new(); + }; + let euc = self + .store + .read(cx) + .announcement + .as_ref() + .and_then(|a| a.euc.clone()); + let user = Backend::global(cx).read(cx).current_user(); + let announcements = RepoListStore::global(cx).read(cx).announcements.clone(); + Announcement::forks_in(&announcements, &addr, euc.as_deref(), user) + .into_iter() + .cloned() + .collect() + } + + pub(crate) fn choose_fork( + &mut self, + announcement: Announcement, + window: &mut Window, + cx: &mut Context, + ) { + let Some(base) = self.store.read(cx).addr().cloned() else { + return; + }; + let mirror_path = Mirrors::path(&base); + let namespace = GitCache::fork_namespace(&announcement); + let clone_urls: Vec = announcement.clone.clone(); + let base_clone_urls: Vec = self + .store + .read(cx) + .announcement + .as_ref() + .map(|a| a.clone.clone()) + .unwrap_or_default(); + self.fork_generation = self.fork_generation.wrapping_add(1); + let generation = self.fork_generation; + let handle = window.window_handle(); + + self.loading = true; + self.error = None; + cx.notify(); + + let task: gpui::Task> = cx.spawn(async move |this, cx| { + let result = cx + .background_spawn({ + let namespace = namespace.clone(); + let mirror_path = mirror_path.clone(); + async move { + Mirrors::ensure(&base, &base_clone_urls)?; + let repo = Repo::open(&mirror_path)?; + repo.delete_refs_with_prefix("refs/fork")?; + repo.fetch_refs( + &clone_urls, + &format!("+refs/heads/*:refs/fork/{namespace}/*"), + )?; + let strip = |refs: Vec, prefix: &str| { + let mut names: Vec = refs + .into_iter() + .filter_map(|name| { + name.strip_prefix(prefix) + .map(|rest| rest.trim_start_matches('/').to_owned()) + }) + .filter(|name| !name.is_empty()) + .collect(); + names.sort(); + names + }; + let base_branches = strip( + repo.refs_with_prefix("refs/remotes/origin")?, + "refs/remotes/origin", + ); + let compare_branches = strip( + repo.refs_with_prefix(&format!("refs/fork/{namespace}"))?, + &format!("refs/fork/{namespace}"), + ); + Ok::<_, anyhow::Error>((base_branches, compare_branches)) + } + }) + .await; + + if let Err(error) = cx.update_window(handle, |_, window, cx| { + this.update(cx, |this, cx| { + if generation != this.fork_generation { + return; + } + this.apply_fork(announcement, mirror_path, namespace, result, window, cx); + }) + }) { + log::warn!("failed to apply fork: {error}"); + } + Ok(()) + }); + self.push_task(task); + } + + fn apply_fork( + &mut self, + announcement: Announcement, + mirror_path: PathBuf, + namespace: String, + result: Result<(Vec, Vec), anyhow::Error>, + window: &mut Window, + cx: &mut Context, + ) { + self.loading = false; + let (base_branches, compare_branches) = match result { + Ok(branches) => branches, + Err(error) => { + self.error = Some(format!("Could not compare against the fork: {error}").into()); + cx.notify(); + return; + } + }; + if compare_branches.is_empty() { + self.error = Some("The fork has no branches to compare".into()); + cx.notify(); + return; + } + if base_branches.is_empty() { + self.error = Some("Could not list the target repository's branches.".into()); + cx.notify(); + return; + } + + let announced = self.store.read(cx).head.clone(); + let base = preferred_branch(&base_branches, announced); + let compare = compare_branches + .iter() + .find(|branch| branch.as_str() == "main") + .map(|branch| SharedString::from(branch.clone())) + .unwrap_or_else(|| SharedString::from(compare_branches[0].clone())); + + self.fork = Some(ForkCompare { + announcement, + namespace, + mirror_path, + }); + self.error = None; + self.base = SharedString::from(base); + self.compare = compare; + self.branches = base_branches.into_iter().map(SharedString::from).collect(); + self.sync_selectors(window, cx); + self.reload_compare(cx); + } + + pub(super) fn reload_compare(&mut self, cx: &mut Context) { + let Some(repo_path) = self.work_path() else { + return; + }; + let base = self.base_ref(); + let compare = self.compare_ref(); + let base_name = self.base.to_string(); + let compare_name = self.compare.to_string(); + + self.loading = true; + self.error = None; + self.compare_generation += 1; + let generation = self.compare_generation; + cx.notify(); + + if base == compare { + self.loading = false; + self.merge_base = None; + self.commits = None; + self.pane.update(cx, |pane, cx| pane.clear(cx)); + self.error = Some("Choose different base and compare branches".into()); + cx.notify(); + return; + } + + let task: gpui::Task> = cx.spawn(async move |this, cx| { + let result = cx + .background_spawn({ + async move { + let repo = Repo::open(Path::new(&repo_path))?; + let merge_base = repo.merge_base(&base, &compare)?.ok_or_else(|| { + anyhow::anyhow!( + "{base_name} and {compare_name} share no common ancestor" + ) + })?; + let commits = repo.commit_range(&merge_base, &compare)?; + let diff = repo.range_diff(&merge_base, &compare)?; + Ok::<_, anyhow::Error>((merge_base, commits, diff)) + } + }) + .await; + + this.update(cx, |this, cx| { + if generation != this.compare_generation { + return; + } + this.loading = false; + match result { + Ok((merge_base, commits, diff)) => { + this.merge_base = Some(merge_base); + this.commits = Some(Arc::new(commits)); + this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx)); + } + Err(error) => { + this.merge_base = None; + this.commits = None; + this.pane.update(cx, |pane, cx| pane.clear(cx)); + this.error = Some(error.to_string().into()); + } + } + cx.notify(); + })?; + Ok(()) + }); + self.push_task(task); + } } impl Panel for NewPullRequestView { @@ -462,6 +840,15 @@ impl Render for NewPullRequestView { } } -fn label(text: &'static str) -> AnyElement { - div().text_xs().font_medium().child(text).into_any_element() +/// 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()) } diff --git a/crates/signed_app/src/pull_requests/new/source.rs b/crates/signed_app/src/pull_requests/new/source.rs deleted file mode 100644 index 49f3298..0000000 --- a/crates/signed_app/src/pull_requests/new/source.rs +++ /dev/null @@ -1,397 +0,0 @@ -use std::path::{Path, PathBuf}; -use std::sync::Arc; - -use gpui::{App, AppContext as _, Context, PathPromptOptions, SharedString, Window}; -use nostr::prelude::Url; -use signed_core::Announcement; -use signed_git::{GitCache, Repo}; -use signed_state::{Backend, CheckoutsStore, Mirrors, RepoListStore}; - -use super::NewPullRequestView; -use crate::pull_requests::helpers::ForkCompare; - -/// 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() - } - - pub(super) fn work_path(&self) -> Option { - match &self.fork { - Some(fork) => Some(fork.mirror_path.clone()), - None => self.repo_path.clone(), - } - } - - pub(super) fn base_ref(&self) -> String { - match &self.fork { - Some(_) => ForkCompare::base_ref(&self.base), - None => self.base.to_string(), - } - } - - pub(super) fn compare_ref(&self) -> String { - match &self.fork { - Some(fork) => fork.compare_ref(&self.compare), - None => self.compare.to_string(), - } - } - - pub(crate) fn choose_checkout(&mut self, window: &mut Window, cx: &mut Context) { - let prompt = cx.prompt_for_paths(PathPromptOptions { - files: false, - directories: true, - multiple: false, - prompt: Some("Choose local checkout".into()), - }); - let task: gpui::Task> = - cx.spawn_in(window, async move |this, cx| { - let picked = match prompt.await { - Ok(Ok(Some(mut paths))) => paths.pop(), - _ => None, - }; - let Some(path) = picked else { - return Ok(()); - }; - this.update_in(cx, |this, window, cx| { - this.apply_folder_path(path, window, cx) - })?; - Ok(()) - }); - self.push_task(task); - } - - pub(crate) fn apply_folder_path( - &mut self, - path: PathBuf, - window: &mut Window, - cx: &mut Context, - ) { - self.fork_generation = self.fork_generation.wrapping_add(1); - let generation = self.fork_generation; - let path_string = path.to_string_lossy().to_string(); - let task: gpui::Task> = - cx.spawn_in(window, async move |this, cx| { - let info = cx - .background_spawn({ - let path = path.clone(); - async move { - let repo = Repo::try_open(&path)?; - match repo.branches() { - Ok(branches) => Some((branches, repo.current_branch())), - Err(error) => { - log::warn!("failed to list branches: {error}"); - None - } - } - } - }) - .await; - this.update_in(cx, |this, window, cx| { - if generation != this.fork_generation { - return; - } - this.apply_checkout(path_string, info, window, cx); - })?; - Ok(()) - }); - self.push_task(task); - } - - fn apply_checkout( - &mut self, - path: String, - info: Option<(Vec, Option)>, - window: &mut Window, - cx: &mut Context, - ) { - self.fork = None; - let Some((branches, current)) = info else { - self.error = Some("The chosen folder is not a git repository".into()); - self.repo_path = None; - self.branches.clear(); - self.merge_base = None; - self.commits = None; - self.pane.update(cx, |pane, cx| pane.clear(cx)); - cx.notify(); - return; - }; - if branches.is_empty() { - self.error = Some("The repository has no branches yet".into()); - self.repo_path = None; - self.branches.clear(); - self.merge_base = None; - self.commits = None; - self.pane.update(cx, |pane, cx| pane.clear(cx)); - cx.notify(); - return; - } - - let announced = self.store.read(cx).head.clone(); - let base = preferred_branch(&branches, announced); - let compare = current - .filter(|branch| branches.contains(branch)) - .unwrap_or_else(|| base.clone()); - - self.repo_path = Some(PathBuf::from(&path)); - self.error = None; - self.branches = branches.into_iter().map(SharedString::from).collect(); - - if let Some(addr) = self.store.read(cx).addr().cloned() { - CheckoutsStore::global(cx).update(cx, |store, cx| { - store.record(PathBuf::from(&path), addr, cx); - }); - } - - self.base = SharedString::from(base); - self.compare = SharedString::from(compare); - self.sync_selectors(window, cx); - self.reload_compare(cx); - } - - fn sync_selectors(&mut self, window: &mut Window, cx: &mut Context) { - let options: Vec<(SharedString, SharedString)> = self - .branches - .iter() - .map(|branch| (branch.clone(), branch.clone())) - .collect(); - let base = self.base.clone(); - let compare = self.compare.clone(); - - self.base_select.update(cx, |state, cx| { - state.set_options(options.clone(), cx); - state.set_selected(Some(base), window, cx); - }); - self.compare_select.update(cx, |state, cx| { - state.set_options(options, cx); - state.set_selected(Some(compare), window, cx); - }); - } - - pub(super) fn fork_candidates(&self, cx: &App) -> Vec { - let Some(addr) = self.store.read(cx).addr().cloned() else { - return Vec::new(); - }; - let euc = self - .store - .read(cx) - .announcement - .as_ref() - .and_then(|a| a.euc.clone()); - let user = Backend::global(cx).read(cx).current_user(); - let announcements = RepoListStore::global(cx).read(cx).announcements.clone(); - Announcement::forks_in(&announcements, &addr, euc.as_deref(), user) - .into_iter() - .cloned() - .collect() - } - - pub(crate) fn choose_fork( - &mut self, - announcement: Announcement, - window: &mut Window, - cx: &mut Context, - ) { - let Some(base) = self.store.read(cx).addr().cloned() else { - return; - }; - let mirror_path = Mirrors::path(&base); - let namespace = GitCache::fork_namespace(&announcement); - let clone_urls: Vec = announcement.clone.clone(); - let base_clone_urls: Vec = self - .store - .read(cx) - .announcement - .as_ref() - .map(|a| a.clone.clone()) - .unwrap_or_default(); - self.fork_generation = self.fork_generation.wrapping_add(1); - let generation = self.fork_generation; - let handle = window.window_handle(); - - self.loading = true; - self.error = None; - cx.notify(); - - let task: gpui::Task> = cx.spawn(async move |this, cx| { - let result = cx - .background_spawn({ - let namespace = namespace.clone(); - let mirror_path = mirror_path.clone(); - async move { - Mirrors::ensure(&base, &base_clone_urls)?; - let repo = Repo::open(&mirror_path)?; - repo.delete_refs_with_prefix("refs/fork")?; - repo.fetch_refs( - &clone_urls, - &format!("+refs/heads/*:refs/fork/{namespace}/*"), - )?; - let strip = |refs: Vec, prefix: &str| { - let mut names: Vec = refs - .into_iter() - .filter_map(|name| { - name.strip_prefix(prefix) - .map(|rest| rest.trim_start_matches('/').to_owned()) - }) - .filter(|name| !name.is_empty()) - .collect(); - names.sort(); - names - }; - let base_branches = strip( - repo.refs_with_prefix("refs/remotes/origin")?, - "refs/remotes/origin", - ); - let compare_branches = strip( - repo.refs_with_prefix(&format!("refs/fork/{namespace}"))?, - &format!("refs/fork/{namespace}"), - ); - Ok::<_, anyhow::Error>((base_branches, compare_branches)) - } - }) - .await; - - if let Err(error) = cx.update_window(handle, |_, window, cx| { - this.update(cx, |this, cx| { - if generation != this.fork_generation { - return; - } - this.apply_fork(announcement, mirror_path, namespace, result, window, cx); - }) - }) { - log::warn!("failed to apply fork: {error}"); - } - Ok(()) - }); - self.push_task(task); - } - - fn apply_fork( - &mut self, - announcement: Announcement, - mirror_path: PathBuf, - namespace: String, - result: Result<(Vec, Vec), anyhow::Error>, - window: &mut Window, - cx: &mut Context, - ) { - self.loading = false; - let (base_branches, compare_branches) = match result { - Ok(branches) => branches, - Err(error) => { - self.error = Some(format!("Could not compare against the fork: {error}").into()); - cx.notify(); - return; - } - }; - if compare_branches.is_empty() { - self.error = Some("The fork has no branches to compare".into()); - cx.notify(); - return; - } - if base_branches.is_empty() { - self.error = Some("Could not list the target repository's branches.".into()); - cx.notify(); - return; - } - - let announced = self.store.read(cx).head.clone(); - let base = preferred_branch(&base_branches, announced); - let compare = compare_branches - .iter() - .find(|branch| branch.as_str() == "main") - .map(|branch| SharedString::from(branch.clone())) - .unwrap_or_else(|| SharedString::from(compare_branches[0].clone())); - - self.fork = Some(ForkCompare { - announcement, - namespace, - mirror_path, - }); - self.error = None; - self.base = SharedString::from(base); - self.compare = compare; - self.branches = base_branches.into_iter().map(SharedString::from).collect(); - self.sync_selectors(window, cx); - self.reload_compare(cx); - } - - pub(super) fn reload_compare(&mut self, cx: &mut Context) { - let Some(repo_path) = self.work_path() else { - return; - }; - let base = self.base_ref(); - let compare = self.compare_ref(); - let base_name = self.base.to_string(); - let compare_name = self.compare.to_string(); - - self.loading = true; - self.error = None; - self.compare_generation += 1; - let generation = self.compare_generation; - cx.notify(); - - if base == compare { - self.loading = false; - self.merge_base = None; - self.commits = None; - self.pane.update(cx, |pane, cx| pane.clear(cx)); - self.error = Some("Choose different base and compare branches".into()); - cx.notify(); - return; - } - - let task: gpui::Task> = cx.spawn(async move |this, cx| { - let result = cx - .background_spawn({ - async move { - let repo = Repo::open(Path::new(&repo_path))?; - let merge_base = repo.merge_base(&base, &compare)?.ok_or_else(|| { - anyhow::anyhow!( - "{base_name} and {compare_name} share no common ancestor" - ) - })?; - let commits = repo.commit_range(&merge_base, &compare)?; - let diff = repo.range_diff(&merge_base, &compare)?; - Ok::<_, anyhow::Error>((merge_base, commits, diff)) - } - }) - .await; - - this.update(cx, |this, cx| { - if generation != this.compare_generation { - return; - } - this.loading = false; - match result { - Ok((merge_base, commits, diff)) => { - this.merge_base = Some(merge_base); - this.commits = Some(Arc::new(commits)); - this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx)); - } - Err(error) => { - this.merge_base = None; - this.commits = None; - this.pane.update(cx, |pane, cx| pane.clear(cx)); - this.error = Some(error.to_string().into()); - } - } - cx.notify(); - })?; - Ok(()) - }); - self.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 595bb0e..20e947c 100644 --- a/crates/signed_app/src/pull_requests/send_patch.rs +++ b/crates/signed_app/src/pull_requests/send_patch.rs @@ -11,6 +11,7 @@ use ui::input::{Input, InputState}; use ui::layout::panel::Panel; use ui::theme::ActiveTheme as _; +use crate::shared::log_dropped; use crate::shared::progress::error_row; use crate::workspace::Workspace; @@ -83,7 +84,7 @@ impl SendPatchView { Ok(()) => { this.update(cx, |this, cx| { let panel_id = this.panel_id.clone(); - crate::shared::log_dropped( + log_dropped( this.workspace .update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)), ); @@ -122,7 +123,7 @@ impl SendPatchView { .loading(self.submitting) .disabled(!can_submit) .on_click(move |_, _, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| this.submit(cx))); + log_dropped(weak.update(cx, |this, cx| this.submit(cx))); }), ) .into_any_element() diff --git a/crates/signed_app/src/repo/commit_diff.rs b/crates/signed_app/src/repo/commit_diff.rs index dc23e02..b3339d2 100644 --- a/crates/signed_app/src/repo/commit_diff.rs +++ b/crates/signed_app/src/repo/commit_diff.rs @@ -14,20 +14,21 @@ use ui::badge::GroupedBadge; use ui::button::{Button, ButtonVariant}; 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::layout::panel::Panel; use ui::layout::resizable::{Resizable, ResizableState}; +use ui::scrollbar::Scrollbar; use ui::separator::Separator; +use ui::spinner::Spinner; use ui::switch::Switch; use ui::theme::ActiveTheme as _; use ui::toggle::Toggle; use ui::tooltip::Tooltip; -use ui::tree::{Tree, TreeItem}; +use ui::tree::{Tree, TreeItem, TreeItemSeed}; use utils::relative_time_secs; -use super::helpers::{DiffRow, co_authors, diff_rows, render_diff_row, short_id}; -use crate::shared::tree::{TreeItemSeed, TreeRow, build_tree_items, collect_expanded, flatten}; -use crate::shared::widgets::{centered_spinner, empty_state, scroll_overlay}; +use super::helpers::{DiffRow, co_authors, diff_rows, short_id}; /// Emitted when the user activates the Download commit button. pub enum DiffPaneEvent { @@ -59,7 +60,7 @@ pub struct DiffPane { diff: Option, seeds: Vec, expanded: HashSet, - rows: Vec, + rows: Vec, selected_index: Option, tree_visible: bool, split: Entity, @@ -103,9 +104,9 @@ impl DiffPane { .collect(); paths.sort(); - self.seeds = build_tree_items(&paths); - self.expanded = collect_expanded(&self.seeds); - self.rows = flatten(&self.seeds, &self.expanded); + self.seeds = TreeItemSeed::from_paths(&paths); + self.expanded = TreeItemSeed::collect_expanded(&self.seeds); + self.rows = TreeItemSeed::flatten_all(&self.seeds, &self.expanded); self.selected_index = None; self.diff = Some(diff); @@ -172,7 +173,10 @@ impl DiffPane { } fn select_tree_file(&mut self, path: &str, cx: &mut Context) { - self.selected_index = self.rows.iter().position(|row| row.id == path); + self.selected_index = self + .rows + .iter() + .position(|row| row.key().to_string() == path); if self.expanded_files.insert(path.to_owned()) { self.rebuild_rows(); } @@ -249,7 +253,7 @@ impl DiffPane { if !self.expanded.remove(id) { self.expanded.insert(id.to_owned()); } - self.rows = flatten(&self.seeds, &self.expanded); + self.rows = TreeItemSeed::flatten_all(&self.seeds, &self.expanded); self.selected_index = self .selected_index .and_then(|index| self.rows.get(index).map(|_| index)); @@ -269,22 +273,7 @@ impl DiffPane { .child( Tree::new("commit-diff-tree") .selected(selected) - .items(move |_, _| { - rows.iter() - .map(|row| { - let item = TreeItem::new(row.id.clone(), row.label.clone()) - .depth(row.depth) - .expandable(row.expandable) - .expanded(row.expanded); - - if row.expandable { - item.icon(Icon::named(IconRole::Folder)) - } else { - item.icon(Icon::named(IconRole::File)) - } - }) - .collect() - }) + .items(move |_, _| rows.clone()) .on_change(move |index, window, cx| { if let Some(index) = index && let Err(error) = change_view.update(cx, |this, cx| { @@ -298,7 +287,10 @@ impl DiffPane { let view = view; move |index, _, cx| { if let Err(error) = view.update(cx, |this, cx| { - let id = this.rows.get(index).map(|row| row.id.clone()); + let id = this + .rows + .get(index) + .map(|row| row.key().to_string()); if let Some(id) = id { this.toggle_folder(&id, cx); } @@ -315,8 +307,8 @@ impl DiffPane { let Some(row) = self.rows.get(index) else { return; }; - let id = row.id.clone(); - let expandable = row.expandable; + let id = row.key().to_string(); + let expandable = row.is_expandable(); self.selected_index = Some(index); if expandable { @@ -427,7 +419,7 @@ impl DiffPane { fn render_file_list(&self, cx: &mut Context) -> AnyElement { let Some(diff) = self.diff.as_ref() else { - return empty_state("No changes"); + return EmptyState::centered("No changes"); }; let files = diff.files.clone(); @@ -451,7 +443,7 @@ impl DiffPane { .size_full() .p_2(), ) - .child(scroll_overlay("commit-diff-files", self.list.clone())) + .child(Scrollbar::vertical("commit-diff-files", self.list.clone())) .into_any_element() } } @@ -562,7 +554,7 @@ fn render_pane_row( .border_color(border) .bg(surface) .when(*last, |this| this.border_b_1().rounded_b_lg()) - .child(render_diff_row(&file.hunks, *row, wrap, cx)) + .child(row.render(&file.hunks, wrap, cx)) .into_any_element() } } @@ -571,13 +563,13 @@ fn render_pane_row( impl Render for DiffPane { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { if self.diff.is_none() { - return empty_state("No changes"); + return EmptyState::centered("No changes"); } let diff = self.diff.as_ref().expect("diff checked above"); if diff.files.is_empty() { - return empty_state("No files changed"); + return EmptyState::centered("No files changed"); } let toolbar = self.render_toolbar(cx); @@ -898,9 +890,9 @@ impl Panel for CommitDiffView { impl Render for CommitDiffView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let body = if self.loading { - centered_spinner("commit-diff-loading") + Spinner::centered("commit-diff-loading") } else if let Some(error) = self.error.clone() { - empty_state(error) + EmptyState::centered(error) } else { self.pane.clone().into_any_element() }; diff --git a/crates/signed_app/src/repo/dialogs/create.rs b/crates/signed_app/src/repo/dialogs/create.rs index 9598d83..b1a99a7 100644 --- a/crates/signed_app/src/repo/dialogs/create.rs +++ b/crates/signed_app/src/repo/dialogs/create.rs @@ -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, run_dialog_task_with}; +use crate::shared::progress::{DialogProgress, dialog_submit_button, 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. @@ -229,17 +229,18 @@ impl Render for CreateRepoDialog { let busy = action_state.read(cx).busy; let this = this.clone(); - let create: AnyElement = Button::new("create-repository") - .label("Create repository") - .icon(Icon::named(IconRole::Plus)) - .loading(busy) - .disabled(busy) - .on_click(move |_, window, cx| { - crate::shared::log_dropped( - this.update(cx, |this, cx| this.create(window, cx)), - ); - }) - .into_any_element(); + let create: AnyElement = dialog_submit_button( + "create-repository", + "Create repository", + Some(IconRole::Plus), + busy, + &this, + |this, window, cx| { + this.create(window, cx); + Ok(()) + }, + ) + .into_any_element(); vec![create] }) diff --git a/crates/signed_app/src/repo/dialogs/init.rs b/crates/signed_app/src/repo/dialogs/init.rs index ede1124..b10a6a2 100644 --- a/crates/signed_app/src/repo/dialogs/init.rs +++ b/crates/signed_app/src/repo/dialogs/init.rs @@ -9,11 +9,10 @@ use settings::SettingsStore; use signed_core::RepoAddr; use signed_git::Repo; use signed_state::Backend; -use ui::button::Button; use ui::common::{ResultLogErr as _, v_flex}; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; -use ui::icons::{Icon, IconRole}; +use ui::icons::IconRole; use ui::input::{Input, InputState}; use ui::layout::h_flex; use ui::select::{Select, SelectOption}; @@ -21,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, run_dialog_task_with}; +use crate::shared::progress::{DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task_with}; pub struct InitRepoDialog { handle: DialogHandle, @@ -246,17 +245,18 @@ impl Render for InitRepoDialog { let busy = action_state.read(cx).busy; let this = this.clone(); - let init: AnyElement = Button::new("initialize-repository") - .label("Initialize") - .icon(Icon::named(IconRole::Plus)) - .loading(busy) - .disabled(busy) - .on_click(move |_, window, cx| { - crate::shared::log_dropped( - this.update(cx, |this, cx| this.init_repository(window, cx)), - ); - }) - .into_any_element(); + let init: AnyElement = dialog_submit_button( + "initialize-repository", + "Initialize", + Some(IconRole::Plus), + busy, + &this, + |this, window, cx| { + this.init_repository(window, cx); + Ok(()) + }, + ) + .into_any_element(); vec![init] }) diff --git a/crates/signed_app/src/repo/files.rs b/crates/signed_app/src/repo/files.rs index a916727..6ab684f 100644 --- a/crates/signed_app/src/repo/files.rs +++ b/crates/signed_app/src/repo/files.rs @@ -10,15 +10,14 @@ use gpui::{ use signed_git::{FileCommit, Repo, WorktreeSnapshot}; use ui::code::CodeViewState; use ui::common::{StyledExt as _, h_flex, v_flex}; -use ui::icons::{Icon, IconRole}; +use ui::empty_state::EmptyState; use ui::markdown::MarkdownViewState; +use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; -use ui::tree::{Tree, TreeItem}; +use ui::tree::{Tree, TreeItem, TreeItemSeed}; -use super::helpers::{code_language, is_markdown_path, preview_spinner, source_hash}; +use super::helpers::{code_language, is_markdown_path, source_hash}; use crate::repo::helpers::short_id; -use crate::shared::tree::{TreeItemSeed, TreeRow, collect_expanded, flatten}; -use crate::shared::widgets::empty_state; const MAX_PREVIEW_BYTES: usize = 1024 * 1024; const MAX_PREVIEWED_FILES: usize = 32; @@ -56,7 +55,7 @@ struct CodeView { pub struct RepoFilesView { seeds: Vec, expanded: HashSet, - rows: Vec, + rows: Vec, selected_index: Option, worktree: Option, worktree_paths: Vec, @@ -112,18 +111,22 @@ impl RepoFilesView { ) { self.worktree_paths = paths; self.seeds = tree; - let folder_ids = collect_expanded(&self.seeds); + let folder_ids = TreeItemSeed::collect_expanded(&self.seeds); self.expanded.retain(|id| folder_ids.contains(id)); self.rebuild_rows(); cx.notify(); } fn rebuild_rows(&mut self) { - self.rows = flatten(&self.seeds, &self.expanded); + self.rows = TreeItemSeed::flatten_all(&self.seeds, &self.expanded); self.selected_index = self .selected_file .as_ref() - .and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref())); + .and_then(|path| { + self.rows + .iter() + .position(|row| row.key().to_string() == path.as_ref()) + }); } fn toggle_folder(&mut self, id: &str) { @@ -235,8 +238,8 @@ impl RepoFilesView { let Some(row) = self.rows.get(index) else { return; }; - let id = row.id.clone(); - let expandable = row.expandable; + let id = row.key().to_string(); + let expandable = row.is_expandable(); self.selected_index = Some(index); @@ -261,22 +264,7 @@ impl RepoFilesView { .child( Tree::new("repo-tree") .selected(selected) - .items(move |_, _| { - rows.iter() - .map(|row| { - let item = TreeItem::new(row.id.clone(), row.label.clone()) - .depth(row.depth) - .expandable(row.expandable) - .expanded(row.expanded); - - if row.expandable { - item.icon(Icon::named(IconRole::Folder)) - } else { - item.icon(Icon::named(IconRole::File)) - } - }) - .collect() - }) + .items(move |_, _| rows.clone()) .on_change({ let view = change_view; move |index, window, cx| { @@ -293,7 +281,10 @@ impl RepoFilesView { let view = disclosure_view; move |index, _, cx| { if let Err(error) = view.update(cx, |this, cx| { - let id = this.rows.get(index).map(|row| row.id.clone()); + let id = this + .rows + .get(index) + .map(|row| row.key().to_string()); if let Some(id) = id { this.toggle_folder(&id); cx.emit(RepoFilesEvent::Activated); @@ -319,15 +310,17 @@ impl RepoFilesView { self.code_element(path.as_ref()) } } - Some(FileContent::Binary) => empty_state("Binary file - preview not supported"), - Some(FileContent::TooLarge) => empty_state("File is too large to preview"), - Some(FileContent::Failed(message)) => empty_state(message), - None => preview_spinner(), + Some(FileContent::Binary) => EmptyState::centered( + "Binary file - preview not supported", + ), + Some(FileContent::TooLarge) => EmptyState::centered("File is too large to preview"), + Some(FileContent::Failed(message)) => EmptyState::centered(message), + None => Spinner::centered("repo-preview-spinner"), } } else if self.readme_name.is_some() { self.markdown_element(None) } else { - empty_state("No README found") + EmptyState::centered("No README found") }; let commit = match &self.selected_file { @@ -426,7 +419,7 @@ impl RepoFilesView { fn markdown_element(&self, path: Option<&str>) -> AnyElement { let Some(md) = &self.md else { - return preview_spinner(); + return Spinner::centered("repo-preview-spinner"); }; let ready = match path { @@ -435,7 +428,7 @@ impl RepoFilesView { }; if !ready { - return preview_spinner(); + return Spinner::centered("repo-preview-spinner"); } div() @@ -481,10 +474,10 @@ impl RepoFilesView { fn code_element(&self, path: &str) -> AnyElement { let Some(code) = &self.code else { - return preview_spinner(); + return Spinner::centered("repo-preview-spinner"); }; if code.path.as_ref() != path { - return preview_spinner(); + return Spinner::centered("repo-preview-spinner"); } div() diff --git a/crates/signed_app/src/repo/header.rs b/crates/signed_app/src/repo/header.rs deleted file mode 100644 index 68064eb..0000000 --- a/crates/signed_app/src/repo/header.rs +++ /dev/null @@ -1,455 +0,0 @@ -use std::collections::HashSet; - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - AnyElement, Context, InteractiveElement as _, IntoElement, ParentElement as _, SharedString, - StatefulInteractiveElement as _, Styled as _, Window, div, px, -}; -use signed_state::{Backend, Nip34Kind}; -use ui::avatar::Avatar; -use ui::button::{Button, ButtonVariant}; -use ui::common::{Sizable, StyledExt as _, h_flex, v_flex}; -use ui::dropdown_menu::DropdownMenu; -use ui::icons::{Icon, IconRole}; -use ui::menu::MenuItem; -use ui::popover::Popover; -use ui::theme::ActiveTheme as _; -use ui::tooltip::Tooltip; -use utils::relative_time_secs; - -use super::helpers::{bound_repo_label, clone_group, fork_row, nostr_clone_url, repo_display_name}; -use super::{RepoDetailView, actions, dialogs}; -use crate::shared::widgets::clone_row; - -impl RepoDetailView { - pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context) { - let Some(addr) = self - .announcement(cx) - .and_then(|announcement| announcement.upstream.as_ref()) - .and_then(|upstream| upstream.addr.clone()) - else { - return; - }; - - actions::open_repo_panel(&self.workspace, &addr, None, window, cx); - } - - /// Open the dialog that publishes the local repository to NIP-34. - fn open_init_dialog(&mut self, window: &mut Window, cx: &mut Context) { - let Some(local_path) = self.store.read(cx).path.clone() else { - return; - }; - self.init = Some(dialogs::init::InitRepoDialog::new( - local_path, - cx.entity().downgrade(), - window, - cx, - )); - cx.notify(); - } - - pub(super) fn render_about(&mut self, cx: &mut Context) -> AnyElement { - if self.store.read(cx).addr().is_none() { - return self.render_init_banner(cx); - } - - let backend = Backend::global(cx); - let store = self.store.read(cx); - let pushing = store.pushing; - let cloning = store.cloning; - - let Some(announcement) = store.announcement.clone() else { - return div().into_any_element(); - }; - - let nip05 = self - .directory - .read(cx) - .profile(&announcement.owner, cx) - .metadata() - .nip05 - .clone() - .filter(|nip05| !nip05.trim().is_empty()); - - let nostr_url = nostr_clone_url(&announcement, nip05.as_deref()); - let ngit_command = SharedString::from(format!("git clone {nostr_url}")); - let nak_command = SharedString::from(format!("nak git clone {nostr_url}")); - let git_commands: Vec = announcement.clone_urls(); - - let name = repo_display_name(self.store.read(cx)); - let description = announcement.description(); - let avatar = Avatar::new(format!("{}:{}", announcement.owner, announcement.id)); - - let announcement_for_menu = announcement.clone(); - let weak_menu_open = cx.entity().downgrade(); - let weak_menu_items = cx.entity().downgrade(); - let weak_clone = cx.entity().downgrade(); - let weak_download = cx.entity().downgrade(); - let ngit_for_popover = ngit_command.clone(); - let nak_for_popover = nak_command.clone(); - let git_for_popover = git_commands.clone(); - - h_flex() - .p_6() - .w_full() - .gap_6() - .items_start() - .justify_between() - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_2() - .child( - h_flex() - .gap_2() - .text_sm() - .font_semibold() - .child(avatar) - .child(name), - ) - .child( - div() - .min_w_0() - .text_sm() - .text_color(cx.theme().colors.muted_foreground) - .line_clamp(3) - .child(description), - ) - .when_some(fork_row(&announcement, cx), |this, row| this.child(row)), - ) - .child( - h_flex() - .flex_none() - .gap_2() - .justify_end() - .child( - Popover::new("code-popover") - .open(self.clone_open) - .on_change(move |open, _, cx| { - if let Err(error) = weak_clone.update(cx, |this, cx| { - this.clone_open = open; - cx.notify(); - }) { - log::warn!("failed to update clone popover: {error}"); - } - }) - .trigger(move |_, _| { - Button::new("code") - .label("Code") - .icon(Icon::named(IconRole::GitClone)) - .tooltip(Tooltip::text("Clone repository")) - .loading(cloning) - .disabled(cloning) - .into_any_element() - }) - .content(move |_, cx| { - v_flex() - .w(px(440.)) - .p_3() - .gap_4() - .child(clone_group( - "Clone with ngit", - "copy-ngit".into(), - &ngit_for_popover, - cx, - )) - .child(clone_group( - "Clone with nak", - "copy-nak".into(), - &nak_for_popover, - cx, - )) - .child( - v_flex() - .gap_1() - .child( - div() - .text_xs() - .font_semibold() - .child("Grasp Servers"), - ) - .when(git_for_popover.is_empty(), |this| { - this.child( - div() - .text_xs() - .text_center() - .text_color( - cx.theme().colors.muted_foreground, - ) - .child("No git clone urls."), - ) - }) - .children(git_for_popover.iter().enumerate().map( - |(ix, command)| { - clone_row( - SharedString::from(format!( - "copy-git-{ix}" - )), - command.clone().into(), - cx, - ) - }, - )), - ) - .child( - h_flex().justify_end().child( - Button::new("download") - .icon(Icon::named(IconRole::GitClone)) - .label("Download") - .on_click({ - let weak = weak_download.clone(); - move |_, window, cx| { - if let Err(error) = - weak.update(cx, |this, cx| { - this.clone_to_folder(window, cx); - }) - { - log::warn!("failed to clone: {error}"); - } - } - }), - ), - ) - .into_any_element() - }), - ) - .child( - DropdownMenu::new("repo-menu") - .icon(IconRole::EllipsisVertical) - .variant(ButtonVariant::Ghost) - .disabled(pushing) - .open(self.repo_menu_open) - .on_open_change(move |open, _, cx| { - if let Err(error) = weak_menu_open.update(cx, |this, cx| { - this.repo_menu_open = open; - cx.notify(); - }) { - log::warn!("failed to update repo menu: {error}"); - } - }) - .items(move |_, cx| { - let owner = backend.read(cx).current_user() - == Some(announcement_for_menu.owner); - - let mut items = vec![MenuItem::new("About").handler({ - let weak = weak_menu_items.clone(); - let announcement = announcement_for_menu.clone(); - move |_, cx| { - if let Err(error) = weak.update(cx, |this, cx| { - this.about = Some(dialogs::about::AboutDialog::new( - announcement.clone(), - this.directory.clone(), - cx, - )); - cx.notify(); - }) { - log::warn!("failed to open about: {error}"); - } - } - })]; - - if owner { - items.push(MenuItem::new("Republish").handler({ - let weak = weak_menu_items.clone(); - move |window, cx| { - if let Err(error) = weak.update(cx, |this, cx| { - this.push_repository(window, cx); - }) { - log::warn!("failed to republish: {error}"); - } - } - })); - items.push(MenuItem::new("Reset remote to local").handler({ - let weak = weak_menu_items.clone(); - move |window, cx| { - if let Err(error) = weak.update(cx, |this, cx| { - this.reset_remote(window, cx); - }) { - log::warn!("failed to reset remote: {error}"); - } - } - })); - items.push(MenuItem::separator()); - items.push(MenuItem::new("Delete").destructive(true).handler( - { - let weak = weak_menu_items.clone(); - move |window, cx| { - if let Err(error) = weak.update(cx, |this, cx| { - this.delete_repository(window, cx); - }) { - log::warn!("failed to delete: {error}"); - } - } - }, - )); - } - - items - }), - ), - ) - .into_any_element() - } - - fn render_init_banner(&self, cx: &mut Context) -> AnyElement { - let binding = self - .store - .read(cx) - .nip34 - .as_ref() - .filter(|binding| binding.kind == Nip34Kind::Initialized); - - let path = self - .store - .read(cx) - .path - .as_ref() - .map(|path| path.display().to_string()) - .unwrap_or_default(); - - v_flex() - .flex_none() - .p_6() - .h_32() - .w_full() - .items_center() - .justify_center() - .gap_2() - .map(|this| match binding { - Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)), - None => this.child( - Button::new("init") - .icon(Icon::named(IconRole::ArrowUp)) - .label("Initialize on Nostr") - .tooltip(Tooltip::text("Publish this repository to Nostr")) - .on_click(cx.listener(|this, _, window, cx| { - this.open_init_dialog(window, cx); - })), - ), - }) - .child( - div() - .min_w_0() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .child(path), - ) - .into_any_element() - } - - pub(super) fn render_metadata(&self, cx: &mut Context) -> AnyElement { - h_flex() - .px_6() - .h_12() - .w_full() - .gap_4() - .items_center() - .justify_between() - .child(self.render_maintainers(cx)) - .child(self.render_ref_controls(cx)) - .into_any_element() - } - - fn render_ref_controls(&self, cx: &mut Context) -> AnyElement { - h_flex() - .justify_end() - .flex_none() - .gap_2() - .when_some(self.render_last_commit(cx), |this, commit| { - this.child(commit) - }) - .child(self.refs.branch_select.clone()) - .child(self.refs.tag_select.clone()) - .into_any_element() - } - - fn render_last_commit(&self, cx: &mut Context) -> Option { - let commit = self.head_commit.as_ref()?; - let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned(); - let history = self.history.clone(); - let commit_id = commit.id.clone(); - - Some( - h_flex() - .id("last-commit") - .h_8() - .px_2() - .gap_2() - .min_w_0() - .rounded(cx.theme().radius.control) - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .tooltip(Tooltip::text("View latest commit")) - .on_click(move |_, window, cx| { - history.update(cx, |history, cx| { - history.open_commit_diff(&commit_id, window, cx); - }); - }) - .child(Icon::named(IconRole::GitCommit).color(cx.theme().colors.muted_foreground)) - .child( - div() - .font_family(cx.theme().mono_font) - .text_sm() - .text_color(cx.theme().colors.muted_foreground) - .child(SharedString::from(short)), - ) - .child( - div() - .max_w(px(220.)) - .text_sm() - .text_ellipsis() - .whitespace_nowrap() - .child(commit.summary.clone()), - ) - .child( - div() - .text_sm() - .text_color(cx.theme().colors.muted_foreground) - .child(relative_time_secs(commit.time)), - ) - .into_any_element(), - ) - } - - fn render_maintainers(&self, cx: &mut Context) -> AnyElement { - let Some(announcement) = self.announcement(cx) else { - return div().into_any_element(); - }; - - let mut seen = HashSet::new(); - - let rest: Vec<_> = announcement - .maintainers - .iter() - .copied() - .filter(|key| key != &announcement.owner && seen.insert(*key)) - .collect(); - - let owner = self.directory.read(cx).profile(&announcement.owner, cx); - let owner_name = owner.name(); - - h_flex() - .min_w_0() - .gap_2() - .child( - h_flex() - .gap_2() - .child( - Avatar::new(announcement.owner) - .name(owner_name.clone()) - .picture(owner.picture()) - .small(), - ) - .child(div().text_xs().whitespace_nowrap().child(owner_name)), - ) - .when(!rest.is_empty(), |this| { - this.child( - div() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .child(SharedString::from(format!("+{}", rest.len()))), - ) - }) - .into_any_element() - } -} diff --git a/crates/signed_app/src/repo/helpers.rs b/crates/signed_app/src/repo/helpers.rs index aab8867..141eb67 100644 --- a/crates/signed_app/src/repo/helpers.rs +++ b/crates/signed_app/src/repo/helpers.rs @@ -8,22 +8,92 @@ use gpui::{ }; use metadata::ProfileDirectory; use nostr::prelude::{RelayUrl, ToBech32}; -use signed_core::Announcement; +use signed_core::{Announcement, RepoAddr}; use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo, WorktreeSnapshot}; use signed_state::{Nip34Binding, RepoListStore, RepoStore}; use ui::avatar::Avatar; +use ui::clipboard::CopyRow; use ui::combobox::ComboboxState; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::icons::{Icon, IconRole}; use ui::theme::ActiveTheme as _; -use utils::relative_time_secs; use super::RepoDetailView; -use crate::shared::tree::{TreeItemSeed, build_tree_items, sorted_worktree_paths}; +use ui::tree::TreeItemSeed; const GUTTER_WIDTH: f32 = 44.; pub const DIFF_ROW_HEIGHT: f32 = 20.; -pub const COMMIT_ROW_HEIGHT: f32 = 56.; + +#[derive(Clone, Copy)] +pub(super) enum DiffRow { + Hunk { + old_start: u32, + old_lines: u32, + new_start: u32, + new_lines: u32, + }, + Line { + hunk: usize, + line: usize, + }, +} + +impl DiffRow { + /// Renders one diff row against the file's hunks. + pub(super) fn render(self, hunks: &[DiffHunk], wrap: bool, cx: &App) -> AnyElement { + match self { + DiffRow::Hunk { + old_start, + old_lines, + new_start, + new_lines, + } => div() + .px_2() + .w_full() + .h(px(DIFF_ROW_HEIGHT)) + .font_family(cx.theme().mono_font) + .text_xs() + .bg(cx.theme().colors.muted) + .border_y_1() + .border_color(cx.theme().colors.border) + .text_color(cx.theme().colors.muted_foreground) + .child(SharedString::from(format!( + "@@ -{},{} +{},{} @@", + old_start, old_lines, new_start, new_lines + ))) + .into_any_element(), + DiffRow::Line { hunk, line } => { + match hunks.get(hunk).and_then(|h| h.lines.get(line)) { + Some(line) => render_diff_line(line, wrap, 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(), + } + } + } + } +} + +pub(super) struct RepoData { + pub(super) tree: Vec, + pub(super) entries: Vec, + pub(super) readme_path: Option, + pub(super) readme: Option>, + pub(super) worktree: Option, + pub(super) branches: Vec, + pub(super) tags: Vec, + pub(super) current_branch: Option, + pub(super) head_commit: Option, +} + +/// Sorted relative paths of a worktree snapshot. +pub(crate) fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec { + let mut paths: Vec = entries + .iter() + .map(|path| path.to_string_lossy().into_owned()) + .collect(); + paths.sort(); + paths +} /// The announcement's name, falling back to its id. pub fn announcement_display_name(announcement: &Announcement) -> SharedString { @@ -67,43 +137,12 @@ 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 tree = TreeItemSeed::from_paths(&snapshot.entries); let paths = sorted_worktree_paths(&snapshot.entries); Ok((snapshot, tree, paths)) } -#[derive(Clone, Copy)] -pub(super) enum DiffRow { - Hunk { - old_start: u32, - old_lines: u32, - new_start: u32, - new_lines: u32, - }, - Line { - hunk: usize, - line: usize, - }, -} - -pub(super) struct RepoData { - pub(super) tree: Vec, - pub(super) entries: Vec, - pub(super) readme_path: Option, - pub(super) readme: Option>, - pub(super) worktree: Option, - pub(super) branches: Vec, - pub(super) tags: Vec, - pub(super) current_branch: Option, - pub(super) head_commit: Option, -} - -pub(super) fn clone_group( - label: &str, - id: SharedString, - command: &SharedString, - cx: &App, -) -> AnyElement { +pub(super) fn clone_group(label: &str, id: SharedString, command: &SharedString) -> AnyElement { v_flex() .gap_1() .min_w_0() @@ -113,7 +152,7 @@ pub(super) fn clone_group( .font_semibold() .child(SharedString::from(label)), ) - .child(crate::shared::widgets::clone_row(id, command.clone(), cx)) + .child(CopyRow::new(id, command.clone())) .into_any_element() } @@ -134,6 +173,20 @@ pub(super) fn nostr_clone_url(announcement: &Announcement, nip05: Option<&str>) SharedString::from(url) } +/// The display name of the announcement addressing `addr`, falling back to its identifier. +pub(crate) fn upstream_display_name(addr: &RepoAddr, announcements: &[Announcement]) -> SharedString { + announcements + .iter() + .find(|a| a.addr() == *addr) + .map(|a| { + a.name + .as_deref() + .map(SharedString::from) + .unwrap_or_else(|| SharedString::from(a.id.clone())) + }) + .unwrap_or_else(|| SharedString::from(addr.identifier().to_owned())) +} + pub(super) fn fork_row( announcement: &Announcement, cx: &mut Context, @@ -142,18 +195,10 @@ pub(super) fn fork_row( let (label, clickable) = match &upstream.addr { Some(addr) => { - let name = RepoListStore::global(cx) - .read(cx) - .announcements - .iter() - .find(|a| a.addr() == *addr) - .map(|a| { - a.name - .as_deref() - .map(SharedString::from) - .unwrap_or_else(|| SharedString::from(a.id.clone())) - }) - .unwrap_or_else(|| SharedString::from(addr.identifier().to_owned())); + let name = upstream_display_name( + addr, + &RepoListStore::global(cx).read(cx).announcements, + ); (SharedString::from(format!("Forked from {name}")), true) } None => (SharedString::from(upstream.display().as_str()), false), @@ -180,7 +225,7 @@ pub(super) fn fork_row( pub(super) fn load_repo_data(repo: &Repo) -> Result { let snapshot = repo.snapshot()?; let worktree = repo.workdir().map(Path::to_path_buf); - let tree = build_tree_items(&snapshot.entries); + let tree = TreeItemSeed::from_paths(&snapshot.entries); Ok(RepoData { tree, @@ -267,10 +312,6 @@ pub(super) fn source_hash(text: &str) -> u64 { hasher.finish() } -pub(super) fn preview_spinner() -> AnyElement { - crate::shared::widgets::centered_spinner("repo-preview-spinner") -} - /// The kit grammar for a path; only four languages are supported. pub(super) fn code_language(path: &str) -> ui::highlight::Language { use ui::highlight::Language; @@ -318,41 +359,6 @@ pub(super) fn diff_rows(file: &FileDiff) -> Vec { rows } -pub(super) fn render_diff_row( - hunks: &[DiffHunk], - row: DiffRow, - wrap: bool, - cx: &App, -) -> AnyElement { - match row { - DiffRow::Hunk { - old_start, - old_lines, - new_start, - new_lines, - } => div() - .px_2() - .w_full() - .h(px(DIFF_ROW_HEIGHT)) - .font_family(cx.theme().mono_font) - .text_xs() - .bg(cx.theme().colors.muted) - .border_y_1() - .border_color(cx.theme().colors.border) - .text_color(cx.theme().colors.muted_foreground) - .child(SharedString::from(format!( - "@@ -{},{} +{},{} @@", - old_start, old_lines, new_start, new_lines - ))) - .into_any_element(), - DiffRow::Line { hunk, line } => match hunks.get(hunk).and_then(|h| h.lines.get(line)) { - Some(line) => render_diff_line(line, wrap, 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(), - }, - } -} - fn render_diff_line(line: &DiffLine, wrap: bool, cx: &App) -> AnyElement { let bg = match line.kind { DiffLineKind::Addition => Some(cx.theme().ramps.success.base.opacity(0.2)), @@ -399,63 +405,6 @@ fn render_diff_line(line: &DiffLine, wrap: bool, cx: &App) -> AnyElement { .into_any_element() } -pub(crate) fn commit_row( - ix: usize, - commit: &FileCommit, - action: Option, - on_click: impl Fn(&mut Window, &mut gpui::App) + 'static, - cx: &gpui::App, -) -> gpui::AnyElement { - h_flex() - .id(ix) - .px_4() - .h(px(COMMIT_ROW_HEIGHT)) - .w_full() - .gap_3() - .border_b_1() - .border_color(cx.theme().colors.border) - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_1() - .justify_center() - .child( - h_flex() - .gap_2() - .overflow_hidden() - .child( - div() - .font_family(cx.theme().mono_font) - .text_sm() - .text_color(cx.theme().colors.muted_foreground) - .child(short_id(&commit.id)), - ) - .child( - div() - .flex_1() - .min_w_0() - .text_sm() - .text_ellipsis() - .whitespace_nowrap() - .child(commit.summary.clone()), - ), - ) - .child( - h_flex() - .gap_2() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .child(commit.author.clone()) - .child(relative_time_secs(commit.time)), - ), - ) - .when_some(action, |row, action| row.child(action)) - .on_click(move |_, window, cx| on_click(window, cx)) - .into_any_element() -} - pub(super) fn sync_selector( select: &Entity>, cached: &mut Vec, diff --git a/crates/signed_app/src/repo/history.rs b/crates/signed_app/src/repo/history.rs index 2827ec4..9df0217 100644 --- a/crates/signed_app/src/repo/history.rs +++ b/crates/signed_app/src/repo/history.rs @@ -12,7 +12,9 @@ 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::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; +use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; @@ -159,7 +161,7 @@ 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") + Spinner::centered("commits-loading") } else if let Some(error) = self.error.clone() { let weak = cx.entity().downgrade(); v_flex() @@ -183,12 +185,12 @@ impl Render for RepoHistoryView { ) .into_any_element() } else { - crate::shared::widgets::empty_state("Failed to load commits") + EmptyState::centered("Failed to load commits") }; }; if self.commits.is_empty() { - return crate::shared::widgets::empty_state("No commits found"); + return EmptyState::centered("No commits found"); } let commits = Arc::clone(&self.commits); @@ -261,7 +263,6 @@ impl Render for RepoHistoryView { log::warn!("failed to open commit diff: {error}"); } }, - cx, ); v_flex() diff --git a/crates/signed_app/src/repo/mod.rs b/crates/signed_app/src/repo/mod.rs index 1654dfc..055d9a3 100644 --- a/crates/signed_app/src/repo/mod.rs +++ b/crates/signed_app/src/repo/mod.rs @@ -5,49 +5,58 @@ use anyhow::Error; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, - ParentElement as _, PathPromptOptions, Render, SharedString, Styled as _, Subscription, - SystemNotification, Task, WeakEntity, Window, div, + ParentElement as _, PathPromptOptions, Render, SharedString, StatefulInteractiveElement as _, + Styled as _, Subscription, SystemNotification, Task, WeakEntity, Window, div, px, }; use metadata::ProfileDirectory; use nostr::prelude::{PublicKey, Url}; use signed_core::{Announcement, RepoAddr}; use signed_git::{FileCommit, GitCache, Repo}; use signed_state::{ - Backend, BackendEvent, LocalReposStore, Mirrors, Nip34Binding, PushStepStatus, RepoStore, - SyncStatusDirectory, + Backend, BackendEvent, LocalReposStore, Mirrors, Nip34Binding, Nip34Kind, PushStepStatus, + RepoStore, SyncStatusDirectory, }; use ui::alert::{Alert, AlertSeverity}; use ui::avatar::Avatar; use ui::badge::Badge; use ui::button::{Button, ButtonVariant}; -use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::clipboard::CopyRow; +use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::dialog::Dialog; +use ui::dropdown_menu::DropdownMenu; use ui::icons::{Icon, IconRole}; use ui::layout::panel::Panel; +use ui::menu::MenuItem; +use ui::popover::Popover; use ui::sidebar::{Sidebar, SidebarEntry}; use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; +use ui::tooltip::Tooltip; pub mod actions; pub mod commit_diff; pub mod dialogs; pub mod files; -mod header; pub mod helpers; pub mod history; pub mod refs; use files::RepoFilesView; -use helpers::{RepoData, announcement_display_name, load_repo_data, snapshot_worktree}; +use helpers::{ + RepoData, announcement_display_name, bound_repo_label, clone_group, fork_row, + load_repo_data, nostr_clone_url, repo_display_name, snapshot_worktree, +}; use history::RepoHistoryView; use refs::RefSwitcher; +use utils::relative_time_secs; use crate::issues::IssuesView; use crate::pull_requests::PullRequestsView; use crate::shared::log_dropped; -use crate::shared::tree::sorted_worktree_paths; use crate::workspace::Workspace; +use crate::repo::helpers::{short_id, sorted_worktree_paths}; + #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum RepoSection { Files, @@ -193,7 +202,7 @@ impl RepoDetailView { let store_for_attach = store.clone(); window.defer(cx, move |window, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { this.attach_store(&store_for_attach, window, cx); this.load_repo(window, cx); })); @@ -828,7 +837,7 @@ impl RepoDetailView { match result { Ok(()) => { if let Some(tag) = &tag { - let short = crate::repo::helpers::short_id(&commit); + let short = 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}")), @@ -978,7 +987,7 @@ impl RepoDetailView { (Some(2), true) => RepoSection::PullRequests, _ => return, }; - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { this.active_section = section; cx.notify(); })); @@ -1028,6 +1037,434 @@ impl RepoDetailView { RepoSection::PullRequests => self.pulls.clone().into_any_element(), } } + + pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context) { + let Some(addr) = self + .announcement(cx) + .and_then(|announcement| announcement.upstream.as_ref()) + .and_then(|upstream| upstream.addr.clone()) + else { + return; + }; + + actions::open_repo_panel(&self.workspace, &addr, None, window, cx); + } + + /// Open the dialog that publishes the local repository to NIP-34. + fn open_init_dialog(&mut self, window: &mut Window, cx: &mut Context) { + let Some(local_path) = self.store.read(cx).path.clone() else { + return; + }; + self.init = Some(dialogs::init::InitRepoDialog::new( + local_path, + cx.entity().downgrade(), + window, + cx, + )); + cx.notify(); + } + + pub(super) fn render_about(&mut self, cx: &mut Context) -> AnyElement { + if self.store.read(cx).addr().is_none() { + return self.render_init_banner(cx); + } + + let backend = Backend::global(cx); + let store = self.store.read(cx); + let pushing = store.pushing; + let cloning = store.cloning; + + let Some(announcement) = store.announcement.clone() else { + return div().into_any_element(); + }; + + let nip05 = self + .directory + .read(cx) + .profile(&announcement.owner, cx) + .metadata() + .nip05 + .clone() + .filter(|nip05| !nip05.trim().is_empty()); + + let nostr_url = nostr_clone_url(&announcement, nip05.as_deref()); + let ngit_command = SharedString::from(format!("git clone {nostr_url}")); + let nak_command = SharedString::from(format!("nak git clone {nostr_url}")); + let git_commands: Vec = announcement.clone_urls(); + + let name = repo_display_name(self.store.read(cx)); + let description = announcement.description(); + let avatar = Avatar::new(format!("{}:{}", announcement.owner, announcement.id)); + + let announcement_for_menu = announcement.clone(); + let weak_menu_open = cx.entity().downgrade(); + let weak_menu_items = cx.entity().downgrade(); + let weak_clone = cx.entity().downgrade(); + let weak_download = cx.entity().downgrade(); + let ngit_for_popover = ngit_command.clone(); + let nak_for_popover = nak_command.clone(); + let git_for_popover = git_commands.clone(); + + h_flex() + .p_6() + .w_full() + .gap_6() + .items_start() + .justify_between() + .child( + v_flex() + .flex_1() + .min_w_0() + .gap_2() + .child( + h_flex() + .gap_2() + .text_sm() + .font_semibold() + .child(avatar) + .child(name), + ) + .child( + div() + .min_w_0() + .text_sm() + .text_color(cx.theme().colors.muted_foreground) + .line_clamp(3) + .child(description), + ) + .when_some(fork_row(&announcement, cx), |this, row| this.child(row)), + ) + .child( + h_flex() + .flex_none() + .gap_2() + .justify_end() + .child( + Popover::new("code-popover") + .open(self.clone_open) + .on_change(move |open, _, cx| { + if let Err(error) = weak_clone.update(cx, |this, cx| { + this.clone_open = open; + cx.notify(); + }) { + log::warn!("failed to update clone popover: {error}"); + } + }) + .trigger(move |_, _| { + Button::new("code") + .label("Code") + .icon(Icon::named(IconRole::GitClone)) + .tooltip(Tooltip::text("Clone repository")) + .loading(cloning) + .disabled(cloning) + .into_any_element() + }) + .content(move |_, cx| { + v_flex() + .w(px(440.)) + .p_3() + .gap_4() + .child(clone_group( + "Clone with ngit", + "copy-ngit".into(), + &ngit_for_popover, + )) + .child(clone_group( + "Clone with nak", + "copy-nak".into(), + &nak_for_popover, + )) + .child( + v_flex() + .gap_1() + .child( + div() + .text_xs() + .font_semibold() + .child("Grasp Servers"), + ) + .when(git_for_popover.is_empty(), |this| { + this.child( + div() + .text_xs() + .text_center() + .text_color( + cx.theme().colors.muted_foreground, + ) + .child("No git clone urls."), + ) + }) + .children(git_for_popover.iter().enumerate().map( + |(ix, command)| { + CopyRow::new( + SharedString::from(format!( + "copy-git-{ix}" + )), + command.clone(), + ) + }, + )), + ) + .child( + h_flex().justify_end().child( + Button::new("download") + .icon(Icon::named(IconRole::GitClone)) + .label("Download") + .on_click({ + let weak = weak_download.clone(); + move |_, window, cx| { + if let Err(error) = + weak.update(cx, |this, cx| { + this.clone_to_folder(window, cx); + }) + { + log::warn!("failed to clone: {error}"); + } + } + }), + ), + ) + .into_any_element() + }), + ) + .child( + DropdownMenu::new("repo-menu") + .icon(IconRole::EllipsisVertical) + .variant(ButtonVariant::Ghost) + .disabled(pushing) + .open(self.repo_menu_open) + .on_open_change(move |open, _, cx| { + if let Err(error) = weak_menu_open.update(cx, |this, cx| { + this.repo_menu_open = open; + cx.notify(); + }) { + log::warn!("failed to update repo menu: {error}"); + } + }) + .items(move |_, cx| { + let owner = backend.read(cx).current_user() + == Some(announcement_for_menu.owner); + + let mut items = vec![MenuItem::new("About").handler({ + let weak = weak_menu_items.clone(); + let announcement = announcement_for_menu.clone(); + move |_, cx| { + if let Err(error) = weak.update(cx, |this, cx| { + this.about = Some(dialogs::about::AboutDialog::new( + announcement.clone(), + this.directory.clone(), + cx, + )); + cx.notify(); + }) { + log::warn!("failed to open about: {error}"); + } + } + })]; + + if owner { + items.push(MenuItem::new("Republish").handler({ + let weak = weak_menu_items.clone(); + move |window, cx| { + if let Err(error) = weak.update(cx, |this, cx| { + this.push_repository(window, cx); + }) { + log::warn!("failed to republish: {error}"); + } + } + })); + items.push(MenuItem::new("Reset remote to local").handler({ + let weak = weak_menu_items.clone(); + move |window, cx| { + if let Err(error) = weak.update(cx, |this, cx| { + this.reset_remote(window, cx); + }) { + log::warn!("failed to reset remote: {error}"); + } + } + })); + items.push(MenuItem::separator()); + items.push(MenuItem::new("Delete").destructive(true).handler( + { + let weak = weak_menu_items.clone(); + move |window, cx| { + if let Err(error) = weak.update(cx, |this, cx| { + this.delete_repository(window, cx); + }) { + log::warn!("failed to delete: {error}"); + } + } + }, + )); + } + + items + }), + ), + ) + .into_any_element() + } + + fn render_init_banner(&self, cx: &mut Context) -> AnyElement { + let binding = self + .store + .read(cx) + .nip34 + .as_ref() + .filter(|binding| binding.kind == Nip34Kind::Initialized); + + let path = self + .store + .read(cx) + .path + .as_ref() + .map(|path| path.display().to_string()) + .unwrap_or_default(); + + v_flex() + .flex_none() + .p_6() + .h_32() + .w_full() + .items_center() + .justify_center() + .gap_2() + .map(|this| match binding { + Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)), + None => this.child( + Button::new("init") + .icon(Icon::named(IconRole::ArrowUp)) + .label("Initialize on Nostr") + .tooltip(Tooltip::text("Publish this repository to Nostr")) + .on_click(cx.listener(|this, _, window, cx| { + this.open_init_dialog(window, cx); + })), + ), + }) + .child( + div() + .min_w_0() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child(path), + ) + .into_any_element() + } + + pub(super) fn render_metadata(&self, cx: &mut Context) -> AnyElement { + h_flex() + .px_6() + .h_12() + .w_full() + .gap_4() + .items_center() + .justify_between() + .child(self.render_maintainers(cx)) + .child(self.render_ref_controls(cx)) + .into_any_element() + } + + fn render_ref_controls(&self, cx: &mut Context) -> AnyElement { + h_flex() + .justify_end() + .flex_none() + .gap_2() + .when_some(self.render_last_commit(cx), |this, commit| { + this.child(commit) + }) + .child(self.refs.branch_select.clone()) + .child(self.refs.tag_select.clone()) + .into_any_element() + } + + fn render_last_commit(&self, cx: &mut Context) -> Option { + let commit = self.head_commit.as_ref()?; + let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned(); + let history = self.history.clone(); + let commit_id = commit.id.clone(); + + Some( + h_flex() + .id("last-commit") + .h_8() + .px_2() + .gap_2() + .min_w_0() + .rounded(cx.theme().radius.control) + .hover(|this| this.bg(cx.theme().colors.muted_hover)) + .tooltip(Tooltip::text("View latest commit")) + .on_click(move |_, window, cx| { + history.update(cx, |history, cx| { + history.open_commit_diff(&commit_id, window, cx); + }); + }) + .child(Icon::named(IconRole::GitCommit).color(cx.theme().colors.muted_foreground)) + .child( + div() + .font_family(cx.theme().mono_font) + .text_sm() + .text_color(cx.theme().colors.muted_foreground) + .child(SharedString::from(short)), + ) + .child( + div() + .max_w(px(220.)) + .text_sm() + .text_ellipsis() + .whitespace_nowrap() + .child(commit.summary.clone()), + ) + .child( + div() + .text_sm() + .text_color(cx.theme().colors.muted_foreground) + .child(relative_time_secs(commit.time)), + ) + .into_any_element(), + ) + } + + fn render_maintainers(&self, cx: &mut Context) -> AnyElement { + let Some(announcement) = self.announcement(cx) else { + return div().into_any_element(); + }; + + let mut seen = HashSet::new(); + + let rest: Vec<_> = announcement + .maintainers + .iter() + .copied() + .filter(|key| key != &announcement.owner && seen.insert(*key)) + .collect(); + + let owner = self.directory.read(cx).profile(&announcement.owner, cx); + let owner_name = owner.name(); + + h_flex() + .min_w_0() + .gap_2() + .child( + h_flex() + .gap_2() + .child( + Avatar::new(announcement.owner) + .name(owner_name.clone()) + .picture(owner.picture()) + .small(), + ) + .child(div().text_xs().whitespace_nowrap().child(owner_name)), + ) + .when(!rest.is_empty(), |this| { + this.child( + div() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child(SharedString::from(format!("+{}", rest.len()))), + ) + }) + .into_any_element() + } } impl Panel for RepoDetailView { diff --git a/crates/signed_app/src/settings/helpers.rs b/crates/signed_app/src/settings/helpers.rs index e98838d..17e30f2 100644 --- a/crates/signed_app/src/settings/helpers.rs +++ b/crates/signed_app/src/settings/helpers.rs @@ -1,11 +1,11 @@ use std::path::PathBuf; use gpui::{ - AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, PathPromptOptions, - SharedString, Styled as _, Window, div, px, + AnyElement, App, AppContext as _, Div, Entity, IntoElement, ParentElement as _, + PathPromptOptions, SharedString, Styled as _, Window, div, px, }; use settings::{AppearanceMode, EventFetchingStrategy, SettingsStore}; -use ui::button::Button; +use ui::button::{Button, ButtonVariant}; use ui::common::{StyledExt as _, h_flex, v_flex}; use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState}; @@ -13,8 +13,26 @@ use ui::select::{Select, SelectOption}; use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; +use crate::apply_appearance_mode; use crate::repo::dialogs::grasp_servers::{normalize_server, server_host}; +/// The title and description a settings row or block opens with. +fn setting_header( + cx: &App, + title: impl Into, + description: impl Into, +) -> Div { + v_flex() + .gap_1() + .child(div().text_sm().font_semibold().child(title.into())) + .child( + div() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child(description.into()), + ) +} + /// A settings row with the label and description on the left and the control on the right. pub fn setting_row( cx: &App, @@ -26,19 +44,7 @@ pub fn setting_row( .w_full() .justify_between() .gap_4() - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_1() - .child(div().text_sm().font_semibold().child(title.into())) - .child( - div() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .child(description.into()), - ), - ) + .child(setting_header(cx, title, description)) .child(div().w(px(200.)).flex_shrink_0().child(control)) .into_any_element() } @@ -53,17 +59,7 @@ pub fn setting_block( v_flex() .w_full() .gap_3() - .child( - v_flex() - .gap_1() - .child(div().text_sm().font_semibold().child(title.into())) - .child( - div() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .child(description.into()), - ), - ) + .child(setting_header(cx, title, description)) .child(control) .into_any_element() } @@ -84,7 +80,7 @@ pub fn appearance_select(cx: &App) -> Select { SettingsStore::global(cx).update(cx, |store, cx| { store.edit(|settings| settings.appearance = mode, cx); }); - crate::apply_appearance_mode(mode, cx); + apply_appearance_mode(mode, cx); }) } @@ -106,6 +102,36 @@ pub fn event_fetching_select(cx: &App) -> Select { }) } +/// One editable value: a muted row with a trailing remove button. +fn editor_value_row( + id: String, + text: SharedString, + on_remove: impl Fn(&mut App) + 'static, + cx: &App, +) -> AnyElement { + h_flex() + .gap_1() + .child( + h_flex() + .flex_1() + .h_8() + .px_2() + .bg(cx.theme().colors.muted) + .text_color(cx.theme().colors.muted_foreground) + .text_xs() + .rounded(cx.theme().radius.control) + .child(text), + ) + .child( + Button::new(id) + .icon(Icon::named(IconRole::Close)) + .variant(ButtonVariant::Ghost) + .tooltip(Tooltip::text("Remove")) + .on_click(move |_, _, cx| on_remove(cx)), + ) + .into_any_element() +} + pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement { let store = SettingsStore::global(cx); let servers = store @@ -119,48 +145,30 @@ pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement .gap_2() .children(servers.iter().enumerate().map(|(ix, server)| { let server = server.clone(); - h_flex() - .gap_1() - .child( - h_flex() - .flex_1() - .h_8() - .px_2() - .bg(cx.theme().colors.muted) - .text_color(cx.theme().colors.muted_foreground) - .text_xs() - .rounded(cx.theme().radius.control) - .child(display_server(&server)), - ) - .child( - Button::new(format!("settings-remove-server:{ix}")) - .icon(Icon::named(IconRole::Close)) - .variant(ui::button::ButtonVariant::Ghost) - .tooltip(Tooltip::text("Remove")) - .on_click({ - let store = store.clone(); - move |_, _, cx| { - store.update(cx, |store, cx| { - store.edit( - |settings| { - // 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, - ); - }); - } - }), - ) - .into_any_element() + editor_value_row( + format!("settings-remove-server:{ix}"), + display_server(&server), + move |cx| { + let store = SettingsStore::global(cx); + store.update(cx, |store, cx| { + store.edit( + |settings| { + // A row's index can desync after a prior removal; match by value. + if let Some(at) = settings + .grasp_servers + .default_servers + .iter() + .position(|known| known == &server) + { + settings.grasp_servers.default_servers.remove(at); + } + }, + cx, + ); + }); + }, + cx, + ) })) .child( h_flex() @@ -173,7 +181,7 @@ pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement .child( Button::new("settings-add-server") .icon(Icon::named(IconRole::Plus)) - .variant(ui::button::ButtonVariant::Ghost) + .variant(ButtonVariant::Ghost) .tooltip(Tooltip::text("Add grasp server")) .on_click({ let input = input.clone(); @@ -229,46 +237,30 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement { .gap_2() .children(scan_paths.iter().enumerate().map(|(ix, path)| { let path = path.clone(); - h_flex() - .gap_1() - .child( - h_flex() - .flex_1() - .h_8() - .px_2() - .bg(cx.theme().colors.muted) - .text_color(cx.theme().colors.muted_foreground) - .text_xs() - .rounded(cx.theme().radius.control) - .child(path.display().to_string()), - ) - .child( - Button::new(format!("settings-remove-path:{ix}")) - .icon(Icon::named(IconRole::Close)) - .variant(ui::button::ButtonVariant::Ghost) - .tooltip(Tooltip::text("Remove")) - .on_click(move |_, _, cx| { - let store = SettingsStore::global(cx); - store.update(cx, |store, cx| { - store.edit( - |settings| { - // 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, - ); - }); - }), - ) - .into_any_element() + editor_value_row( + format!("settings-remove-path:{ix}"), + SharedString::from(path.display().to_string()), + move |cx| { + let store = SettingsStore::global(cx); + store.update(cx, |store, cx| { + store.edit( + |settings| { + // A row's index can desync after a prior removal; match by value. + if let Some(at) = settings + .local_repos + .scan_paths + .iter() + .position(|known| known == &path) + { + settings.local_repos.scan_paths.remove(at); + } + }, + cx, + ); + }); + }, + cx, + ) })) .child( h_flex().justify_end().child( @@ -328,7 +320,7 @@ pub fn default_folder_selector(default_folder: &Entity) -> AnyElemen .child( Button::new("settings-choose-folder") .icon(Icon::named(IconRole::Folder)) - .variant(ui::button::ButtonVariant::Ghost) + .variant(ButtonVariant::Ghost) .tooltip(Tooltip::text("Choose folder")) .on_click(move |_, window, cx| { choose_default_folder(&folder, window, cx); diff --git a/crates/signed_app/src/shared/event_list.rs b/crates/signed_app/src/shared/event_list.rs index f602d7c..8d63d90 100644 --- a/crates/signed_app/src/shared/event_list.rs +++ b/crates/signed_app/src/shared/event_list.rs @@ -15,30 +15,22 @@ use signed_core::RepoStatus; use signed_git::FileCommit; use ui::avatar::Avatar; use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::empty_state::EmptyState; +use ui::scrollbar::Scrollbar; use ui::theme::ActiveTheme as _; +use utils::relative_time_secs; -use crate::repo::helpers::commit_row; -use crate::shared::widgets::{empty_state, scroll_overlay, status_badge}; +use crate::repo::helpers::short_id; +use crate::shared::widgets::status_badge; /// The height of one issue or pull-request row. pub const ROW_HEIGHT: f32 = 73.; +/// The height of one commit row in the commit list. +pub const COMMIT_ROW_HEIGHT: f32 = 56.; /// 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, @@ -52,8 +44,68 @@ pub struct EventRow { pub on_click: EventHandler, } -/// The shared issue and pull-request list: toolbar, uniform rows, scrollbar -/// overlay, and empty state. +impl EventRow { + /// Renders one issue or pull-request row. + fn render(&self, row_height: Pixels, cx: &App) -> AnyElement { + h_flex() + .id(self.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 = self.on_click.clone(); + move |event, window, cx| on_click(event, window, cx) + }) + .child(status_badge(self.status)) + .child( + v_flex() + .flex_1() + .min_w_0() + .gap_1() + .child( + div() + .text_base() + .text_ellipsis() + .whitespace_nowrap() + .child(self.title.clone()), + ) + .child(self.meta_row(cx)), + ) + .into_any_element() + } + + /// The author, age, and id line under a row's title. + fn meta_row(&self, cx: &App) -> AnyElement { + h_flex() + .gap_2() + .text_xs() + .child( + h_flex() + .gap_1() + .child( + Avatar::new(self.pubkey) + .name(self.author.clone()) + .picture(self.picture.clone()) + .small(), + ) + .child(div().child(self.author.clone())), + ) + .child(SharedString::from("opened")) + .child( + div() + .text_color(cx.theme().colors.muted_foreground) + .child(self.short_id.clone()), + ) + .child(self.age.clone()) + .into_any_element() + } +} + +/// The shared issue and pull-request list, pub struct EventList { id: ElementId, toolbar: Option, @@ -118,86 +170,39 @@ impl EventList { let Some(row) = rows.get(ix) else { return div().into_any_element(); }; - event_row(row, row_height, cx) + row.render(row_height, cx) }) .collect() }) .track_scroll(&self.scroll_handle) .size_full(), ) - .child(scroll_overlay( + .child(Scrollbar::vertical( (self.id.clone(), "scroll"), self.scroll_handle.clone(), )) }) .when(count == 0, |this| { - this.child(empty_state(self.empty_message)) + this.child(EmptyState::centered(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 { +/// 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() - .id(row.id.clone()) - .w_full() - .h(row_height) - .gap_4() .px_4() + .w_full() + .gap_3() .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()) + .bg(cx.theme().colors.muted) + .children(children) .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, @@ -205,7 +210,6 @@ pub fn commit_list( 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(); @@ -234,6 +238,64 @@ pub fn commit_list( .track_scroll(&scroll_handle) .size_full(), ) - .child(scroll_overlay(scroll_id, scroll_handle)) + .child(Scrollbar::vertical(scroll_id, scroll_handle)) + .into_any_element() +} + +/// One copyable commit summary row: id, subject, author, and age. +pub(crate) fn commit_row( + ix: usize, + commit: &FileCommit, + action: Option, + on_click: impl Fn(&mut Window, &mut gpui::App) + 'static, + cx: &gpui::App, +) -> gpui::AnyElement { + h_flex() + .id(ix) + .px_4() + .h(px(COMMIT_ROW_HEIGHT)) + .w_full() + .gap_3() + .border_b_1() + .border_color(cx.theme().colors.border) + .hover(|this| this.bg(cx.theme().colors.muted_hover)) + .child( + v_flex() + .flex_1() + .min_w_0() + .gap_1() + .justify_center() + .child( + h_flex() + .gap_2() + .overflow_hidden() + .child( + div() + .font_family(cx.theme().mono_font) + .text_sm() + .text_color(cx.theme().colors.muted_foreground) + .child(short_id(&commit.id)), + ) + .child( + div() + .flex_1() + .min_w_0() + .text_sm() + .text_ellipsis() + .whitespace_nowrap() + .child(commit.summary.clone()), + ), + ) + .child( + h_flex() + .gap_2() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child(commit.author.clone()) + .child(relative_time_secs(commit.time)), + ), + ) + .when_some(action, |row, action| row.child(action)) + .on_click(move |_, window, cx| on_click(window, cx)) .into_any_element() } diff --git a/crates/signed_app/src/shared/mod.rs b/crates/signed_app/src/shared/mod.rs index 4c39d39..c520504 100644 --- a/crates/signed_app/src/shared/mod.rs +++ b/crates/signed_app/src/shared/mod.rs @@ -5,7 +5,7 @@ use nostr::prelude::PublicKey; pub mod event_list; pub mod panels; pub mod progress; -pub mod tree; + pub mod widgets; /// Logs a discarded `Result` with its source location instead of dropping it silently. diff --git a/crates/signed_app/src/shared/panels.rs b/crates/signed_app/src/shared/panels.rs index 4912f36..140dc46 100644 --- a/crates/signed_app/src/shared/panels.rs +++ b/crates/signed_app/src/shared/panels.rs @@ -5,6 +5,86 @@ use ui::layout::panel::{Panel, PanelView}; use crate::workspace::Workspace; +/// Which slot of the workspace a panel opens into. +#[derive(Clone, Copy)] +enum PanelSlot { + Main, + Detail, +} + +impl PanelSlot { + /// Whether the slot already holds a panel under `id`. + fn has(self, workspace: &WeakEntity, id: &SharedString, cx: &App) -> bool { + match self { + PanelSlot::Main => workspace + .read_with(cx, |workspace, _| workspace.has_main(id)) + .unwrap_or(false), + PanelSlot::Detail => workspace + .read_with(cx, |workspace, _| workspace.has_detail(id)) + .unwrap_or(false), + } + } + + /// Activates the slot's cached panel under `id`. + fn activate(self, workspace: &WeakEntity, id: &SharedString, cx: &mut App) { + let result = match self { + PanelSlot::Main => { + workspace.update(cx, |workspace, cx| workspace.activate_main(id, cx)) + } + PanelSlot::Detail => { + workspace.update(cx, |workspace, cx| workspace.activate_detail(id, cx)) + } + }; + if let Err(error) = result { + log::warn!("failed to activate panel {id}: {error}"); + } + } + + /// Shows the panel in the slot. + fn show( + self, + workspace: &WeakEntity, + id: SharedString, + view: Arc, + cx: &mut App, + ) { + let result = match self { + PanelSlot::Main => { + workspace.update(cx, |workspace, cx| workspace.show_main(id, view, cx)) + } + PanelSlot::Detail => { + workspace.update(cx, |workspace, cx| workspace.show_detail(id, view, cx)) + } + }; + if let Err(error) = result { + log::warn!("failed to open panel: {error}"); + } + } +} + +/// Opens a panel in `slot`, reusing it when it is already cached. +fn open_slot( + slot: PanelSlot, + workspace: &WeakEntity, + id: impl Into, + build: F, + window: &mut Window, + cx: &mut App, +) where + P: Panel + 'static, + F: Fn(&mut Window, &mut App) -> Entity

+ 'static, +{ + let id = id.into(); + + if slot.has(workspace, &id, cx) { + slot.activate(workspace, &id, cx); + return; + } + + let view: Arc = Arc::new(build(window, cx)); + slot.show(workspace, id, view, cx); +} + /// Opens a repository in the main panel, reusing it when it is already cached. pub fn open_primary( workspace: &WeakEntity, @@ -16,25 +96,14 @@ pub fn open_primary( P: Panel + 'static, F: Fn(&mut Window, &mut App) -> Entity

+ 'static, { - let id = id.into(); - - if workspace - .read_with(cx, |workspace, _| workspace.has_main(&id)) - .unwrap_or(false) - { - if let Err(error) = workspace.update(cx, |workspace, cx| workspace.activate_main(&id, cx)) { - log::warn!("failed to activate repository {id}: {error}"); - } - return; - } - - let view: Arc = Arc::new(build(window, cx)); - - if let Err(error) = workspace.update(cx, |workspace, cx| { - workspace.show_main(id.clone(), view, cx) - }) { - log::warn!("failed to open repository {id}: {error}"); - } + open_slot( + PanelSlot::Main, + workspace, + id, + build, + window, + cx, + ); } /// Opens a detail panel beside the main panel, reusing it when it is already cached. @@ -48,24 +117,12 @@ pub fn open_detail( P: Panel + 'static, F: Fn(&mut Window, &mut App) -> Entity

+ 'static, { - let id = id.into(); - - if workspace - .read_with(cx, |workspace, _| workspace.has_detail(&id)) - .unwrap_or(false) - { - if let Err(error) = workspace.update(cx, |workspace, cx| workspace.activate_detail(&id, cx)) - { - log::warn!("failed to activate detail panel {id}: {error}"); - } - return; - } - - let view: Arc = Arc::new(build(window, cx)); - - if let Err(error) = workspace.update(cx, |workspace, cx| { - workspace.show_detail(id.clone(), view, cx) - }) { - log::warn!("failed to open detail panel {id}: {error}"); - } + open_slot( + PanelSlot::Detail, + workspace, + id, + build, + window, + cx, + ); } diff --git a/crates/signed_app/src/shared/progress.rs b/crates/signed_app/src/shared/progress.rs index b633245..4a148af 100644 --- a/crates/signed_app/src/shared/progress.rs +++ b/crates/signed_app/src/shared/progress.rs @@ -1,15 +1,45 @@ use gpui::{ AnyElement, App, AsyncApp, Context, Entity, IntoElement as _, ParentElement as _, SharedString, - Styled as _, Subscription, Task, div, + Styled as _, Subscription, Task, WeakEntity, Window, div, }; use signed_core::RepoAddr; use signed_state::{Backend, BackendEvent, PushStepStatus}; +use ui::button::Button; 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 _; +use super::log_dropped; + +/// The dialog's submit button: loading/disabled while busy, closing over the dialog's submit. +pub fn dialog_submit_button( + id: &'static str, + label: impl Into, + icon: Option, + busy: bool, + this: &WeakEntity, + submit: F, +) -> Button +where + T: 'static, + F: Fn(&mut T, &mut Window, &mut Context) -> Result<(), anyhow::Error> + 'static, +{ + let mut button = Button::new(id).label(label); + if let Some(icon) = icon { + button = button.icon(Icon::named(icon)); + } + + let this = this.clone(); + button + .loading(busy) + .disabled(busy) + .on_click(move |_, window, cx| { + log_dropped(this.update(cx, |this, cx| submit(this, window, cx))); + }) +} + /// Progress of an async dialog action: a busy flag that disables the form and an error shown below it. #[derive(Debug, Default)] pub struct DialogProgress { diff --git a/crates/signed_app/src/shared/tree.rs b/crates/signed_app/src/shared/tree.rs deleted file mode 100644 index d1f38bf..0000000 --- a/crates/signed_app/src/shared/tree.rs +++ /dev/null @@ -1,188 +0,0 @@ -use std::collections::{HashMap, HashSet}; -use std::path::PathBuf; - -pub struct TreeItemSeed { - /// Path of the node, relative to the worktree root. - pub id: String, - pub label: String, - pub children: Vec, -} - -/// One visible row of the flattened tree. -#[derive(Clone)] -pub struct TreeRow { - pub id: String, - pub label: String, - pub depth: usize, - pub expandable: bool, - pub expanded: bool, -} - -/// Flattens the seeds into the rows a flat tree renders, honoring `expanded`. -pub fn flatten(seeds: &[TreeItemSeed], expanded: &HashSet) -> Vec { - fn push( - seed: &TreeItemSeed, - depth: usize, - expanded: &HashSet, - rows: &mut Vec, - ) { - let is_expanded = expanded.contains(&seed.id); - rows.push(TreeRow { - id: seed.id.clone(), - label: seed.label.clone(), - depth, - expandable: !seed.children.is_empty(), - expanded: is_expanded, - }); - - if is_expanded { - for child in &seed.children { - push(child, depth + 1, expanded, rows); - } - } - } - - let mut rows = Vec::new(); - for seed in seeds { - push(seed, 0, expanded, &mut rows); - } - rows -} - -/// Every folder id, for starting with the tree fully expanded. -pub fn collect_expanded(seeds: &[TreeItemSeed]) -> HashSet { - fn push(seed: &TreeItemSeed, expanded: &mut HashSet) { - if !seed.children.is_empty() { - expanded.insert(seed.id.clone()); - for child in &seed.children { - push(child, expanded); - } - } - } - - let mut expanded = HashSet::new(); - for seed in seeds { - push(seed, &mut expanded); - } - expanded -} - -/// Build nested tree items from a flat entry list sorted dirs-first. -pub fn build_tree_items(entries: &[PathBuf]) -> Vec { - // Node indices by full path, so parents resolve in constant time while inserting. - let mut index: HashMap = HashMap::new(); - let mut nodes: Vec<(String, String, Vec)> = Vec::new(); - let mut roots: Vec = Vec::new(); - - for entry in entries { - let mut parent: Option = None; - let mut path = String::new(); - for part in entry.components() { - let label = part.as_os_str().to_string_lossy().into_owned(); - path = if path.is_empty() { - label.clone() - } else { - format!("{path}/{label}") - }; - let ix = *index.entry(path.clone()).or_insert_with(|| { - let ix = nodes.len(); - nodes.push((path.clone(), label.clone(), Vec::new())); - match parent { - Some(parent) => nodes[parent].2.push(ix), - None => roots.push(ix), - } - ix - }); - parent = Some(ix); - } - } - - fn assemble(ix: usize, nodes: &[(String, String, Vec)]) -> TreeItemSeed { - let (id, label, children) = &nodes[ix]; - TreeItemSeed { - id: id.clone(), - label: label.clone(), - children: children - .iter() - .map(|child| assemble(*child, nodes)) - .collect(), - } - } - - roots.iter().map(|root| assemble(*root, &nodes)).collect() -} - -/// Sorted relative paths of a worktree snapshot. -pub fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec { - let mut paths: Vec = entries - .iter() - .map(|path| path.to_string_lossy().into_owned()) - .collect(); - paths.sort(); - paths -} - -#[cfg(test)] -mod tests { - use super::*; - - fn ids(rows: &[TreeRow]) -> Vec<(&str, usize)> { - rows.iter() - .map(|row| (row.id.as_str(), row.depth)) - .collect() - } - - #[test] - fn collapsed_folders_hide_children() { - let seeds = build_tree_items(&[ - PathBuf::from("src"), - PathBuf::from("src/lib.rs"), - PathBuf::from("README.md"), - ]); - - let rows = flatten(&seeds, &HashSet::new()); - - assert_eq!(ids(&rows), vec![("src", 0), ("README.md", 0)]); - assert!(rows[0].expandable); - assert!(!rows[0].expanded); - } - - #[test] - fn expanding_a_folder_shows_children_in_order() { - let seeds = build_tree_items(&[ - PathBuf::from("src"), - PathBuf::from("src/lib.rs"), - PathBuf::from("src/views/mod.rs"), - PathBuf::from("README.md"), - ]); - let expanded = HashSet::from(["src".to_owned(), "src/views".to_owned()]); - - let rows = flatten(&seeds, &expanded); - - assert_eq!( - ids(&rows), - vec![ - ("src", 0), - ("src/lib.rs", 1), - ("src/views", 1), - ("src/views/mod.rs", 2), - ("README.md", 0), - ] - ); - } - - #[test] - fn indices_map_to_row_ids() { - let seeds = build_tree_items(&[ - PathBuf::from("docs"), - PathBuf::from("docs/guide.md"), - PathBuf::from("README.md"), - ]); - let expanded = HashSet::from(["docs".to_owned()]); - let rows = flatten(&seeds, &expanded); - - assert_eq!(rows[0].id, "docs"); - assert_eq!(rows[1].id, "docs/guide.md"); - assert_eq!(rows[2].id, "README.md"); - } -} diff --git a/crates/signed_app/src/shared/widgets.rs b/crates/signed_app/src/shared/widgets.rs index 8783a6f..0014432 100644 --- a/crates/signed_app/src/shared/widgets.rs +++ b/crates/signed_app/src/shared/widgets.rs @@ -1,15 +1,6 @@ -use gpui::{ - AnyElement, App, ElementId, IntoElement, ParentElement as _, SharedString, Styled as _, div, -}; use signed_core::RepoStatus; use ui::badge::{Badge, BadgeVariant}; -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; /// The status pill shown on issue and pull-request rows. @@ -26,75 +17,3 @@ pub fn status_badge(status: RepoStatus) -> Badge { .icon(Icon::named(icon)) .tooltip(Tooltip::text(label)) } - -/// A centered empty-state message filling the available space. -pub fn empty_state(message: impl Into) -> AnyElement { - let message = message.into(); - v_flex() - .size_full() - .items_center() - .justify_center() - .child(EmptyState::new(message)) - .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() - .text_xs() - .font_medium() - .text_color(cx.theme().colors.muted_foreground) - .child(text.into()) - .into_any_element() -} diff --git a/crates/signed_app/src/titlebar/mod.rs b/crates/signed_app/src/titlebar/mod.rs index bc3ad64..19eb66b 100644 --- a/crates/signed_app/src/titlebar/mod.rs +++ b/crates/signed_app/src/titlebar/mod.rs @@ -56,49 +56,6 @@ pub(crate) struct SwitchRepository { #[action(namespace = signed, no_json)] pub(crate) struct CreateRepository; -pub(crate) fn bind_repository_shortcuts(cx: &mut App) { - let context = match KeyBindingContextPredicate::parse(REPOSITORY_KEY_CONTEXT) { - Ok(context) => Some(Rc::new(context)), - Err(error) => { - log::error!("failed to parse repository key context: {error}"); - return; - } - }; - - let bindings = REPOSITORY_KEYSTROKES - .into_iter() - .enumerate() - .map(|(index, keystroke)| { - KeyBinding::load( - keystroke, - Box::new(SwitchRepository { index }), - context.clone(), - false, - None, - cx, - ) - }) - .chain(std::iter::once(KeyBinding::load( - CREATE_KEYSTROKE, - Box::new(CreateRepository), - context.clone(), - false, - None, - cx, - ))) - .collect::, _>>(); - - let bindings = match bindings { - Ok(bindings) => bindings, - Err(error) => { - log::error!("failed to parse repository shortcut keystrokes: {error}"); - return; - } - }; - - cx.bind_keys(bindings); -} - pub struct TitlebarView { weak: WeakEntity, workspace: WeakEntity, @@ -626,3 +583,46 @@ fn local_key(entry: &ResolvedLocalRepo) -> SharedString { None => SharedString::from(format!("repo-local:{}", entry.path.display())), } } + +pub(crate) fn bind_repository_shortcuts(cx: &mut App) { + let context = match KeyBindingContextPredicate::parse(REPOSITORY_KEY_CONTEXT) { + Ok(context) => Some(Rc::new(context)), + Err(error) => { + log::error!("failed to parse repository key context: {error}"); + return; + } + }; + + let bindings = REPOSITORY_KEYSTROKES + .into_iter() + .enumerate() + .map(|(index, keystroke)| { + KeyBinding::load( + keystroke, + Box::new(SwitchRepository { index }), + context.clone(), + false, + None, + cx, + ) + }) + .chain(std::iter::once(KeyBinding::load( + CREATE_KEYSTROKE, + Box::new(CreateRepository), + context.clone(), + false, + None, + cx, + ))) + .collect::, _>>(); + + let bindings = match bindings { + Ok(bindings) => bindings, + Err(error) => { + log::error!("failed to parse repository shortcut keystrokes: {error}"); + return; + } + }; + + cx.bind_keys(bindings); +} diff --git a/crates/ui/src/components/alert.rs b/crates/ui/src/components/alert.rs index 13af3f0..6f4ce9f 100644 --- a/crates/ui/src/components/alert.rs +++ b/crates/ui/src/components/alert.rs @@ -269,7 +269,7 @@ impl RenderOnce for Alert { /// One pushed alert, with its identity in the stack. #[derive(Clone)] -pub struct AlertEntry { +struct AlertEntry { /// The id [`Alerts::push`] returned. pub id: usize, /// The alert as pushed. @@ -338,14 +338,9 @@ impl Alerts { } /// The stacked alerts, oldest first. - pub fn entries(&self) -> &[AlertEntry] { + fn entries(&self) -> &[AlertEntry] { &self.entries } - - /// How many alerts are stacked. - pub fn count(&self) -> usize { - self.entries.len() - } } /// The floating stack of pushed alerts, topmost right. diff --git a/crates/ui/src/components/avatar.rs b/crates/ui/src/components/avatar.rs index 1c2eb80..22279da 100644 --- a/crates/ui/src/components/avatar.rs +++ b/crates/ui/src/components/avatar.rs @@ -14,6 +14,7 @@ use std::collections::HashMap; use std::fmt::Display; +use gpui::prelude::FluentBuilder as _; use gpui::{ App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div, @@ -140,6 +141,78 @@ impl RenderOnce for Avatar { } } +/// An avatar with the display name beside it. +#[derive(IntoElement)] +#[must_use] +pub struct IdentityRow { + id: SharedString, + name: SharedString, + picture: Option, + size: Size, + truncate: bool, + style: StyleRefinement, +} + +impl IdentityRow { + /// Creates the row for `id` (the pixel-fallback seed) showing `name`. + pub fn new(id: ID, name: N, picture: Option) -> Self + where + ID: Into, + N: Into, + { + Self { + id: id.into(), + name: name.into(), + picture, + size: Size::default(), + truncate: false, + style: StyleRefinement::default(), + } + } + + /// Truncates the name to one line inside the available width. + pub fn truncate(mut self) -> Self { + self.truncate = true; + self + } +} + +impl Sizable for IdentityRow { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl gpui::Styled for IdentityRow { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for IdentityRow { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + h_flex() + .refine_style(&self.style) + .child( + Avatar::new(self.id.clone()) + .name(self.name.clone()) + .picture(self.picture) + .with_size(self.size), + ) + .child( + div() + .when(self.truncate, |name| { + name.flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + }) + .child(self.name), + ) + } +} + /// A deterministic, offline pixel-art avatar. #[derive(IntoElement)] struct PixelAvatar { @@ -218,6 +291,28 @@ thread_local! { std::cell::RefCell::new(HashMap::new()); } +/// Tiny xorshift64* PRNG for deriving the pattern from the seed. +struct PixelRng(u64); + +impl PixelRng { + fn new(seed: u64) -> Self { + Self(seed.max(1)) + } + + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + + fn chance(&mut self, probability: f32) -> bool { + self.next() as f32 / (u64::MAX as f32) < probability + } +} + 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 { @@ -284,25 +379,3 @@ fn fnv1a(bytes: &[u8]) -> u64 { } hash } - -/// Tiny xorshift64* PRNG for deriving the pattern from the seed. -struct PixelRng(u64); - -impl PixelRng { - fn new(seed: u64) -> Self { - Self(seed.max(1)) - } - - fn next(&mut self) -> u64 { - let mut x = self.0; - x ^= x >> 12; - x ^= x << 25; - x ^= x >> 27; - self.0 = x; - x.wrapping_mul(0x2545_f491_4f6c_dd1d) - } - - fn chance(&mut self, probability: f32) -> bool { - self.next() as f32 / (u64::MAX as f32) < probability - } -} diff --git a/crates/ui/src/components/button.rs b/crates/ui/src/components/button.rs index 32969bc..b4515cc 100644 --- a/crates/ui/src/components/button.rs +++ b/crates/ui/src/components/button.rs @@ -46,18 +46,6 @@ 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 { @@ -117,6 +105,18 @@ pub enum ButtonSide { Right, } +/// 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, +} + /// A push button that renders a label, an icon, or both, and fires /// [`Button::on_click`] on click, Enter, or Space. #[derive(IntoElement)] diff --git a/crates/ui/src/components/clipboard.rs b/crates/ui/src/components/clipboard.rs index 54e32c2..a7966ff 100644 --- a/crates/ui/src/components/clipboard.rs +++ b/crates/ui/src/components/clipboard.rs @@ -15,21 +15,20 @@ use std::time::Duration; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyView, App, ClipboardItem, ElementId, Entity, IntoElement, RenderOnce, SharedString, - StyleRefinement, Task, Window, + AnyView, App, ClipboardItem, ElementId, Entity, IntoElement, ParentElement as _, RenderOnce, + SharedString, StyleRefinement, Styled as _, Task, Window, div, }; use crate::components::button::{Button, ButtonVariant}; -use crate::components::common::{ResultLogErr as _, Sizable, StyledExt as _}; +use crate::components::common::{ResultLogErr as _, Sizable, StyledExt as _, h_flex}; use crate::icons::IconRole; -use crate::theme::Size; +use crate::theme::{ActiveTheme as _, Size}; /// How long the check mark shows before reverting to the copy icon. -pub const COPIED_DURATION: Duration = Duration::from_secs(1); +const COPIED_DURATION: Duration = Duration::from_secs(1); /// The tooltip view builder gpui's `.tooltip(...)` expects. type TooltipBuilder = Rc AnyView>; - /// Runs after the value lands on the clipboard. type CopiedHandler = Box; @@ -184,3 +183,68 @@ impl RenderOnce for ClipboardButton { }) } } + +/// A copyable value shown as a boxed row with a trailing copy button. +#[derive(IntoElement)] +#[must_use] +pub struct CopyRow { + id: SharedString, + value: SharedString, + large_text: bool, +} + +impl CopyRow { + /// Monospace `value` in a secondary-background row (the clone-command look). + pub fn new(id: ID, value: V) -> Self + where + ID: Into, + V: Into, + { + Self { + id: id.into(), + value: value.into(), + large_text: false, + } + } + + /// Base-size label and default-size copy button (the about-dialog list look). + pub fn text_base(mut self) -> Self { + self.large_text = true; + self + } +} + +impl RenderOnce for CopyRow { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + + h_flex() + .h_8() + .px_2() + .gap_2() + .min_w_0() + .bg(theme.colors.secondary) + .rounded(theme.radius.control) + .text_color(theme.colors.secondary_foreground) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .when(self.large_text, |text| text.text_base()) + .when(!self.large_text, |text| { + text.font_family(theme.mono_font).text_xs() + }) + .child(self.value.clone()), + ) + .child(if self.large_text { + ClipboardButton::new(self.id, self.value).into_any_element() + } else { + ClipboardButton::new(self.id, self.value) + .xsmall() + .into_any_element() + }) + } +} diff --git a/crates/ui/src/components/code.rs b/crates/ui/src/components/code.rs index f256639..1cf079f 100644 --- a/crates/ui/src/components/code.rs +++ b/crates/ui/src/components/code.rs @@ -47,34 +47,13 @@ actions!(code_view, [Copy]); /// The key context the code view declares while it holds focus. pub const CODE_VIEW_CONTEXT: &str = "CodeView"; -/// Binds the code view's copy chord: cmd-c on macOS, ctrl-c elsewhere. -/// -/// Call once at startup. Without it, selection copy has no key. -pub fn bind_code_view_keys(cx: &mut App) { - let context = match KeyBindingContextPredicate::parse(CODE_VIEW_CONTEXT) { - Ok(context) => Some(Rc::new(context)), - Err(error) => { - log::error!("failed to parse code view key context: {error}"); - return; - } - }; - let binding = match KeyBinding::load("secondary-c", Box::new(Copy), context, false, None, cx) { - Ok(binding) => binding, - Err(error) => { - log::error!("failed to parse code view copy keystroke: {error}"); - return; - } - }; - cx.bind_keys([binding]); -} - /// A point in the source, in lines and characters (not bytes). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct SelectionPoint { +struct SelectionPoint { /// The zero-based line index. - pub row: usize, + row: usize, /// The zero-based character offset within the line. - pub col: usize, + col: usize, } impl SelectionPoint { @@ -235,24 +214,8 @@ impl CodeViewState { self.active_line } - /// Selects a range, endpoints in lines and characters. - pub fn select_range( - &mut self, - start: SelectionPoint, - end: SelectionPoint, - cx: &mut Context, - ) { - self.selection = if start.earlier_than(&end) { - Some((start, end)) - } else { - Some((end, start)) - }; - self.selecting = false; - cx.notify(); - } - /// The selected range, endpoints in document order, when there is one. - pub fn selection(&self) -> Option<(SelectionPoint, SelectionPoint)> { + fn selection(&self) -> Option<(SelectionPoint, SelectionPoint)> { self.selection.map(|(anchor, head)| { if anchor.earlier_than(&head) { (anchor, head) @@ -263,7 +226,7 @@ impl CodeViewState { } /// The selected text, or `None` when nothing is selected. - pub fn selected_text(&self) -> Option { + fn selected_text(&self) -> Option { let (start, end) = self.selection()?; let lines: Vec<&str> = self.source.split('\n').collect(); @@ -325,6 +288,128 @@ impl CodeViewState { SelectionPoint { row, col } } + + #[allow(clippy::too_many_arguments)] + fn render_row( + &self, + id: &ElementId, + line_ix: usize, + active: bool, + selection: Option<(SelectionPoint, SelectionPoint)>, + mono_font: &'static str, + colors: ColorTokens, + ramps: Ramps, + text_size: Pixels, + line_height: Pixels, + cx: &App, + ) -> gpui::AnyElement { + let layout = self.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 selected = vec![false; char_count]; + + if let Some((start, end)) = selection + && line_ix >= start.row + && line_ix <= end.row + { + let start_col = if line_ix == start.row { + start.col.min(char_count) + } else { + 0 + }; + + let end_col = if line_ix == end.row { + end.col.min(char_count) + } else { + char_count + }; + + for slot in &mut selected[start_col..end_col] { + *slot = true; + } + } + + let mut highlights: Vec<(std::ops::Range, HighlightStyle)> = Vec::new(); + let mut run_start = 0usize; + let mut run_end = 0usize; + let mut run_role = Role::Text; + let mut run_selected = false; + + for (char_ix, (byte_ix, character)) in text.char_indices().enumerate() { + let fresh = + char_ix == 0 || roles[char_ix] != run_role || selected[char_ix] != run_selected; + if fresh { + if char_ix > 0 { + highlights.push(( + run_start..run_end, + run_role.run_style(run_selected, colors, ramps), + )); + } + run_start = byte_ix; + run_role = roles[char_ix]; + run_selected = selected[char_ix]; + } + run_end = byte_ix + character.len_utf8(); + } + + if run_end > run_start || !text.is_empty() { + highlights.push(( + run_start..run_end, + run_role.run_style(run_selected, colors, ramps), + )); + } + + let style = TextStyle { + color: colors.foreground, + font_family: SharedString::from(mono_font), + font_size: text_size.into(), + line_height: line_height.into(), + white_space: gpui::WhiteSpace::Nowrap, + ..Default::default() + }; + + div() + .debug_selector(move || format!("{id}-row-{line_ix}")) + .id(("code-row", line_ix)) + .w_full() + .text_xs() + .h(line_height) + .flex() + .items_center() + .overflow_hidden() + .when(active, |row| { + row.bg(Hsla { + a: colors.muted.a * WASH_ALPHA_SOFT, + ..colors.muted + }) + }) + .child( + gutter_cell( + cx, + if active { + colors.foreground + } else { + colors.muted_foreground + }, + format!("{}", line_ix + 1), + ) + .justify_end() + .pr_2() + .whitespace_nowrap(), + ) + .child( + div() + .flex_1() + .min_w_0() + .ml_4() + .overflow_hidden() + .whitespace_nowrap() + .child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)), + ) + .into_any_element() + } } impl gpui::Focusable for CodeViewState { @@ -362,8 +447,7 @@ impl Render for CodeViewState { range .map(|line_ix| { - render_row( - code, + code.render_row( &id, line_ix, active_line == Some(line_ix), @@ -523,123 +607,23 @@ impl Render for CodeViewState { } } -#[allow(clippy::too_many_arguments)] -fn render_row( - code: &CodeViewState, - id: &ElementId, - line_ix: usize, - active: bool, - selection: Option<(SelectionPoint, SelectionPoint)>, - mono_font: &'static str, - colors: ColorTokens, - ramps: Ramps, - text_size: Pixels, - line_height: Pixels, - cx: &App, -) -> gpui::AnyElement { - 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 selected = vec![false; char_count]; - - if let Some((start, end)) = selection - && line_ix >= start.row - && line_ix <= end.row - { - let start_col = if line_ix == start.row { - start.col.min(char_count) - } else { - 0 - }; - - let end_col = if line_ix == end.row { - end.col.min(char_count) - } else { - char_count - }; - - for slot in &mut selected[start_col..end_col] { - *slot = true; +/// Binds the code view's copy chord: cmd-c on macOS, ctrl-c elsewhere. +/// +/// Call once at startup. Without it, selection copy has no key. +pub fn bind_code_view_keys(cx: &mut App) { + let context = match KeyBindingContextPredicate::parse(CODE_VIEW_CONTEXT) { + Ok(context) => Some(Rc::new(context)), + Err(error) => { + log::error!("failed to parse code view key context: {error}"); + return; } - } - - let mut highlights: Vec<(std::ops::Range, HighlightStyle)> = Vec::new(); - let mut run_start = 0usize; - let mut run_end = 0usize; - let mut run_role = Role::Text; - let mut run_selected = false; - - for (char_ix, (byte_ix, character)) in text.char_indices().enumerate() { - let fresh = char_ix == 0 || roles[char_ix] != run_role || selected[char_ix] != run_selected; - if fresh { - if char_ix > 0 { - highlights.push(( - run_start..run_end, - run_role.run_style(run_selected, colors, ramps), - )); - } - run_start = byte_ix; - run_role = roles[char_ix]; - run_selected = selected[char_ix]; - } - run_end = byte_ix + character.len_utf8(); - } - - if run_end > run_start || !text.is_empty() { - highlights.push(( - run_start..run_end, - run_role.run_style(run_selected, colors, ramps), - )); - } - - let style = TextStyle { - color: colors.foreground, - font_family: SharedString::from(mono_font), - font_size: text_size.into(), - line_height: line_height.into(), - white_space: gpui::WhiteSpace::Nowrap, - ..Default::default() }; - - div() - .debug_selector(move || format!("{id}-row-{line_ix}")) - .id(("code-row", line_ix)) - .w_full() - .text_xs() - .h(line_height) - .flex() - .items_center() - .overflow_hidden() - .when(active, |row| { - row.bg(Hsla { - a: colors.muted.a * WASH_ALPHA_SOFT, - ..colors.muted - }) - }) - .child( - gutter_cell( - cx, - if active { - colors.foreground - } else { - colors.muted_foreground - }, - format!("{}", line_ix + 1), - ) - .justify_end() - .pr_2() - .whitespace_nowrap(), - ) - .child( - div() - .flex_1() - .min_w_0() - .ml_4() - .overflow_hidden() - .whitespace_nowrap() - .child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)), - ) - .into_any_element() + let binding = match KeyBinding::load("secondary-c", Box::new(Copy), context, false, None, cx) { + Ok(binding) => binding, + Err(error) => { + log::error!("failed to parse code view copy keystroke: {error}"); + return; + } + }; + cx.bind_keys([binding]); } diff --git a/crates/ui/src/components/combobox.rs b/crates/ui/src/components/combobox.rs index 4f9fd31..1aff129 100644 --- a/crates/ui/src/components/combobox.rs +++ b/crates/ui/src/components/combobox.rs @@ -2,9 +2,8 @@ //! //! The state is the view: [`ComboboxState`] owns the query field and the //! options, and the owner renders the entity itself. Typing filters, the -//! arrow keys move a highlight, Enter commits, and what happens to unmatched -//! text when the field loses focus is decided by [`UnmatchedText`], which -//! reverts by default. +//! arrow keys move a highlight, Enter commits, and unmatched text reverts to +//! the chosen option's label (or empties the field) when focus is lost. //! //! # Examples //! @@ -33,13 +32,12 @@ use gpui::{ App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, 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, + UniformListScrollHandle, Window, actions, canvas, div, uniform_list, }; use crate::components::common::{ - ControlSizing, OVERLAY_LAYER, ResultLogErr as _, Sizable, StyledExt as _, floating_panel, - h_flex, paint_highlighted_row, v_flex, wrapping_adjacent_selectable, + ControlSizing, 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}; @@ -54,41 +52,10 @@ actions!( /// The key context the combobox's wrapper declares. pub const COMBOBOX_CONTEXT: &str = "Combobox"; -/// Binds the combobox's four keys: down, up, enter, and escape. -pub fn bind_combobox_keys(cx: &mut App) { - let under_input = Some("Combobox > Input"); - cx.bind_keys([ - KeyBinding::new("down", HighlightNext, under_input), - KeyBinding::new("up", HighlightPrevious, under_input), - KeyBinding::new("enter", Choose, under_input), - KeyBinding::new("escape", Dismiss, under_input), - KeyBinding::new("down", HighlightNext, Some(COMBOBOX_CONTEXT)), - KeyBinding::new("up", HighlightPrevious, Some(COMBOBOX_CONTEXT)), - KeyBinding::new("enter", Choose, Some(COMBOBOX_CONTEXT)), - KeyBinding::new("escape", Dismiss, Some(COMBOBOX_CONTEXT)), - ]); -} - -/// What happens to text that matches no option when the field loses focus. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum UnmatchedText { - /// Restore the chosen option's label, or empty the field. - #[default] - Revert, - /// Leave the text and leave the value cleared. - Keep, - /// Hand the text to the `on_create` handler. - Create, -} - /// An option for a [`Combobox`]: a value and the label the filter matches on. pub type ComboboxOption = (T, SharedString); /// Reports the value whenever it changes. pub type ComboboxHandler = Rc, &mut Window, &mut App)>; -/// Receives unmatched text when the field loses focus in create mode. -pub type ComboboxCreateHandler = Rc; -/// Decides which options survive a query: the query, the value, the label. -pub type ComboboxFilter = Rc bool>; /// Builder for a combobox, consumed by [`ComboboxState::new`]. #[must_use] @@ -102,9 +69,6 @@ where selected: Option, placeholder: SharedString, on_change: Option>, - on_create: Option, - filter: Option>, - unmatched: UnmatchedText, size: Size, /// Icon shown at the field's leading edge while a value is selected. selected_icon: Option, @@ -127,9 +91,6 @@ where selected: None, placeholder: SharedString::from("Select..."), on_change: None, - on_create: None, - filter: None, - unmatched: UnmatchedText::default(), size: Size::default(), selected_icon: None, style: StyleRefinement::default(), @@ -169,31 +130,6 @@ where self } - /// Hands unmatched text to `handler` when the field loses focus. - pub fn on_create(mut self, handler: F) -> Self - where - F: Fn(SharedString, &mut Window, &mut App) + 'static, - { - self.on_create = Some(Rc::new(handler)); - self.unmatched = UnmatchedText::Create; - self - } - - /// Sets the matcher that decides which options survive a query. - pub fn filter(mut self, filter: F) -> Self - where - F: Fn(&str, &T, &SharedString) -> bool + 'static, - { - self.filter = Some(Rc::new(filter)); - self - } - - /// Leaves unmatched text in the field on blur. - pub fn keep_unmatched_text(mut self) -> Self { - self.unmatched = UnmatchedText::Keep; - self - } - /// Overrides the accessibility label. pub fn accessibility_label(mut self, label: L) -> Self where @@ -250,9 +186,6 @@ where /// The highlighted popup *row*, when the popup is open. highlight: Option, on_change: Option>, - on_create: Option, - filter: ComboboxFilter, - unmatched: UnmatchedText, size: Size, /// Width refinements from the builder, applied to the wrapper each render. style: StyleRefinement, @@ -312,11 +245,6 @@ where visible, highlight: None, on_change: combobox.on_change, - on_create: combobox.on_create, - filter: combobox.filter.unwrap_or_else(|| { - Rc::new(|query, _value, label| label.to_lowercase().contains(&query.to_lowercase())) - }), - unmatched: combobox.unmatched, size: combobox.size, style: combobox.style, selected_icon: combobox.selected_icon, @@ -326,21 +254,6 @@ where } } - /// The text currently in the field. - pub fn text(&self, cx: &App) -> String { - self.query.read(cx).value().to_string() - } - - /// Focuses the query field. - pub fn focus(&self, window: &mut Window, cx: &mut App) { - window.focus(&self.query.read(cx).focus_handle(), cx); - } - - /// Whether the option list is showing. - pub fn is_open(&self) -> bool { - self.highlight.is_some() - } - /// The chosen value. pub fn selected(&self) -> Option<&T> { self.selected.as_ref() @@ -367,11 +280,6 @@ where cx.notify(); } - /// A copy of the current choice list. - pub fn options_snapshot(&self) -> Vec> { - self.options.clone() - } - /// The label of the chosen option, if there is one. fn selected_label(&self) -> Option { let selected = self.selected.as_ref()?; @@ -383,12 +291,12 @@ where /// Recomputes `visible` for `query` and clamps the highlight onto it. fn refilter(&mut self, query: &str) { - let filter = self.filter.clone(); + let needle = query.to_lowercase(); self.visible = self .options .iter() .enumerate() - .filter(|(_, (value, label))| filter(query, value, label)) + .filter(|(_, (_, label))| label.to_lowercase().contains(&needle)) .map(|(index, _)| index) .collect(); self.highlight = self.highlight.filter(|row| *row < self.visible.len()); @@ -452,7 +360,7 @@ where cx.notify(); } - /// Losing focus. [`UnmatchedText`] decides what the text becomes. + /// Losing focus: unmatched text reverts to the chosen option's label. fn blurred(&mut self, window: &mut Window, cx: &mut Context) { self.highlight = None; let text = self.query_text(cx); @@ -462,26 +370,10 @@ where return; } - match self.unmatched { - UnmatchedText::Revert => { - let restored = self.selected_label().unwrap_or_default().to_string(); - self.query - .update(cx, |query, cx| query.set_value_silent(restored, window, cx)); - } - UnmatchedText::Keep => {} - UnmatchedText::Create => { - if !text.is_empty() - && let Some(on_create) = self.on_create.clone() - { - let text = SharedString::from(text); - let task = window.spawn(cx, async move |cx| { - cx.update(|window, cx| on_create(text, window, cx)) - .log_err(); - }); - self.task.replace(task); - } - } - } + let restored = self.selected_label().unwrap_or_default().to_string(); + self.query.update(cx, |query, cx| { + query.set_value_silent(restored, window, cx); + }); cx.notify(); } @@ -798,10 +690,26 @@ where .inset_0(), ); - wrapper.child( - deferred(anchored().offset(point(px(0.), px(4.))).child(panel)) - .with_priority(OVERLAY_LAYER), - ) + wrapper.child(crate::components::menu::anchored_overlay( + None, + panel.into_any_element(), + None, + )) }) } } + +/// Binds the combobox's four keys: down, up, enter, and escape. +pub fn bind_combobox_keys(cx: &mut App) { + let under_input = Some("Combobox > Input"); + cx.bind_keys([ + KeyBinding::new("down", HighlightNext, under_input), + KeyBinding::new("up", HighlightPrevious, under_input), + KeyBinding::new("enter", Choose, under_input), + KeyBinding::new("escape", Dismiss, under_input), + KeyBinding::new("down", HighlightNext, Some(COMBOBOX_CONTEXT)), + KeyBinding::new("up", HighlightPrevious, Some(COMBOBOX_CONTEXT)), + KeyBinding::new("enter", Choose, Some(COMBOBOX_CONTEXT)), + KeyBinding::new("escape", Dismiss, Some(COMBOBOX_CONTEXT)), + ]); +} diff --git a/crates/ui/src/components/command_palette.rs b/crates/ui/src/components/command_palette.rs index 154132f..89d30b8 100644 --- a/crates/ui/src/components/command_palette.rs +++ b/crates/ui/src/components/command_palette.rs @@ -30,7 +30,7 @@ use gpui::prelude::FluentBuilder; use gpui::{ AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, MouseButton, ParentElement as _, Render, Role, SharedString, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, Subscription, UniformListScrollHandle, Window, actions, canvas, + StyleRefinement, Styled as _, Subscription, UniformListScrollHandle, Window, actions, deferred, div, relative, rems, uniform_list, }; @@ -51,20 +51,10 @@ actions!( /// The key context the palette's panel declares. pub const COMMAND_PALETTE_CONTEXT: &str = "CommandPalette"; -/// Binds the palette's four keys: down, up, enter, and escape. -pub fn bind_command_palette_keys(cx: &mut App) { - let under_input = Some("CommandPalette > Input"); - cx.bind_keys([ - KeyBinding::new("down", HighlightNext, under_input), - KeyBinding::new("up", HighlightPrevious, under_input), - KeyBinding::new("enter", Choose, under_input), - KeyBinding::new("escape", Dismiss, under_input), - KeyBinding::new("down", HighlightNext, Some(COMMAND_PALETTE_CONTEXT)), - KeyBinding::new("up", HighlightPrevious, Some(COMMAND_PALETTE_CONTEXT)), - KeyBinding::new("enter", Choose, Some(COMMAND_PALETTE_CONTEXT)), - KeyBinding::new("escape", Dismiss, Some(COMMAND_PALETTE_CONTEXT)), - ]); -} +/// Filters and ranks the commands for a query. +pub type CommandMatcher = Rc Vec>; +/// Runs the chosen command. +pub type CommandHandler = Rc; /// A command the palette can run: a stable id and the label the matcher sees. #[derive(Clone)] @@ -117,11 +107,6 @@ impl Command { // Command is a data builder, not an element, adopt the combinators explicitly. impl FluentBuilder for Command {} -/// Filters and ranks the commands for a query. -pub type CommandMatcher = Rc Vec>; -/// Runs the chosen command. -pub type CommandHandler = Rc; - /// Builder for a command palette, consumed by [`CommandPaletteState::new`]. #[must_use] pub struct CommandPalette { @@ -525,18 +510,10 @@ impl Render for CommandPaletteState { .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(), - ); + .child(crate::components::menu::focus_capture( + query_focus.clone(), + move |window, cx| !query_focus.contains_focused(window, cx), + )); let scrim = div() .absolute() @@ -566,3 +543,18 @@ impl Render for CommandPaletteState { .into_any_element() } } + +/// Binds the palette's four keys: down, up, enter, and escape. +pub fn bind_command_palette_keys(cx: &mut App) { + let under_input = Some("CommandPalette > Input"); + cx.bind_keys([ + KeyBinding::new("down", HighlightNext, under_input), + KeyBinding::new("up", HighlightPrevious, under_input), + KeyBinding::new("enter", Choose, under_input), + KeyBinding::new("escape", Dismiss, under_input), + KeyBinding::new("down", HighlightNext, Some(COMMAND_PALETTE_CONTEXT)), + KeyBinding::new("up", HighlightPrevious, Some(COMMAND_PALETTE_CONTEXT)), + KeyBinding::new("enter", Choose, Some(COMMAND_PALETTE_CONTEXT)), + KeyBinding::new("escape", Dismiss, Some(COMMAND_PALETTE_CONTEXT)), + ]); +} diff --git a/crates/ui/src/components/common.rs b/crates/ui/src/components/common.rs index fa90204..006c3a7 100644 --- a/crates/ui/src/components/common.rs +++ b/crates/ui/src/components/common.rs @@ -19,8 +19,33 @@ use gpui::{ WindowId, div, px, rems, }; -pub use crate::theme::Size; -use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD}; +use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD, Size}; + +/// Deferred draw priority of window-modal surfaces; default layer 0 stays for in-flow chrome like resize handles. +pub const DIALOG_LAYER: usize = 1; +/// Deferred draw priority of floating panels, so controls inside a dialog open above it. +pub const OVERLAY_LAYER: usize = 2; +/// Deferred draw priority of passive notifications, so they stay visible over dialogs. +pub const TOAST_LAYER: usize = 3; + +/// A handler told to clean up after a dismissed surface. +pub type DismissHandler = std::rc::Rc; + +/// The painted bounds of elements that tooltips anchor to, per window and element id. +#[derive(Default)] +struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds>); + +impl Global for AnchorBoundsRegistry {} + +impl AnchorBoundsRegistry { + fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds) { + self.0.insert((window, id), bounds); + } + + fn get(&self, window: WindowId, id: &ElementId) -> Option> { + self.0.get(&(window, id.clone())).copied() + } +} /// A row whose children center on the cross axis. #[must_use] @@ -87,23 +112,6 @@ pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusH .clone() } -/// The painted bounds of elements that tooltips anchor to, per window and element id. -/// Entries are never evicted: bounds are bounded by live windows, though long-lived processes minting dynamic per-item ids could accumulate. -#[derive(Default)] -struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds>); - -impl Global for AnchorBoundsRegistry {} - -impl AnchorBoundsRegistry { - fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds) { - self.0.insert((window, id), bounds); - } - - fn get(&self, window: WindowId, id: &ElementId) -> Option> { - self.0.get(&(window, id.clone())).copied() - } -} - /// The last bounds an element painted at, in the given window. pub fn anchor_bounds(window: WindowId, id: &ElementId, cx: &App) -> Option> { cx.try_global::() @@ -250,16 +258,6 @@ where }) } -/// A handler told to clean up after a dismissed surface. -pub type DismissHandler = std::rc::Rc; - -/// Deferred draw priority of window-modal surfaces; default layer 0 stays for in-flow chrome like resize handles. -pub const DIALOG_LAYER: usize = 1; -/// Deferred draw priority of floating panels, so controls inside a dialog open above it. -pub const OVERLAY_LAYER: usize = 2; -/// Deferred draw priority of passive notifications, so they stay visible over dialogs. -pub const TOAST_LAYER: usize = 3; - /// A component that can be told which size to render at. pub trait Sizable: Sized { /// Sets the size. diff --git a/crates/ui/src/components/context_menu.rs b/crates/ui/src/components/context_menu.rs deleted file mode 100644 index a41d89e..0000000 --- a/crates/ui/src/components/context_menu.rs +++ /dev/null @@ -1,145 +0,0 @@ -//! Renders a menu at the pointer when its target element is right-clicked. -//! -//! # Examples -//! -//! ```no_run -//! use gpui::{IntoElement as _, ParentElement as _, SharedString, div}; -//! use ui::context_menu::ContextMenu; -//! use ui::menu::MenuItem; -//! -//! let context = ContextMenu::new("project-context") -//! .target(|_window, _cx| { -//! div() -//! .child(SharedString::from("project.el")) -//! .into_any_element() -//! }) -//! .items(|_window, _cx| vec![MenuItem::new("Delete").handler(|_window, _cx| {})]); -//! ``` - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - App, ElementId, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent, - ParentElement as _, RenderOnce, SharedString, StyleRefinement, Window, div, -}; - -use crate::components::common::StyledExt as _; -use crate::components::menu::{Menu, MenuItem}; - -/// Builds the element that opens the menu on right-click. -type TargetFn = Box gpui::AnyElement>; -/// Builds the menu's items fresh each render. -type ItemsFn = Box Vec>; - -/// A menu that opens at the pointer when its target is right-clicked. -/// -/// Open state is owned internally by design, unlike the controlled [`Menu`]. -#[derive(IntoElement)] -#[must_use] -pub struct ContextMenu { - id: ElementId, - target: Option, - items: Option, - a11y_label: Option, - style: StyleRefinement, -} - -impl ContextMenu { - /// Creates a context menu over a target set with [`ContextMenu::target`]. - pub fn new(id: I) -> Self - where - I: Into, - { - Self { - id: id.into(), - target: None, - items: None, - a11y_label: None, - style: StyleRefinement::default(), - } - } - - /// Sets the element that opens the menu on right-click. - pub fn target(mut self, target: F) -> Self - where - F: Fn(&mut Window, &mut App) -> gpui::AnyElement + 'static, - { - self.target = Some(Box::new(target)); - self - } - - /// Sets the menu's items, built fresh each render. - pub fn items(mut self, items: F) -> Self - where - F: Fn(&mut Window, &mut App) -> Vec + 'static, - { - self.items = Some(Box::new(items)); - self - } - - /// Overrides the menu's accessibility label. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } -} - -impl RenderOnce for ContextMenu { - fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { - let open = window.with_element_namespace(self.id.clone(), |window| { - window - .use_keyed_state("context-open", cx, |_, _| false) - .clone() - }); - - let at = window.with_element_namespace(self.id.clone(), |window| { - window - .use_keyed_state("context-position", cx, |_, _| None) - .clone() - }); - - let is_open = *open.read(cx); - let position = *at.read(cx); - - let target = self.target; - let at_for_target = at.clone(); - - let trigger = move |window: &mut Window, cx: &mut App| { - let base = target - .as_ref() - .map(|build| build(window, cx)) - .unwrap_or_else(|| div().into_any_element()); - - div() - .on_mouse_down(MouseButton::Right, { - let at = at_for_target.clone(); - move |event: &MouseDownEvent, _window, cx| { - at.update(cx, |at, _| *at = Some(event.position)); - } - }) - .child(base) - .into_any_element() - }; - - let items = move |window: &mut Window, cx: &mut App| { - self.items - .as_ref() - .map(|build| build(window, cx)) - .unwrap_or_default() - }; - - Menu::new(self.id) - .open(is_open) - .on_change(move |next, _window, cx| open.update(cx, |open, _| *open = next)) - .open_at(position) - .trigger_button(MouseButton::Right) - .trigger(trigger) - .items(items) - .refine_style(&self.style) - .when_some(self.a11y_label.clone(), |menu, label| { - menu.accessibility_label(label) - }) - } -} diff --git a/crates/ui/src/components/dialog.rs b/crates/ui/src/components/dialog.rs index 9f62145..090dff5 100644 --- a/crates/ui/src/components/dialog.rs +++ b/crates/ui/src/components/dialog.rs @@ -42,7 +42,7 @@ use crate::icons::IconRole; use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH}; /// Requests the dialog's close: `false` closes. -pub type ChangeHandler = Rc; +type ChangeHandler = Rc; type ContentFn = Box AnyElement>; type ActionsFn = Box Vec>; diff --git a/crates/ui/src/components/diff.rs b/crates/ui/src/components/diff.rs deleted file mode 100644 index a7fe65c..0000000 --- a/crates/ui/src/components/diff.rs +++ /dev/null @@ -1,720 +0,0 @@ -//! Renders a unified, syntax-highlighted diff of two versions of a file: -//! change bars or `+`/`-` markers, tinted number gutters, word-level -//! intra-line highlights, and collapsed hunk separators. -//! -//! Rows reuse the code view's highlighting. Consumers that already hold a -//! git diff can build [`DiffRow`]s themselves instead of calling -//! [`DiffViewState::diff_rows`]. -//! -//! # Examples -//! -//! ```no_run -//! use gpui::{App, AppContext as _}; -//! use ui::diff::{DiffIndicators, DiffViewState}; -//! use ui::highlight::Language; -//! -//! fn patch(cx: &mut App) -> gpui::Entity { -//! let state = DiffViewState::new( -//! "patch", -//! "# gpui\nA UI kit for gpui.", -//! "# gpui\nA UI toolkit for gpui.", -//! Language::Rust, -//! ) -//! .indicators(DiffIndicators::Bars); -//! -//! cx.new(|_| state) -//! } -//! ``` - -use std::ops::Range; - -use gpui::prelude::FluentBuilder as _; -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, 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 _, 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)] -pub enum DiffRowKind { - /// Present in both versions. - Context, - /// Only in the new version. - Added, - /// Only in the old version. - Removed, - /// A hunk separator introducing the rows after it. - Hunk, -} - -/// One row of a unified diff: a diff line or a hunk separator. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct DiffRow { - pub kind: DiffRowKind, - /// The highlighted line content; empty for hunk separators. - pub content: Line, - /// 1-based line number in the old version, when the row exists there. - pub old_number: Option, - /// 1-based line number in the new version, when the row exists there. - pub new_number: Option, - /// Byte ranges of intra-line word changes, tinted on changed rows. - pub changed_ranges: Vec>, - /// The `@@ -a,b +c,d @@` header, for hunk separator rows. - pub header: SharedString, - /// Unchanged lines collapsed into this separator row; zero elsewhere. - pub hidden_lines: usize, -} - -/// How changed rows are marked. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum DiffIndicators { - /// A two-pixel bar on the row's left edge. - #[default] - Bars, - /// Classic `+`/`-` glyphs in a marker column. - Classic, - /// Only the background washes. - None, -} - -/// How collapsed regions between hunks render. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum HunkSeparator { - /// The collapsed unchanged line count, centered. - #[default] - LineInfo, - /// The patch-style `@@ -a,b +c,d @@` header. - Metadata, - /// A minimal `···` bar. - Simple, -} - -/// Presentation options for the diff view. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct DiffViewOptions { - /// How changed rows are marked. - pub indicators: DiffIndicators, - /// How collapsed regions between hunks render. - pub separator: HunkSeparator, - /// Whether the line-number gutter renders. - pub line_numbers: bool, -} - -impl Default for DiffViewOptions { - fn default() -> Self { - Self { - indicators: DiffIndicators::Bars, - separator: HunkSeparator::LineInfo, - line_numbers: true, - } - } -} - -impl DiffRow { - /// Assembles a diff line row from a `similar` change. - pub(crate) fn from_change( - change: &Change<&str>, - code: &HighlightedCode, - changed_ranges: Vec>, - ) -> DiffRow { - let content = match change.tag() { - ChangeTag::Equal => change - .new_index() - .and_then(|ix| code.lines.get(ix)) - .cloned() - .unwrap_or_default(), - ChangeTag::Delete => change - .old_index() - .and_then(|ix| code.lines.get(ix)) - .cloned() - .unwrap_or_default(), - ChangeTag::Insert => change - .new_index() - .and_then(|ix| code.lines.get(ix)) - .cloned() - .unwrap_or_default(), - }; - - let (old_number, new_number) = match change.tag() { - ChangeTag::Equal => ( - change.old_index().map(|ix| ix + 1), - change.new_index().map(|ix| ix + 1), - ), - ChangeTag::Delete => (change.old_index().map(|ix| ix + 1), None), - ChangeTag::Insert => (None, change.new_index().map(|ix| ix + 1)), - }; - - DiffRow { - kind: match change.tag() { - ChangeTag::Equal => DiffRowKind::Context, - ChangeTag::Delete => DiffRowKind::Removed, - ChangeTag::Insert => DiffRowKind::Added, - }, - content, - old_number, - new_number, - changed_ranges, - header: Default::default(), - hidden_lines: 0, - } - } - - /// The row's text length, in characters. - fn char_count(&self) -> usize { - self.content.text().chars().count() - } - - /// Stable element id: the kind and line numbers packed into one integer. - fn element_id(&self, hunk_ordinal: usize) -> ElementId { - let kind = match self.kind { - DiffRowKind::Context => 0u64, - DiffRowKind::Added => 1, - DiffRowKind::Removed => 2, - DiffRowKind::Hunk => { - return ElementId::named_usize("diff-hunk", hunk_ordinal); - } - }; - // Line numbers saturate at 2^31 so the two fields never overlap. - let old = self.old_number.unwrap_or(0).min((1 << 31) - 1) as u64; - let new = self.new_number.unwrap_or(0).min((1 << 31) - 1) as u64; - ElementId::named_usize("diff-row", ((kind << 62) | (old << 31) | new) as usize) - } -} - -/// Retained state for a diff view. -/// -/// Build one in a [`gpui::Entity`], render the entity, and call its setters -/// to update the rendered view. -pub struct DiffViewState { - id: ElementId, - rows: Vec, - /// Cached per-row id and text length, parallel to `rows`. - row_layouts: Vec, - /// The row whose width drives horizontal scroll extent, `rows`-derived. - widest_row: Option, - options: DiffViewOptions, - /// Drives both scroll axes of the virtualized row list. - handle: UniformListScrollHandle, - a11y_label: Option, -} - -/// Cached per-row render data, computed once when the rows are set. -struct RowLayout { - id: ElementId, - char_count: usize, -} - -impl DiffViewState { - /// Builds the state, diffing `old` against `new`. - pub fn new(id: I, old: O, new: N, language: Language) -> Self - where - I: Into, - O: AsRef, - N: AsRef, - { - let mut state = Self { - id: id.into(), - rows: Vec::new(), - row_layouts: Vec::new(), - widest_row: None, - options: DiffViewOptions::default(), - handle: UniformListScrollHandle::new(), - a11y_label: None, - }; - state.set_rows(old, new, language); - state - } - - /// Replaces the rows, recomputing the per-row layout cache with them. - fn set_rows(&mut self, old: O, new: N, language: Language) - where - O: AsRef, - N: AsRef, - { - self.rows = Self::diff_rows(old.as_ref(), new.as_ref(), language); - - let mut hunk_ordinal = 0usize; - self.row_layouts = self - .rows - .iter() - .map(|row| { - let ordinal = if row.kind == DiffRowKind::Hunk { - hunk_ordinal += 1; - hunk_ordinal - } else { - 0 - }; - RowLayout { - id: row.element_id(ordinal), - char_count: row.char_count(), - } - }) - .collect(); - - self.widest_row = self - .rows - .iter() - .zip(&self.row_layouts) - .enumerate() - .filter(|(_, (row, _))| row.kind != DiffRowKind::Hunk) - .max_by_key(|(_, (_, layout))| layout.char_count) - .map(|(widest, _)| widest); - } - - /// Computes unified rows between two texts, highlighting every line with - /// `language`. Rows include [`DiffRowKind::Hunk`] separators between - /// hunks. - pub fn diff_rows(old: &str, new: &str, language: Language) -> Vec { - let old_code = highlight(old, language); - let new_code = highlight(new, language); - let diff = TextDiff::from_lines(old, new); - - let mut rows = Vec::new(); - let mut collapsed_before = 0usize; - - for group in diff.grouped_ops(3) { - let (Some(first), Some(last)) = (group.first(), group.last()) else { - continue; - }; - - let old_range = first.old_range().start..last.old_range().end; - let new_range = first.new_range().start..last.new_range().end; - - // git prints the line before a pure insertion when the count is zero. - let old_start = if old_range.is_empty() { - old_range.start - } else { - old_range.start + 1 - }; - - let new_start = if new_range.is_empty() { - new_range.start - } else { - new_range.start + 1 - }; - - let collapsed = first.old_range().start.saturating_sub(collapsed_before); - if collapsed > 0 { - rows.push(DiffRow { - kind: DiffRowKind::Hunk, - content: Line::default(), - old_number: None, - new_number: None, - changed_ranges: Vec::new(), - header: format!( - "@@ -{},{} +{},{} @@", - old_start, - old_range.len(), - new_start, - new_range.len() - ) - .into(), - hidden_lines: collapsed, - }); - } - collapsed_before = last.old_range().end; - - for op in &group { - let changes: Vec<_> = diff.iter_changes(op).collect(); - let mut index = 0; - - while index < changes.len() { - if changes[index].tag() == ChangeTag::Equal { - rows.push(DiffRow::from_change(&changes[index], &new_code, Vec::new())); - index += 1; - continue; - } - - let deletions = changes[index..] - .iter() - .take_while(|change| change.tag() == ChangeTag::Delete) - .count(); - - let insertions = changes[index + deletions..] - .iter() - .take_while(|change| change.tag() == ChangeTag::Insert) - .count(); - - let mut deletion_ranges = vec![Vec::new(); deletions]; - let mut insertion_ranges = vec![Vec::new(); insertions]; - - for pair in 0..deletions.min(insertions) { - let old_text = changes[index + pair].value().trim_end_matches('\n'); - let new_text = changes[index + deletions + pair] - .value() - .trim_end_matches('\n'); - let words = TextDiff::from_words(old_text, new_text); - - let (mut old_offset, mut new_offset) = (0usize, 0usize); - - for word in words.iter_all_changes() { - let len = word.value().len(); - - match word.tag() { - ChangeTag::Delete => { - deletion_ranges[pair].push(old_offset..old_offset + len); - old_offset += len; - } - ChangeTag::Insert => { - insertion_ranges[pair].push(new_offset..new_offset + len); - new_offset += len; - } - ChangeTag::Equal => { - old_offset += len; - new_offset += len; - } - } - } - } - - for pair in 0..deletions { - rows.push(DiffRow::from_change( - &changes[index + pair], - &old_code, - deletion_ranges[pair].clone(), - )); - } - - for pair in 0..insertions { - rows.push(DiffRow::from_change( - &changes[index + deletions + pair], - &new_code, - insertion_ranges[pair].clone(), - )); - } - - index += deletions + insertions; - } - } - } - - rows - } - - /// Sets how changed rows are marked. - pub fn indicators(mut self, indicators: DiffIndicators) -> Self { - self.options.indicators = indicators; - self - } - - /// Sets how collapsed regions between hunks render. - pub fn hunk_separator(mut self, separator: HunkSeparator) -> Self { - self.options.separator = separator; - self - } - - /// Shows or hides the line-number gutter. - pub fn line_numbers(mut self, show: bool) -> Self { - self.options.line_numbers = show; - self - } - - /// Replaces the versions and re-diffs them. - pub fn set_versions(&mut self, old: O, new: N, language: Language, cx: &mut Context) - where - O: AsRef, - N: AsRef, - { - self.set_rows(old, new, language); - self.handle.scroll_to_item(0, ScrollStrategy::Top); - // The replaced versions rarely share the old width; start at the left. - let offset = ScrollbarHandle::offset(&self.handle); - ScrollbarHandle::set_offset(&self.handle, point(Pixels::ZERO, offset.y)); - cx.notify(); - } - - /// The diff rows. - pub fn rows(&self) -> &[DiffRow] { - &self.rows - } - - /// Scrolls the first added or removed row to the top of the view. - pub fn scroll_to_first_change(&self) { - let Some(row) = self - .rows - .iter() - .position(|row| matches!(row.kind, DiffRowKind::Added | DiffRowKind::Removed)) - else { - return; - }; - self.handle.scroll_to_item(row, ScrollStrategy::Top); - } - - /// Overrides the accessibility label of the view. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } -} - -impl Render for DiffViewState { - fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { - let text_size = rems(0.75).to_pixels(window.rem_size()); - - let id = self.id.clone(); - let state = cx.entity(); - let row_count = self.rows.len(); - let options = self.options; - let widest_row = self.widest_row; - - let mut rows = uniform_list((id.clone(), "rows"), row_count, { - move |range, _window, cx| { - let diff = state.read(cx); - range - .map(|row_index| { - render_row( - &diff.rows[row_index], - &diff.row_layouts[row_index], - row_index, - options, - text_size, - cx, - ) - }) - .collect() - } - }) - .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained) - .with_width_from_item(widest_row) - .track_scroll(&self.handle) - .h_full(); - - // Lock each gesture to its initial axis - rows.interactivity().base_style.restrict_scroll_to_axis = Some(true); - - div() - .id((id.clone(), "view")) - .relative() - .size_full() - .text_xs() - .when_some(self.a11y_label.clone(), |view, label| { - view.aria_label(label) - }) - .child(rows) - .child( - Scrollbar::vertical((self.id.clone(), "v-scrollbar"), self.handle.clone()) - .visibility(ScrollbarVisibility::Platform), - ) - .child( - Scrollbar::horizontal((self.id.clone(), "h-scrollbar"), self.handle.clone()) - .visibility(ScrollbarVisibility::Platform), - ) - } -} - -fn render_row( - row: &DiffRow, - layout: &RowLayout, - row_index: usize, - options: DiffViewOptions, - text_size: Pixels, - cx: &App, -) -> gpui::AnyElement { - let theme = cx.theme(); - let mono_font = theme.mono_font; - let colors = theme.colors; - let ramps = theme.ramps; - let line_height = text_size * CODE_LINE_HEIGHT; - let char_width = text_size * MONO_ADVANCE_RATIO; - - let frame = div() - .debug_selector(move || format!("diff-row-{row_index}")) - .id(layout.id.clone()) - .w_full() - .h(line_height) - .font_family(mono_font) - .text_xs() - .overflow_hidden(); - - if row.kind == DiffRowKind::Hunk { - let content = match options.separator { - HunkSeparator::LineInfo => { - SharedString::from(format!("{} unchanged lines", row.hidden_lines)) - } - HunkSeparator::Metadata => row.header.clone(), - HunkSeparator::Simple => SharedString::from("···"), - }; - - return frame - .flex() - .items_center() - .text_color(colors.muted_foreground) - .when( - options.indicators == DiffIndicators::Classic, - |row_element| row_element.child(div().w(CODE_GUTTER_WIDTH).flex_none()), - ) - .when(options.line_numbers, |row_element| { - row_element.child(div().w(CODE_GUTTER_WIDTH).flex_none()) - }) - .when( - options.indicators == DiffIndicators::Bars && !options.line_numbers, - |row_element| { - row_element.child( - div() - .flex_none() - .border_l(CHANGE_BAR_WIDTH) - .border_color(gpui::transparent_black()), - ) - }, - ) - .child(div().flex_none().ml_2().child(content)) - .into_any_element(); - } - - let change_color = match row.kind { - DiffRowKind::Added => ramps.success.base, - DiffRowKind::Removed => ramps.destructive.base, - DiffRowKind::Context | DiffRowKind::Hunk => gpui::transparent_black(), - }; - - let wash = match row.kind { - DiffRowKind::Added => Some(wash(ramps.success.base)), - DiffRowKind::Removed => Some(wash(ramps.destructive.base)), - DiffRowKind::Context | DiffRowKind::Hunk => None, - }; - - let mut text = String::new(); - let mut spans: Vec<(Range, Role)> = Vec::new(); - - for span in &row.content.spans { - let start = text.len(); - text.push_str(&span.text); - if span.role != Role::Text { - spans.push((start..text.len(), span.role)); - } - } - - let mut boundaries: Vec = spans - .iter() - .flat_map(|(range, _)| [range.start, range.end]) - .chain( - row.changed_ranges - .iter() - .flat_map(|range| [range.start, range.end]), - ) - .collect(); - - boundaries.sort_unstable(); - boundaries.dedup(); - - let mut highlights: Vec<(std::ops::Range, HighlightStyle)> = Vec::new(); - let mut span_ix = 0; - - for window in boundaries.windows(2) { - let (start, end) = (window[0], window[1]); - while span_ix < spans.len() && spans[span_ix].0.end <= start { - span_ix += 1; - } - - let mut segment = HighlightStyle::default(); - if let Some((range, role)) = spans.get(span_ix) - && range.contains(&start) - && *role != Role::Text - { - segment = segment.highlight(HighlightStyle { - color: Some(role.color(colors, ramps)), - ..Default::default() - }); - } - - if row - .changed_ranges - .iter() - .any(|range| range.contains(&start)) - { - segment = segment.highlight(HighlightStyle { - background_color: Some(wash_strong(change_color)), - ..Default::default() - }); - } - - highlights.push((start..end, segment)); - } - - let style = TextStyle { - color: colors.foreground, - font_family: SharedString::from(mono_font), - font_size: text_size.into(), - line_height: line_height.into(), - ..Default::default() - }; - - frame - .flex() - .items_center() - .when_some(wash, |row_element, tint| row_element.bg(tint)) - .when( - options.indicators == DiffIndicators::Classic, - |row_element| { - row_element.child(gutter_cell( - cx, - if row.kind == DiffRowKind::Context { - gpui::transparent_black() - } else { - change_color - }, - match row.kind { - DiffRowKind::Added => "+", - DiffRowKind::Removed => "-", - _ => "", - }, - )) - }, - ) - .when(options.line_numbers, |row_element| { - row_element.child( - gutter_cell( - cx, - colors.muted_foreground, - row.new_number - .or(row.old_number) - .map(|number| number.to_string()) - .unwrap_or_default(), - ) - .w(CODE_GUTTER_WIDTH) - .whitespace_nowrap() - .bg(match row.kind { - DiffRowKind::Context => wash_gutter(&colors), - _ => wash_strong(change_color), - }) - .when(options.indicators == DiffIndicators::Bars, |number| { - number.border_l(CHANGE_BAR_WIDTH).border_color(change_color) - }), - ) - }) - .when( - options.indicators == DiffIndicators::Bars && !options.line_numbers, - |row_element| { - row_element.child( - div() - .h_full() - .flex_none() - .border_l(CHANGE_BAR_WIDTH) - .border_color(change_color), - ) - }, - ) - .child( - div() - .flex_none() - .ml_2() - .w(char_width * layout.char_count as f32) - .whitespace_nowrap() - .child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)), - ) - .into_any_element() -} diff --git a/crates/ui/src/components/empty_state.rs b/crates/ui/src/components/empty_state.rs index 2bccb08..323cd29 100644 --- a/crates/ui/src/components/empty_state.rs +++ b/crates/ui/src/components/empty_state.rs @@ -11,8 +11,8 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _, - Window, div, rems, + AnyElement, App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement, + Styled as _, Window, div, rems, }; use crate::components::common::{StyledExt, v_flex}; @@ -45,6 +45,19 @@ impl EmptyState { } } + /// The empty state centered in the full available space. + pub fn centered(message: L) -> AnyElement + where + L: Into, + { + v_flex() + .size_full() + .items_center() + .justify_center() + .child(Self::new(message)) + .into_any_element() + } + /// Sets a large muted icon above the headline. pub fn icon(mut self, icon: I) -> Self where diff --git a/crates/ui/src/components/grain.rs b/crates/ui/src/components/grain.rs index 36c0643..7e047a7 100644 --- a/crates/ui/src/components/grain.rs +++ b/crates/ui/src/components/grain.rs @@ -29,11 +29,6 @@ const TILE_PX: u32 = 256; #[must_use] pub struct Grain; -/// Creates a grain overlay. -pub fn grain() -> Grain { - Grain -} - impl RenderOnce for Grain { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { let texture = texture(); @@ -74,6 +69,11 @@ impl RenderOnce for Grain { } } +/// Creates a grain overlay. +pub fn grain() -> Grain { + Grain +} + /// Returns the shared noise tile so every tile reuses one atlas entry. fn texture() -> Arc { static TEXTURE: OnceLock> = OnceLock::new(); diff --git a/crates/ui/src/components/highlight.rs b/crates/ui/src/components/highlight.rs index 6dcd45d..3d293f3 100644 --- a/crates/ui/src/components/highlight.rs +++ b/crates/ui/src/components/highlight.rs @@ -28,14 +28,6 @@ thread_local! { RefCell::new(HashMap::new()); } -/// A grammar's parser and compiled highlight query. -#[cfg(not(target_arch = "wasm32"))] -struct Highlighter { - parser: tree_sitter::Parser, - query: tree_sitter::Query, - roles: Vec>, -} - /// A language source can highlight as. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Language { @@ -64,6 +56,14 @@ pub enum Role { Escape, } +/// A grammar's parser and compiled highlight query. +#[cfg(not(target_arch = "wasm32"))] +struct Highlighter { + parser: tree_sitter::Parser, + query: tree_sitter::Query, + roles: Vec>, +} + /// A run of text sharing one role. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Span { diff --git a/crates/ui/src/components/input.rs b/crates/ui/src/components/input.rs index b5a9f40..07daf1e 100644 --- a/crates/ui/src/components/input.rs +++ b/crates/ui/src/components/input.rs @@ -12,7 +12,7 @@ //! use ui::input::{Input, InputState, bind_input_keys}; //! //! # let mut cx: gpui::App = unimplemented!(); -//! bind_input_keys(&mut cx, None); +//! bind_input_keys(&mut cx); //! //! let state = InputState::builder() //! .text("Ada Lovelace") @@ -131,10 +131,9 @@ actions!( /// The keybindings [`bind_input_keys`] registers on the application. /// /// A `None` field leaves its action unbound. Start from [`InputBindings::default`] -/// to rebind one action and keep the platform defaults, or from -/// [`InputBindings::empty`] to bind only what you set. +/// to rebind one action and keep the platform defaults. #[derive(Clone, Debug)] -pub struct InputBindings { +pub(crate) struct InputBindings { pub escape: Option, pub submit: Option, pub secondary_submit: Option, @@ -260,43 +259,6 @@ impl Default for InputBindings { } impl InputBindings { - /// A table with every key unbound, for building custom bindings. - pub fn empty() -> Self { - Self { - escape: None, - submit: None, - secondary_submit: None, - insert_newline: None, - backspace: None, - delete: None, - delete_word_left: None, - delete_word_right: None, - delete_to_beginning_of_line: None, - left: None, - right: None, - up: None, - down: None, - select_left: None, - select_right: None, - select_up: None, - select_down: None, - word_left: None, - word_right: None, - select_word_left: None, - select_word_right: None, - home: None, - end: None, - select_home: None, - select_end: None, - select_all: None, - copy: None, - cut: None, - paste: None, - undo: None, - redo: None, - } - } - /// Collects the table into keybindings. pub(crate) fn into_bindings(self) -> Vec { let mut bindings: Vec = [ @@ -508,55 +470,6 @@ impl HistoryEntry { } } -/// The application-owned state of a text field that [`Input`] renders. -pub struct InputState { - text: String, - /// The caret's byte offset. - cursor: usize, - /// The byte offset the selection extends from. - anchor: usize, - /// The byte range of in-progress IME composition, if any. - marked_range: Option>, - /// Whether the field had focus at the last paint, for focus transitions. - focused: bool, - focus_handle: gpui::FocusHandle, - /// The key-down handler, bound to this entity with `cx.listener`. - key_down_handler: KeyDownHandler, - /// The mouse-down handler, bound to this entity with `cx.listener`. - mouse_down_handler: MouseDownHandler, - /// Whether a drag-select is in progress. - dragging: bool, - /// Patch history. `redo_stack` holds undone entries awaiting redo. - undo_stack: Vec, - redo_stack: Vec, - /// Consecutive edits within this interval merge into one undo entry. - group_interval: Duration, - /// When set, user edits are refused; focus, movement, selection, and copy still work. - read_only: bool, - /// When set, the field is a password field. - password: bool, - /// Whether a password field currently shows its content. - revealed: bool, - /// Whether the field holds multiple lines of text. - multiline: bool, - /// Which keystroke submits a multiline field. - submit_on: SubmitOn, - /// The x the caret keeps across vertical movement, reset on any other move. - goal_x: Option, - /// Content scroll inside the field: x for single-line, y for multiline, clamped at paint. - scroll_offset: gpui::Point, - /// Set by every caret-affecting change. - scroll_to_caret_pending: bool, - /// Bumped on every edit. - caret_epoch: usize, - /// When the current caret epoch started. - 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 { @@ -567,8 +480,6 @@ struct ShapeCacheKey { color: gpui::Hsla, } -impl EventEmitter for InputState {} - /// Builder for [`InputState`] settings that are fixed at creation. #[derive(Default)] pub struct InputStateBuilder { @@ -628,6 +539,57 @@ impl InputStateBuilder { } } +/// The application-owned state of a text field that [`Input`] renders. +pub struct InputState { + text: String, + /// The caret's byte offset. + cursor: usize, + /// The byte offset the selection extends from. + anchor: usize, + /// The byte range of in-progress IME composition, if any. + marked_range: Option>, + /// Whether the field had focus at the last paint, for focus transitions. + focused: bool, + focus_handle: gpui::FocusHandle, + /// The key-down handler, bound to this entity with `cx.listener`. + key_down_handler: KeyDownHandler, + /// The mouse-down handler, bound to this entity with `cx.listener`. + mouse_down_handler: MouseDownHandler, + /// Whether a drag-select is in progress. + dragging: bool, + /// Patch history. `redo_stack` holds undone entries awaiting redo. + undo_stack: Vec, + redo_stack: Vec, + /// Consecutive edits within this interval merge into one undo entry. + group_interval: Duration, + /// When set, user edits are refused; focus, movement, selection, and copy still work. + read_only: bool, + /// When set, the field is a password field. + password: bool, + /// Whether a password field currently shows its content. + revealed: bool, + /// Whether the field holds multiple lines of text. + multiline: bool, + /// Which keystroke submits a multiline field. + submit_on: SubmitOn, + /// The x the caret keeps across vertical movement, reset on any other move. + goal_x: Option, + /// Content scroll inside the field: x for single-line, y for multiline, clamped at paint. + scroll_offset: gpui::Point, + /// Set by every caret-affecting change. + scroll_to_caret_pending: bool, + /// Bumped on every edit. + caret_epoch: usize, + /// When the current caret epoch started. + 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>, +} + +impl EventEmitter for InputState {} + impl InputState { fn new_inner(cx: &mut Context) -> Self { Self { @@ -2517,14 +2479,8 @@ impl RenderOnce for Input { } /// Registers the input keybindings on the application, once at startup. -/// -/// Pass `None` for the platform defaults or an [`InputBindings`] table for -/// custom ones. -pub fn bind_input_keys(cx: &mut App, bindings: B) -where - B: Into>, -{ - cx.bind_keys(bindings.into().unwrap_or_default().into_bindings()); +pub fn bind_input_keys(cx: &mut App) { + cx.bind_keys(InputBindings::default().into_bindings()); } /// The row holding `display`. diff --git a/crates/ui/src/components/kbd.rs b/crates/ui/src/components/kbd.rs index a56cdf2..b9529fa 100644 --- a/crates/ui/src/components/kbd.rs +++ b/crates/ui/src/components/kbd.rs @@ -3,23 +3,19 @@ //! # Examples //! //! ```no_run -//! use gpui::{Keystroke, ParentElement as _}; -//! use ui::kbd::{Kbd, KbdGroup}; +//! use gpui::Keystroke; +//! use ui::kbd::Kbd; //! //! let save = Kbd::new(Keystroke::parse("cmd-s").unwrap()); -//! let combo = KbdGroup::new() -//! .child(Kbd::new(Keystroke::parse("ctrl-b").unwrap())) -//! .child(Kbd::new(Keystroke::parse("ctrl-k").unwrap())); //! ``` -use gpui::prelude::FluentBuilder as _; use gpui::{ - Action, AnyElement, App, FocusHandle, InteractiveElement as _, IntoElement, KeyBinding, - KeyContext, Keystroke, OperatingSystem, ParentElement as _, RenderOnce, SharedString, - StyleRefinement, Styled as _, Window, div, relative, + Action, App, InteractiveElement as _, IntoElement, KeyBinding, KeyContext, Keystroke, + OperatingSystem, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _, + Window, div, relative, }; -use crate::components::common::{StyledExt as _, h_flex}; +use crate::components::common::StyledExt as _; use crate::theme::ActiveTheme as _; /// A key or shortcut shown as a small key cap, like `⌘S` or `Ctrl+S`. @@ -27,7 +23,6 @@ use crate::theme::ActiveTheme as _; #[must_use] pub struct Kbd { stroke: Keystroke, - appearance: bool, style: StyleRefinement, } @@ -42,7 +37,6 @@ impl Kbd { pub fn new(stroke: Keystroke) -> Self { Self { stroke, - appearance: true, style: StyleRefinement::default(), } } @@ -52,12 +46,6 @@ impl Kbd { &self.stroke } - /// When false, paints the formatted shortcut as plain text without the key cap. - pub fn appearance(mut self, appearance: bool) -> Self { - self.appearance = appearance; - self - } - /// Returns a key cap for the highest-precedence binding of `action`. pub fn binding_for_action( action: &dyn Action, @@ -73,23 +61,6 @@ impl Kbd { Self::from_binding(&binding) } - /// Returns a key cap for the binding of `action`. - pub fn binding_for_action_in( - action: &dyn Action, - focus_handle: &FocusHandle, - window: &Window, - ) -> Option { - let binding = window.highest_precedence_binding_for_action_in(action, focus_handle)?; - Self::from_binding(&binding) - } - - /// Returns a key cap for the binding of `action` registered without a key context. - pub fn global_binding_for_action(action: &dyn Action, window: &Window) -> Option { - let binding = window - .highest_precedence_binding_for_action_in_context(action, KeyContext::default())?; - Self::from_binding(&binding) - } - /// Shows the binding's keystroke as the keymap holds it. fn from_binding(binding: &KeyBinding) -> Option { binding.keystrokes().first().map(|stroke| { @@ -102,7 +73,7 @@ impl Kbd { } /// Formats `stroke` for `os`: modifier symbols on macOS, `Ctrl+` words elsewhere. - pub fn format(stroke: &Keystroke, os: OperatingSystem) -> String { + fn format(stroke: &Keystroke, os: OperatingSystem) -> String { let mac = os == OperatingSystem::Mac; let separator = if mac { "" } else { "+" }; let mut parts: Vec<&str> = Vec::new(); @@ -253,60 +224,18 @@ impl RenderOnce for Kbd { let label = SharedString::from(Self::format(&self.stroke, os)); div() - // Lets a test ask whether this shortcut hint was painted this frame. .debug_selector(move || selector) - .when(self.appearance, |key| { - key.flex_none() - .border_1() - .border_color(theme.colors.border) - .bg(theme.colors.muted) - .text_color(theme.colors.muted_foreground) - .py_0p5() - .px_1() - .min_w_5() - .rounded(theme.radius.sm) - .text_center() - .line_height(relative(1.)) - .text_xs() - }) + .flex_none() + .bg(theme.colors.muted) + .text_color(theme.colors.muted_foreground) + .py_0p5() + .px_1() + .min_w_5() + .rounded(theme.radius.sm) + .text_center() + .line_height(relative(1.)) + .text_xs() .refine_style(&self.style) .child(label) } } - -/// A row of key caps, grouping the keys of a multi-key hint. -#[derive(IntoElement, Default)] -#[must_use] -pub struct KbdGroup { - style: StyleRefinement, - children: Vec, -} - -impl KbdGroup { - /// Creates an empty group. - pub fn new() -> Self { - Self::default() - } -} - -impl gpui::ParentElement for KbdGroup { - fn extend(&mut self, elements: impl IntoIterator) { - self.children.extend(elements); - } -} - -impl gpui::Styled for KbdGroup { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl RenderOnce for KbdGroup { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - h_flex() - .flex_none() - .gap_1() - .refine_style(&self.style) - .children(self.children) - } -} diff --git a/crates/ui/src/components/link.rs b/crates/ui/src/components/link.rs deleted file mode 100644 index 1442b3d..0000000 --- a/crates/ui/src/components/link.rs +++ /dev/null @@ -1,154 +0,0 @@ -//! Renders a link that opens a URL or fires a click handler. -//! -//! # Examples -//! -//! ```no_run -//! use ui::link::Link; -//! -//! let docs = Link::new("docs-link") -//! .label("Documentation") -//! .href("https://example.com/docs"); -//! -//! let settings = Link::new("settings-link") -//! .label("Open settings") -//! .on_click(|_event, _window, _cx| println!("open settings")); -//! ``` - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - App, ClickEvent, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, - RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, - Window, -}; - -use crate::components::common::{ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; - -/// The handler called with the [`gpui::ClickEvent`], replacing the default `href` opening. -type ClickHandler = Box; - -/// A hyperlink that opens a URL or fires a click handler. -#[derive(IntoElement)] -#[must_use] -pub struct Link { - id: ElementId, - label: Option, - href: Option, - size: Size, - disabled: bool, - a11y_label: Option, - on_click: Option, - style: StyleRefinement, -} - -impl Link { - /// Creates a link without a label or target. - pub fn new(id: I) -> Self - where - I: Into, - { - Self { - id: id.into(), - label: None, - href: None, - size: Size::default(), - disabled: false, - a11y_label: None, - on_click: None, - style: StyleRefinement::default(), - } - } - - /// Sets the visible label. - pub fn label(mut self, label: L) -> Self - where - L: Into, - { - self.label = Some(label.into()); - self - } - - /// Sets the URL the link opens through the platform. - pub fn href(mut self, href: U) -> Self - where - U: Into, - { - self.href = Some(href.into()); - self - } - - /// Renders the link inert, unfocusable, and dimmed; disabled always wins. - pub fn disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } - - /// Overrides the accessibility label, which defaults to the visible label. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } - - /// Replaces the default `href` opening with this handler. - pub fn on_click(mut self, handler: F) -> Self - where - F: Fn(&ClickEvent, &mut Window, &mut App) + 'static, - { - self.on_click = Some(Box::new(handler)); - self - } -} - -impl gpui::Styled for Link { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl Sizable for Link { - fn apply_size(&mut self, size: Size) { - self.size = size; - } -} - -impl RenderOnce for Link { - fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { - let theme = cx.theme(); - let colors = theme.colors; - let ramps = theme.ramps; - let size = self.size; - - let on_click = self.on_click; - let href = self.href; - let a11y_label = self.a11y_label.or_else(|| self.label.clone()); - - h_flex() - .id(self.id) - .control_text(size) - .text_color(ramps.primary.base) - .underline() - .refine_style(&self.style) - .role(Role::Link) - .when_some(a11y_label, |link, label| link.aria_label(label)) - .when(self.disabled, |link| link.opacity(DISABLED_OPACITY)) - .when(!self.disabled, |link| { - link.cursor_pointer() - .focusable() - .tab_stop(true) - .hover(move |style| style.text_color(ramps.primary.hover)) - .focus_visible(|style| style.shadow(focus_ring(colors.ring))) - .on_click(move |event, window, cx| match on_click.as_ref() { - Some(on_click) => on_click(event, window, cx), - None => { - if let Some(href) = href.as_ref() { - cx.open_url(href); - } - } - }) - }) - .when_some(self.label, |link, label| link.child(label)) - } -} diff --git a/crates/ui/src/components/list.rs b/crates/ui/src/components/list.rs deleted file mode 100644 index 9523ec3..0000000 --- a/crates/ui/src/components/list.rs +++ /dev/null @@ -1,290 +0,0 @@ -//! Renders a single-selection list of [`ListItem`] rows with keyboard navigation. -//! -//! # Examples -//! -//! ```no_run -//! use ui::list::{List, ListItem}; -//! -//! let folders = List::new("folders") -//! .selected(Some(0)) -//! .items(|_, _| { -//! vec![ -//! ListItem::new("documents", "Documents").detail("24 files"), -//! ListItem::new("downloads", "Downloads"), -//! ] -//! }) -//! .on_change(|_selected, _window, _cx| println!("selection changed")); -//! ``` - -use std::rc::Rc; - -use gpui::prelude::FluentBuilder; -use gpui::{ - AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, - ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, - 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, v_flex, -}; -use crate::icons::Icon; -use crate::theme::ActiveTheme as _; - -/// The change reporter, fired with the next selection by pointer and keys. -type ChangeHandler = Rc, &mut Window, &mut App)>; -/// The row builder, run during render. -type ItemsFn = Box Vec>; - -/// One row of a [`List`]. -#[must_use] -pub struct ListItem { - key: ElementId, - label: SharedString, - icon: Option, - detail: Option, - disabled: bool, -} - -impl ListItem { - /// Creates a row shown as `label`, identified by `key`. - pub fn new(key: K, label: L) -> Self - where - K: Into, - L: Into, - { - Self { - key: key.into(), - label: label.into(), - icon: None, - detail: None, - disabled: false, - } - } - - /// Shows an icon leading the label, a role or any custom [`crate::icons::IconNamed`]. - pub fn icon(mut self, icon: I) -> Self - where - I: Into, - { - self.icon = Some(icon.into()); - self - } - - /// Shows muted trailing text. - pub fn detail(mut self, detail: D) -> Self - where - D: Into, - { - self.detail = Some(detail.into()); - self - } - - /// Renders the row dimmed; clicks and keyboard skip it. - pub fn disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } -} - -// ListItem is a data builder, not an element, adopt the combinators explicitly. -impl FluentBuilder for ListItem {} - -/// A single-selection list of [`ListItem`] rows. -#[derive(IntoElement)] -#[must_use] -pub struct List { - id: ElementId, - selected: Option, - a11y_label: Option, - on_change: Option, - items: Option, - style: StyleRefinement, -} - -impl List { - /// Creates a list with nothing selected. - pub fn new(id: I) -> Self - where - I: Into, - { - Self { - id: id.into(), - selected: None, - a11y_label: None, - on_change: None, - items: None, - style: StyleRefinement::default(), - } - } - - /// Sets the current selection. - pub fn selected(mut self, selected: Option) -> Self { - self.selected = selected; - self - } - - /// Reports the next selection, from clicks and keys alike. - pub fn on_change(mut self, handler: F) -> Self - where - F: Fn(Option, &mut Window, &mut App) + 'static, - { - self.on_change = Some(Rc::new(handler)); - self - } - - /// Sets the rows; the closure runs during render and must not mutate entities or notify. - pub fn items(mut self, items: F) -> Self - where - F: Fn(&mut Window, &mut App) -> Vec + 'static, - { - self.items = Some(Box::new(items)); - self - } - - /// Overrides the accessibility label, which defaults to the id. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } -} - -impl gpui::Styled for List { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl RenderOnce for List { - fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { - let items = match self.items { - Some(build) => build(window, cx), - None => Vec::new(), - }; - - let selectable: Vec = items - .iter() - .enumerate() - .filter(|(_, item)| !item.disabled) - .map(|(index, _)| index) - .collect(); - - let focus = focus_handle(&self.id, window, cx); - - let label = self - .a11y_label - .clone() - .unwrap_or_else(|| SharedString::from(self.id.to_string())); - - let rows: Vec = items - .iter() - .enumerate() - .map(|(index, item)| { - item.render_row( - cx, - index, - items.len(), - self.selected == Some(index), - &self.on_change, - &focus, - ) - }) - .collect(); - - v_flex() - .id(self.id) - .gap_0p5() - .text_sm() - .refine_style(&self.style) - .track_focus(&focus) - .focusable() - .tab_stop(true) - .role(Role::List) - .aria_label(label) - .on_key_down({ - let selected = self.selected; - let on_change = self.on_change.clone(); - - move |event: &KeyDownEvent, window, cx| { - if nav_key(&selectable, selected, &event.keystroke.key, |next| { - if let Some(on_change) = &on_change { - on_change(next, window, cx); - } - }) { - cx.stop_propagation(); - } - } - }) - .children(rows) - } -} - -impl ListItem { - fn render_row( - &self, - cx: &App, - index: usize, - count: usize, - selected: bool, - on_change: &Option, - focus: &FocusHandle, - ) -> AnyElement { - let theme = cx.theme(); - let label_color = selectable_label_color(cx, selected, self.disabled); - let disabled = self.disabled; - - div() - .id((self.key.clone(), "list-item")) - .flex() - .items_center() - .gap_2() - .px_2() - .py_1() - .min_h_8() - .rounded(theme.radius.sm) - .role(Role::ListItem) - .aria_selected(selected) - .aria_position_in_set(index + 1) - .aria_size_of_set(count) - .map(|row| paint_selectable_row(cx, row, selected, disabled)) - .when(!disabled, |row| { - row.cursor_pointer().on_click({ - let on_change = on_change.clone(); - let focus = focus.clone(); - move |_, window, cx| { - window.focus(&focus, cx); - if let Some(on_change) = &on_change { - on_change(Some(index), window, cx); - } - } - }) - }) - .when_some(self.icon.clone(), |row, icon| { - row.child(icon.size(rems(1.0)).color(label_color)) - }) - .child( - div() - .flex_1() - .text_color(label_color) - .child(self.label.clone()), - ) - .when_some(self.detail.clone(), |row, detail| { - row.child( - div() - .flex_none() - .text_sm() - .text_color(if selected { - theme.colors.primary_foreground - } else { - theme.colors.muted_foreground - }) - .child(detail), - ) - }) - .into_any_element() - } -} diff --git a/crates/ui/src/components/markdown.rs b/crates/ui/src/components/markdown.rs index 068b502..0b94e6f 100644 --- a/crates/ui/src/components/markdown.rs +++ b/crates/ui/src/components/markdown.rs @@ -19,8 +19,6 @@ //! fn notes(cx: &mut App) -> TextView { //! let state = cx.new(|_| MarkdownViewState::new("notes", "# Notes\n- [x] shipped")); //! TextView::new(&state) -//! .on_link_click(|destination, _window, _cx| println!("{destination}")) -//! .on_task_toggle(|index, checked, _window, _cx| println!("{index}: {checked}")) //! } //! ``` @@ -29,7 +27,6 @@ use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; use std::ops::Range; use std::rc::Rc; -use std::sync::Arc; use gpui::prelude::FluentBuilder as _; use gpui::{ @@ -56,11 +53,6 @@ const BODY_LINE_HEIGHT: f32 = 1.6; /// The key context the text view declares while it holds focus. pub const TEXT_VIEW_CONTEXT: &str = "TextView"; -/// The callback a view invokes when the user clicks a markdown link. -pub type LinkClickHandler = Arc; -/// The callback a view invokes when the user toggles a task checkbox. -pub type TaskToggleHandler = Arc; - actions!(text_view, [Copy]); /// A heading level, 1 to 6. @@ -191,6 +183,94 @@ impl MarkdownBlock { self.hash(&mut hasher); hasher.finish() } + + /// The block's selectable text units, in render order. + fn block_text_units(&self) -> Vec { + match self { + MarkdownBlock::Heading { spans, .. } => vec![spans_text_of(spans)], + MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => { + let mut units: Vec = Vec::new(); + for item in items { + match item { + InlineItem::Text(span) => match units.last_mut() { + // Consecutive text items share the unit between images. + Some(unit) => unit.push_str(&span.text), + None => units.push(span.text.as_ref().to_string()), + }, + // An image starts the next unit; the render emits no + // element for it. + InlineItem::Image { .. } => units.push(String::new()), + } + } + units + } + MarkdownBlock::Code { lines, .. } => { + lines.lines.iter().map(|line| line.text()).collect() + } + MarkdownBlock::Table { table, .. } => table + .rows + .iter() + .flat_map(|row| row.cells.iter()) + .map(|cell| spans_text_of(&cell.spans)) + .collect(), + MarkdownBlock::Image { .. } | MarkdownBlock::ThematicBreak { .. } => Vec::new(), + } + } + + /// Renders one parsed block as a list row. + fn render_block(&self, block_index: usize, ctx: &BlockContext, cx: &App) -> AnyElement { + let gap = rems(0.75); + + match self { + MarkdownBlock::Heading { + level, + spans, + indent, + quote, + } => heading_row( + *level, + spans, + *indent, + *quote, + if block_index == 0 { + Rems::ZERO + } else { + rems(0.375) + }, + ctx, + cx, + ), + MarkdownBlock::Paragraph { + items, + indent, + quote, + } => text_row(items, *indent, *quote, gap, None, ctx, cx), + MarkdownBlock::ListItem { + marker, + items, + indent, + quote, + } => text_row(items, *indent, *quote, rems(0.2), Some(*marker), ctx, cx), + MarkdownBlock::Image { + source, + alt, + indent, + quote, + } => image_row(source, alt, *indent, *quote, ctx, cx), + MarkdownBlock::Code { + language, + lines, + indent, + quote, + } => code_row(lines, language.as_ref(), *indent, *quote, ctx, cx), + MarkdownBlock::ThematicBreak { indent, quote } => rule_row(*indent, *quote, ctx, cx), + MarkdownBlock::Table { + table, + indent, + quote, + } => table_row(table, *indent, *quote, ctx, cx), + } + } } /// One run of inline text sharing a style. @@ -235,8 +315,6 @@ pub struct MarkdownViewState { /// Drives the vertical scroll of the virtualized block list. handle: ListState, a11y_label: Option, - link_handler: Option, - task_toggle_handler: Option, /// `(anchor, head)` in the order they were set, over the rendered text. selection: Option<(usize, usize)>, /// Whether a drag is still extending the selection. @@ -265,8 +343,6 @@ impl MarkdownViewState { highlight_code: true, handle: ListState::new(count, ListAlignment::Top, CODE_OVERSCROLL_MAX), a11y_label: None, - link_handler: None, - task_toggle_handler: None, selection: None, selecting: false, focus_handle: None, @@ -360,34 +436,6 @@ impl MarkdownViewState { self } - /// Invokes `handler` when the user clicks a link, instead of opening it. - pub fn on_link_click(mut self, handler: F) -> Self - where - F: Fn(&SharedString, &mut Window, &mut App) + 'static, - { - self.link_handler = Some(Arc::new(handler)); - self - } - - /// Replaces the link click handler. - pub fn set_link_handler(&mut self, handler: LinkClickHandler) { - self.link_handler = Some(handler); - } - - /// Invokes `handler(block, checked)` when the user toggles a task checkbox. - pub fn on_task_toggle(mut self, handler: F) -> Self - where - F: Fn(usize, bool, &mut Window, &mut App) + 'static, - { - self.task_toggle_handler = Some(Arc::new(handler)); - self - } - - /// Replaces the task toggle handler. - pub fn set_task_toggle_handler(&mut self, handler: TaskToggleHandler) { - self.task_toggle_handler = Some(handler); - } - /// Selects a range over the rendered text, endpoints in byte offsets. pub fn select_range(&mut self, start: usize, end: usize, cx: &mut Context) { self.selection = Some((start, end)); @@ -430,8 +478,6 @@ impl Render for MarkdownViewState { let focus_handle = self.focus_handle(cx); let frame = std::rc::Rc::new(ViewFrame { state: state.clone(), - link_handler: self.link_handler.clone(), - task_toggle: self.task_toggle_handler.clone(), selection: self.selection(), focus_handle, pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)), @@ -455,7 +501,7 @@ impl Render for MarkdownViewState { block_index, block_id, }; - render_block(block, block_index, &ctx, cx) + block.render_block(block_index, &ctx, cx) } None => div().into_any_element(), } @@ -481,8 +527,6 @@ impl Render for MarkdownViewState { /// The per-frame context the view's renderers wire themselves from. struct ViewFrame { state: Entity, - link_handler: Option, - task_toggle: Option, /// The selection over the rendered text, endpoints in document order. selection: Option<(usize, usize)>, focus_handle: gpui::FocusHandle, @@ -525,7 +569,6 @@ impl BlockContext<'_> { Some(PieceContext { state: self.frame.state.clone(), - link_handler: self.frame.link_handler.clone(), doc_range: piece.range.clone(), selected, pressed_on_piece: self.frame.pressed_on_piece.clone(), @@ -536,7 +579,6 @@ impl BlockContext<'_> { /// What one selectable text element wires itself from. struct PieceContext { state: Entity, - link_handler: Option, /// The piece's byte range in the rendered text. doc_range: Range, /// The selection overlap, in piece-local bytes. @@ -579,7 +621,7 @@ impl TextDocument { .iter() .position(|piece| piece.block_index != block_index) .map_or(self.pieces.len(), |offset| piece_ix + offset); - let units = block_text_units(block); + let units = block.block_text_units(); for piece in &self.pieces[piece_ix..block_end] { let Some(unit) = units.get(piece.sub_index).filter(|unit| !unit.is_empty()) else { @@ -602,8 +644,6 @@ pub struct TextView { id: ElementId, source: Option, state: Option>, - link_handler: Option, - task_toggle_handler: Option, style: StyleRefinement, } @@ -618,8 +658,6 @@ impl TextView { id: id.into(), source: Some(source.into()), state: None, - link_handler: None, - task_toggle_handler: None, style: StyleRefinement::default(), } } @@ -630,29 +668,9 @@ impl TextView { id: ElementId::from(SharedString::from(format!("{}", state.entity_id()))), source: None, state: Some(state.clone()), - link_handler: None, - task_toggle_handler: None, style: StyleRefinement::default(), } } - - /// Invokes `handler` when the user clicks a link, instead of opening it. - pub fn on_link_click(mut self, handler: F) -> Self - where - F: Fn(&SharedString, &mut Window, &mut App) + 'static, - { - self.link_handler = Some(Arc::new(handler)); - self - } - - /// Invokes `handler(block, checked)` when the user toggles a task checkbox. - pub fn on_task_toggle(mut self, handler: F) -> Self - where - F: Fn(usize, bool, &mut Window, &mut App) + 'static, - { - self.task_toggle_handler = Some(Arc::new(handler)); - self - } } impl Styled for TextView { @@ -693,8 +711,6 @@ impl Element for TextView { }; let source = self.source.clone(); - let link_handler = self.link_handler.clone(); - let task_toggle = self.task_toggle_handler.clone(); let (selection, focus_handle) = state.update(cx, |view, cx| (view.selection(), view.focus_handle(cx))); @@ -703,19 +719,11 @@ impl Element for TextView { if let Some(source) = source { view.set_source(source, cx); } - if let Some(link_handler) = link_handler { - view.set_link_handler(link_handler); - } - if let Some(task_toggle) = task_toggle { - view.set_task_toggle_handler(task_toggle); - } }); let view = state.read(cx); let frame = ViewFrame { state: state.clone(), - link_handler: view.link_handler.clone(), - task_toggle: view.task_toggle_handler.clone(), selection, focus_handle, pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)), @@ -908,7 +916,7 @@ fn render_blocks( block_index, block_id, }; - render_block(block, block_index, &ctx, cx) + block.render_block(block_index, &ctx, cx) }, )) } @@ -917,37 +925,6 @@ fn spans_text_of(spans: &[InlineSpan]) -> String { spans.iter().map(|span| span.text.as_ref()).collect() } -/// The selectable text units of a block. -fn block_text_units(block: &MarkdownBlock) -> Vec { - match block { - MarkdownBlock::Heading { spans, .. } => vec![spans_text_of(spans)], - MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => { - let mut units: Vec = Vec::new(); - for item in items { - match item { - InlineItem::Text(span) => match units.last_mut() { - // Consecutive text items share the unit between images. - Some(unit) => unit.push_str(&span.text), - None => units.push(span.text.as_ref().to_string()), - }, - // An image starts the next unit; the render emits no - // element for it. - InlineItem::Image { .. } => units.push(String::new()), - } - } - units - } - MarkdownBlock::Code { lines, .. } => lines.lines.iter().map(|line| line.text()).collect(), - MarkdownBlock::Table { table, .. } => table - .rows - .iter() - .flat_map(|row| row.cells.iter()) - .map(|cell| spans_text_of(&cell.spans)) - .collect(), - MarkdownBlock::Image { .. } | MarkdownBlock::ThematicBreak { .. } => Vec::new(), - } -} - /// Enumerates the selectable text pieces of `blocks`, in render order. fn text_document(blocks: &[MarkdownBlock]) -> TextDocument { let mut pieces = Vec::new(); @@ -960,7 +937,7 @@ fn text_document(blocks: &[MarkdownBlock]) -> TextDocument { MarkdownBlock::Paragraph { .. } | MarkdownBlock::ListItem { .. } ); - for (sub_index, unit) in block_text_units(block).into_iter().enumerate() { + for (sub_index, unit) in block.block_text_units().into_iter().enumerate() { if unit.is_empty() && skip_empty { continue; } @@ -1405,66 +1382,6 @@ fn flush_item_inline( }); } -/// Renders one parsed block as a list row. -fn render_block( - block: &MarkdownBlock, - block_index: usize, - ctx: &BlockContext, - cx: &App, -) -> AnyElement { - let gap = rems(0.75); - - match block { - MarkdownBlock::Heading { - level, - spans, - indent, - quote, - } => heading_row( - *level, - spans, - *indent, - *quote, - if block_index == 0 { - Rems::ZERO - } else { - rems(0.375) - }, - ctx, - cx, - ), - MarkdownBlock::Paragraph { - items, - indent, - quote, - } => text_row(items, *indent, *quote, gap, None, ctx, cx), - MarkdownBlock::ListItem { - marker, - items, - indent, - quote, - } => text_row(items, *indent, *quote, rems(0.2), Some(*marker), ctx, cx), - MarkdownBlock::Image { - source, - alt, - indent, - quote, - } => image_row(source, alt, *indent, *quote, ctx, cx), - MarkdownBlock::Code { - language, - lines, - indent, - quote, - } => code_row(lines, language.as_ref(), *indent, *quote, ctx, cx), - MarkdownBlock::ThematicBreak { indent, quote } => rule_row(*indent, *quote, ctx, cx), - MarkdownBlock::Table { - table, - indent, - quote, - } => table_row(table, *indent, *quote, ctx, cx), - } -} - /// 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(); @@ -1579,22 +1496,17 @@ fn text_row( .into_any_element() } -/// The task marker: a checkbox that reports toggles when a handler is set. +/// The task marker: a checkbox that renders the state without toggling. fn task_toggle(checked: bool, label: SharedString, ctx: &BlockContext) -> AnyElement { let block_index = ctx.block_index; let selector = SharedString::from(format!("task-toggle-{block_index}")); - let checkbox = Checkbox::new((ctx.block_id.clone(), "task")) + Checkbox::new((ctx.block_id.clone(), "task")) .debug_selector(move || selector.to_string()) .checked(checked) .with_size(Size::Small) - .accessibility_label(label); - - match ctx.frame.task_toggle.clone() { - Some(handler) => checkbox - .on_change(move |next, window, cx| handler(block_index, next, window, cx)) - .into_any_element(), - None => checkbox.disabled(true).into_any_element(), - } + .accessibility_label(label) + .disabled(true) + .into_any_element() } /// The item's plain text, for the checkbox's accessibility label. @@ -2016,16 +1928,12 @@ where let inner = if destinations.is_empty() { styled.into_any_element() } else { - let link_handler = piece.as_ref().and_then(|piece| piece.link_handler.clone()); InteractiveText::new(id.clone(), styled) - .on_click(link_ranges, move |range_ix, window, cx| { + .on_click(link_ranges, move |range_ix, _window, cx| { let Some(destination) = destinations.get(range_ix) else { return; }; - match link_handler.as_ref() { - Some(handler) => handler(destination, window, cx), - None => cx.open_url(destination.as_ref()), - } + cx.open_url(destination.as_ref()); }) .into_any_element() }; diff --git a/crates/ui/src/components/menu.rs b/crates/ui/src/components/menu.rs index ba78c63..43d246d 100644 --- a/crates/ui/src/components/menu.rs +++ b/crates/ui/src/components/menu.rs @@ -54,6 +54,14 @@ type TriggerFn = Box AnyElement>; /// The menu's rows, rebuilt on each render while open. type ItemsFn = Box Vec>; +/// One row of a [`Menu`]: an action, a checkable action, a submenu, or a separator. +#[derive(Clone)] +enum MenuItemKind { + Action, + Separator, + Submenu(Rc<[MenuItem]>), +} + /// One row of a [`Menu`]: an action, a checkable action, a submenu, or a separator. #[derive(Clone)] #[must_use] @@ -62,20 +70,12 @@ pub struct MenuItem { kind: MenuItemKind, label: SharedString, icon: Option, - shortcut: Option, handler: Option, disabled: bool, destructive: bool, checked: bool, } -#[derive(Clone)] -enum MenuItemKind { - Action, - Separator, - Submenu(Rc<[MenuItem]>), -} - impl MenuItem { /// Creates an action row with this label. pub fn new(label: L) -> Self @@ -87,7 +87,6 @@ impl MenuItem { kind: MenuItemKind::Action, label: label.into(), icon: None, - shortcut: None, handler: None, disabled: false, destructive: false, @@ -102,7 +101,6 @@ impl MenuItem { kind: MenuItemKind::Separator, label: SharedString::default(), icon: None, - shortcut: None, handler: None, disabled: false, destructive: false, @@ -137,15 +135,6 @@ impl MenuItem { self } - /// Shows a shortcut hint after the label. - pub fn shortcut(mut self, shortcut: S) -> Self - where - S: Into, - { - self.shortcut = Some(shortcut.into()); - self - } - /// Marks the item non-selectable and non-activatable. pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; @@ -185,6 +174,226 @@ impl MenuItem { fn selectable(&self) -> bool { matches!(self.kind, MenuItemKind::Action | MenuItemKind::Submenu(_)) && !self.disabled } + + /// Renders one menu row. + fn render_item( + &self, + window: &mut Window, + cx: &mut App, + index: usize, + selected: bool, + env: &RowEnv, + ) -> AnyElement { + match &self.kind { + MenuItemKind::Separator => div() + .h_px() + .debug_selector(move || format!("{}-separator-{index}", env.debug_prefix)) + .mx_2() + .my_1() + .bg(env.chrome.border) + .into_any_element(), + MenuItemKind::Action => { + let label_color = self.row_color(selected, false, env.chrome); + let disabled = self.disabled; + let checked = self.checked; + let icon = self.icon.clone(); + + self.row_shell(cx, index, selected, env) + .on_click({ + let handler = self.handler.clone(); + let on_activate = env.on_activate.clone(); + move |_, window, cx| { + if disabled { + return; + } + + if let Some(on_activate) = &on_activate { + on_activate(false, window, cx); + } + + if let Some(handler) = &handler { + handler(window, cx); + } + } + }) + .when_some(icon, |row, icon| { + row.child(icon.size(rems(1.0)).color(label_color)) + }) + .child( + div() + .flex_1() + .text_color(label_color) + .child(self.label.clone()), + ) + .when(checked, |row| { + row.child( + icon_glyph(IconRole::Check) + .size(rems(0.75)) + .color(label_color), + ) + }) + .into_any_element() + } + MenuItemKind::Submenu(items) => { + let chrome = env.chrome; + let flyout = env.flyout; + let disabled = self.disabled; + let open = *flyout.open.read(cx) == Some(index); + let label_color = self.row_color(selected, open, chrome); + let row_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); + + self.row_shell(cx, index, selected, env) + .on_click({ + let set_flyout = flyout.set_flyout.clone(); + move |_, _window, cx| { + if disabled { + return; + } + // Hover already opens the flyout; a click never closes it. + set_flyout(Some(index), false, cx); + } + }) + .child( + div() + .flex_1() + .text_color(label_color) + .child(self.label.clone()), + ) + .child( + icon_glyph(IconRole::ChevronRight) + .size(rems(0.75)) + .color(label_color), + ) + .aria_expanded(open) + .when(open, |row| { + row.child( + canvas( + { + let cell = row_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + .child( + deferred(div().absolute().left_full().top_0().child(menu_panel( + window, + cx, + flyout.state, + MenuPanelParams { + id: &flyout.id, + items: items.clone(), + initial_selection: None, + preselect: *flyout.preselect.read(cx), + min_width: flyout.min_width, + label: self.label.clone(), + dismiss_bounds: &row_bounds, + bounds_sink: Some(flyout.bounds), + outer_stack: Some(flyout.stack), + on_dismiss: Some(flyout.dismiss.clone()), + on_activate: flyout.on_activate.clone(), + is_flyout: true, + chrome, + enter_duration: flyout.enter_duration, + debug_prefix: "submenu", + }, + ))) + .with_priority(OVERLAY_LAYER), + ) + }) + .into_any_element() + } + } + } + + /// The shared row shell: dimensions, highlight, and hover-selection. + fn row_shell( + &self, + cx: &App, + index: usize, + selected: bool, + env: &RowEnv, + ) -> gpui::Stateful { + let chrome = env.chrome; + let selectable = self.selectable(); + let opens_submenu = self.submenu_items().is_some(); + let flyout_open = *env.flyout.open.read(cx) == Some(index); + let row_id = self + .id + .clone() + .unwrap_or_else(|| ("menu-item", index).into()); + + div() + .id(row_id) + .role(Role::MenuItem) + .debug_selector(move || format!("{}-item-{index}", env.debug_prefix)) + .flex() + .items_center() + .gap_2() + .min_h_8() + .px_4() + .text_sm() + .line_height(relative(1.0)) + .rounded(chrome.radius_full) + .map(|row| { + if self.disabled { + row + } else if selected && flyout_open { + row.bg(chrome.muted_hover) + } else if selected { + let highlight = if self.destructive { + chrome.destructive + } else { + chrome.primary + }; + row.bg(highlight) + } else { + row.hover(|row| row.bg(chrome.muted_hover)) + } + }) + .on_mouse_move({ + let selection = env.selection.clone(); + let flyout_open = env.flyout.open.clone(); + let set_flyout = env.flyout.set_flyout.clone(); + let dismiss = env.flyout.dismiss.clone(); + move |_, window, cx| { + if !selectable { + return; + } + + if *selection.read(cx) != Some(index) { + selection.update(cx, |selection, _| *selection = Some(index)); + } + + if opens_submenu { + set_flyout(Some(index), false, cx); + } else if flyout_open.read(cx).is_some() { + dismiss(false, window, cx); + } + } + }) + } + + /// The row's label/icon color. + fn row_color(&self, selected: bool, flyout_open: bool, chrome: &MenuChrome) -> gpui::Hsla { + if self.disabled { + return chrome.muted_foreground; + } + if self.destructive { + return if selected && !flyout_open { + chrome.destructive_foreground + } else { + chrome.destructive + }; + } + if selected && !flyout_open { + chrome.primary_foreground + } else { + chrome.foreground + } + } } // MenuItem is a data builder, not an element, adopt the combinators explicitly. @@ -378,49 +587,12 @@ impl RenderOnce for Menu { div() .relative() .refine_style(&self.style) - .child( - canvas( - { - let cell = trigger_bounds.clone(); - move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) - }, - { - let on_change = on_change; - let open = self.open; - let trigger_button = self.trigger_button; - let cell = trigger_bounds.clone(); - - move |_, _, window, _cx| { - let trigger_bounds = cell; - - window.on_mouse_event({ - let on_change = on_change.clone(); - move |event: &MouseDownEvent, phase, window, cx| { - if phase != DispatchPhase::Bubble - || event.button != trigger_button - { - return; - } - - let on_trigger = trigger_bounds - .borrow() - .is_some_and(|bounds| bounds.contains(&event.position)); - if !on_trigger { - return; - } - - if let Some(on_change) = &on_change { - on_change(!open, window, cx); - } - cx.stop_propagation(); - } - }); - } - }, - ) - .absolute() - .inset_0(), - ) + .child(trigger_toggle( + &trigger_bounds, + self.open, + on_change.clone(), + self.trigger_button, + )) .when_some(self.trigger, |wrapper, trigger| { wrapper.child(trigger(window, cx)) }) @@ -455,15 +627,6 @@ struct MenuPanelState { selection: Entity>, } -fn create_menu_panel_state(id: &ElementId, window: &mut Window, cx: &mut App) -> MenuPanelState { - MenuPanelState { - focus: focus_handle(&(id.clone(), "panel").into(), window, cx), - was_open: window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false), - scroll: window.use_keyed_state((id.clone(), "menu-scroll"), cx, |_, _| ScrollHandle::new()), - selection: window.use_keyed_state((id.clone(), "menu-selection"), cx, |_, _| None), - } -} - struct MenuPanelParams<'a> { id: &'a ElementId, items: Rc<[MenuItem]>, @@ -513,6 +676,104 @@ struct RowEnv<'a> { debug_prefix: &'static str, } +/// Everything key navigation needs from the panel. +struct MenuKeyEnv<'a> { + items: &'a [MenuItem], + selection: &'a Entity>, + set_flyout: &'a FlyoutSetter, + on_dismiss: &'a Option, + on_activate: &'a Option, + left_dismisses: bool, +} + +/// Canvas that records the trigger's painted bounds and toggles `open` on click. +pub(crate) fn trigger_toggle( + bounds: &TriggerBoundsCell, + open: bool, + on_change: Option, + button: MouseButton, +) -> AnyElement { + let painted = bounds.clone(); + + canvas( + { + let cell = bounds.clone(); + move |painted, _window, _cx| *cell.borrow_mut() = Some(painted) + }, + move |_, _, window, _cx| { + let cell = painted.clone(); + window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble || event.button != button { + return; + } + + let on_trigger = cell + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)); + if !on_trigger { + return; + } + + if let Some(on_change) = &on_change { + on_change(!open, window, cx); + } + cx.stop_propagation(); + }); + }, + ) + .absolute() + .inset_0() + .into_any_element() +} + +/// Deferred anchored overlay on OVERLAY_LAYER, optionally fading in. +pub(crate) fn anchored_overlay( + position: Option>, + panel: AnyElement, + fade: Option<(&'static str, std::time::Duration)>, +) -> AnyElement { + let anchored = match position { + Some(position) => anchored().position(position), + None => anchored(), + } + .offset(point(px(0.), px(4.))); + + // AnyElement lacks `Styled`, so the opacity animation rides a wrapper. + let panel = match fade { + Some((id, duration)) => div() + .child(panel) + .with_animation( + id, + Animation::new(duration).with_easing(ease_out_quint()), + |panel, delta| panel.opacity(delta), + ) + .into_any_element(), + None => panel, + }; + + deferred(anchored.child(panel)) + .with_priority(OVERLAY_LAYER) + .into_any_element() +} + +/// Canvas that grabs focus when `should_grab` holds. +pub(crate) fn focus_capture( + focus: FocusHandle, + should_grab: impl Fn(&mut Window, &mut App) -> bool + 'static, +) -> AnyElement { + canvas( + |_, _, _| {}, + move |_, _, window, cx| { + if should_grab(window, cx) { + window.focus(&focus, cx); + } + }, + ) + .absolute() + .inset_0() + .into_any_element() +} + /// Assembles the floating menu panel anchored to its trigger. pub(crate) fn anchored_menu_panel( window: &mut Window, @@ -524,8 +785,6 @@ pub(crate) fn anchored_menu_panel( ) -> Option { let was_open = window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false); - // Render-phase residue: trigger-toggle and owner-driven closes bypass every - // dismissal handler, so this closed frame is the only universal close hook. if !spec.open { was_open.update(cx, |was_open, _| *was_open = false); // A closed menu drops any open flyout; fresh state on the next open. @@ -562,17 +821,7 @@ pub(crate) fn anchored_menu_panel( }, ); - let anchored = match spec.position { - Some(position) => anchored().position(position), - None => anchored(), - } - .offset(point(px(0.), px(4.))); - - Some( - deferred(anchored.child(panel)) - .with_priority(OVERLAY_LAYER) - .into_any_element(), - ) + Some(anchored_overlay(spec.position, panel, None)) } /// Builds one menu panel: chrome, rows, focus, navigation, and dismissals. @@ -668,10 +917,9 @@ fn menu_panel( .iter() .enumerate() .map(|(index, item)| { - render_item( + item.render_item( window, cx, - item, index, selected == Some(index), &RowEnv { @@ -791,254 +1039,6 @@ fn menu_panel( .into_any_element() } -/// Renders one menu row. -fn render_item( - window: &mut Window, - cx: &mut App, - item: &MenuItem, - index: usize, - selected: bool, - env: &RowEnv, -) -> AnyElement { - match &item.kind { - MenuItemKind::Separator => div() - .h_px() - .debug_selector(move || format!("{}-separator-{index}", env.debug_prefix)) - .mx_2() - .my_1() - .bg(env.chrome.border) - .into_any_element(), - MenuItemKind::Action => { - let label_color = row_color(item, selected, false, env.chrome); - let disabled = item.disabled; - let destructive = item.destructive; - let checked = item.checked; - let shortcut = item.shortcut.clone(); - let icon = item.icon.clone(); - - row_shell(cx, item, index, selected, env) - .on_click({ - let handler = item.handler.clone(); - let on_activate = env.on_activate.clone(); - move |_, window, cx| { - if disabled { - return; - } - - if let Some(on_activate) = &on_activate { - on_activate(false, window, cx); - } - - if let Some(handler) = &handler { - handler(window, cx); - } - } - }) - .when_some(icon, |row, icon| { - row.child(icon.size(rems(1.0)).color(label_color)) - }) - .child( - div() - .flex_1() - .text_color(label_color) - .child(item.label.clone()), - ) - .when_some(shortcut, |row, shortcut| { - row.child( - div() - .text_color(if selected && !destructive && !disabled { - env.chrome.primary_foreground - } else { - env.chrome.muted_foreground - }) - .child(shortcut), - ) - }) - .when(checked, |row| { - row.child( - icon_glyph(IconRole::Check) - .size(rems(0.75)) - .color(label_color), - ) - }) - .into_any_element() - } - MenuItemKind::Submenu(items) => { - let chrome = env.chrome; - let flyout = env.flyout; - let disabled = item.disabled; - let open = *flyout.open.read(cx) == Some(index); - let label_color = row_color(item, selected, open, chrome); - let row_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); - - row_shell(cx, item, index, selected, env) - .on_click({ - let set_flyout = flyout.set_flyout.clone(); - move |_, _window, cx| { - if disabled { - return; - } - // Hover already opens the flyout; a click never closes it. - set_flyout(Some(index), false, cx); - } - }) - .child( - div() - .flex_1() - .text_color(label_color) - .child(item.label.clone()), - ) - .child( - icon_glyph(IconRole::ChevronRight) - .size(rems(0.75)) - .color(label_color), - ) - .aria_expanded(open) - .when(open, |row| { - row.child( - canvas( - { - let cell = row_bounds.clone(); - move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) - }, - |_, _, _, _| {}, - ) - .absolute() - .inset_0(), - ) - .child( - deferred(div().absolute().left_full().top_0().child(menu_panel( - window, - cx, - flyout.state, - MenuPanelParams { - id: &flyout.id, - items: items.clone(), - initial_selection: None, - preselect: *flyout.preselect.read(cx), - min_width: flyout.min_width, - label: item.label.clone(), - dismiss_bounds: &row_bounds, - bounds_sink: Some(flyout.bounds), - outer_stack: Some(flyout.stack), - on_dismiss: Some(flyout.dismiss.clone()), - on_activate: flyout.on_activate.clone(), - is_flyout: true, - chrome, - enter_duration: flyout.enter_duration, - debug_prefix: "submenu", - }, - ))) - .with_priority(OVERLAY_LAYER), - ) - }) - .into_any_element() - } - } -} - -/// The shared row shell: dimensions, highlight, and hover-selection. -fn row_shell( - cx: &App, - item: &MenuItem, - index: usize, - selected: bool, - env: &RowEnv, -) -> gpui::Stateful { - let chrome = env.chrome; - let selectable = item.selectable(); - let opens_submenu = item.submenu_items().is_some(); - let flyout_open = *env.flyout.open.read(cx) == Some(index); - let row_id = item - .id - .clone() - .unwrap_or_else(|| ("menu-item", index).into()); - - div() - .id(row_id) - .role(Role::MenuItem) - .debug_selector(move || format!("{}-item-{index}", env.debug_prefix)) - .flex() - .items_center() - .gap_2() - .min_h_8() - .px_4() - .text_sm() - .line_height(relative(1.0)) - .rounded(chrome.radius_full) - .map(|row| { - if item.disabled { - row - } else if selected && flyout_open { - row.bg(chrome.muted_hover) - } else if selected { - let highlight = if item.destructive { - chrome.destructive - } else { - chrome.primary - }; - row.bg(highlight) - } else { - row.hover(|row| row.bg(chrome.muted_hover)) - } - }) - .on_mouse_move({ - let selection = env.selection.clone(); - let flyout_open = env.flyout.open.clone(); - let set_flyout = env.flyout.set_flyout.clone(); - let dismiss = env.flyout.dismiss.clone(); - move |_, window, cx| { - if !selectable { - return; - } - - if *selection.read(cx) != Some(index) { - selection.update(cx, |selection, _| *selection = Some(index)); - } - - if opens_submenu { - set_flyout(Some(index), false, cx); - } else if flyout_open.read(cx).is_some() { - dismiss(false, window, cx); - } - } - }) -} - -/// The row's label/icon color. -fn row_color( - item: &MenuItem, - selected: bool, - flyout_open: bool, - chrome: &MenuChrome, -) -> gpui::Hsla { - if item.disabled { - return chrome.muted_foreground; - } - if item.destructive { - return if selected && !flyout_open { - chrome.destructive_foreground - } else { - chrome.destructive - }; - } - if selected && !flyout_open { - chrome.primary_foreground - } else { - chrome.foreground - } -} - -/// Everything key navigation needs from the panel. -struct MenuKeyEnv<'a> { - items: &'a [MenuItem], - selection: &'a Entity>, - set_flyout: &'a FlyoutSetter, - on_dismiss: &'a Option, - on_activate: &'a Option, - left_dismisses: bool, -} - /// Handles the panel's navigation keys. fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, cx: &mut App) { let selectable: Vec = env @@ -1111,3 +1111,13 @@ fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, c cx.stop_propagation(); } + +/// Creates one panel's keyed state: focus, open tracking, scroll, and selection. +fn create_menu_panel_state(id: &ElementId, window: &mut Window, cx: &mut App) -> MenuPanelState { + MenuPanelState { + focus: focus_handle(&(id.clone(), "panel").into(), window, cx), + was_open: window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false), + scroll: window.use_keyed_state((id.clone(), "menu-scroll"), cx, |_, _| ScrollHandle::new()), + selection: window.use_keyed_state((id.clone(), "menu-selection"), cx, |_, _| None), + } +} diff --git a/crates/ui/src/components/mod.rs b/crates/ui/src/components/mod.rs index 4dbaaa7..c213d56 100644 --- a/crates/ui/src/components/mod.rs +++ b/crates/ui/src/components/mod.rs @@ -10,9 +10,7 @@ pub mod code; pub mod combobox; pub mod command_palette; pub mod common; -pub mod context_menu; pub mod dialog; -pub mod diff; pub mod dropdown_menu; pub mod empty_state; pub mod field; @@ -20,21 +18,15 @@ pub mod grain; pub mod highlight; pub mod input; pub mod kbd; -pub mod link; -pub mod list; pub mod markdown; pub mod menu; pub mod popover; -pub mod progress; -pub mod radio; pub mod scroll_area; pub mod scrollbar; pub mod segmented; pub mod select; pub mod separator; pub mod sidebar; -pub mod slider; -pub mod speech; pub mod spinner; pub mod status_dot; pub mod switch; diff --git a/crates/ui/src/components/popover.rs b/crates/ui/src/components/popover.rs index 29bd36c..c6c67af 100644 --- a/crates/ui/src/components/popover.rs +++ b/crates/ui/src/components/popover.rs @@ -24,24 +24,21 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder as _; use gpui::{ - Animation, AnimationExt as _, AnyElement, App, Bounds, DispatchPhase, ElementId, - InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, - ParentElement as _, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, Window, anchored, canvas, deferred, div, ease_out_quint, point, - px, + AnyElement, App, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, + ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, + StyleRefinement, Styled as _, Window, div, }; -use crate::components::common::{OVERLAY_LAYER, StyledExt as _, floating_panel, v_flex}; +use crate::components::menu::{ + ChangeHandler, TriggerBoundsCell, anchored_overlay, focus_capture, trigger_toggle, +}; +use crate::components::common::{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. -type ChangeHandler = Rc; /// The element the panel anchors below, built during render. type TriggerFn = Box AnyElement>; /// The panel's contents, built when it opens. type ContentFn = Box AnyElement>; -/// Bounds captured during the last paint, shared with the dismissal listener. -type BoundsCell = Rc>>>; /// A floating panel anchored below its trigger. #[derive(IntoElement)] @@ -134,7 +131,7 @@ impl RenderOnce for Popover { ) }; - let trigger_bounds: BoundsCell = Rc::new(RefCell::new(None)); + let trigger_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); let fallback_label = self .a11y_label @@ -144,49 +141,12 @@ impl RenderOnce for Popover { div() .relative() .refine_style(&self.style) - .child( - canvas( - { - let cell = trigger_bounds.clone(); - move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) - }, - { - let on_change = self.on_change.clone(); - let open = self.open; - let cell = trigger_bounds.clone(); - - move |_, _, window, _cx| { - window.on_mouse_event({ - let on_change = on_change.clone(); - let trigger_bounds = cell; - move |event: &MouseDownEvent, phase, window, cx| { - if phase != DispatchPhase::Bubble - || event.button != MouseButton::Left - { - return; - } - - let on_trigger = trigger_bounds - .borrow() - .is_some_and(|bounds| bounds.contains(&event.position)); - - if !on_trigger { - return; - } - - if let Some(on_change) = &on_change { - on_change(!open, window, cx); - } - - cx.stop_propagation(); - } - }); - } - }, - ) - .absolute() - .inset_0(), - ) + .child(trigger_toggle( + &trigger_bounds, + self.open, + self.on_change.clone(), + MouseButton::Left, + )) .when_some(self.trigger, |wrapper, trigger| { wrapper.child(trigger(window, cx)) }) @@ -238,29 +198,16 @@ impl RenderOnce for Popover { } }) .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(), - ); + .child(focus_capture( + focus.clone(), + move |window, cx| !focus.contains_focused(window, cx), + )); - wrapper.child( - deferred(anchored().offset(point(Pixels::ZERO, px(4.))).child( - panel.with_animation( - "popover-enter", - Animation::new(enter_duration).with_easing(ease_out_quint()), - |panel, delta| panel.opacity(delta), - ), - )) - .with_priority(OVERLAY_LAYER), - ) + wrapper.child(anchored_overlay( + None, + panel.into_any_element(), + Some(("popover-enter", enter_duration)), + )) }) } } diff --git a/crates/ui/src/components/progress.rs b/crates/ui/src/components/progress.rs deleted file mode 100644 index 040cd47..0000000 --- a/crates/ui/src/components/progress.rs +++ /dev/null @@ -1,132 +0,0 @@ -//! Renders a progress bar with a determinate fill or an indeterminate sweep. -//! -//! # Examples -//! -//! ```no_run -//! use ui::progress::Progress; -//! -//! let upload = Progress::new("upload", 0.4); -//! let loading = Progress::new("loading", 0.0).indeterminate(true); -//! ``` - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - Animation, AnimationExt as _, App, ElementId, InteractiveElement as _, IntoElement, - ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, Window, div, relative, -}; - -use crate::components::common::{Sizable, StyledExt as _}; -use crate::theme::{ActiveTheme as _, PROGRESS_ANIMATION_PERIOD, Size}; - -/// A bar that paints a determinate fill from its `value`, or an indeterminate sweep. -#[derive(IntoElement)] -#[must_use] -pub struct Progress { - id: ElementId, - value: f32, - indeterminate: bool, - size: Size, - a11y_label: Option, - style: StyleRefinement, -} - -impl Progress { - /// Creates a determinate progress bar at `value` (`0..=1`). - pub fn new(id: I, value: f32) -> Self - where - I: Into, - { - Self { - id: id.into(), - value, - indeterminate: false, - size: Size::default(), - a11y_label: None, - style: StyleRefinement::default(), - } - } - - /// Sweeps instead of painting a fill, for work of unknown length. - pub fn indeterminate(mut self, indeterminate: bool) -> Self { - self.indeterminate = indeterminate; - self - } - - /// Sets the accessibility label. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } -} - -impl gpui::Styled for Progress { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl Sizable for Progress { - fn apply_size(&mut self, size: Size) { - self.size = size; - } -} - -impl RenderOnce for Progress { - 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; - let size = self.size; - - let value = self.value.clamp(0.0, 1.0); - - let track = div().w_full().rounded(radius.full).bg(colors.border); - let track = match size { - Size::XSmall => track.h_0p5(), - Size::Small | Size::Medium => track.h_1(), - Size::Large => track.h_1p5(), - }; - - div() - .id(self.id) - .w_full() - .refine_style(&self.style) - .role(Role::ProgressIndicator) - .when_some(self.a11y_label, |progress, label| { - progress.aria_label(label) - }) - .when(!self.indeterminate, |progress| { - progress - .aria_numeric_value(f64::from(value)) - .aria_min_numeric_value(0.0) - .aria_max_numeric_value(1.0) - }) - .child(track.child(if self.indeterminate { - div() - .h_full() - .w(relative(0.3)) - .rounded(radius.full) - .bg(ramps.primary.base) - .with_animation( - "indeterminate", - Animation::new(PROGRESS_ANIMATION_PERIOD) - .repeat() - .with_max_fps(30.), - |pill, delta| pill.ml(relative(delta * 0.7)), - ) - .into_any_element() - } else { - div() - .h_full() - .w(relative(value)) - .rounded(radius.full) - .bg(ramps.primary.base) - .into_any_element() - })) - } -} diff --git a/crates/ui/src/components/radio.rs b/crates/ui/src/components/radio.rs deleted file mode 100644 index fd92a94..0000000 --- a/crates/ui/src/components/radio.rs +++ /dev/null @@ -1,259 +0,0 @@ -//! Renders a group of radio buttons that reports the clicked choice. -//! -//! # Examples -//! -//! ```no_run -//! use ui::radio::{Radio, RadioGroup}; -//! -//! let plan = RadioGroup::new("plan") -//! .selected(Some("monthly")) -//! .child(Radio::new("monthly", "monthly").label("Monthly")) -//! .child(Radio::new("yearly", "yearly").label("Yearly")) -//! .on_change(|value, _window, _cx| println!("selected: {value}")); -//! ``` - -use gpui::prelude::FluentBuilder; -use gpui::{ - App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, - SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, - div, -}; - -use crate::components::common::{ - ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex, v_flex, -}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; - -/// The group's change reporter, fired with the clicked radio's value. -type ChangeHandler = std::rc::Rc; - -/// A single choice in a [`RadioGroup`]. -/// -/// Each radio is its own tab stop; the full ARIA radiogroup pattern (single -/// stop plus arrow-key roving focus) needs a group owner that does not exist yet. -#[must_use] -pub struct Radio { - id: ElementId, - value: V, - label: Option, - disabled: bool, - a11y_label: Option, -} - -impl Radio -where - V: Clone + PartialEq + 'static, -{ - /// Creates a radio representing `value`. - pub fn new(id: I, value: V) -> Self - where - I: Into, - { - Self { - id: id.into(), - value, - label: None, - disabled: false, - a11y_label: None, - } - } - - /// Sets the visible label; clicking it selects the radio too. - pub fn label(mut self, label: L) -> Self - where - L: Into, - { - self.label = Some(label.into()); - self - } - - /// Renders the radio inert, unfocusable, and dimmed. - pub fn disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } - - /// Overrides the accessibility label, which defaults to the visible label. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } -} - -// Radio is a data builder, not an element, adopt the combinators explicitly. -impl FluentBuilder for Radio {} - -/// A set of [`Radio`] choices that reports clicks through [`RadioGroup::on_change`]. -#[derive(IntoElement)] -#[must_use] -pub struct RadioGroup -where - V: Clone + PartialEq + 'static, -{ - id: ElementId, - selected: Option, - children: Vec>, - size: Size, - a11y_label: Option, - on_change: Option>, - style: StyleRefinement, -} - -impl RadioGroup -where - V: Clone + PartialEq + 'static, -{ - /// Creates an empty group with nothing selected. - pub fn new(id: I) -> Self - where - I: Into, - { - Self { - id: id.into(), - selected: None, - children: Vec::new(), - size: Size::default(), - a11y_label: None, - on_change: None, - style: StyleRefinement::default(), - } - } - - /// Sets the currently selected value. - pub fn selected(mut self, selected: Option) -> Self { - self.selected = selected; - self - } - - /// Adds a radio to the group. - pub fn child(mut self, radio: Radio) -> Self { - self.children.push(radio); - self - } - - /// Sets the group's accessibility label. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } - - /// Sets the handler fired with the clicked radio's value. - pub fn on_change(mut self, handler: F) -> Self - where - F: Fn(V, &mut Window, &mut App) + 'static, - { - self.on_change = Some(std::rc::Rc::new(handler)); - self - } -} - -impl Sizable for RadioGroup -where - V: Clone + PartialEq + 'static, -{ - fn apply_size(&mut self, size: Size) { - self.size = size; - } -} - -impl gpui::Styled for RadioGroup -where - V: Clone + PartialEq + 'static, -{ - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl RenderOnce for RadioGroup -where - V: Clone + PartialEq + 'static, -{ - 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; - let size = self.size; - let selected = self.selected; - let on_change = self.on_change; - let group_label = self.a11y_label; - - v_flex() - .id(self.id) - .gap_2() - .control_text(size) - .refine_style(&self.style) - .role(Role::RadioGroup) - .when_some(group_label.clone(), |group, label| group.aria_label(label)) - .children(self.children.into_iter().map(move |radio| { - let is_selected = selected.as_ref() == Some(&radio.value); - let disabled = radio.disabled; - let row_on_change = on_change.clone(); - - let a11y_label = radio - .a11y_label - .or(radio.label.clone()) - .or_else(|| group_label.clone()); - - h_flex() - .id(radio.id) - .gap_2() - .role(Role::RadioButton) - .when_some(a11y_label, |row, label| row.aria_label(label)) - .aria_toggled(Toggled::from(is_selected)) - .when(disabled, |row| row.opacity(DISABLED_OPACITY)) - .when(!disabled, move |row| { - let value = radio.value.clone(); - row.cursor_pointer() - .focusable() - .tab_stop(true) - .focus_visible(|style| style.shadow(focus_ring(colors.ring))) - .when_some(row_on_change, |row, on_change| { - row.on_click(move |_, window, cx| { - on_change(value.clone(), window, cx) - }) - }) - }) - .child( - h_flex() - .justify_center() - .flex_none() - .control_indicator(size) - .rounded(radius.full) - .border_1() - .when(is_selected, |indicator| { - indicator - .bg(ramps.primary.base) - .border_color(ramps.primary.base) - .hover(|style| { - style - .bg(ramps.primary.hover) - .border_color(ramps.primary.hover) - }) - .child({ - let dot = match size { - Size::XSmall => div().size_1p5(), - Size::Small | Size::Medium => div().size_2(), - Size::Large => div().size_2p5(), - }; - dot.rounded(radius.full).bg(colors.primary_foreground) - }) - }) - .when(!is_selected, |indicator| { - indicator - .bg(colors.input) - .border_color(colors.border) - .hover(|style| style.border_color(colors.muted_foreground)) - }), - ) - .when_some(radio.label, |row, label| row.child(label)) - })) - } -} diff --git a/crates/ui/src/components/scrollbar.rs b/crates/ui/src/components/scrollbar.rs index 7636566..58a0d7e 100644 --- a/crates/ui/src/components/scrollbar.rs +++ b/crates/ui/src/components/scrollbar.rs @@ -42,6 +42,39 @@ pub enum ScrollbarVisibility { /// How often the autohide fade repaints while it runs. const FADE_STEP: Duration = Duration::from_millis(50); +/// The drag state shared between the scrollbar's mouse handlers. +type Drag = Option<(Pixels, Pixels)>; + +/// Which direction the scrollbar lies along. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Axis { + Vertical, + Horizontal, +} + +impl Axis { + fn along(self, position: Point) -> Pixels { + match self { + Axis::Vertical => position.y, + Axis::Horizontal => position.x, + } + } + + fn with_along(self, position: Point, along: Pixels) -> Point { + match self { + Axis::Vertical => point(position.x, along), + Axis::Horizontal => point(along, position.y), + } + } + + fn viewport_along(self, viewport: &Bounds) -> Pixels { + match self { + Axis::Vertical => viewport.size.height, + Axis::Horizontal => viewport.size.width, + } + } +} + /// The shared autohide timeline for an overlay scrollbar. #[derive(Clone)] struct Autohide { @@ -199,36 +232,6 @@ impl ScrollbarHandle for ListState { } } -/// Which direction the scrollbar lies along. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Axis { - Vertical, - Horizontal, -} - -impl Axis { - fn along(self, position: Point) -> Pixels { - match self { - Axis::Vertical => position.y, - Axis::Horizontal => position.x, - } - } - - fn with_along(self, position: Point, along: Pixels) -> Point { - match self { - Axis::Vertical => point(position.x, along), - Axis::Horizontal => point(along, position.y), - } - } - - fn viewport_along(self, viewport: &Bounds) -> Pixels { - match self { - Axis::Vertical => viewport.size.height, - Axis::Horizontal => viewport.size.width, - } - } -} - /// An overlay scrollbar, rendered over the scrolled surface. #[derive(IntoElement)] #[must_use] @@ -239,6 +242,20 @@ pub struct Scrollbar { id: ElementId, } +impl RenderOnce for Scrollbar { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + canvas(|_, _, _| {}, { + let handle = self.handle; + let axis = self.axis; + let visibility = self.visibility; + let id = self.id; + move |_, _, window, cx| Self::paint(&handle, axis, visibility, &id, window, cx) + }) + .absolute() + .inset_0() + } +} + impl Scrollbar { /// Creates a vertical scrollbar named by `id`, driven by `handle`. pub fn vertical(id: I, handle: H) -> Self @@ -304,26 +321,7 @@ impl Scrollbar { ..color }) } -} -impl RenderOnce for Scrollbar { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - canvas(|_, _, _| {}, { - let handle = self.handle; - let axis = self.axis; - let visibility = self.visibility; - let id = self.id; - move |_, _, window, cx| Self::paint(&handle, axis, visibility, &id, window, cx) - }) - .absolute() - .inset_0() - } -} - -/// The drag state shared between the scrollbar's mouse handlers. -type Drag = Option<(Pixels, Pixels)>; - -impl Scrollbar { fn paint( handle: &Rc, axis: Axis, diff --git a/crates/ui/src/components/select.rs b/crates/ui/src/components/select.rs index 264583b..1bd491f 100644 --- a/crates/ui/src/components/select.rs +++ b/crates/ui/src/components/select.rs @@ -29,7 +29,7 @@ use crate::icons::{Icon, IconRole, icon}; use crate::theme::{ActiveTheme as _, Size}; /// Reports the value the user chose. `None` means the select holds no value. -pub type SelectHandler = Rc, &mut Window, &mut App)>; +type SelectHandler = Rc, &mut Window, &mut App)>; /// Select option for a [`Select`] control. #[derive(Clone)] diff --git a/crates/ui/src/components/sidebar.rs b/crates/ui/src/components/sidebar.rs index 2750bee..ec06f45 100644 --- a/crates/ui/src/components/sidebar.rs +++ b/crates/ui/src/components/sidebar.rs @@ -143,6 +143,129 @@ impl SidebarEntry { } self } + + #[allow(clippy::too_many_arguments)] + fn render_entry( + self, + cx: &App, + index: usize, + position_in_set: usize, + size_of_set: usize, + selected: bool, + material: bool, + on_change: &Option, + focus: &FocusHandle, + ) -> AnyElement { + let theme = cx.theme(); + + match self { + SidebarEntry::Header { + label, + prefix, + suffix, + } => { + // The id is required for the role to surface in the a11y tree. + div() + .id(("sidebar-header".into(), label.clone())) + .flex() + .items_center() + .gap_2() + .px_2() + .pt_2() + .pb_1() + .text_sm() + .font_semibold() + .text_color(theme.colors.muted_foreground) + .role(Role::Heading) + .when_some(prefix, |header, prefix| header.child(prefix)) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .child(label), + ) + .when_some(suffix, |header, suffix| header.child(suffix)) + .into_any_element() + } + SidebarEntry::Custom(element) => element, + SidebarEntry::Row { + key, + label, + detail, + prefix, + suffix, + disabled: row_disabled, + } => { + let label_color = selectable_label_color(cx, selected, row_disabled); + + div() + .id((key.clone(), "sidebar-row")) + .flex() + .items_center() + .gap_2() + .px_2() + .py_1() + .min_h_8() + .rounded(theme.radius.sm) + .text_color(label_color) + .role(Role::ListItem) + .aria_selected(selected) + .aria_position_in_set(position_in_set) + .aria_size_of_set(size_of_set) + .map(|row| { + if material && !row_disabled { + if selected { + row.bg(theme.material.selection) + } else { + row.hover(|row| row.bg(theme.material.hover)) + } + } else { + paint_selectable_row(cx, row, selected, row_disabled) + } + }) + .when(!row_disabled, |row| { + row.cursor_pointer().on_click({ + let on_change = on_change.clone(); + let focus = focus.clone(); + move |_, window, cx| { + window.focus(&focus, cx); + if let Some(on_change) = &on_change { + on_change(Some(index), window, cx); + } + } + }) + }) + .when_some(prefix, |row, prefix| row.child(prefix)) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .child(label), + ) + .when_some(detail, |row, detail| { + row.child( + div() + .flex_none() + .text_sm() + .text_color(if selected { + theme.colors.primary_foreground + } else { + theme.colors.muted_foreground + }) + .child(detail), + ) + }) + .when_some(suffix, |row, suffix| row.child(suffix)) + .into_any_element() + } + } + } } // SidebarEntry is a data builder, not an element, adopt the combinators explicitly. @@ -198,48 +321,12 @@ impl Sidebar { self } - /// Whether translucent material fills are painted. - pub fn is_transparent(&self) -> bool { - self.transparent - } - - /// Textures the sidebar with a film-grain overlay. - pub fn grain(mut self, grain: bool) -> Self { - self.grain = grain; - self - } - /// Paints a hairline border on the sidebar's right edge. pub fn border_right(mut self, border_right: bool) -> Self { self.border_right = border_right; self } - /// Whether the right-edge border is painted. - pub fn has_border_right(&self) -> bool { - self.border_right - } - - /// Insets the entry list from the sidebar's edges; the scrollbar stays on the edge. - pub fn padded(mut self, padded: bool) -> Self { - self.padded = padded; - self - } - - /// Whether the entry list is inset from the sidebar's edges. - pub fn is_padded(&self) -> bool { - self.padded - } - - /// Sets the sidebar's width, overriding the default. - pub fn width(mut self, width: W) -> Self - where - W: Into, - { - self.width = width.into(); - self - } - /// Reports the next selected row, from clicks and keys alike. pub fn on_change(mut self, handler: F) -> Self where @@ -404,128 +491,3 @@ impl RenderOnce for Sidebar { .when(material && grain, |sidebar| sidebar.child(grain_overlay())) } } - -impl SidebarEntry { - #[allow(clippy::too_many_arguments)] - fn render_entry( - self, - cx: &App, - index: usize, - position_in_set: usize, - size_of_set: usize, - selected: bool, - material: bool, - on_change: &Option, - focus: &FocusHandle, - ) -> AnyElement { - let theme = cx.theme(); - - match self { - SidebarEntry::Header { - label, - prefix, - suffix, - } => { - // The id is required for the role to surface in the a11y tree. - div() - .id(("sidebar-header".into(), label.clone())) - .flex() - .items_center() - .gap_2() - .px_2() - .pt_2() - .pb_1() - .text_sm() - .font_semibold() - .text_color(theme.colors.muted_foreground) - .role(Role::Heading) - .when_some(prefix, |header, prefix| header.child(prefix)) - .child( - div() - .flex_1() - .min_w_0() - .overflow_hidden() - .whitespace_nowrap() - .text_ellipsis() - .child(label), - ) - .when_some(suffix, |header, suffix| header.child(suffix)) - .into_any_element() - } - SidebarEntry::Custom(element) => element, - SidebarEntry::Row { - key, - label, - detail, - prefix, - suffix, - disabled: row_disabled, - } => { - let label_color = selectable_label_color(cx, selected, row_disabled); - - div() - .id((key.clone(), "sidebar-row")) - .flex() - .items_center() - .gap_2() - .px_2() - .py_1() - .min_h_8() - .rounded(theme.radius.sm) - .text_color(label_color) - .role(Role::ListItem) - .aria_selected(selected) - .aria_position_in_set(position_in_set) - .aria_size_of_set(size_of_set) - .map(|row| { - if material && !row_disabled { - if selected { - row.bg(theme.material.selection) - } else { - row.hover(|row| row.bg(theme.material.hover)) - } - } else { - paint_selectable_row(cx, row, selected, row_disabled) - } - }) - .when(!row_disabled, |row| { - row.cursor_pointer().on_click({ - let on_change = on_change.clone(); - let focus = focus.clone(); - move |_, window, cx| { - window.focus(&focus, cx); - if let Some(on_change) = &on_change { - on_change(Some(index), window, cx); - } - } - }) - }) - .when_some(prefix, |row, prefix| row.child(prefix)) - .child( - div() - .flex_1() - .min_w_0() - .overflow_hidden() - .whitespace_nowrap() - .text_ellipsis() - .child(label), - ) - .when_some(detail, |row, detail| { - row.child( - div() - .flex_none() - .text_sm() - .text_color(if selected { - theme.colors.primary_foreground - } else { - theme.colors.muted_foreground - }) - .child(detail), - ) - }) - .when_some(suffix, |row, suffix| row.child(suffix)) - .into_any_element() - } - } - } -} diff --git a/crates/ui/src/components/slider.rs b/crates/ui/src/components/slider.rs deleted file mode 100644 index b461549..0000000 --- a/crates/ui/src/components/slider.rs +++ /dev/null @@ -1,341 +0,0 @@ -//! Renders a controlled slider that reports its next value on click, drag, and arrow keys. -//! -//! # Examples -//! -//! ```no_run -//! use ui::slider::Slider; -//! -//! let opacity = Slider::new("opacity", 1.0) -//! .step(0.25) -//! .on_change(|value, _window, _cx| println!("opacity: {value}")); -//! ``` - -use std::cell::Cell; -use std::rc::Rc; - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - App, Bounds, DispatchPhase, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, - MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, RenderOnce, Role, - SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas, - div, relative, -}; - -use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; - -/// The change reporter, fired with the next value by click, drag, and arrows. -type ChangeHandler = Rc; - -/// The pointer→value setter shared by the click and drag listeners. -type ValueSetter = Rc; - -/// The arrow-key stride as a share of the range when the slider is continuous. -const FALLBACK_STEP_FRACTION: f32 = 0.05; - -impl Slider { - /// Clamps `value` into `[min, max]` and snaps it to `step` when stepped. - fn constrain(min: f32, max: f32, step: f32, value: f32) -> f32 { - let clamped = value.clamp(min, max); - if step > 0.0 { - (min + ((clamped - min) / step).round() * step).clamp(min, max) - } else { - clamped - } - } -} - -/// A controlled slider over `[min, max]`. -#[derive(IntoElement)] -#[must_use] -pub struct Slider { - id: ElementId, - min: f32, - max: f32, - step: f32, - value: f32, - size: Size, - disabled: bool, - a11y_label: Option, - on_change: Option, - style: StyleRefinement, -} - -impl Slider { - /// Creates a slider over `0..=1` with no stepping, at `value`. - pub fn new(id: I, value: f32) -> Self - where - I: Into, - { - Self { - id: id.into(), - min: 0.0, - max: 1.0, - step: 0.0, - value, - size: Size::default(), - disabled: false, - a11y_label: None, - on_change: None, - style: StyleRefinement::default(), - } - } - - /// Sets the range's lower bound. - pub fn min(mut self, min: f32) -> Self { - self.min = min; - self - } - - /// Sets the range's upper bound. - pub fn max(mut self, max: f32) -> Self { - self.max = max; - self - } - - /// Sets the step; values snap to `min + n * step`. `0` is continuous. - pub fn step(mut self, step: f32) -> Self { - self.step = step; - self - } - - /// Renders the slider inert, unfocusable, and dimmed; disabled always wins. - pub fn disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } - - /// Sets the accessibility label, required for an unlabeled slider. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } - - /// Sets the change handler, fired with the next value by click, drag, and arrows. - pub fn on_change(mut self, handler: F) -> Self - where - F: Fn(f32, &mut Window, &mut App) + 'static, - { - self.on_change = Some(Rc::new(handler)); - self - } -} - -impl gpui::Styled for Slider { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl Sizable for Slider { - fn apply_size(&mut self, size: Size) { - self.size = size; - } -} - -impl RenderOnce for Slider { - 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; - - let rem = window.rem_size(); - let row_height = self.size.slider_row_rems() * rem; - let track_height = self.size.slider_track_rems() * rem; - let knob = self.size.indicator_rems() * rem; - - let value = self.value.clamp(self.min, self.max); - let fraction = if self.max > self.min { - (value - self.min) / (self.max - self.min) - } else { - 0.0 - }; - - let bounds_cell = Rc::new(Cell::new(None::>)); - let focus_handle = crate::components::common::focus_handle(&self.id, window, cx); - - let dragging = - window.use_keyed_state((self.id.clone(), "slider-dragging"), cx, |_, _| false); - - let set_value: ValueSetter = { - let bounds_cell = bounds_cell.clone(); - let on_change = self.on_change.clone(); - let (min, max, step) = (self.min, self.max, self.step); - - Rc::new(move |x: Pixels, window: &mut Window, cx: &mut App| { - if let (Some(bounds), Some(on_change)) = (bounds_cell.get(), on_change.as_ref()) - && bounds.size.width > Pixels::ZERO - { - let fraction = ((x - bounds.origin.x) / bounds.size.width).clamp(0.0, 1.0); - on_change( - Self::constrain(min, max, step, min + fraction * (max - min)), - window, - cx, - ); - } - }) - }; - - let down_dragging = dragging.clone(); - let down_set_value = set_value.clone(); - let disabled = self.disabled; - - h_flex() - .id(self.id) - .relative() - .w_full() - .map(|slider| match self.size { - Size::XSmall => slider.h_6(), - Size::Small => slider.h_9(), - Size::Medium => slider.h_10(), - Size::Large => slider.h_12(), - }) - .refine_style(&self.style) - .role(Role::Slider) - .when_some(self.a11y_label.clone(), |slider, label| { - slider.aria_label(label) - }) - .aria_numeric_value(f64::from(value)) - .aria_min_numeric_value(f64::from(self.min)) - .aria_max_numeric_value(f64::from(self.max)) - .when(self.disabled, |slider| slider.opacity(DISABLED_OPACITY)) - .when(!self.disabled, |slider| { - slider - .track_focus(&focus_handle) - .tab_stop(true) - .focus_visible(|style| style.shadow(focus_ring(colors.ring))) - .on_mouse_down(MouseButton::Left, move |event, window, cx| { - down_dragging.update(cx, |dragging, _| *dragging = true); - down_set_value(event.position.x, window, cx); - }) - .on_key_down(move |event: &KeyDownEvent, window, cx| { - if !focus_handle.contains_focused(window, cx) { - return; - } - - let single_step = if self.step > 0.0 { - self.step - } else { - (self.max - self.min) * FALLBACK_STEP_FRACTION - }; - - let next = match event.keystroke.key.as_str() { - "left" | "down" => Some(value - single_step), - "right" | "up" => Some(value + single_step), - "home" => Some(self.min), - "end" => Some(self.max), - _ => None, - }; - - if let Some(next) = next - && let Some(on_change) = self.on_change.as_ref() - { - on_change( - Self::constrain(self.min, self.max, self.step, next), - window, - cx, - ); - cx.stop_propagation(); - } - }) - }) - .child( - canvas( - { - let bounds_cell = bounds_cell.clone(); - move |bounds, _, _| bounds_cell.set(Some(bounds)) - }, - { - let dragging = dragging.clone(); - let set_value = set_value.clone(); - move |_, _, window, _cx| { - if disabled { - return; - } - window.on_mouse_event({ - let dragging = dragging.clone(); - let set_value = set_value.clone(); - move |event: &MouseMoveEvent, phase, window, cx| { - if phase == DispatchPhase::Bubble - && *dragging.read(cx) - && event.pressed_button == Some(MouseButton::Left) - { - set_value(event.position.x, window, cx); - } - } - }); - window.on_mouse_event({ - let dragging = dragging.clone(); - move |event: &MouseUpEvent, phase, _window, cx| { - if phase == DispatchPhase::Bubble - && event.button == MouseButton::Left - { - dragging.update(cx, |dragging, _| *dragging = false); - } - } - }); - } - }, - ) - .absolute() - .inset_0(), - ) - .child( - div() - .absolute() - .left_0() - .top((row_height - track_height) / 2.0) - .map(|track| match self.size { - Size::XSmall => track.h_0p5(), - Size::Small | Size::Medium => track.h_1(), - Size::Large => track.h_1p5(), - }) - .w_full() - .rounded(radius.full) - .bg(colors.border), - ) - .child( - div() - .absolute() - .left_0() - .top((row_height - track_height) / 2.0) - .map(|track| match self.size { - Size::XSmall => track.h_0p5(), - Size::Small | Size::Medium => track.h_1(), - Size::Large => track.h_1p5(), - }) - .w(relative(fraction)) - .rounded(radius.full) - .bg(ramps.primary.base), - ) - .child( - h_flex() - .absolute() - .left_0() - .top_0() - .h_full() - .w(relative(fraction)) - .justify_end() - .items_center() - .child( - div() - .map(|dot| match self.size { - Size::XSmall => dot.size_2p5(), - Size::Small => dot.size_3p5(), - Size::Medium => dot.size_4(), - Size::Large => dot.size_5(), - }) - .flex_none() - .rounded(radius.full) - .bg(colors.primary_foreground) - .border_1() - .border_color(colors.border) - .mr(-knob / 2.0), - ), - ) - } -} diff --git a/crates/ui/src/components/speech.rs b/crates/ui/src/components/speech.rs deleted file mode 100644 index d603382..0000000 --- a/crates/ui/src/components/speech.rs +++ /dev/null @@ -1,1126 +0,0 @@ -//! Dictation: a state that turns speech into text, a button that drives the -//! session, and a waveform that shows what the microphone hears. -//! -//! The application owns where the text goes: subscribe to [`SpeechEvent`] and -//! insert the final transcript where it belongs. Recognition and capture are -//! both replaceable seams; without further setup the state uses [`Microphone`] -//! and has no recognizer, so [`SpeechButton`] renders nothing until the -//! application provides one. -//! -//! # Examples -//! -//! ```no_run -//! use ui::speech::{SpeechButton, SpeechRecognizer, SpeechState}; -//! -//! # use gpui::{App, AppContext as _}; -//! # fn bind(cx: &mut App, recognizer: R) -//! # where -//! # R: SpeechRecognizer + 'static, -//! # { -//! // Create the state once and hold its entity in the owning view. -//! let speech = cx.new(|cx| SpeechState::new(cx).recognizer(recognizer)); -//! -//! let dictation = SpeechButton::new(&speech); -//! # } -//! ``` - -#[cfg(not(target_arch = "wasm32"))] -use std::sync::{Arc, Mutex}; -use std::time::Duration; - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - 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, -}; - -use crate::components::common::{ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex}; -use crate::components::spinner::Spinner; -use crate::components::tooltip::Tooltip; -use crate::icons::{IconRole, icon}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, SPEECH_WAVEFORM_WIDTH, Size}; - -/// One input-level entry per this much of captured audio. -const LEVEL_BUCKET: Duration = Duration::from_millis(80); -/// The level history a waveform draws, one entry per [`LEVEL_BUCKET`]. -const MAX_LEVELS: usize = 128; -/// Amplitude below which background noise reads as silence. -const NOISE_GATE: f32 = 0.03; -/// How much of a full-scale peak maps to a full bar. -const LEVEL_SCALE: f32 = 0.5; -/// How fast a peak falls back before the next bucket's level. -const LEVEL_FALL: f32 = 0.72; -/// How long a session waits for the recognizer's final result once stopped. -const DEFAULT_STOP_TIMEOUT: Duration = Duration::from_secs(3); -/// The bars [`SpeechButton`] shows while capturing. -const BUTTON_BARS: usize = 4; -/// The share of the bar height a silent bar keeps, so silence reads as a dot. -const DOT_HEIGHT: f32 = 0.14; -/// The bar height reduced motion holds at. -const STILL_HEIGHT: f32 = 0.35; - -/// The PCM layout a recognizer consumes: interleaved 16-bit samples. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct AudioFormat { - sample_rate: u32, - channels: u8, -} - -impl AudioFormat { - /// Creates a format at the given sample rate and channel count. - pub fn new(sample_rate: u32, channels: u8) -> Self { - Self { - sample_rate, - channels: channels.max(1), - } - } - - /// Samples per second per channel. - pub fn sample_rate(&self) -> u32 { - self.sample_rate - } - - /// The number of interleaved channels. - pub fn channels(&self) -> u8 { - self.channels - } -} - -impl Default for AudioFormat { - /// 16 kHz mono, what most recognizers consume. - fn default() -> Self { - Self::new(16_000, 1) - } -} - -/// Why a dictation session failed. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct SpeechError { - message: SharedString, -} - -impl SpeechError { - /// A recognizer failed to start or to report a result. - pub fn recognizer(error: E) -> Self - where - E: std::fmt::Display, - { - Self::new(format!("Speech recognizer error: {error}")) - } - - /// Audio capture failed to start or to deliver samples. - pub fn input(error: E) -> Self - where - E: std::fmt::Display, - { - Self::new(format!("Audio input error: {error}")) - } - - fn new(message: String) -> Self { - Self { - message: message.into(), - } - } -} - -impl std::fmt::Display for SpeechError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.message) - } -} - -impl std::error::Error for SpeechError {} - -/// Turns captured audio into text. -pub trait SpeechRecognizer { - /// The PCM layout [`RecognitionSession::push_audio`] delivers. - fn audio_format(&self) -> AudioFormat { - AudioFormat::default() - } - - /// Whether the recognizer can run right now. - fn is_available(&self, _cx: &App) -> bool { - true - } - - /// Opens a session. - /// - /// # Errors - /// - /// Errors when the recognizer cannot open a session. - fn start( - &self, - sink: SpeechSink, - cx: &mut App, - ) -> Result, SpeechError>; -} - -/// A recognition session opened by [`SpeechRecognizer::start`]. -pub trait RecognitionSession { - /// Delivers interleaved 16-bit PCM in the recognizer's [`SpeechRecognizer::audio_format`]. - fn push_audio(&mut self, samples: &[i16], cx: &mut App); - - /// The user stopped talking. - fn finish(&mut self, cx: &mut App); -} - -/// Reports recognition results for the active session. -#[derive(Clone)] -pub struct SpeechSink { - state: WeakEntity, - generation: u64, -} - -impl SpeechSink { - /// The recognizer accepts audio; the status moves to `Recording`. - pub fn ready(&self, cx: &mut App) { - self.defer(cx, |state, cx| state.mark_ready(cx)); - } - - /// Replaces the hypothesis of the phrase being spoken. - pub fn hypothesis(&self, text: T, cx: &mut App) - where - T: Into + 'static, - { - self.defer(cx, move |state, cx| { - state.report_hypothesis(text.into(), cx) - }); - } - - /// Commits a recognized phrase to the transcript. - pub fn phrase(&self, text: T, cx: &mut App) - where - T: Into + 'static, - { - self.defer(cx, move |state, cx| state.report_phrase(text.into(), cx)); - } - - /// Ends the session normally with what has been recognized so far. - pub fn finish(&self, cx: &mut App) { - self.defer(cx, |state, cx| state.report_finish(cx)); - } - - /// Ends the session with a failure. - pub fn error(&self, error: SpeechError, cx: &mut App) { - self.defer(cx, move |state, cx| state.report_error(error, cx)); - } - - fn defer(&self, cx: &mut App, apply: F) - where - F: FnOnce(&mut SpeechState, &mut Context) + 'static, - { - let state = self.state.clone(); - let generation = self.generation; - cx.defer(move |cx| { - // A report arriving after the state dropped is a normal lifecycle outcome. - if let Some(state) = state.upgrade() { - state.update(cx, |state, cx| state.apply(generation, cx, apply)); - } - }); - } -} - -/// Captures audio for a session. -pub trait AudioInput { - /// Starts capture in `format`, pushing samples to `sink`; dropping the - /// returned `Subscription` stops capture. - /// - /// # Errors - /// - /// Errors when capture cannot start; no samples are delivered. - fn start( - &self, - format: AudioFormat, - sink: AudioSink, - cx: &mut App, - ) -> Result; -} - -/// Delivers captured audio to the active session. -#[derive(Clone)] -pub struct AudioSink { - state: WeakEntity, - generation: u64, -} - -impl AudioSink { - /// Pushes interleaved 16-bit PCM in the recognizer's format. - pub fn push(&self, samples: S, cx: &mut App) - where - S: Into> + 'static, - { - let state = self.state.clone(); - let generation = self.generation; - cx.defer(move |cx| { - // Audio arriving after the state dropped is a normal lifecycle outcome. - if let Some(state) = state.upgrade() { - state.update(cx, |state, cx| { - state.receive_audio(generation, samples.into(), cx) - }); - } - }); - } -} - -/// Where a dictation session is in its life. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum SpeechStatus { - /// No session is running. - #[default] - Idle, - /// Audio is captured while the recognizer connects. - Connecting, - /// Audio is captured and recognized. - Recording, - /// Capture stopped; waiting for the final result. - Stopping, -} - -impl SpeechStatus { - /// True for every status but `Idle`. - pub fn is_active(self) -> bool { - self != Self::Idle - } - - /// True while audio is captured. - pub fn is_capturing(self) -> bool { - matches!(self, Self::Connecting | Self::Recording) - } -} - -/// What a session reports. -#[derive(Clone, Debug, PartialEq)] -pub enum SpeechEvent { - /// A session started and audio is being captured. - Started, - /// The transcript changed while the user speaks. - Partial(SharedString), - /// The session ended normally. The text may be empty. - Final(SharedString), - /// The session was cancelled and its transcript discarded. - Cancelled, - /// The session failed and ended. - Error(SpeechError), -} - -/// Owns a dictation session. -pub struct SpeechState { - recognizer: Option>, - input: Option>, - stop_timeout: Duration, - format: AudioFormat, - status: SpeechStatus, - phrases: Vec, - hypothesis: Option, - levels: Vec, - bucket: Vec, - session: Option>, - capture: Option, - generation: u64, - stop_task: Option>, -} - -impl EventEmitter for SpeechState {} - -impl SpeechState { - /// Creates an idle state without a recognizer or input. - pub fn new(_cx: &mut Context) -> Self { - Self { - recognizer: None, - input: None, - stop_timeout: DEFAULT_STOP_TIMEOUT, - format: AudioFormat::default(), - status: SpeechStatus::Idle, - phrases: Vec::new(), - hypothesis: None, - levels: Vec::new(), - bucket: Vec::new(), - session: None, - capture: None, - generation: 0, - stop_task: None, - } - } - - /// Sets the recognizer every session runs with. - pub fn recognizer(mut self, recognizer: R) -> Self - where - R: SpeechRecognizer + 'static, - { - self.recognizer = Some(Box::new(recognizer)); - self - } - - /// Sets the audio source every session captures with. - pub fn input(mut self, input: I) -> Self - where - I: AudioInput + 'static, - { - self.input = Some(Box::new(input)); - self - } - - /// How long `stop` waits for the recognizer's final result. - pub fn stop_timeout(mut self, timeout: Duration) -> Self { - self.stop_timeout = timeout; - self - } - - /// Where the session is. - pub fn status(&self) -> SpeechStatus { - self.status - } - - /// Whether a session can run on this platform. - pub fn has_recognizer(&self) -> bool { - self.recognizer.is_some() && (self.input.is_some() || Self::has_default_input()) - } - - /// Whether the recognizer reports itself ready to run. - pub fn is_available(&self, cx: &App) -> bool { - self.recognizer - .as_ref() - .is_some_and(|recognizer| recognizer.is_available(cx)) - } - - /// The whole transcript so far. - pub fn transcript(&self) -> SharedString { - let mut transcript = String::new(); - - for phrase in &self.phrases { - transcript.push_str(phrase); - } - - if let Some(hypothesis) = &self.hypothesis { - transcript.push_str(hypothesis); - } - - transcript.into() - } - - /// The recent input levels in `0.0..=1.0`, oldest first, one per 80 ms of audio. - pub fn levels(&self) -> &[f32] { - &self.levels - } - - /// Starts a session. Does nothing while one is running. - pub fn start(&mut self, cx: &mut Context) { - if self.status.is_active() { - return; - } - - self.generation = self.generation.wrapping_add(1); - let generation = self.generation; - - let Some(recognizer) = self.recognizer.as_ref() else { - self.fail("No speech recognizer is set up on this platform.", cx); - return; - }; - - if !recognizer.is_available(cx) { - self.fail("The speech recognizer is not available right now.", cx); - return; - } - - self.format = recognizer.audio_format(); - let sink = SpeechSink { - state: cx.entity().downgrade(), - generation, - }; - - let session = match recognizer.start(sink, cx) { - Ok(session) => session, - Err(error) => { - self.fail(error, cx); - return; - } - }; - - let audio_sink = AudioSink { - state: cx.entity().downgrade(), - generation, - }; - - let capture = match self.capture_input(self.format, audio_sink, cx) { - Ok(capture) => capture, - Err(error) => { - self.fail(error, cx); - return; - } - }; - - self.session = Some(session); - self.capture = Some(capture); - self.phrases.clear(); - self.hypothesis = None; - self.levels.clear(); - self.bucket.clear(); - self.status = SpeechStatus::Connecting; - cx.emit(SpeechEvent::Started); - cx.notify(); - } - - /// Ends the session and emits `Final` once the result is in, at the latest after the stop timeout. - pub fn stop(&mut self, cx: &mut Context) { - if !self.status.is_capturing() { - return; - } - self.capture = None; - self.status = SpeechStatus::Stopping; - cx.notify(); - - let generation = self.generation; - let stop_timeout = self.stop_timeout; - - if let Some(mut session) = self.session.take() { - session.finish(cx); - } - - self.stop_task = Some(cx.spawn(async move |this, cx| { - cx.background_executor().timer(stop_timeout).await; - // The state may drop while the timeout is still pending. - this.update(cx, |state, cx| state.apply_stop_timeout(generation, cx)) - .ok(); - })); - } - - /// Cancels the session at once and discards its transcript. - pub fn cancel(&mut self, cx: &mut Context) { - if !self.status.is_active() { - return; - } - self.capture = None; - self.session = None; - self.stop_task = None; - self.reset(); - cx.emit(SpeechEvent::Cancelled); - cx.notify(); - } - - /// `start` when idle, otherwise `stop`. - pub fn toggle(&mut self, cx: &mut Context) { - if self.status == SpeechStatus::Idle { - self.start(cx); - } else { - self.stop(cx); - } - } - - fn has_default_input() -> bool { - cfg!(not(target_arch = "wasm32")) - } - - #[cfg(not(target_arch = "wasm32"))] - fn default_input() -> Option> { - Some(Box::new(Microphone)) - } - - #[cfg(target_arch = "wasm32")] - fn default_input() -> Option> { - None - } - - fn capture_input( - &self, - format: AudioFormat, - sink: AudioSink, - cx: &mut App, - ) -> Result { - if let Some(input) = &self.input { - return input.start(format, sink, cx); - } - match Self::default_input() { - Some(input) => input.start(format, sink, cx), - None => Err(SpeechError::input( - "No audio input is available on this platform; provide one with `SpeechState::input`.", - )), - } - } - - fn reset(&mut self) { - self.generation = self.generation.wrapping_add(1); - self.status = SpeechStatus::Idle; - self.phrases.clear(); - self.hypothesis = None; - self.levels.clear(); - self.bucket.clear(); - } - - /// Ends a failed start without ever emitting `Started`. - fn fail(&mut self, message: M, cx: &mut Context) - where - M: std::fmt::Display, - { - self.capture = None; - self.session = None; - self.reset(); - cx.emit(SpeechEvent::Error(SpeechError::new(message.to_string()))); - cx.notify(); - } - - /// Ends the session normally, emitting `Final` with the transcript so far. - fn finalize(&mut self, cx: &mut Context) { - self.capture = None; - self.session = None; - self.stop_task = None; - let transcript = self.transcript(); - self.reset(); - cx.emit(SpeechEvent::Final(transcript)); - cx.notify(); - } - - fn apply(&mut self, generation: u64, cx: &mut Context, apply: F) - where - F: FnOnce(&mut Self, &mut Context), - { - if self.generation != generation { - return; - } - apply(self, cx); - } - - fn mark_ready(&mut self, cx: &mut Context) { - if self.status == SpeechStatus::Connecting { - self.status = SpeechStatus::Recording; - cx.notify(); - } - } - - fn report_hypothesis(&mut self, text: SharedString, cx: &mut Context) { - if !self.status.is_active() { - return; - } - self.hypothesis = Some(text); - cx.emit(SpeechEvent::Partial(self.transcript())); - cx.notify(); - } - - fn report_phrase(&mut self, text: SharedString, cx: &mut Context) { - if !self.status.is_active() { - return; - } - self.phrases.push(text); - self.hypothesis = None; - cx.emit(SpeechEvent::Partial(self.transcript())); - cx.notify(); - } - - fn report_finish(&mut self, cx: &mut Context) { - if self.status.is_active() { - self.finalize(cx); - } - } - - fn report_error(&mut self, error: SpeechError, cx: &mut Context) { - if !self.status.is_active() { - return; - } - self.capture = None; - self.session = None; - self.stop_task = None; - self.reset(); - cx.emit(SpeechEvent::Error(error)); - cx.notify(); - } - - fn apply_stop_timeout(&mut self, generation: u64, cx: &mut Context) { - if self.generation == generation && self.status == SpeechStatus::Stopping { - self.finalize(cx); - } - } - - fn receive_audio(&mut self, generation: u64, samples: Vec, cx: &mut Context) { - if self.generation != generation || !self.status.is_capturing() { - return; - } - if let Some(session) = self.session.as_mut() { - session.push_audio(&samples, cx); - } - if self.update_levels(&samples) { - cx.notify(); - } - } - - /// Fills one level per bucket; returns whether any level was recorded. - fn update_levels(&mut self, samples: &[i16]) -> bool { - let channels = self.format.channels() as usize; - let bucket_len = ((self.format.sample_rate() as f32 * LEVEL_BUCKET.as_secs_f32()) as usize - * channels) - .max(channels); - self.bucket.extend_from_slice(samples); - - let mut recorded = false; - while self.bucket.len() >= bucket_len { - let peak = self - .bucket - .drain(..bucket_len) - .map(|sample| sample.unsigned_abs() as f32 / i16::MAX as f32) - .fold(0.0f32, f32::max); - let previous = self.levels.last().copied().unwrap_or(0.0); - let level = ((peak - NOISE_GATE).max(0.0) / LEVEL_SCALE) - .min(1.0) - .max(previous * LEVEL_FALL); - self.levels.push(level); - if self.levels.len() > MAX_LEVELS { - self.levels.remove(0); - } - recorded = true; - } - recorded - } -} - -/// Starts and stops a dictation session. -#[derive(IntoElement)] -#[must_use] -pub struct SpeechButton { - speech: Entity, - size: Size, - disabled: bool, - show_when_unsupported: bool, - style: StyleRefinement, -} - -impl SpeechButton { - /// Creates the button driving the given state. - pub fn new(speech: &Entity) -> Self { - Self { - speech: speech.clone(), - size: Size::default(), - disabled: false, - show_when_unsupported: false, - style: StyleRefinement::default(), - } - } - - /// Shows the button even when dictation is unsupported, rendered disabled. - pub fn show_when_unsupported(mut self, show: bool) -> Self { - self.show_when_unsupported = show; - self - } - - /// Disables the button for application reasons, such as a readonly field. - pub fn disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } -} - -impl gpui::Styled for SpeechButton { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl Sizable for SpeechButton { - fn apply_size(&mut self, size: Size) { - self.size = size; - } -} - -/// 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(); - if unsupported && !self.show_when_unsupported { - return div().into_any_element(); - } - - let (status, unavailable, capturing, bars) = { - let state = self.speech.read(cx); - let status = state.status(); - let levels = state.levels(); - let tail_start = levels.len().saturating_sub(BUTTON_BARS); - ( - status, - unsupported || !state.is_available(cx), - status.is_capturing(), - levels[tail_start..].to_vec(), - ) - }; - - let stopping = status == SpeechStatus::Stopping; - let disabled = self.disabled || unavailable || stopping; - - let theme = cx.theme(); - let colors = theme.colors; - let size = self.size; - let id: ElementId = ("speech-button", self.speech.entity_id()).into(); - - let group = SharedString::from(format!( - "speech-button-{}", - self.speech.entity_id().as_u64() - )); - - let label: SharedString = if unavailable { - "Dictation is unavailable".into() - } else if capturing { - "Stop dictation".into() - } else { - "Start dictation".into() - }; - - let foreground = colors.foreground; - let bar_color = |_| theme.ramps.primary.base; - - h_flex() - .id(id.clone()) - .group(group.clone()) - .role(Role::Button) - .justify_center() - .control_height(size) - .control_dense_padding_x(size) - .gap_0p5() - .rounded(theme.radius.control) - .text_color(foreground) - .when(capturing, |button| button.bg(colors.muted)) - .refine_style(&self.style) - .when(disabled, |button| button.opacity(DISABLED_OPACITY)) - .aria_label(label.clone()) - .tooltip(Tooltip::text(label)) - .child(if stopping { - Spinner::new(("speech-spinner", self.speech.entity_id())) - .with_size(self.size) - .color(foreground) - .into_any_element() - } else if capturing { - h_flex() - .id(("speech-bars", self.speech.entity_id())) - .h(size.icon_rems()) - .items_end() - .gap_0p5() - .children(waveform_bars(&bars, size, cx, bar_color)) - .group_hover(group.clone(), |style| style.invisible()) - .into_any_element() - } else { - icon(IconRole::Microphone) - .size(size.icon_rems()) - .color(foreground) - .into_any_element() - }) - .when(capturing, |button| { - button.child( - div() - .invisible() - .group_hover(group, |style| style.visible()) - .child( - icon(IconRole::Stop) - .size(size.icon_rems()) - .color(foreground), - ), - ) - }) - .when(!disabled, |button| { - let speech = self.speech.clone(); - button - .cursor_pointer() - .focusable() - .tab_stop(true) - .hover(move |style| style.bg(colors.muted_hover)) - .active(move |style| style.bg(theme.ramps.secondary.pressed)) - .focus_visible(move |style| style.shadow(focus_ring(colors.ring))) - .on_click(move |_, _, cx| speech.update(cx, |state, cx| state.toggle(cx))) - }) - .into_any_element() - } -} - -/// A live waveform of what a dictation session hears. -#[derive(IntoElement)] -#[must_use] -pub struct SpeechWaveform { - speech: Entity, - size: Size, - style: gpui::StyleRefinement, -} - -impl SpeechWaveform { - /// Creates the waveform drawn from the given state. - pub fn new(speech: &Entity) -> Self { - Self { - speech: speech.clone(), - size: Size::default(), - style: gpui::StyleRefinement::default(), - } - } -} - -impl Sizable for SpeechWaveform { - fn apply_size(&mut self, size: Size) { - self.size = size; - } -} - -impl Styled for SpeechWaveform { - fn style(&mut self) -> &mut gpui::StyleRefinement { - &mut self.style - } -} - -impl RenderOnce for SpeechWaveform { - fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { - if !self.speech.read(cx).status().is_capturing() { - return div().into_any_element(); - } - let levels = { - let state = self.speech.read(cx); - state.levels().to_vec() - }; - - let theme = cx.theme(); - let colors = theme.colors; - let size = self.size; - let bar_color = |level: f32| { - if level <= 0.0 { - colors.muted_foreground - } else { - theme.ramps.primary.base - } - }; - - h_flex() - .id(("speech-waveform", self.speech.entity_id())) - .items_end() - .justify_end() - .gap_0p5() - .h(size.icon_rems()) - .w(SPEECH_WAVEFORM_WIDTH) - .overflow_hidden() - .children(waveform_bars(&levels, size, cx, bar_color)) - .refine_style(&self.style) - .into_any_element() - } -} - -#[cfg(not(target_arch = "wasm32"))] -/// The built-in input. -pub struct Microphone; - -#[cfg(not(target_arch = "wasm32"))] -impl AudioInput for Microphone { - fn start( - &self, - format: AudioFormat, - sink: AudioSink, - cx: &mut App, - ) -> Result { - use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; - - let host = cpal::default_host(); - let device = host - .default_input_device() - .ok_or_else(|| SpeechError::input("No microphone is connected."))?; - - let config = device.default_input_config().map_err(SpeechError::input)?; - let stream_config = cpal::StreamConfig { - channels: config.channels(), - sample_rate: config.sample_rate(), - buffer_size: cpal::BufferSize::Default, - }; - let device_channels = stream_config.channels.max(1) as usize; - - 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 = { - 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( - stream_config, - Microphone::callback( - |sample: f32| sample, - device_channels, - format, - converter.clone(), - sender.clone(), - ), - error_handler, - None, - ), - cpal::SampleFormat::I16 => device.build_input_stream( - stream_config, - Microphone::callback( - |sample: i16| sample as f32 / i16::MAX as f32, - device_channels, - format, - converter.clone(), - sender.clone(), - ), - error_handler, - None, - ), - cpal::SampleFormat::U16 => device.build_input_stream( - stream_config, - Microphone::callback( - |sample: u16| (sample as f32 - u16::MAX as f32 / 2.0) / (u16::MAX as f32 / 2.0), - device_channels, - format, - converter.clone(), - sender.clone(), - ), - error_handler, - None, - ), - sample_format => { - return Err(SpeechError::input(format!( - "Unsupported microphone sample format: {sample_format}" - ))); - } - } - .map_err(SpeechError::input)?; - - stream.play().map_err(SpeechError::input)?; - - let task = cx.spawn(async move |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) - }) - }); - } - }); - } - } - } - }); - - Ok(Subscription::new(move || { - drop(stream); - drop(task); - })) - } -} - -#[cfg(not(target_arch = "wasm32"))] -impl Microphone { - fn callback( - to_sample: fn(T) -> f32, - device_channels: usize, - format: AudioFormat, - converter: Arc>, - sender: flume::Sender, String>>, - ) -> impl FnMut(&[T], &cpal::InputCallbackInfo) + Send + 'static - where - T: Copy + 'static, - { - move |data: &[T], _: &cpal::InputCallbackInfo| { - // 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); - for frame in data.chunks(device_channels) { - let total: f32 = frame.iter().map(|sample| to_sample(*sample)).sum(); - mono.push(total / frame.len() as f32); - } - - let mut resampled = Vec::with_capacity(mono.len()); - converter.resample(&mono, &mut resampled); - - let channels = format.channels() as usize; - let mut samples = Vec::with_capacity(resampled.len() * channels); - - for value in resampled { - let sample = (value * i16::MAX as f32) - .round() - .clamp(i16::MIN as f32, i16::MAX as f32) as i16; - for _ in 0..channels { - samples.push(sample); - } - } - - if sender.send(Ok(samples)).is_err() { - log::debug!("speech session closed before its audio arrived"); - } - } - } -} - -#[cfg(not(target_arch = "wasm32"))] -/// A minimal linear resampler that carries its phase across callbacks. -struct Resampler { - step: f32, - phase: f32, - last: Option, -} - -#[cfg(not(target_arch = "wasm32"))] -impl Resampler { - fn new(step: f32) -> Self { - Self { - step, - phase: 0.0, - last: None, - } - } - - fn resample(&mut self, input: &[f32], output: &mut Vec) { - if input.is_empty() { - return; - } - let mut phase = self.phase; - while phase < input.len() as f32 { - let index = (phase as usize).min(input.len() - 1); - let fraction = phase - index as f32; - let previous = if index == 0 { - self.last.unwrap_or(input[0]) - } else { - input[index - 1] - }; - output.push(previous + (input[index] - previous) * fraction); - phase += self.step; - } - self.phase = phase - input.len() as f32; - self.last = Some(input[input.len() - 1]); - } -} diff --git a/crates/ui/src/components/spinner.rs b/crates/ui/src/components/spinner.rs index 4e3fbb5..a85b0bb 100644 --- a/crates/ui/src/components/spinner.rs +++ b/crates/ui/src/components/spinner.rs @@ -10,11 +10,12 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, - Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div, + AnyElement, App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, + RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, + Window, div, }; -use crate::components::common::{Sizable, StyledExt as _}; +use crate::components::common::{Sizable, StyledExt as _, v_flex}; use crate::icons::{IconRole, icon}; use crate::theme::{ActiveTheme as _, SPINNER_PERIOD, Size}; @@ -44,6 +45,19 @@ impl Spinner { } } + /// The spinner centered in the full available space. + pub fn centered(id: I) -> AnyElement + where + I: Into, + { + v_flex() + .size_full() + .items_center() + .justify_center() + .child(Self::new(id)) + .into_any_element() + } + /// Overrides the icon color, for accent-filled surfaces. pub fn color(mut self, color: Hsla) -> Self { self.color = Some(color); diff --git a/crates/ui/src/components/tabs.rs b/crates/ui/src/components/tabs.rs index d8d3092..cf61bbf 100644 --- a/crates/ui/src/components/tabs.rs +++ b/crates/ui/src/components/tabs.rs @@ -388,6 +388,292 @@ impl Tab { self.wrap = Some(Box::new(wrap)); self } + + fn render_tab(mut self, ctx: &StripCtx, cx: &App, index: usize) -> AnyElement { + let selected = index == ctx.selected; + // A pinned tab always wears the active treatment, selected or not. + let active = selected || self.pinned; + + let theme = cx.theme(); + 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)); + let close = (self.closeable && ctx.on_close.is_some() && !self.disabled) + .then(|| self.render_tab_close(&ctx.id, index, &ctx.on_close)); + + let label = div() + .flex_grow(1.0) + .when(titlebar, |label| { + let fade = if active { + theme.colors.background + } else { + theme.colors.muted + }; + + let hover_fade = if active { + theme.colors.background + } else { + theme.colors.muted_hover + }; + + let fade_width = rems(0.75); + let hover_fade_width = rems(1.5); + + label + .min_w_0() + .relative() + .overflow_hidden() + .child( + div() + .w_full() + .whitespace_nowrap() + .text_overflow(TextOverflow::Truncate(SharedString::default())) + .child(self.label.clone()), + ) + .child( + div() + .absolute() + .top_0() + .right_0() + .bottom_0() + .w(fade_width) + .bg(linear_gradient( + 90., + linear_color_stop(fade.opacity(0.), 0.), + linear_color_stop(fade, 1.), + )), + ) + .child( + div() + .absolute() + .top_0() + .right_0() + .bottom_0() + .w(hover_fade_width) + .bg(linear_gradient( + 90., + linear_color_stop(hover_fade.opacity(0.), 0.), + linear_color_stop(hover_fade, 1.), + )) + .invisible() + .group_hover(group.clone(), |style| style.visible()), + ) + }) + .when(!titlebar, |label| label.child(self.label.clone())); + + let strip_tab = div() + .id((self.key.clone(), "tab")) + .debug_selector({ + let tabs_id = ctx.id.clone(); + let label = self.label.clone(); + move || format!("{tabs_id}-tab-{}", label) + }) + .flex() + .items_center() + .gap_2() + .role(Role::Tab) + .aria_selected(selected) + .text_color(label_color) + .when(titlebar, |strip_tab| strip_tab.group(group.clone())) + .when(!self.disabled && !active, |strip_tab| { + strip_tab.hover(|strip_tab| { + strip_tab.bg(match ctx.variant { + TabsVariant::Titlebar => theme.colors.muted_hover, + _ => theme.colors.muted, + }) + }) + }) + .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) + .when(ctx.variant == TabsVariant::Pill, |strip_tab| { + strip_tab.child(div().flex_none().w_4()) + }) + .when(self.busy && !self.disabled, |strip_tab| { + strip_tab.child( + Spinner::new((self.key.clone(), "tab-busy")) + .small() + .accessibility_label("Loading"), + ) + }) + .when_some(close, |strip_tab, close| { + if titlebar { + strip_tab.child( + div() + .flex_none() + .invisible() + .group_hover(group, |style| style.visible()) + .child(close), + ) + } else { + strip_tab.child(close) + } + }) + .when( + { + let drop = ctx.drop_at.read(cx); + drop.onto == Some(index) && !drop.canceled() + }, + |strip_tab| { + strip_tab.child( + div() + .absolute() + .left_0() + .top_0p5() + .bottom_0p5() + .w_0p5() + .rounded(theme.radius.sm) + .bg(theme.ramps.primary.base), + ) + }, + ) + .when_some(ctx.measure.clone(), |strip_tab, measure| { + let key = measure.key.clone(); + let root_bounds = measure.root_bounds.clone(); + let tab_key = self.key.to_string(); + strip_tab.child( + canvas( + move |bounds, _, cx| { + let root = root_bounds.borrow(); + if let Some(root) = root.as_ref() { + cx.default_global::().record_tab( + &key, + tab_key, + TabMeasure { + left: bounds.origin.x - root.origin.x, + width: bounds.size.width, + }, + ); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + }) + .when(!self.disabled, |strip_tab| { + strip_tab.cursor_pointer().on_click({ + let selected = ctx.selected; + let on_change = ctx.on_change.clone(); + let focus = ctx.focus.clone(); + move |_, window, cx| { + window.focus(&focus, cx); + if index != selected + && let Some(on_change) = &on_change + { + on_change(index, window, cx); + } + } + }) + }) + .when(ctx.draggable && !self.disabled, |strip_tab| { + strip_tab + .on_mouse_down(MouseButton::Left, { + let drop_at = ctx.drop_at.clone(); + move |event, _, cx| { + cx.stop_propagation(); + drop_at.update(cx, |drop, cx| { + let fresh = TabDrop { + origin: Some(event.position), + ..TabDrop::default() + }; + if *drop != fresh { + *drop = fresh; + cx.notify(); + } + }); + } + }) + .on_drag(TabDrag { index }, { + let label = self.label.clone(); + move |_, _, _, cx| { + cx.new(|_| TabDragPreview { + label: label.clone(), + }) + } + }) + .drag_over::({ + let drop_at = ctx.drop_at.clone(); + move |style, drag, _, cx| { + let drop = *drop_at.read(cx); + let hovered = drag.index != index && !drop.canceled(); + drop_at.update(cx, |drop, cx| match (hovered, drop.onto) { + (true, current) if current != Some(index) => { + drop.onto = Some(index); + cx.notify(); + } + (false, Some(_)) => { + drop.onto = None; + cx.notify(); + } + _ => {} + }); + style + } + }) + .on_drop::({ + let on_reorder = ctx.on_reorder.clone(); + let drop_at = ctx.drop_at.clone(); + move |drag, window, cx| { + let canceled = drop_at.read(cx).canceled(); + drop_at.update(cx, |drop, cx| { + if drop.onto.is_some() { + drop.onto = None; + cx.notify(); + } + }); + let target = (!canceled) + .then(|| reorder_target(drag.index, index)) + .flatten(); + if let (Some(to), Some(on_reorder)) = (target, on_reorder.as_ref()) { + on_reorder(drag.index, to, window, cx); + } + } + }) + }); + + match self.wrap { + Some(wrap) => wrap(strip_tab), + None => strip_tab.into_any_element(), + } + } + + fn render_tab_close( + &self, + tabs_id: &ElementId, + index: usize, + on_close: &Option, + ) -> AnyElement { + Button::new((self.key.clone(), "tab-close")) + .icon(IconRole::Close) + .variant(ButtonVariant::Ghost) + .xsmall() + .fully_rounded(true) + .tab_stop(false) + .debug_selector({ + let tabs_id = tabs_id.clone(); + let label = self.label.clone(); + move || format!("{tabs_id}-close-{}", label) + }) + .tooltip(Tooltip::text("Close")) + .accessibility_label(SharedString::from(format!("Close {}", self.label))) + .on_click({ + let on_close = on_close.clone(); + move |_, window, cx| { + cx.stop_propagation(); + if let Some(on_close) = &on_close { + on_close(index, window, cx); + } + } + }) + .into_any_element() + } } // Tab is a data builder, not an element, adopt the combinators explicitly. @@ -1060,290 +1346,3 @@ impl RenderOnce for Tabs { } } -impl Tab { - fn render_tab(mut self, ctx: &StripCtx, cx: &App, index: usize) -> AnyElement { - let selected = index == ctx.selected; - // A pinned tab always wears the active treatment, selected or not. - let active = selected || self.pinned; - - let theme = cx.theme(); - 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)); - let close = (self.closeable && ctx.on_close.is_some() && !self.disabled) - .then(|| self.render_tab_close(&ctx.id, index, &ctx.on_close)); - - let label = div() - .flex_grow(1.0) - .when(titlebar, |label| { - let fade = if active { - theme.colors.background - } else { - theme.colors.muted - }; - - let hover_fade = if active { - theme.colors.background - } else { - theme.colors.muted_hover - }; - - let fade_width = rems(0.75); - let hover_fade_width = rems(1.5); - - label - .min_w_0() - .relative() - .overflow_hidden() - .child( - div() - .w_full() - .whitespace_nowrap() - .text_overflow(TextOverflow::Truncate(SharedString::default())) - .child(self.label.clone()), - ) - .child( - div() - .absolute() - .top_0() - .right_0() - .bottom_0() - .w(fade_width) - .bg(linear_gradient( - 90., - linear_color_stop(fade.opacity(0.), 0.), - linear_color_stop(fade, 1.), - )), - ) - .child( - div() - .absolute() - .top_0() - .right_0() - .bottom_0() - .w(hover_fade_width) - .bg(linear_gradient( - 90., - linear_color_stop(hover_fade.opacity(0.), 0.), - linear_color_stop(hover_fade, 1.), - )) - .invisible() - .group_hover(group.clone(), |style| style.visible()), - ) - }) - .when(!titlebar, |label| label.child(self.label.clone())); - - let strip_tab = div() - .id((self.key.clone(), "tab")) - .debug_selector({ - let tabs_id = ctx.id.clone(); - let label = self.label.clone(); - move || format!("{tabs_id}-tab-{}", label) - }) - .flex() - .items_center() - .gap_2() - .role(Role::Tab) - .aria_selected(selected) - .text_color(label_color) - .when(titlebar, |strip_tab| strip_tab.group(group.clone())) - .when(!self.disabled && !active, |strip_tab| { - strip_tab.hover(|strip_tab| { - strip_tab.bg(match ctx.variant { - TabsVariant::Titlebar => theme.colors.muted_hover, - _ => theme.colors.muted, - }) - }) - }) - .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) - .when(ctx.variant == TabsVariant::Pill, |strip_tab| { - strip_tab.child(div().flex_none().w_4()) - }) - .when(self.busy && !self.disabled, |strip_tab| { - strip_tab.child( - Spinner::new((self.key.clone(), "tab-busy")) - .small() - .accessibility_label("Loading"), - ) - }) - .when_some(close, |strip_tab, close| { - if titlebar { - strip_tab.child( - div() - .flex_none() - .invisible() - .group_hover(group, |style| style.visible()) - .child(close), - ) - } else { - strip_tab.child(close) - } - }) - .when( - { - let drop = ctx.drop_at.read(cx); - drop.onto == Some(index) && !drop.canceled() - }, - |strip_tab| { - strip_tab.child( - div() - .absolute() - .left_0() - .top_0p5() - .bottom_0p5() - .w_0p5() - .rounded(theme.radius.sm) - .bg(theme.ramps.primary.base), - ) - }, - ) - .when_some(ctx.measure.clone(), |strip_tab, measure| { - let key = measure.key.clone(); - let root_bounds = measure.root_bounds.clone(); - let tab_key = self.key.to_string(); - strip_tab.child( - canvas( - move |bounds, _, cx| { - let root = root_bounds.borrow(); - if let Some(root) = root.as_ref() { - cx.default_global::().record_tab( - &key, - tab_key, - TabMeasure { - left: bounds.origin.x - root.origin.x, - width: bounds.size.width, - }, - ); - } - }, - |_, _, _, _| {}, - ) - .absolute() - .inset_0(), - ) - }) - .when(!self.disabled, |strip_tab| { - strip_tab.cursor_pointer().on_click({ - let selected = ctx.selected; - let on_change = ctx.on_change.clone(); - let focus = ctx.focus.clone(); - move |_, window, cx| { - window.focus(&focus, cx); - if index != selected - && let Some(on_change) = &on_change - { - on_change(index, window, cx); - } - } - }) - }) - .when(ctx.draggable && !self.disabled, |strip_tab| { - strip_tab - .on_mouse_down(MouseButton::Left, { - let drop_at = ctx.drop_at.clone(); - move |event, _, cx| { - cx.stop_propagation(); - drop_at.update(cx, |drop, cx| { - let fresh = TabDrop { - origin: Some(event.position), - ..TabDrop::default() - }; - if *drop != fresh { - *drop = fresh; - cx.notify(); - } - }); - } - }) - .on_drag(TabDrag { index }, { - let label = self.label.clone(); - move |_, _, _, cx| { - cx.new(|_| TabDragPreview { - label: label.clone(), - }) - } - }) - .drag_over::({ - let drop_at = ctx.drop_at.clone(); - move |style, drag, _, cx| { - let drop = *drop_at.read(cx); - let hovered = drag.index != index && !drop.canceled(); - drop_at.update(cx, |drop, cx| match (hovered, drop.onto) { - (true, current) if current != Some(index) => { - drop.onto = Some(index); - cx.notify(); - } - (false, Some(_)) => { - drop.onto = None; - cx.notify(); - } - _ => {} - }); - style - } - }) - .on_drop::({ - let on_reorder = ctx.on_reorder.clone(); - let drop_at = ctx.drop_at.clone(); - move |drag, window, cx| { - let canceled = drop_at.read(cx).canceled(); - drop_at.update(cx, |drop, cx| { - if drop.onto.is_some() { - drop.onto = None; - cx.notify(); - } - }); - let target = (!canceled) - .then(|| reorder_target(drag.index, index)) - .flatten(); - if let (Some(to), Some(on_reorder)) = (target, on_reorder.as_ref()) { - on_reorder(drag.index, to, window, cx); - } - } - }) - }); - - match self.wrap { - Some(wrap) => wrap(strip_tab), - None => strip_tab.into_any_element(), - } - } - - fn render_tab_close( - &self, - tabs_id: &ElementId, - index: usize, - on_close: &Option, - ) -> AnyElement { - Button::new((self.key.clone(), "tab-close")) - .icon(IconRole::Close) - .variant(ButtonVariant::Ghost) - .xsmall() - .fully_rounded(true) - .tab_stop(false) - .debug_selector({ - let tabs_id = tabs_id.clone(); - let label = self.label.clone(); - move || format!("{tabs_id}-close-{}", label) - }) - .tooltip(Tooltip::text("Close")) - .accessibility_label(SharedString::from(format!("Close {}", self.label))) - .on_click({ - let on_close = on_close.clone(); - move |_, window, cx| { - cx.stop_propagation(); - if let Some(on_close) = &on_close { - on_close(index, window, cx); - } - } - }) - .into_any_element() - } -} diff --git a/crates/ui/src/components/toast.rs b/crates/ui/src/components/toast.rs index 0405678..ca45215 100644 --- a/crates/ui/src/components/toast.rs +++ b/crates/ui/src/components/toast.rs @@ -2,17 +2,7 @@ //! //! A [`Toasts`] entity holds the raised toast, and a [`ToastsView`] renders //! it; mount the view at the window root. -//! -//! # Examples -//! -//! ```no_run -//! use ui::toast::{Toast, ToastAction}; -//! -//! let toast = Toast::new("Copied to clipboard") -//! .action(ToastAction::new("Undo", |_cx| println!("undo"))); -//! ``` -use std::rc::Rc; use std::time::Duration; use gpui::prelude::FluentBuilder; @@ -25,45 +15,18 @@ use gpui::{ use crate::components::button::{Button, ButtonVariant}; use crate::components::common::{ - DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, floating_panel, - v_flex, + 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}; -/// The action handler of a [`Toast`]. -pub type ActionHandler = Rc; - -/// One user action offered by a toast. -#[derive(Clone)] -pub struct ToastAction { - label: SharedString, - handler: ActionHandler, -} - -impl ToastAction { - /// Creates an action with this label. - pub fn new(label: L, handler: F) -> Self - where - L: Into, - F: Fn(&mut App) + 'static, - { - Self { - label: label.into(), - handler: Rc::new(handler), - } - } -} - /// A toast notification. #[derive(Clone)] #[must_use] pub struct Toast { message: SharedString, icon: Option, - action: Option, duration: Option, - on_dismiss: Option, style: StyleRefinement, } @@ -79,9 +42,7 @@ impl Toast { Self { message: message.into(), icon: None, - action: None, duration: Some(Self::DURATION), - on_dismiss: None, style: StyleRefinement::default(), } } @@ -94,27 +55,6 @@ impl Toast { self.icon = Some(icon.into()); self } - - /// Offers the user this action. - pub fn action(mut self, action: ToastAction) -> Self { - self.action = Some(action); - self - } - - /// Sets the time before the toast dismisses itself. - pub fn duration(mut self, duration: Duration) -> Self { - self.duration = Some(duration); - self - } - - /// Runs when the toast is dismissed by any means, once it is fully gone. - pub fn on_dismiss(mut self, handler: F) -> Self - where - F: Fn(&mut App) + 'static, - { - self.on_dismiss = Some(Rc::new(handler)); - self - } } // Toast is a data builder, not an element, adopt the combinators explicitly. @@ -127,6 +67,68 @@ pub struct ToastEntry { pub toast: Toast, } +impl ToastEntry { + /// The rendered pill for this toast. + fn pill(&self, toasts: &Entity, cx: &App) -> gpui::Stateful { + let theme = cx.theme(); + let foreground = theme.colors.foreground; + let radius = theme.radius.full; + let toast = &self.toast; + let toasts = toasts.clone(); + let id = self.id; + + 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_none() + .flex() + .items_center() + .child(icon.size(rems(1.0)).color(foreground)), + ) + }) + .child( + div() + .flex_1() + .min_w(px(0.)) + .truncate() + .text_sm() + .text_color(foreground) + .child(toast.message.clone()), + ) + .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); + }); + }), + ), + ) + } +} + /// The store of raised toasts. #[derive(Default)] pub struct Toasts { @@ -177,33 +179,13 @@ impl Toasts { } } - /// Dismisses the toast on screen. - pub fn clear(&mut self, cx: &mut Context) { - if let Some(entry) = self.current.take() { - self.start_exit(entry, cx); - } else { - self.finish_exit(cx); - } - } - /// The toast now showing, if any. pub fn current(&self) -> Option<&ToastEntry> { self.current.as_ref() } - /// How many toasts are on screen, including one fading out. - pub fn count(&self) -> usize { - usize::from(self.current.is_some()) + usize::from(self.exiting.is_some()) - } - /// Moves a toast into the fade-out phase. fn start_exit(&mut self, entry: ToastEntry, cx: &mut Context) { - if let Some(previous) = self.exiting.take() - && let Some(on_dismiss) = &previous.toast.on_dismiss - { - on_dismiss(cx); - } - self.exiting = Some(entry); cx.notify(); @@ -217,11 +199,8 @@ impl Toasts { } fn finish_exit(&mut self, cx: &mut Context) { - if let Some(entry) = self.exiting.take() { + if self.exiting.take().is_some() { cx.notify(); - if let Some(on_dismiss) = &entry.toast.on_dismiss { - on_dismiss(cx); - } } } } @@ -282,82 +261,3 @@ impl RenderOnce for ToastsView { .with_priority(TOAST_LAYER) } } - -impl ToastEntry { - /// The rendered pill for this toast. - fn pill(&self, toasts: &Entity, cx: &App) -> gpui::Stateful { - let theme = cx.theme(); - let foreground = theme.colors.foreground; - let radius = theme.radius.full; - let toast = &self.toast; - let toasts = toasts.clone(); - let id = self.id; - - 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_none() - .flex() - .items_center() - .child(icon.size(rems(1.0)).color(foreground)), - ) - }) - .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-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( - 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/tree.rs b/crates/ui/src/components/tree.rs index 6b5cfe3..2299b6f 100644 --- a/crates/ui/src/components/tree.rs +++ b/crates/ui/src/components/tree.rs @@ -15,6 +15,8 @@ //! .on_change(|_selected, _window, _cx| println!("selection changed")); //! ``` +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; use std::rc::Rc; use gpui::prelude::FluentBuilder; @@ -71,6 +73,16 @@ impl TreeItem { } } + /// The row's key: the path-like id its builder passed. + pub fn key(&self) -> &ElementId { + &self.key + } + + /// Whether the row has children and paints a chevron. + pub fn is_expandable(&self) -> bool { + self.expandable + } + /// Shows a custom icon leading the label. pub fn icon(mut self, icon: I) -> Self where @@ -103,11 +115,299 @@ impl TreeItem { self.disabled = disabled; self } + + #[allow(clippy::too_many_arguments)] + fn render_row( + &self, + cx: &App, + index: usize, + position_in_set: usize, + size_of_set: usize, + selected: bool, + on_change: &Option, + on_disclosure: &Option, + focus: &FocusHandle, + ) -> AnyElement { + let theme = cx.theme(); + let label_color = selectable_label_color(cx, selected, self.disabled); + let disabled = self.disabled; + + 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() + .id((self.key.clone(), "tree-item")) + .relative() + .flex() + .items_center() + .gap_2() + .pl(indent) + .pr_2() + .py_1() + .min_h_8() + .rounded(theme.radius.sm) + .role(Role::TreeItem) + .aria_selected(selected) + .aria_level(self.depth + 1) + .aria_position_in_set(position_in_set) + .aria_size_of_set(size_of_set) + .when(self.expandable, |row| row.aria_expanded(self.expanded)) + .map(|row| paint_selectable_row(cx, row, selected, disabled)) + .when(!disabled, |row| { + row.cursor_pointer().on_click({ + let on_change = on_change.clone(); + let on_disclosure = on_disclosure.clone(); + let expandable = self.expandable; + let focus = focus.clone(); + + move |_, window, cx| { + window.focus(&focus, cx); + if let Some(on_change) = &on_change { + on_change(Some(index), window, cx); + } + // A folder row toggles with its own click, not just its chevron. + if expandable && let Some(on_disclosure) = &on_disclosure { + on_disclosure(index, window, cx); + } + } + }) + }) + .children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| { + let step = level as f32; + div() + .absolute() + .left(rems(0.75 * (step + 0.5))) + .top_0() + .bottom_0() + .border_l_1() + .border_color(theme.colors.border) + })) + .child(self.render_disclosure(cx, selected)) + .when_some( + self.icon + .clone() + .or_else(|| (!self.expandable).then(|| icon(IconRole::File))), + |row, icon| row.child(icon.size(rems(1.0)).color(label_color)), + ) + .child( + div() + .flex_1() + .text_color(label_color) + .child(self.label.clone()), + ) + .into_any_element() + } + + fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement { + let theme = cx.theme(); + let glyph_color = if self.disabled || !selected { + theme.colors.muted_foreground + } else { + theme.colors.primary_foreground + }; + + // Only expandable rows draw a chevron; the empty cell keeps labels aligned with folders. + div() + .flex_none() + .size_4() + .flex() + .items_center() + .justify_center() + .when(self.expandable, |cell| { + cell.child( + icon(if self.expanded { + IconRole::ChevronDown + } else { + IconRole::ChevronRight + }) + .size(rems(0.75)) + .color(glyph_color), + ) + }) + .into_any_element() + } } // TreeItem is a data builder, not an element, adopt the combinators explicitly. impl FluentBuilder for TreeItem {} +/// A nested path node; `flatten_all` turns a forest of these into rows. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TreeItemSeed { + /// Path of the node, relative to the worktree root. + pub id: String, + pub label: String, + pub children: Vec, +} + +impl TreeItemSeed { + /// Flattens the seeds into the rows a flat tree renders, honoring `expanded`. + /// + /// Expandable rows carry the folder icon; leaves fall back to the file icon + /// the tree paints by default. + pub fn flatten_all(seeds: &[TreeItemSeed], expanded: &HashSet) -> Vec { + fn push( + seed: &TreeItemSeed, + depth: usize, + expanded: &HashSet, + rows: &mut Vec, + ) { + let is_expanded = expanded.contains(&seed.id); + let mut item = TreeItem::new(seed.id.clone(), seed.label.clone()) + .depth(depth) + .expandable(!seed.children.is_empty()) + .expanded(is_expanded); + if !seed.children.is_empty() { + item = item.icon(Icon::named(IconRole::Folder)); + } + rows.push(item); + + if is_expanded { + for child in &seed.children { + push(child, depth + 1, expanded, rows); + } + } + } + + let mut rows = Vec::new(); + for seed in seeds { + push(seed, 0, expanded, &mut rows); + } + rows + } + + /// Every folder id, for starting with the tree fully expanded. + pub fn collect_expanded(seeds: &[TreeItemSeed]) -> HashSet { + fn push(seed: &TreeItemSeed, expanded: &mut HashSet) { + if !seed.children.is_empty() { + expanded.insert(seed.id.clone()); + for child in &seed.children { + push(child, expanded); + } + } + } + + let mut expanded = HashSet::new(); + for seed in seeds { + push(seed, &mut expanded); + } + expanded + } + + /// Builds nested tree items from a flat entry list sorted dirs-first. + pub fn from_paths(paths: &[PathBuf]) -> Vec { + // Node indices by full path, so parents resolve in constant time while inserting. + let mut index: HashMap = HashMap::new(); + let mut nodes: Vec<(String, String, Vec)> = Vec::new(); + let mut roots: Vec = Vec::new(); + + for entry in paths { + let mut parent: Option = None; + let mut path = String::new(); + for part in entry.components() { + let label = part.as_os_str().to_string_lossy().into_owned(); + path = if path.is_empty() { + label.clone() + } else { + format!("{path}/{label}") + }; + let ix = *index.entry(path.clone()).or_insert_with(|| { + let ix = nodes.len(); + nodes.push((path.clone(), label.clone(), Vec::new())); + match parent { + Some(parent) => nodes[parent].2.push(ix), + None => roots.push(ix), + } + ix + }); + parent = Some(ix); + } + } + + fn assemble(ix: usize, nodes: &[(String, String, Vec)]) -> TreeItemSeed { + let (id, label, children) = &nodes[ix]; + TreeItemSeed { + id: id.clone(), + label: label.clone(), + children: children + .iter() + .map(|child| assemble(*child, nodes)) + .collect(), + } + } + + roots.iter().map(|root| assemble(*root, &nodes)).collect() + } +} + +#[cfg(test)] +mod seed_tests { + use super::*; + + fn ids(rows: &[TreeItem]) -> Vec<(String, usize)> { + rows.iter() + .map(|row| (row.key().to_string(), row.depth)) + .collect() + } + + #[test] + fn collapsed_folders_hide_children() { + let seeds = TreeItemSeed::from_paths(&[ + PathBuf::from("src"), + PathBuf::from("src/lib.rs"), + PathBuf::from("README.md"), + ]); + + let rows = TreeItemSeed::flatten_all(&seeds, &HashSet::new()); + + assert_eq!( + ids(&rows), + vec![("src".to_owned(), 0), ("README.md".to_owned(), 0)] + ); + assert!(rows[0].expandable); + assert!(!rows[0].expanded); + } + + #[test] + fn expanding_a_folder_shows_children_in_order() { + let seeds = TreeItemSeed::from_paths(&[ + PathBuf::from("src"), + PathBuf::from("src/lib.rs"), + PathBuf::from("src/views/mod.rs"), + PathBuf::from("README.md"), + ]); + let expanded = HashSet::from(["src".to_owned(), "src/views".to_owned()]); + + let rows = TreeItemSeed::flatten_all(&seeds, &expanded); + + assert_eq!( + ids(&rows), + vec![ + ("src".to_owned(), 0), + ("src/lib.rs".to_owned(), 1), + ("src/views".to_owned(), 1), + ("src/views/mod.rs".to_owned(), 2), + ("README.md".to_owned(), 0), + ] + ); + } + + #[test] + fn indices_map_to_row_ids() { + let seeds = TreeItemSeed::from_paths(&[ + PathBuf::from("docs"), + PathBuf::from("docs/guide.md"), + PathBuf::from("README.md"), + ]); + let expanded = HashSet::from(["docs".to_owned()]); + let rows = TreeItemSeed::flatten_all(&seeds, &expanded); + + assert_eq!(rows[0].key().to_string(), "docs"); + assert_eq!(rows[1].key().to_string(), "docs/guide.md"); + assert_eq!(rows[2].key().to_string(), "README.md"); + } +} + /// A tree of [`TreeItem`] rows with single selection and disclosure handling. #[derive(IntoElement)] #[must_use] @@ -345,116 +645,3 @@ impl RenderOnce for Tree { .children(rows) } } - -impl TreeItem { - #[allow(clippy::too_many_arguments)] - fn render_row( - &self, - cx: &App, - index: usize, - position_in_set: usize, - size_of_set: usize, - selected: bool, - on_change: &Option, - on_disclosure: &Option, - focus: &FocusHandle, - ) -> AnyElement { - let theme = cx.theme(); - let label_color = selectable_label_color(cx, selected, self.disabled); - let disabled = self.disabled; - - 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() - .id((self.key.clone(), "tree-item")) - .relative() - .flex() - .items_center() - .gap_2() - .pl(indent) - .pr_2() - .py_1() - .min_h_8() - .rounded(theme.radius.sm) - .role(Role::TreeItem) - .aria_selected(selected) - .aria_level(self.depth + 1) - .aria_position_in_set(position_in_set) - .aria_size_of_set(size_of_set) - .when(self.expandable, |row| row.aria_expanded(self.expanded)) - .map(|row| paint_selectable_row(cx, row, selected, disabled)) - .when(!disabled, |row| { - row.cursor_pointer().on_click({ - let on_change = on_change.clone(); - let on_disclosure = on_disclosure.clone(); - let expandable = self.expandable; - let focus = focus.clone(); - - move |_, window, cx| { - window.focus(&focus, cx); - if let Some(on_change) = &on_change { - on_change(Some(index), window, cx); - } - // A folder row toggles with its own click, not just its chevron. - if expandable && let Some(on_disclosure) = &on_disclosure { - on_disclosure(index, window, cx); - } - } - }) - }) - .children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| { - let step = level as f32; - div() - .absolute() - .left(rems(0.75 * (step + 0.5))) - .top_0() - .bottom_0() - .border_l_1() - .border_color(theme.colors.border) - })) - .child(self.render_disclosure(cx, selected)) - .when_some( - self.icon - .clone() - .or_else(|| (!self.expandable).then(|| icon(IconRole::File))), - |row, icon| row.child(icon.size(rems(1.0)).color(label_color)), - ) - .child( - div() - .flex_1() - .text_color(label_color) - .child(self.label.clone()), - ) - .into_any_element() - } - - fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement { - let theme = cx.theme(); - let glyph_color = if self.disabled || !selected { - theme.colors.muted_foreground - } else { - theme.colors.primary_foreground - }; - - // Only expandable rows draw a chevron; the empty cell keeps labels aligned with folders. - div() - .flex_none() - .size_4() - .flex() - .items_center() - .justify_center() - .when(self.expandable, |cell| { - cell.child( - icon(if self.expanded { - IconRole::ChevronDown - } else { - IconRole::ChevronRight - }) - .size(rems(0.75)) - .color(glyph_color), - ) - }) - .into_any_element() - } -} diff --git a/crates/ui/src/components/utils.rs b/crates/ui/src/components/utils.rs index 366c63a..4026915 100644 --- a/crates/ui/src/components/utils.rs +++ b/crates/ui/src/components/utils.rs @@ -1,5 +1,5 @@ //! Shared helpers for the editor's views: gutter cells, role colors and run -//! styles, code line text, language mapping and change washes. +//! styles, code line text and language mapping. use std::ops::Range; @@ -8,10 +8,7 @@ use gpui::{ }; use crate::components::highlight::{Language, Line, Role}; -use crate::theme::{ - ActiveTheme as _, CODE_GUTTER_WIDTH, ColorTokens, Ramps, WASH_ALPHA, WASH_ALPHA_GUTTER, - WASH_ALPHA_STRONG, -}; +use crate::theme::{ActiveTheme as _, CODE_GUTTER_WIDTH, ColorTokens, Ramps}; impl Role { /// Maps the role to the theme's semantic palette. @@ -78,30 +75,6 @@ where .child(content) } -/// A change wash: the ramp color at the alpha rows tint with. -pub(crate) fn wash(color: Hsla) -> Hsla { - Hsla { - a: color.a * WASH_ALPHA, - ..color - } -} - -/// The stronger wash under number gutters and intra-line word changes. -pub(crate) fn wash_strong(color: Hsla) -> Hsla { - Hsla { - a: color.a * WASH_ALPHA_STRONG, - ..color - } -} - -/// The subtle wash that sets the number gutter off from the code. -pub(crate) fn wash_gutter(colors: &ColorTokens) -> Hsla { - Hsla { - a: colors.muted.a * WASH_ALPHA_GUTTER, - ..colors.muted - } -} - /// One highlighted code line as styled text, roles resolved from the theme. pub(crate) fn code_line(line: &Line, colors: ColorTokens, ramps: Ramps) -> StyledText { let mut highlights: Vec<(Range, HighlightStyle)> = Vec::new(); diff --git a/crates/ui/src/icons/mod.rs b/crates/ui/src/icons/mod.rs index 76c60d6..053b9f6 100644 --- a/crates/ui/src/icons/mod.rs +++ b/crates/ui/src/icons/mod.rs @@ -150,17 +150,6 @@ pub struct Icon { rotation_period: Option, } -/// Creates an icon for the role at the default size. -pub fn icon(role: IconRole) -> Icon { - Icon { - glyph: Glyph::Role(role), - size: AbsoluteLength::Rems(DEFAULT_ICON_SIZE), - color: None, - transformation: None, - rotation_period: None, - } -} - impl Icon { /// Creates an icon from an application-defined icon set. pub fn named(named: I) -> Self @@ -306,3 +295,14 @@ impl AssetSource for Assets { .collect()) } } + +/// Creates an icon for the role at the default size. +pub fn icon(role: IconRole) -> Icon { + Icon { + glyph: Glyph::Role(role), + size: AbsoluteLength::Rems(DEFAULT_ICON_SIZE), + color: None, + transformation: None, + rotation_period: None, + } +} diff --git a/crates/ui/src/layout/panel.rs b/crates/ui/src/layout/panel.rs index 0efe632..16df7ff 100644 --- a/crates/ui/src/layout/panel.rs +++ b/crates/ui/src/layout/panel.rs @@ -116,6 +116,19 @@ impl PanelView for Arc

{ } } +/// The panel row drawn under the titlebar. +#[derive(IntoElement)] +#[must_use] +pub struct PanelRow { + id: ElementId, + main: Option, + split: Option, + /// The main pane's width when split; `None` splits the row in half. + split_width: Option, + resizable: bool, + style: StyleRefinement, +} + /// The layout the cached panel content lays out with. fn content_style() -> StyleRefinement { StyleRefinement::default().size_full() @@ -135,19 +148,6 @@ fn island(panel: Div, cx: &App) -> Div { .overflow_hidden() } -/// The panel row drawn under the titlebar. -#[derive(IntoElement)] -#[must_use] -pub struct PanelRow { - id: ElementId, - main: Option, - split: Option, - /// The main pane's width when split; `None` splits the row in half. - split_width: Option, - resizable: bool, - style: StyleRefinement, -} - impl PanelRow { /// Creates the panel row. pub fn new(id: I) -> Self diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index 9f4f727..5d12738 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -12,7 +12,7 @@ pub use icons::{Assets, Icon, IconRole}; /// Initializes the theme and every key binding the UI layer owns. pub fn init(cx: &mut App) { theme::Theme::init(cx); - components::input::bind_input_keys(cx, None); + components::input::bind_input_keys(cx); components::combobox::bind_combobox_keys(cx); components::command_palette::bind_command_palette_keys(cx); components::code::bind_code_view_keys(cx); diff --git a/crates/ui/src/theme/colors.rs b/crates/ui/src/theme/colors.rs index 3961590..03664a5 100644 --- a/crates/ui/src/theme/colors.rs +++ b/crates/ui/src/theme/colors.rs @@ -7,14 +7,12 @@ use crate::theme::{ DEFAULT_TRANSPARENCY, MIN_MATERIAL_FILL_DARK, MIN_MATERIAL_FILL_LIGHT, ThemeVariant, }; -fn hex(hex: u32) -> Hsla { - rgb(hex).into() -} - -/// The dim scrim behind modal layers; always a translucent black. -pub(crate) fn scrim(alpha: f32) -> Hsla { - hsla(0., 0., 0., alpha) -} +/// 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 semantic color roles components paint from. #[derive(Clone, Copy, Debug, PartialEq)] @@ -165,9 +163,11 @@ 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(); +fn hex(hex: u32) -> Hsla { + rgb(hex).into() +} + +/// The dim scrim behind modal layers; always a translucent black. +pub(crate) fn scrim(alpha: f32) -> Hsla { + hsla(0., 0., 0., alpha) +} diff --git a/crates/ui/src/theme/mod.rs b/crates/ui/src/theme/mod.rs index 9296620..c58cc8a 100644 --- a/crates/ui/src/theme/mod.rs +++ b/crates/ui/src/theme/mod.rs @@ -113,12 +113,6 @@ pub const PROGRESS_ANIMATION_PERIOD: Duration = Duration::from_millis(1500); pub const SCROLLBAR_AUTOHIDE_DELAY: Duration = Duration::from_millis(700); /// How long the autohide scrollbar's fade runs. pub const SCROLLBAR_FADE_DURATION: Duration = Duration::from_millis(250); -/// How much a change wash tints the rows it covers. -pub const WASH_ALPHA: f32 = 0.14; -/// The stronger wash under number gutters and intra-line word changes. -pub const WASH_ALPHA_STRONG: f32 = 0.34; -/// The subtle wash that sets the number gutter off from the code. -pub const WASH_ALPHA_GUTTER: f32 = 0.18; /// The soft wash that marks the active code row. pub const WASH_ALPHA_SOFT: f32 = 0.45; /// How far a scrolling list renders past its viewport. diff --git a/crates/ui/src/theme/ramps.rs b/crates/ui/src/theme/ramps.rs index 3db2938..a795120 100644 --- a/crates/ui/src/theme/ramps.rs +++ b/crates/ui/src/theme/ramps.rs @@ -40,6 +40,16 @@ impl Oklch { } } +/// The state shades components paint from for one accent color. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct AccentShades { + pub base: Hsla, + pub hover: Hsla, + pub pressed: Hsla, + pub subtle: Hsla, + pub foreground: Hsla, +} + /// Mixes `a` toward `b` by `t` in OKLCH, taking the shortest arc between hues. /// /// `t = 0` returns `a`, `t = 1` returns `b`. @@ -152,16 +162,6 @@ pub fn contrast_foreground(background: Hsla) -> Hsla { } } -/// The state shades components paint from for one accent color. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct AccentShades { - pub base: Hsla, - pub hover: Hsla, - pub pressed: Hsla, - pub subtle: Hsla, - pub foreground: Hsla, -} - /// Derives hover/pressed/subtle shades for an accent against its background. /// /// Where a platform states ramps (WinUI, KDE) those are used instead, diff --git a/crates/ui/src/theme/source/linux.rs b/crates/ui/src/theme/source/linux.rs index 8ef447e..2675d8c 100644 --- a/crates/ui/src/theme/source/linux.rs +++ b/crates/ui/src/theme/source/linux.rs @@ -31,33 +31,6 @@ enum Backend { Fallback, } -fn home_dir() -> Option { - std::env::var_os("HOME").map(PathBuf::from) -} - -/// Whether the session runs on Wayland, where compositors state blur protocols. -fn wayland_session() -> bool { - std::env::var_os("WAYLAND_DISPLAY").is_some() - || std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland") -} - -fn detect(home: &Path, portal_reachable: bool, gsettings_reachable: bool) -> Backend { - let omarchy_marker = home - .join(".local/state/omarchy/current/theme.name") - .exists() - || home.join(".local/state/omarchy/current/theme").is_dir() - || home.join(".config/omarchy").is_dir(); - if omarchy_marker { - Backend::Omarchy - } else if home.join(".config/kdeglobals").exists() { - Backend::Kde - } else if portal_reachable || gsettings_reachable { - Backend::Portal - } else { - Backend::Fallback - } -} - /// What `gsettings` states for GNOME sessions. #[derive(Clone, Copy, Debug, Default, PartialEq)] struct GSettingsSnapshot { @@ -65,68 +38,6 @@ struct GSettingsSnapshot { accent: Option, } -fn gsettings_value(args: &[&str]) -> Option { - let output = std::process::Command::new("gsettings") - .args(args) - .output() - .ok()?; - if !output.status.success() { - return None; - } - String::from_utf8(output.stdout).ok() -} - -/// The named accent colors GNOME ships (libadwaita's background variants). -fn accent_rgb(name: &str) -> Option { - let hex = match name { - "blue" => 0x3584e4, - "teal" => 0x2190a4, - "green" => 0x3a944a, - "yellow" => 0xc88800, - "orange" => 0xed5b00, - "red" => 0xe62d42, - "pink" => 0xd56199, - "purple" => 0x9141ac, - "slate" => 0x6f8396, - _ => return None, - }; - Some(Hsla::from(gpui::rgb(hex))) -} - -fn read_gsettings() -> Option { - let variant = gsettings_value(&["get", "org.gnome.desktop.interface", "color-scheme"]) - .and_then(|value| match value.trim().trim_matches('\'') { - "prefer-dark" => Some(ThemeVariant::Dark), - "prefer-light" => Some(ThemeVariant::Light), - _ => None, - }); - - let accent = gsettings_value(&["get", "org.gnome.desktop.interface", "accent-color"]) - .and_then(|value| accent_rgb(value.trim().trim_matches('\''))); - - if variant.is_none() && accent.is_none() { - return None; - } - Some(GSettingsSnapshot { variant, accent }) -} - -pub(crate) fn platform_source() -> Box { - let portal = portal::io::PortalClient::connect(); - let gsettings = read_gsettings(); - - let backend = home_dir() - .map(|home| detect(&home, portal.is_some(), gsettings.is_some())) - .unwrap_or(Backend::Fallback); - - Box::new(LinuxSource { - backend, - portal, - gsettings, - file_watcher: None, - _signal: None, - }) -} - impl LinuxSource { fn gnome_snapshot( &self, @@ -280,3 +191,92 @@ impl ThemeSource for LinuxSource { } } } + +fn home_dir() -> Option { + std::env::var_os("HOME").map(PathBuf::from) +} + +/// Whether the session runs on Wayland, where compositors state blur protocols. +fn wayland_session() -> bool { + std::env::var_os("WAYLAND_DISPLAY").is_some() + || std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland") +} + +fn detect(home: &Path, portal_reachable: bool, gsettings_reachable: bool) -> Backend { + let omarchy_marker = home + .join(".local/state/omarchy/current/theme.name") + .exists() + || home.join(".local/state/omarchy/current/theme").is_dir() + || home.join(".config/omarchy").is_dir(); + if omarchy_marker { + Backend::Omarchy + } else if home.join(".config/kdeglobals").exists() { + Backend::Kde + } else if portal_reachable || gsettings_reachable { + Backend::Portal + } else { + Backend::Fallback + } +} + +fn gsettings_value(args: &[&str]) -> Option { + let output = std::process::Command::new("gsettings") + .args(args) + .output() + .ok()?; + if !output.status.success() { + return None; + } + String::from_utf8(output.stdout).ok() +} + +/// The named accent colors GNOME ships (libadwaita's background variants). +fn accent_rgb(name: &str) -> Option { + let hex = match name { + "blue" => 0x3584e4, + "teal" => 0x2190a4, + "green" => 0x3a944a, + "yellow" => 0xc88800, + "orange" => 0xed5b00, + "red" => 0xe62d42, + "pink" => 0xd56199, + "purple" => 0x9141ac, + "slate" => 0x6f8396, + _ => return None, + }; + Some(Hsla::from(gpui::rgb(hex))) +} + +fn read_gsettings() -> Option { + let variant = gsettings_value(&["get", "org.gnome.desktop.interface", "color-scheme"]) + .and_then(|value| match value.trim().trim_matches('\'') { + "prefer-dark" => Some(ThemeVariant::Dark), + "prefer-light" => Some(ThemeVariant::Light), + _ => None, + }); + + let accent = gsettings_value(&["get", "org.gnome.desktop.interface", "accent-color"]) + .and_then(|value| accent_rgb(value.trim().trim_matches('\''))); + + if variant.is_none() && accent.is_none() { + return None; + } + Some(GSettingsSnapshot { variant, accent }) +} + +pub(crate) fn platform_source() -> Box { + let portal = portal::io::PortalClient::connect(); + let gsettings = read_gsettings(); + + let backend = home_dir() + .map(|home| detect(&home, portal.is_some(), gsettings.is_some())) + .unwrap_or(Backend::Fallback); + + Box::new(LinuxSource { + backend, + portal, + gsettings, + file_watcher: None, + _signal: None, + }) +} diff --git a/crates/ui/src/theme/source/macos.rs b/crates/ui/src/theme/source/macos.rs index 3ca7e2f..2925dc2 100644 --- a/crates/ui/src/theme/source/macos.rs +++ b/crates/ui/src/theme/source/macos.rs @@ -44,15 +44,6 @@ 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. @@ -82,6 +73,15 @@ pub(crate) struct MacosSource { _signal: Option, } +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] } + } +} + impl MacosSource { fn color_to_hsla(color: &NSColor) -> Option { let srgb = NSColorSpace::sRGBColorSpace(); diff --git a/crates/ui/src/theme/source/windows.rs b/crates/ui/src/theme/source/windows.rs index 87a6f9b..af47619 100644 --- a/crates/ui/src/theme/source/windows.rs +++ b/crates/ui/src/theme/source/windows.rs @@ -55,25 +55,6 @@ pub(crate) struct WindowsSource { _signal: Option, } -pub(crate) fn platform_source() -> Box { - // SAFETY: WinRT activation requires COM on this thread; the STA matches - // the UI thread's message pump, and RPC_E_CHANGED_MODE means COM is - // already initialized in another apartment. - let initialized = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }; - - if initialized.is_err() && initialized != RPC_E_CHANGED_MODE { - log::error!("theme: COM initialization failed: {initialized:?}"); - } - - match WindowsSource::new() { - Some(source) => Box::new(source), - None => { - log::warn!("theme: Windows system theme unavailable; using fallback"); - Box::new(super::fallback::FallbackSource) - } - } -} - impl WindowsSource { fn new() -> Option { let ui_settings = match UISettings::new() { @@ -206,3 +187,22 @@ impl ThemeSource for WindowsSource { SourceKind::Windows.label() } } + +pub(crate) fn platform_source() -> Box { + // SAFETY: WinRT activation requires COM on this thread, + // the STA matches the UI thread's message pump, + // and RPC_E_CHANGED_MODE means COM is already initialized in another apartment. + let initialized = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }; + + if initialized.is_err() && initialized != RPC_E_CHANGED_MODE { + log::error!("theme: COM initialization failed: {initialized:?}"); + } + + match WindowsSource::new() { + Some(source) => Box::new(source), + None => { + log::warn!("theme: Windows system theme unavailable; using fallback"); + Box::new(super::fallback::FallbackSource) + } + } +} diff --git a/desktop/src/main.rs b/desktop/src/main.rs index 5141d38..d8bd5cf 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -46,30 +46,36 @@ fn main() { KeyBinding::new("cmd-q", Quit, None), KeyBinding::new("ctrl-q", Quit, None), ]); + cx.on_action(|_: &Quit, cx| cx.quit()); + cx.set_app_identity("info.reya.signed", "Signed"); let store = cx.new(|cx| SettingsStore::new(paths::settings_file(), cx)); SettingsStore::set_global(store.clone(), cx); + let settings = store.read(cx).settings().clone(); - signed_app::apply_appearance(&settings, cx); + signed_app::apply_appearance_mode(settings.appearance, cx); if let Err(error) = std::fs::create_dir_all(paths::nostr_dir()) { tracing::warn!("failed to create nostr dir: {error}"); } + if let Err(error) = std::fs::create_dir_all(paths::repos_dir()) { tracing::warn!("failed to create repos dir: {error}"); } + signed_state::init( paths::nostr_dir(), paths::repos_dir().clone(), settings.local_repos.scan_paths.clone(), cx, ); + metadata::init(cx); - cx.set_app_identity("info.reya.signed", "Signed"); let theme = cx.theme(); let bounds = Bounds::centered(None, size(px(1120.0), px(750.0)), cx); + let options = WindowOptions { window_bounds: Some(WindowBounds::Windowed(bounds)), window_min_size: Some(size(px(960.0), px(640.0))), diff --git a/docs/gpui-native-kit-gaps.md b/docs/gpui-native-kit-gaps.md index e21ee37..8044cd1 100644 --- a/docs/gpui-native-kit-gaps.md +++ b/docs/gpui-native-kit-gaps.md @@ -4,3 +4,8 @@ Vendored `crates/ui` shortcomings recorded here instead of patched in place. - `PanelRow` (`src/layout/panel.rs`) seeds its split panes from `window.viewport_size()` during the first render frame. On some launches that size is not yet the window's final bounds, so the divider freezes at a wrong position (observed ~24% instead of the intended 50%) until a drag or a double-click reset. Seeding from the canvas-measured extent, or re-seeding while no user resize has happened, would fix it. - `island()` (`src/layout/panel.rs`) rounds and paints `overflow_hidden`, but gpui's `ContentMask` is rectangular only: children are never clipped to the rounded corners. Full-bleed panel content (photos, backgrounds) paints square over the island chrome and must apply the matching `theme.radius.overlay` itself — see the signed-out banner in `signed_app`. +- The popup primitives extracted into `menu.rs` (`trigger_toggle`, `anchored_overlay`, `focus_capture`) cover the trigger-button, anchored-panel, and focus-grab surfaces. They do not cover lists: `ComboboxState` and `CommandPaletteState` keep their own entity-backed virtualized rows outside the `MenuItem` engine because menu rows are built per frame from a `Vec`, while both hold stateful selections the `uniform_list` drives. Any future row engine should absorb those two. +- `toast.rs` and `alert.rs` each re-implement the same scaffolding: a store entity with push/dismiss ids, an entry wrapper, a floating stack view with fade-out. Unification was declined for now; if either gains behavior the other lacks, extract the shared store/stack shell first. +- The toggle family (`checkbox.rs`, `switch.rs`, `toggle.rs`) restates the same control scaffolding three times: sizing, disabled handling, a `when(checked)` style fork, and an on-change handler with optimistic paint. A shared toggle base would shrink the trio. +- `StatusDot` and `Badge` both map a `*Variant` enum onto the same theme tokens (primary/success/warning/destructive ramps plus muted foreground). The tables are duplicated rather than shared. +- `ControlSizing` (`common.rs`) and the `Size::*_rems` methods (`theme`) are parallel lookup tables: one maps `Size` to control metrics, the other to glyph metrics. Adding a size means touching both.