From 44c2dc63455997573e59ee54460105bb709a0f21 Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Fri, 27 Nov 2026 21:05:37 +0700 Subject: [PATCH] chore: restructure ui components --- Cargo.toml | 19 + crates/signed_app/src/app/helpers.rs | 12 - crates/signed_app/src/app/mod.rs | 220 ++- crates/signed_app/src/explore/helpers.rs | 307 +++-- crates/signed_app/src/explore/mod.rs | 241 ++-- crates/signed_app/src/identity/exit.rs | 41 +- crates/signed_app/src/identity/import.rs | 138 +- crates/signed_app/src/identity/onboarding.rs | 101 +- crates/signed_app/src/identity/passphrase.rs | 103 +- crates/signed_app/src/inbox/helpers.rs | 287 ++-- crates/signed_app/src/inbox/mod.rs | 211 +-- crates/signed_app/src/issues/detail.rs | 446 ++++--- crates/signed_app/src/issues/helpers.rs | 180 --- crates/signed_app/src/issues/mod.rs | 282 ++-- crates/signed_app/src/issues/new_issue.rs | 22 +- crates/signed_app/src/lib.rs | 11 - crates/signed_app/src/pull_requests/detail.rs | 517 ++++--- .../src/pull_requests/dialogs/update.rs | 50 +- .../signed_app/src/pull_requests/helpers.rs | 21 +- crates/signed_app/src/pull_requests/mod.rs | 286 ++-- crates/signed_app/src/pull_requests/new.rs | 164 ++- .../src/pull_requests/send_patch.rs | 35 +- crates/signed_app/src/repo/dialogs/create.rs | 298 ++--- .../src/repo/dialogs/grasp_servers.rs | 45 +- crates/signed_app/src/repo/dialogs/init.rs | 244 ++-- crates/signed_app/src/repo/dialogs/mod.rs | 40 +- crates/signed_app/src/repo/dialogs/reset.rs | 156 ++- crates/signed_app/src/repo/files.rs | 188 ++- crates/signed_app/src/repo/helpers.rs | 497 +------ crates/signed_app/src/repo/history.rs | 139 +- crates/signed_app/src/repo/mod.rs | 427 +++--- crates/signed_app/src/repo/refs.rs | 75 +- crates/signed_app/src/settings/helpers.rs | 216 +-- crates/signed_app/src/settings/mod.rs | 112 +- .../src/{repo => shared}/commit_diff.rs | 584 +++++--- crates/signed_app/src/shared/labels.rs | 208 +++ crates/signed_app/src/shared/mod.rs | 22 +- crates/signed_app/src/shared/progress.rs | 196 --- crates/signed_app/src/shared/widgets.rs | 44 + crates/signed_app/src/titlebar/mod.rs | 161 +-- .../src/titlebar/repository_switcher.rs | 25 +- crates/signed_state/src/backend.rs | 2 +- crates/signed_state/src/checkouts.rs | 2 +- crates/signed_state/src/local_repos.rs | 2 +- crates/signed_state/src/repo.rs | 2 +- crates/signed_state/src/repos.rs | 2 +- crates/ui/src/components/alert.rs | 55 +- crates/ui/src/components/avatar.rs | 319 ++--- crates/ui/src/components/badge.rs | 17 +- crates/ui/src/components/button.rs | 19 +- crates/ui/src/components/checkbox.rs | 13 +- crates/ui/src/components/clipboard.rs | 56 +- crates/ui/src/components/code.rs | 209 +-- crates/ui/src/components/combobox.rs | 513 +++---- crates/ui/src/components/command_palette.rs | 160 +-- crates/ui/src/components/common.rs | 360 +++-- crates/ui/src/components/dialog.rs | 252 ++-- crates/ui/src/components/dropdown_menu.rs | 309 ++--- crates/ui/src/components/empty_state.rs | 11 +- crates/ui/src/components/field.rs | 148 +- crates/ui/src/components/highlight.rs | 19 + crates/ui/src/components/input.rs | 118 +- crates/ui/src/components/markdown.rs | 565 ++++---- crates/ui/src/components/menu.rs | 1187 ++++++++++------- crates/ui/src/components/popover.rs | 88 +- crates/ui/src/components/scroll_area.rs | 25 +- crates/ui/src/components/scrollbar.rs | 251 ++-- crates/ui/src/components/segmented.rs | 52 +- crates/ui/src/components/select.rs | 50 +- crates/ui/src/components/separator.rs | 11 +- crates/ui/src/components/sidebar.rs | 13 +- crates/ui/src/components/spinner.rs | 14 +- crates/ui/src/components/status_dot.rs | 36 +- crates/ui/src/components/switch.rs | 9 +- crates/ui/src/components/tabs.rs | 735 +++++----- crates/ui/src/components/toast.rs | 107 +- crates/ui/src/components/toggle.rs | 9 +- crates/ui/src/components/tooltip.rs | 12 +- crates/ui/src/components/tree.rs | 191 +-- crates/ui/src/icons/mod.rs | 128 +- crates/ui/src/layout/mod.rs | 4 +- crates/ui/src/layout/panel.rs | 250 ++-- crates/ui/src/layout/resizable.rs | 131 +- crates/ui/src/layout/resize_handle.rs | 12 +- crates/ui/src/layout/root.rs | 234 +++- crates/ui/src/layout/titlebar.rs | 71 +- crates/ui/src/layout/window_controls.rs | 299 ++--- crates/ui/src/layout/window_frame.rs | 176 --- crates/ui/src/lib.rs | 12 +- crates/ui/src/theme/colors.rs | 127 +- crates/ui/src/theme/definition.rs | 112 +- crates/ui/src/theme/mod.rs | 306 +++-- crates/ui/src/theme/presets.rs | 27 - crates/ui/src/theme/ramps.rs | 265 ++-- crates/ui/src/theme/resolve.rs | 370 +++-- crates/ui/src/theme/source.rs | 95 +- crates/ui/src/theme/source/fallback.rs | 7 +- crates/ui/src/theme/source/macos.rs | 69 +- crates/ui/src/theme/source/signal.rs | 5 +- crates/ui/src/theme/source/windows.rs | 23 +- crates/ui/src/theme/system.rs | 16 +- crates/ui/tests/dialog.rs | 112 ++ crates/ui/tests/input.rs | 64 + crates/ui/tests/menu.rs | 106 ++ crates/ui/tests/panel.rs | 152 +-- crates/ui/tests/popover.rs | 6 +- crates/ui/tests/scroll_area.rs | 2 +- crates/ui/tests/scrollbar.rs | 81 ++ crates/ui/tests/select.rs | 91 ++ crates/ui/tests/sizing.rs | 2 +- crates/ui/tests/tabs.rs | 35 +- crates/ui/tests/theme_definition.rs | 15 + crates/ui/tests/tree.rs | 69 + desktop/src/main.rs | 4 +- 114 files changed, 9117 insertions(+), 7675 deletions(-) delete mode 100644 crates/signed_app/src/app/helpers.rs rename crates/signed_app/src/{repo => shared}/commit_diff.rs (64%) create mode 100644 crates/signed_app/src/shared/labels.rs delete mode 100644 crates/signed_app/src/shared/progress.rs delete mode 100644 crates/ui/src/layout/window_frame.rs delete mode 100644 crates/ui/src/theme/presets.rs create mode 100644 crates/ui/tests/dialog.rs create mode 100644 crates/ui/tests/input.rs create mode 100644 crates/ui/tests/menu.rs create mode 100644 crates/ui/tests/scrollbar.rs create mode 100644 crates/ui/tests/select.rs create mode 100644 crates/ui/tests/theme_definition.rs create mode 100644 crates/ui/tests/tree.rs diff --git a/Cargo.toml b/Cargo.toml index 21861e0..35cb61f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,6 +53,25 @@ panic = "unwind" inherits = "release" debug = true +# Frame pacing in dev builds is dominated by unoptimized layout, text, render and +# syntax crates. These overrides keep `cargo run` representative; release builds +# (`opt-level = "z"`, lto) remain the reference for performance. +[profile.dev.package] +gpui = { opt-level = 3 } +gpui_platform = { opt-level = 3 } +gpui_wgpu = { opt-level = 3 } +gpui_macos = { opt-level = 3 } +taffy = { opt-level = 3 } +cosmic-text = { opt-level = 3 } +swash = { opt-level = 3 } +wgpu = { opt-level = 3 } +wgpu-core = { opt-level = 3 } +wgpu-hal = { opt-level = 3 } +naga = { opt-level = 3 } +resvg = { opt-level = 3 } +usvg = { opt-level = 3 } +tree-sitter = { opt-level = 3 } + [workspace.lints.clippy] all = "deny" perf = "deny" diff --git a/crates/signed_app/src/app/helpers.rs b/crates/signed_app/src/app/helpers.rs deleted file mode 100644 index 224eb0b..0000000 --- a/crates/signed_app/src/app/helpers.rs +++ /dev/null @@ -1,12 +0,0 @@ -use gpui::App; -use settings::AppearanceMode; -use ui::theme::{ThemeVariant, follow_system, set_mode_override}; - -/// Applies one appearance mode to the kit theme. -pub fn apply_appearance_mode(mode: AppearanceMode, cx: &mut App) { - match mode { - AppearanceMode::System => follow_system(cx), - AppearanceMode::Light => set_mode_override(Some(ThemeVariant::Light), cx), - AppearanceMode::Dark => set_mode_override(Some(ThemeVariant::Dark), cx), - } -} diff --git a/crates/signed_app/src/app/mod.rs b/crates/signed_app/src/app/mod.rs index b8e3f47..6a2435d 100644 --- a/crates/signed_app/src/app/mod.rs +++ b/crates/signed_app/src/app/mod.rs @@ -1,29 +1,48 @@ -pub mod helpers; mod placeholder; use gpui::prelude::FluentBuilder as _; use gpui::{ - App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, - ParentElement as _, Render, Styled as _, Subscription, WeakEntity, Window, div, + AnyView, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, + ParentElement as _, Render, SharedString, Styled as _, Subscription, WeakEntity, Window, div, }; -use helpers::apply_appearance_mode; +use nostr::prelude::EventId; use settings::{AppearanceMode, SettingsStore}; -use signed_state::{Backend, BackendEvent}; +use signed_core::{Announcement, RepoAddr}; +use signed_state::{Backend, BackendEvent, RepoStore}; use ui::common::{h_flex, v_flex}; use ui::icons::IconRole; -use ui::layout::panel::PanelStack; -use ui::layout::root::RootContext as _; +use ui::layout::panel::{PanelSlot, PanelStack}; +use ui::layout::root::{Root, RootContext as _}; use ui::layout::titlebar::Titlebar; +use ui::theme::{ThemeEngine, ThemeVariant}; use ui::toast::Toast; use crate::app::placeholder::PlaceholderView; use crate::explore::ExploreView; +use crate::identity::import::ImportDialog; +use crate::identity::onboarding::OnboardingDialog; use crate::identity::passphrase::PassphraseDialog; +use crate::issues::IssuesView; +use crate::issues::detail::IssueDetailView; +use crate::pull_requests::{PullRequestDetailView, PullRequestsView}; +use crate::repo::RepoDetailView; use crate::shared::log_dropped; -use crate::titlebar::{ - CreateRepository, REPOSITORY_KEY_CONTEXT, SwitchRepository, TitlebarView, - bind_repository_shortcuts, -}; +use crate::titlebar::{CreateRepository, REPOSITORY_KEY_CONTEXT, SwitchRepository, TitlebarView}; + +/// An item of a repository to open from outside its detail panel. +pub enum RepoItem { + Issue(EventId), + PullRequest(EventId), + Patch, +} + +/// The issue and pull-request tab views a repository panel embeds. +pub struct RepoTabs { + pub issues: AnyView, + pub pulls: AnyView, + /// Keep the tab totals flowing into the repository panel. + pub(crate) _subscriptions: Vec, +} pub struct AppRoot { panels: Entity, @@ -34,35 +53,40 @@ pub struct AppRoot { impl AppRoot { pub fn new(window: &mut Window, cx: &mut Context) -> Self { - bind_repository_shortcuts(cx); + TitlebarView::bind_keys(cx); - let app = cx.entity().downgrade(); + let app = cx.weak_entity(); let panels = cx.new(|cx| PanelStack::new("signed-panel", cx)); let titlebar = cx.new(|cx| TitlebarView::new(app.clone(), window, cx)); + let empty = cx.new(|_| PlaceholderView::new("Select a repository")); - panels.update(cx, |panels, cx| panels.set_empty(empty, None, cx)); + panels.update(cx, |panels, cx| { + panels.set_empty(empty, None, cx); + }); let backend = Backend::global(cx); let settings = SettingsStore::global(cx); + let mut subscriptions = Vec::new(); subscriptions.push(cx.subscribe_in( &backend, window, - |this, _backend, event, window, cx| match event { - BackendEvent::PassphraseRequired => { - this.open_passphrase(cx); - } - BackendEvent::Error(message) => { - cx.toast(Toast::new(message.clone()).icon(IconRole::Warning)); - } - BackendEvent::SignerChanged => { - let app = cx.entity().downgrade(); - window.defer(cx, move |window, cx| { - Self::reset_to_explore(&app, window, cx) - }); - } - _ => {} + |this, _backend, event, window, cx| { + match event { + BackendEvent::PassphraseRequired => { + this.open_passphrase(cx); + } + BackendEvent::Error(message) => { + cx.toast(Toast::new(message).icon(IconRole::Warning)); + } + BackendEvent::SignerChanged => { + cx.defer_in(window, |this, window, cx| { + this.reset_to_explore(window, cx); + }); + } + _ => {} + }; }, )); @@ -70,15 +94,16 @@ impl AppRoot { let appearance = store.read(cx).settings().appearance; if appearance != this.appearance { this.appearance = appearance; - apply_appearance_mode(appearance, cx); + Self::apply_appearance_mode(appearance, cx); } })); - window.defer(cx, move |window, cx| { - if backend.read(cx).passphrase_required() { - log_dropped(app.update(cx, |this, cx| this.open_passphrase(cx))); + let backend_deferred = backend.clone(); + cx.defer_in(window, move |this, window, cx| { + if backend_deferred.read(cx).passphrase_required() { + this.open_passphrase(cx); } - Self::reset_to_explore(&app, window, cx); + this.reset_to_explore(window, cx); }); Self { @@ -94,18 +119,129 @@ impl AppRoot { cx.open_dialog(dialog); } + /// Builds the window root with the app shell inside it. + pub fn mount(window: &mut Window, cx: &mut App) -> Entity { + let root = cx.new(|cx| Root::new(window, cx)); + let content = cx.new(|cx| AppRoot::new(window, cx)); + root.update(cx, |root, cx| { + root.set_content(content, cx); + }); + root + } + + /// Applies one appearance mode to the kit theme. + pub fn apply_appearance_mode(mode: AppearanceMode, cx: &mut App) { + match mode { + AppearanceMode::System => ThemeEngine::follow_system(cx), + AppearanceMode::Light => ThemeEngine::set_mode_override(Some(ThemeVariant::Light), cx), + AppearanceMode::Dark => ThemeEngine::set_mode_override(Some(ThemeVariant::Dark), cx), + } + } + /// The panel stack: the main stack, the split stack, and the divider between them. pub fn panels(&self) -> &Entity { &self.panels } /// Empties the stack and opens it on the explore panel, where every session starts. - fn reset_to_explore(app: &WeakEntity, window: &mut Window, cx: &mut App) { - let result = app.update(cx, |this, cx| { - this.panels.update(cx, |panels, cx| panels.clear(cx)) + fn reset_to_explore(&mut self, window: &mut Window, cx: &mut Context) { + self.panels.update(cx, |panels, cx| panels.clear(cx)); + ExploreView::open(&self.panels, cx.weak_entity(), window, cx); + } + + /// Builds the tab views for the repository served by `store`, observing their totals into `this`. + pub(crate) fn repo_tabs( + store: &Entity, + workspace: &WeakEntity, + cx: &mut Context, + ) -> RepoTabs { + let issues = cx.new(|cx| IssuesView::new(workspace.clone(), store.clone(), cx)); + let pulls = cx.new(|cx| PullRequestsView::new(workspace.clone(), store.clone(), cx)); + + let subscriptions = vec![ + cx.observe(&issues, |this, view, cx| { + this.issue_count = view.read(cx).total_count() + }), + cx.observe(&pulls, |this, view, cx| { + this.pull_count = view.read(cx).total_count() + }), + ]; + + RepoTabs { + issues: issues.into(), + pulls: pulls.into(), + _subscriptions: subscriptions, + } + } + + /// Opens a repository as the main panel, keyed by its address. + pub(crate) fn open_repo_panel( + &mut self, + addr: &RepoAddr, + hint: Option<&Announcement>, + window: &mut Window, + cx: &mut Context, + ) { + let id = SharedString::from(format!("repo:{addr}")); + let addr = addr.clone(); + let hint = hint.cloned(); + let workspace = cx.weak_entity(); + + self.panels.update(cx, |panels, cx| { + panels.open( + PanelSlot::Main, + id, + move |window, cx| { + let addr = addr.clone(); + let hint = hint.clone(); + cx.new(|cx| RepoDetailView::new(workspace.clone(), addr, hint, window, cx)) + }, + window, + cx, + ); }); - log_dropped(result); - ExploreView::open(app, window, cx); + } + + /// Opens an issue or pull request using a store built here. + pub(crate) fn open_repo_item( + &mut self, + addr: &RepoAddr, + hint: Option<&Announcement>, + item: RepoItem, + window: &mut Window, + cx: &mut Context, + ) { + match item { + RepoItem::Issue(issue_id) => { + let store = cx.new(|cx| RepoStore::new(addr.clone(), hint.cloned(), cx)); + IssueDetailView::open(&self.panels, store, issue_id, window, cx); + } + RepoItem::PullRequest(pr_id) => { + let store = cx.new(|cx| RepoStore::new(addr.clone(), hint.cloned(), cx)); + PullRequestDetailView::open( + &self.panels, + &cx.weak_entity(), + store, + pr_id, + window, + cx, + ); + } + // Opening a patch series directly is not a feature. + RepoItem::Patch => {} + } + } + + /// Opens the dialog that imports an identity from a secret. + pub(crate) fn open_import_dialog(&mut self, _window: &mut Window, cx: &mut Context) { + let dialog = ImportDialog::new(cx); + cx.open_dialog(dialog); + } + + /// Opens the dialog that creates an identity. + pub(crate) fn open_onboarding_dialog(&mut self, cx: &mut Context) { + let dialog = OnboardingDialog::new(cx); + cx.open_dialog(dialog); } } @@ -119,8 +255,12 @@ impl Render for AppRoot { .size_full() .key_context(REPOSITORY_KEY_CONTEXT) .on_action(cx.listener(|this, action: &SwitchRepository, window, cx| { - this.titlebar.update(cx, |titlebar, cx| { - titlebar.activate_shortcut(action.index, window, cx); + let titlebar = this.titlebar.downgrade(); + let index = action.index; + window.defer(cx, move |window, cx| { + log_dropped(titlebar.update(cx, |titlebar, cx| { + titlebar.activate_shortcut(index, window, cx); + })); }); })) .on_action(cx.listener(|this, _: &CreateRepository, window, cx| { diff --git a/crates/signed_app/src/explore/helpers.rs b/crates/signed_app/src/explore/helpers.rs index 0c1475b..9ba32a6 100644 --- a/crates/signed_app/src/explore/helpers.rs +++ b/crates/signed_app/src/explore/helpers.rs @@ -1,9 +1,6 @@ -use std::sync::LazyLock; -use std::time::{SystemTime, UNIX_EPOCH}; - use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, Entity, InteractiveElement as _, IntoElement, ParentElement as _, SharedString, + Entity, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _, WeakEntity, div, px, }; use metadata::ProfileDirectory; @@ -16,23 +13,11 @@ use ui::theme::ActiveTheme as _; use utils::relative_time; use crate::app::AppRoot; -use crate::repo::actions::open_repo_panel; -use crate::repo::helpers::{announcement_display_name, upstream_display_name}; +use crate::shared::labels::{AnnouncementExt as _, AnnouncementsExt as _}; +use crate::shared::log_dropped; const RECENT_COUNT: usize = 10; -/// One of the three banner photos, picked per process launch. -pub fn pick_banner() -> SharedString { - static BANNER: LazyLock = LazyLock::new(|| { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|now| now.subsec_nanos()) - .unwrap_or(0); - SharedString::from(format!("backgrounds/banner{}.jpg", nanos % 3 + 1)) - }); - BANNER.clone() -} - #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub(super) enum RepoFilter { #[default] @@ -64,127 +49,187 @@ impl RepoFilter { } } -pub(super) fn render_card( - announcement: &Announcement, - last_activity: Option, - announcements: &[Announcement], - directory: &Entity, - workspace: &WeakEntity, - cx: &mut gpui::App, -) -> AnyElement { - let owner = directory.read(cx).profile(&announcement.owner, cx); - let owner_name = owner.name(); - let workspace = workspace.clone(); - let announcement = announcement.clone(); +/// One explore card's display strings, built when the row list is rebuilt. +#[derive(Clone)] +pub(super) struct CardData { + /// Index into the store's `announcements`. + pub(super) ix: usize, + /// The announcement's element id. + pub(super) id: SharedString, + pub(super) name: SharedString, + pub(super) description: SharedString, + pub(super) activity: SharedString, + pub(super) fork_label: Option, +} - let name = announcement_display_name(&announcement); +impl CardData { + pub(super) fn new( + ix: usize, + announcement: &Announcement, + announcements: &[Announcement], + last_activity: Option, + ) -> Self { + let activity = last_activity + .map(relative_time) + .map(|label| SharedString::from(format!("Updated {label}"))) + .unwrap_or_default(); - let description = announcement - .description - .as_deref() - .map(SharedString::from) - .unwrap_or_else(|| SharedString::from("No description")); + let fork_label = announcement.upstream.as_ref().and_then(|upstream| { + let addr = upstream.addr.as_ref()?; + let name = announcements.upstream_display_name(addr); + Some(SharedString::from(format!("forked from {name}"))) + }); - let activity = last_activity - .map(relative_time) - .map(|label| SharedString::from(format!("Updated {label}"))) - .unwrap_or_default(); + Self { + ix, + id: SharedString::from(format!("repo-card:{}", announcement.id)), + name: announcement.display_name(), + description: announcement + .description + .as_deref() + .map(SharedString::from) + .unwrap_or_else(|| SharedString::from("No description")), + activity, + fork_label, + } + } +} - let fork_label: Option = announcement.upstream.as_ref().and_then(|upstream| { - let addr = upstream.addr.as_ref()?; - let name = upstream_display_name(addr, announcements); - Some(SharedString::from(format!("forked from {name}"))) - }); +/// One repository card in the explore grid. +#[derive(IntoElement)] +pub(super) struct RepoCard { + data: CardData, + announcement: Announcement, + directory: Entity, + workspace: WeakEntity, +} - v_flex() - .id(SharedString::from(format!("repo-card:{}", announcement.id))) - .flex_1() - .h_full() - .min_w_0() - .px_3() - .rounded(cx.theme().radius.control) - .border_1() - .border_color(cx.theme().colors.border) - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .child( - h_flex() - .h_10() - .gap_2() - .child( - div() - .flex_1() - .min_w_0() - .text_sm() - .font_semibold() - .whitespace_nowrap() - .text_ellipsis() - .child(name), - ) - .when_some(fork_label, |this, label| { - this.child( - h_flex() - .gap_1() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) +impl RepoCard { + pub(super) fn new( + data: &CardData, + announcement: &Announcement, + directory: &Entity, + workspace: &WeakEntity, + ) -> Self { + Self { + data: data.clone(), + announcement: announcement.clone(), + directory: directory.clone(), + workspace: workspace.clone(), + } + } +} + +impl RenderOnce for RepoCard { + fn render(self, _window: &mut gpui::Window, cx: &mut gpui::App) -> impl IntoElement { + let Self { + data, + announcement, + directory, + workspace, + } = self; + + let CardData { + id, + name, + description, + activity, + fork_label, + .. + } = &data; + + let owner = directory.read(cx).profile(&announcement.owner, cx); + let owner_name = owner.name(); + + v_flex() + .id(id.clone()) + .flex_1() + .h_full() + .min_w_0() + .px_3() + .rounded(cx.theme().radius.control) + .border_1() + .border_color(cx.theme().colors.border) + .hover(|this| this.bg(cx.theme().colors.muted_hover)) + .child( + h_flex() + .h_10() + .gap_2() + .child( + div() + .flex_1() + .min_w_0() + .text_sm() + .font_semibold() .whitespace_nowrap() - .child( - Icon::named(IconRole::GitBranch) - .size(px(12.)) - .color(cx.theme().colors.muted_foreground), - ) - .child(label), + .text_ellipsis() + .child(name.clone()), ) - }), - ) - .child( - div() - .h_16() - .min_w_0() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .line_clamp(2) - .child(description), - ) - .child( - h_flex() - .h_12() - .gap_2() - .overflow_hidden() - .child( - h_flex() - .gap_2() - .child( - Avatar::new(announcement.owner) - .name(owner_name.clone()) - .picture(owner.picture()) - .small(), - ) - .child( - div() + .when_some(fork_label.clone(), |this, label| { + this.child( + h_flex() + .flex_shrink_0() + .gap_1() .text_xs() .text_color(cx.theme().colors.muted_foreground) .whitespace_nowrap() - .child(owner_name), - ), - ) - .child( - h_flex() - .flex_1() - .justify_end() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .whitespace_nowrap() - .child(activity), - ), - ) - .on_click(move |_, window, cx| { - open_repo_panel( - &workspace, - &announcement.addr(), - Some(&announcement), - window, - cx, - ); - }) - .into_any_element() + .child( + Icon::named(IconRole::GitBranch) + .size(px(12.)) + .color(cx.theme().colors.muted_foreground), + ) + .child(label), + ) + }), + ) + .child( + div() + .h_16() + .min_w_0() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .line_clamp(2) + .child(description.clone()), + ) + .child( + h_flex() + .h_12() + .gap_2() + .overflow_hidden() + .child( + h_flex() + .min_w_0() + .gap_2() + .child( + Avatar::new(announcement.owner) + .name(owner_name.clone()) + .picture(owner.picture()) + .small(), + ) + .child( + div() + .min_w_0() + .truncate() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child(owner_name), + ), + ) + .child( + h_flex() + .flex_1() + .justify_end() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .whitespace_nowrap() + .child(activity.clone()), + ), + ) + .on_click(move |_, window, cx| { + let result = workspace.update(cx, |root, cx| { + root.open_repo_panel(&announcement.addr(), Some(&announcement), window, cx); + }); + log_dropped(result); + }) + } } diff --git a/crates/signed_app/src/explore/mod.rs b/crates/signed_app/src/explore/mod.rs index df68c12..155131f 100644 --- a/crates/signed_app/src/explore/mod.rs +++ b/crates/signed_app/src/explore/mod.rs @@ -1,3 +1,6 @@ +mod helpers; + +use std::rc::Rc; use std::sync::Arc; use gpui::{ @@ -5,7 +8,7 @@ use gpui::{ ObjectFit, ParentElement as _, Pixels, Render, SharedString, Styled as _, StyledImage as _, Subscription, WeakEntity, Window, div, img, list, px, }; -use helpers::{RepoFilter, render_card}; +use helpers::{CardData, RepoCard, RepoFilter}; use metadata::ProfileDirectory; use nostr::prelude::PublicKey; use signed_state::{Backend, RepoListStore}; @@ -14,24 +17,21 @@ use ui::common::{h_flex, v_flex}; use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState, InputStateEvent}; -use ui::layout::panel::{Panel, PanelSlot, SplitSide}; -use ui::layout::root::RootContext as _; +use ui::layout::panel::{Panel, PanelSlot, PanelStack, SplitSide}; use ui::scrollbar::Scrollbar; use ui::segmented::{Segmented, SegmentedOption}; use ui::theme::ActiveTheme as _; use crate::app::AppRoot; -use crate::explore::helpers::pick_banner; -use crate::identity::import::ImportDialog; -use crate::identity::onboarding::OnboardingDialog; use crate::shared::log_dropped; -mod helpers; - const COLUMNS: usize = 2; // Name row, avatar strip, meta row, and their borders and gaps, in px. const CARD_HEIGHT: f32 = 40. + 64. + 48. + 2. + 6.; +/// Applies a new explore filter. +type FilterHandler = Rc; + pub struct ExploreView { store: Entity, workspace: WeakEntity, @@ -39,6 +39,8 @@ pub struct ExploreView { filter: RepoFilter, /// Indices matching [`Self::filter`] into the store's `announcements`. visible: Vec, + /// The visible cards' display strings, rebuilt with `visible`. + cards: Arc>, search: Entity, /// Profiles for the card owners. directory: Entity, @@ -53,28 +55,28 @@ impl ExploreView { pub(crate) const PANEL_ID: &'static str = "Explore"; /// Opens the explore panel in the main panel, reusing it when it is already cached. - pub(crate) fn open(workspace: &WeakEntity, window: &mut Window, cx: &mut App) { - log_dropped(workspace.update(cx, |root, cx| { - root.panels().clone().update(cx, |panels, cx| { - panels.open( - PanelSlot::Main, - Self::PANEL_ID, - { - let workspace = workspace.clone(); - move |_, cx| cx.new(|cx| Self::new(workspace.clone(), cx)) - }, - window, - cx, - ) - }) - })); + pub(crate) fn open( + panels: &Entity, + workspace: WeakEntity, + window: &mut Window, + cx: &mut App, + ) { + panels.update(cx, |panels, cx| { + panels.open( + PanelSlot::Main, + Self::PANEL_ID, + move |_, cx| cx.new(|cx| Self::new(workspace.clone(), cx)), + window, + cx, + ); + }); } pub fn new(workspace: WeakEntity, cx: &mut Context) -> Self { let store = RepoListStore::global(cx); let directory = ProfileDirectory::new(cx); - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); let search = InputState::new(cx); let search_subscription = cx.subscribe(&search, |this, _search, event, cx| { @@ -103,6 +105,7 @@ impl ExploreView { scroll_handle: ListState::new(1, ListAlignment::Top, px(320.)), filter: RepoFilter::default(), visible: Vec::new(), + cards: Arc::new(Vec::new()), search, directory, _search_subscription: search_subscription, @@ -118,6 +121,21 @@ impl ExploreView { let store = self.store.read(cx); self.visible = filter.visible(store, &query); + self.cards = Arc::new( + self.visible + .iter() + .filter_map(|ix| { + let announcement = store.announcements.get(*ix)?; + let activity = store.last_activity.get(&announcement.addr()).copied(); + Some(CardData::new( + *ix, + announcement, + &store.announcements, + activity, + )) + }) + .collect(), + ); let owners: Vec = self .visible @@ -156,8 +174,10 @@ impl ExploreView { log::warn!("failed to watch the panel stack: the app root is gone"); return; }; - self._stack_subscription = - Some(cx.observe(&stack, |this, _stack, cx| this.sync_sidebar(cx))); + + self._stack_subscription = Some(cx.observe(&stack, |this, _stack, cx| { + this.sync_sidebar(cx); + })); self.sync_sidebar(cx); } @@ -172,7 +192,9 @@ impl ExploreView { let shown = signed_out && stack.is_active(PanelSlot::Main, &explore); if shown && !stack.is_open(PanelSlot::Split, &sidebar) { - let view = Arc::new(cx.new(|_| OnboardingSidebar)); + let view = Arc::new(cx.new(|_| OnboardingSidebar { + workspace: self.workspace.clone(), + })); stack.insert_split_at( sidebar.clone(), OnboardingSidebar::WIDTH, @@ -180,7 +202,7 @@ impl ExploreView { view, cx, ); - } else if !shown { + } else if !shown && stack.is_open(PanelSlot::Split, &sidebar) { stack.close(PanelSlot::Split, &sidebar, cx); } }) @@ -191,12 +213,63 @@ impl ExploreView { } } + /// One list row: the search header, or one strip of repository cards. + fn render_list_item(&mut self, item: usize, cx: &mut Context) -> AnyElement { + if item == 0 { + let on_filter: FilterHandler = + Rc::new(cx.processor(|this, filter: RepoFilter, _, cx| { + this.filter = filter; + this.rebuild_rows(false, cx); + })); + return Self::render_header(self.search.clone(), self.filter, on_filter, cx) + .into_any_element(); + } + + if self.visible.is_empty() { + return v_flex() + .w_full() + .h(px(320.)) + .items_center() + .justify_center() + .child(EmptyState::new("No repositories match your search")) + .into_any_element(); + } + + let store = self.store.read(cx); + let row = item - 1; + let mut rendered = Vec::with_capacity(COLUMNS); + + for col in 0..COLUMNS { + let Some(data) = self.cards.get(row * COLUMNS + col) else { + break; + }; + let Some(announcement) = store.announcements.get(data.ix) else { + break; + }; + rendered.push(RepoCard::new( + data, + announcement, + &self.directory, + &self.workspace, + )); + } + + h_flex() + .w_full() + .h(px(CARD_HEIGHT)) + .gap_3() + .px_4() + .pt_4() + .children(rendered) + .into_any_element() + } + fn render_header( search: Entity, filter: RepoFilter, - weak: WeakEntity, + on_filter: FilterHandler, cx: &App, - ) -> AnyElement { + ) -> impl IntoElement { let muted = cx.theme().colors.muted_foreground; div() @@ -231,17 +304,11 @@ impl ExploreView { .label("Recent") .icon(Icon::named(IconRole::Clock).small().color(muted)), ]) - .on_change(move |filter, _, cx| { - if let Err(error) = weak.update(cx, |this, cx| { - this.filter = filter; - this.rebuild_rows(false, cx); - }) { - log::warn!("failed to change explore filter: {error}"); - } + .on_change(move |filter, window, cx| { + on_filter(filter, window, cx); }), ), ) - .into_any_element() } } @@ -262,67 +329,16 @@ impl Panel for ExploreView { impl Render for ExploreView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let store = self.store.read(cx); - let announcements = store.announcements.clone(); - let last_activity = store.last_activity.clone(); - let visible = self.visible.clone(); - let directory = self.directory.clone(); - let workspace = self.workspace.clone(); - let has_repos = !visible.is_empty(); - let search = self.search.clone(); - let filter = self.filter; - let weak = cx.entity().downgrade(); let scroll_handle = self.scroll_handle.clone(); div() .relative() .size_full() .child( - list(self.scroll_handle.clone(), move |item, _, cx| { - if item == 0 { - return Self::render_header(search.clone(), filter, weak.clone(), cx); - } - - if !has_repos { - return v_flex() - .w_full() - .h(px(320.)) - .items_center() - .justify_center() - .child(EmptyState::new("No repositories match your search")) - .into_any_element(); - } - - let row = item - 1; - let mut cards = Vec::with_capacity(COLUMNS); - - for col in 0..COLUMNS { - let Some(&ix) = visible.get(row * COLUMNS + col) else { - break; - }; - let Some(announcement) = announcements.get(ix) else { - break; - }; - let activity = last_activity.get(&announcement.addr()).copied(); - cards.push(render_card( - announcement, - activity, - &announcements, - &directory, - &workspace, - cx, - )); - } - - h_flex() - .w_full() - .h(px(CARD_HEIGHT)) - .gap_3() - .px_4() - .pt_4() - .children(cards) - .into_any_element() - }) + list( + self.scroll_handle.clone(), + cx.processor(|this, item: usize, _window, cx| this.render_list_item(item, cx)), + ) .size_full(), ) .child(Scrollbar::vertical("explore-scroll", scroll_handle)) @@ -330,13 +346,27 @@ impl Render for ExploreView { } /// The onboarding sidebar shown beside the explore panel while signed out. -struct OnboardingSidebar; +struct OnboardingSidebar { + workspace: WeakEntity, +} impl OnboardingSidebar { /// The identifier of the sidebar in the panel stack; shown as its tab label. const PANEL_ID: &'static str = "Onboarding"; /// The width the sidebar opens at. const WIDTH: Pixels = px(300.); + + /// One of the three banner photos, picked per process launch. + fn banner() -> SharedString { + static BANNER: std::sync::LazyLock = std::sync::LazyLock::new(|| { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|now| now.subsec_nanos()) + .unwrap_or(0); + SharedString::from(format!("backgrounds/banner{}.jpg", nanos % 3 + 1)) + }); + BANNER.clone() + } } impl Panel for OnboardingSidebar { @@ -349,6 +379,7 @@ impl Render for OnboardingSidebar { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = cx.theme(); let colors = theme.colors; + let workspace = self.workspace.clone(); v_flex() .size_full() @@ -358,7 +389,7 @@ impl Render for OnboardingSidebar { .overflow_hidden() .child( div().absolute().inset_0().child( - img(pick_banner()) + img(OnboardingSidebar::banner()) .size_full() .object_fit(ObjectFit::Cover) .rounded(theme.radius.overlay), @@ -379,18 +410,26 @@ impl Render for OnboardingSidebar { Button::new("join") .label("Join now") .variant(ButtonVariant::Primary) - .on_click(|_, _, cx| { - let dialog = OnboardingDialog::new(cx); - cx.open_dialog(dialog) + .on_click({ + let workspace = workspace.clone(); + move |_, _, cx| { + log_dropped(workspace.update(cx, |root, cx| { + root.open_onboarding_dialog(cx) + })); + } }), ) .child( Button::new("import") .label("Import identity") .variant(ButtonVariant::Secondary) - .on_click(|_, _, cx| { - let dialog = ImportDialog::new(cx); - cx.open_dialog(dialog) + .on_click({ + let workspace = workspace.clone(); + move |_, window, cx| { + log_dropped(workspace.update(cx, |root, cx| { + root.open_import_dialog(window, cx) + })); + } }), ), ), diff --git a/crates/signed_app/src/identity/exit.rs b/crates/signed_app/src/identity/exit.rs index a5233f9..d1ba7ec 100644 --- a/crates/signed_app/src/identity/exit.rs +++ b/crates/signed_app/src/identity/exit.rs @@ -1,6 +1,6 @@ use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, - Styled as _, Window, div, px, + App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, + Window, div, px, }; use signed_state::Backend; use ui::button::{Button, ButtonVariant}; @@ -41,27 +41,28 @@ impl Render for ExitDialog { ) .into_any_element() }) - .actions(move |_, _| { + .actions(move |_, cx| { + let backend = Backend::global(cx); let cancel_close = cancel_close.clone(); let confirm_close = confirm_close.clone(); - let cancel: AnyElement = Button::new("cancel-exit") - .label("Cancel") - .variant(ButtonVariant::Secondary) - .on_click(move |_, _, cx| cancel_close.close(cx)) - .into_any_element(); - - let exit: AnyElement = Button::new("confirm-exit") - .label("Exit") - .variant(ButtonVariant::Destructive) - .on_click(move |_, _, cx| { - let backend = Backend::global(cx); - backend.update(cx, |backend, cx| backend.sign_out(cx)); - confirm_close.close(cx); - }) - .into_any_element(); - - vec![cancel, exit] + vec![ + Button::new("cancel-exit") + .label("Cancel") + .variant(ButtonVariant::Secondary) + .on_click(move |_, _, cx| { + cancel_close.close(cx); + }) + .into_any_element(), + Button::new("confirm-exit") + .label("Exit") + .variant(ButtonVariant::Destructive) + .on_click(move |_, _, cx| { + backend.update(cx, |backend, cx| backend.sign_out(cx)); + confirm_close.close(cx); + }) + .into_any_element(), + ] }) } } diff --git a/crates/signed_app/src/identity/import.rs b/crates/signed_app/src/identity/import.rs index d1e0213..3dfc911 100644 --- a/crates/signed_app/src/identity/import.rs +++ b/crates/signed_app/src/identity/import.rs @@ -1,6 +1,6 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, + App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Subscription, Task, Window, div, px, }; use signed_state::Backend; @@ -11,8 +11,6 @@ use ui::field::Field; use ui::input::{Input, InputState, InputStateEvent}; use ui::theme::ActiveTheme as _; -use crate::shared::progress::{DialogProgress, error_row, run_dialog_task_with}; - #[derive(Clone, Copy, Default, PartialEq, Eq)] enum Stage { #[default] @@ -51,7 +49,9 @@ impl Credential { pub struct ImportState { stage: Stage, credential: String, - progress: DialogProgress, + busy: bool, + error: Option, + task: Option>, } pub struct ImportDialog { @@ -110,6 +110,7 @@ impl ImportDialog { impl Render for ImportDialog { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let state = self.state.clone(); + let busy = state.read(cx).busy; let secret_input = self.secret_input.clone(); let pass_input = self.pass_input.clone(); @@ -122,8 +123,6 @@ impl Render for ImportDialog { let action_repass = repass_input.clone(); let action_close = self.handle.clone(); - let busy = state.read(cx).progress.busy; - Dialog::new("import-dialog") .handle(self.handle.clone()) .close_on_escape(!busy) @@ -135,34 +134,11 @@ impl Render for ImportDialog { let stage = state.stage; let description = match stage { - Stage::Credential => { - "Paste the secret key or bunker URI of an existing identity." - } + Stage::Credential => "Paste the secret key or bunker of an existing identity.", Stage::Encrypt => "Choose a passphrase to encrypt your key on this device.", Stage::Decrypt => "Enter the passphrase used to encrypt this key.", }; - let form = match stage { - Stage::Credential => v_flex().gap_3().child( - Field::new("secret-field", "Secret key or bunker URI") - .child(Input::new("secret-input", secret_input.clone())), - ), - Stage::Encrypt => v_flex() - .gap_3() - .child( - Field::new("passphrase-field", "Passphrase") - .child(Input::new("passphrase-input", pass_input.clone())), - ) - .child( - Field::new("repeat-field", "Repeat passphrase") - .child(Input::new("repeat-input", repass_input.clone())), - ), - Stage::Decrypt => v_flex().gap_3().child( - Field::new("passphrase-field", "Passphrase") - .child(Input::new("passphrase-input", pass_input.clone())), - ), - }; - v_flex() .gap_3() .child( @@ -171,15 +147,39 @@ impl Render for ImportDialog { .text_color(cx.theme().colors.muted_foreground) .child(description), ) - .child(form) - .when_some(error_row(&state.progress.error, cx), |el, error| { - el.child(error) + .child(match stage { + Stage::Credential => v_flex().gap_3().child( + Field::new("secret-field", "Secret key or bunker URI") + .child(Input::new("secret-input", secret_input.clone())), + ), + Stage::Encrypt => v_flex() + .gap_3() + .child( + Field::new("passphrase-field", "Passphrase") + .child(Input::new("passphrase-input", pass_input.clone())), + ) + .child( + Field::new("repeat-field", "Repeat passphrase") + .child(Input::new("repeat-input", repass_input.clone())), + ), + Stage::Decrypt => v_flex().gap_3().child( + Field::new("passphrase-field", "Passphrase") + .child(Input::new("passphrase-input", pass_input.clone())), + ), + }) + .when_some(state.error.clone(), |el, error| { + el.child( + div() + .text_sm() + .text_color(cx.theme().ramps.destructive.base) + .child(error), + ) }) .into_any_element() }) .actions(move |_, cx| { let state = action_state.read(cx); - let busy = state.progress.busy; + let busy = state.busy; let label = match state.stage { Stage::Credential => "Continue", @@ -193,16 +193,16 @@ impl Render for ImportDialog { let state = action_state.clone(); let handle = action_close.clone(); - let import: AnyElement = Button::new("import-identity") - .label(label) - .loading(busy) - .disabled(busy) - .on_click(move |_, _, cx| { - submit(&secret, &pass, &repass, &state, &handle, cx); - }) - .into_any_element(); - - vec![import] + vec![ + Button::new("import-identity") + .label(label) + .loading(busy) + .disabled(busy) + .on_click(move |_, _, cx| { + submit(&secret, &pass, &repass, &state, &handle, cx); + }) + .into_any_element(), + ] }) } } @@ -215,7 +215,7 @@ fn submit( handle: &DialogHandle, cx: &mut App, ) { - if state.read(cx).progress.busy { + if state.read(cx).busy { return; } @@ -237,9 +237,7 @@ fn start_import( Some(credential) => credential, None => { state.update(cx, |state, cx| { - state - .progress - .fail("Enter an nsec, ncryptsec or bunker:// URI"); + state.error = Some("Enter an nsec, ncryptsec or bunker:// URI".into()); cx.notify(); }); return; @@ -251,7 +249,7 @@ fn start_import( state.update(cx, |state, cx| { state.credential = secret; state.stage = Stage::Encrypt; - state.progress.error = None; + state.error = None; cx.notify(); }); } @@ -259,16 +257,16 @@ fn start_import( state.update(cx, |state, cx| { state.credential = secret; state.stage = Stage::Decrypt; - state.progress.error = None; + state.error = None; cx.notify(); }); } Credential::Bunker(uri) => { state.update(cx, |state, cx| { - state.progress.begin(); + state.busy = true; + state.error = None; cx.notify(); }); - let backend = Backend::global(cx); let task = backend.update(cx, |backend, cx| backend.import_bunker(&uri, cx)); finish_import(task, state, handle, cx); @@ -291,7 +289,7 @@ fn import_nsec( if pass.is_empty() { state.update(cx, |state, cx| { - state.progress.fail("Passphrase must not be empty"); + state.error = Some("Passphrase must not be empty".into()); cx.notify(); }); return; @@ -299,14 +297,15 @@ fn import_nsec( if pass != repass { state.update(cx, |state, cx| { - state.progress.fail("Passphrases do not match"); + state.error = Some("Passphrases do not match".into()); cx.notify(); }); return; } state.update(cx, |state, cx| { - state.progress.begin(); + state.busy = true; + state.error = None; cx.notify(); }); @@ -327,14 +326,15 @@ fn import_ncryptsec( if pass.is_empty() { state.update(cx, |state, cx| { - state.progress.fail("Passphrase must not be empty"); + state.error = Some("Passphrase must not be empty".into()); cx.notify(); }); return; } state.update(cx, |state, cx| { - state.progress.begin(); + state.busy = true; + state.error = None; cx.notify(); }); @@ -352,16 +352,20 @@ fn finish_import( cx: &mut App, ) { let handle = handle.clone(); - let state = state.clone(); - run_dialog_task_with( - task, - cx, - move |_, cx| cx.update(|cx| handle.close(cx)), - move |error, cx| { - state.update(cx, |state, cx| { - state.progress.fail(error.to_string()); + let weak = state.clone(); + + let task = cx.spawn(async move |cx| match task.await { + Ok(_) => cx.update(|cx| handle.close(cx)), + Err(error) => { + weak.update(cx, |state, cx| { + state.busy = false; + state.error = Some(error.to_string().into()); cx.notify(); }); - }, - ); + } + }); + + state.update(cx, |state, _| { + state.task = Some(task); + }); } diff --git a/crates/signed_app/src/identity/onboarding.rs b/crates/signed_app/src/identity/onboarding.rs index 7f305d5..8c1f00b 100644 --- a/crates/signed_app/src/identity/onboarding.rs +++ b/crates/signed_app/src/identity/onboarding.rs @@ -1,28 +1,30 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, - Styled as _, Window, div, px, + App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, + Styled as _, Task, Window, div, px, }; use signed_state::Backend; +use ui::button::Button; use ui::common::v_flex; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; -use crate::shared::progress::{DialogProgress, dialog_submit_button, error_row, run_dialog_task}; +use crate::shared::log_dropped; pub struct OnboardingDialog { handle: DialogHandle, name_input: Entity, pass_input: Entity, repass_input: Entity, - state: Entity, + busy: bool, + error: Option, + task: Option>, } impl OnboardingDialog { pub fn new(cx: &mut App) -> Entity { - let state = cx.new(|_| DialogProgress::default()); let name_input = InputState::new(cx); let pass_input = InputState::builder().password().build(cx); let repass_input = InputState::builder().password().build(cx); @@ -32,12 +34,14 @@ impl OnboardingDialog { name_input, pass_input, repass_input, - state, + busy: false, + error: None, + task: None, }) } fn create_identity(&mut self, cx: &mut Context) { - if self.state.read(cx).busy { + if self.busy { return; } @@ -46,33 +50,51 @@ impl OnboardingDialog { let repass = self.repass_input.read(cx).value().to_string(); if pass != repass { - self.state.update(cx, |state, cx| { - state.fail("Passphrases do not match"); - cx.notify(); - }); + self.busy = false; + self.error = Some("Passphrases do not match".into()); + cx.notify(); return; } - self.state.update(cx, |state, cx| { - state.begin(); - cx.notify(); - }); + self.busy = true; + self.error = None; let backend = Backend::global(cx); let task = backend.update(cx, |backend, cx| backend.create_identity(&name, &pass, cx)); - run_dialog_task(task, &self.state, &self.handle, cx); + let handle = self.handle.clone(); + + self.task = Some(cx.spawn(async move |this, cx| { + match task.await { + Ok(_) => { + cx.update(|cx| handle.close(cx)); + log_dropped(this.update(cx, |this, cx| { + this.busy = false; + cx.notify(); + })); + } + Err(error) => { + log_dropped(this.update(cx, |this, cx| { + this.busy = false; + this.error = Some(error.to_string().into()); + cx.notify(); + })); + } + }; + })); } } impl Render for OnboardingDialog { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + const INTRO: &str = "Set up your Signed identity to get started."; + let name_input = self.name_input.clone(); let pass_input = self.pass_input.clone(); let repass_input = self.repass_input.clone(); - let state = self.state.clone(); - let action_state = state.clone(); - let this = cx.entity().downgrade(); - let busy = state.read(cx).busy; + let error = self.error.clone(); + let busy = self.busy; + + let this = cx.weak_entity(); Dialog::new("onboarding-dialog") .handle(self.handle.clone()) @@ -81,14 +103,13 @@ impl Render for OnboardingDialog { .min_width(px(520.)) .title("Create identity") .content(move |_window, cx| { - let progress = state.read(cx); v_flex() .gap_3() .child( div() .text_sm() .text_color(cx.theme().colors.muted_foreground) - .child("Set up your Signed identity to get started."), + .child(INTRO), ) .child( Field::new("name-field", "Name") @@ -103,27 +124,29 @@ impl Render for OnboardingDialog { Field::new("repeat-field", "Repeat passphrase") .child(Input::new("repeat-input", repass_input.clone())), ) - .when_some(error_row(&progress.error, cx), |el, error| el.child(error)) + .when_some(error.clone(), |el, error| { + el.child( + div() + .text_sm() + .text_color(cx.theme().ramps.destructive.base) + .child(error), + ) + }) .into_any_element() }) - .actions(move |_, cx| { - let busy = action_state.read(cx).busy; + .actions(move |_, _cx| { let this = this.clone(); - 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] + vec![ + Button::new("create-identity") + .label("Create new identity") + .loading(busy) + .disabled(busy) + .on_click(move |_, _, cx| { + log_dropped(this.update(cx, |this, cx| this.create_identity(cx))); + }) + .into_any_element(), + ] }) } } diff --git a/crates/signed_app/src/identity/passphrase.rs b/crates/signed_app/src/identity/passphrase.rs index bfc2f24..095f169 100644 --- a/crates/signed_app/src/identity/passphrase.rs +++ b/crates/signed_app/src/identity/passphrase.rs @@ -1,29 +1,30 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, - Styled as _, Subscription, Window, px, + App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, + Styled as _, Subscription, Task, Window, div, px, }; use signed_state::Backend; +use ui::button::Button; use ui::common::v_flex; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; -use ui::icons::IconRole; +use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState, InputStateEvent}; +use ui::theme::ActiveTheme as _; -use crate::shared::progress::{ - DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task, -}; +use crate::shared::log_dropped; pub struct PassphraseDialog { handle: DialogHandle, pass_input: Entity, - state: Entity, + busy: bool, + error: Option, + task: Option>, _enter_subscription: Subscription, } impl PassphraseDialog { pub fn new(cx: &mut App) -> Entity { - let state = cx.new(|_| DialogProgress::default()); let pass_input = InputState::builder().password().build(cx); cx.new(|cx| { @@ -37,44 +38,59 @@ impl PassphraseDialog { Self { handle: DialogHandle::new(true), pass_input, - state, + busy: false, + error: None, + task: None, _enter_subscription: enter_subscription, } }) } fn unlock(&mut self, cx: &mut Context) { - if self.state.read(cx).busy { + if self.busy { return; } let pass = self.pass_input.read(cx).value().to_string(); - if pass.is_empty() { - self.state.update(cx, |state, cx| { - state.fail("Passphrase must not be empty"); - cx.notify(); - }); + self.busy = false; + self.error = Some("Passphrase must not be empty".into()); + cx.notify(); return; } - self.state.update(cx, |state, cx| { - state.begin(); - cx.notify(); - }); + self.busy = true; + self.error = None; let backend = Backend::global(cx); let task = backend.update(cx, |backend, cx| backend.restore_with_passphrase(&pass, cx)); - run_dialog_task(task, &self.state, &self.handle, cx); + let handle = self.handle.clone(); + + self.task = Some(cx.spawn(async move |this, cx| match task.await { + Ok(_) => { + cx.update(|cx| handle.close(cx)); + log_dropped(this.update(cx, |this, cx| { + this.busy = false; + cx.notify(); + })); + } + Err(error) => { + log_dropped(this.update(cx, |this, cx| { + this.busy = false; + this.error = Some(error.to_string().into()); + cx.notify(); + })); + } + })); } } impl Render for PassphraseDialog { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let pass_input = self.pass_input.clone(); - let state = self.state.clone(); - let action_state = state.clone(); - let this = cx.entity().downgrade(); + let error = self.error.clone(); + let this = cx.weak_entity(); + let busy = self.busy; Dialog::new("passphrase-dialog") .handle(self.handle.clone()) @@ -83,7 +99,6 @@ impl Render for PassphraseDialog { .min_width(px(420.)) .title("Unlock your identity") .content(move |_window, cx| { - let progress = state.read(cx); v_flex() .gap_3() .child( @@ -93,30 +108,32 @@ impl Render for PassphraseDialog { ) .child(Input::new("passphrase-input", pass_input.clone())), ) - .when_some(error_row(&progress.error, cx), |el, error| el.child(error)) - .when_some(push_steps_row(&progress.push_steps, cx), |el, steps| { - el.child(steps) + .when_some(error.clone(), |el, error| { + el.child( + div() + .text_sm() + .text_color(cx.theme().ramps.destructive.base) + .child(error), + ) }) .into_any_element() }) - .actions(move |_, cx| { - let busy = action_state.read(cx).busy; + .actions(move |_, _cx| { let this = this.clone(); - 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] + vec![ + Button::new("unlock") + .label("Unlock") + .icon(Icon::named(IconRole::Unlock)) + .loading(busy) + .disabled(busy) + .on_click(move |_, _, cx| { + log_dropped(this.update(cx, |this, cx| { + this.unlock(cx); + })); + }) + .into_any_element(), + ] }) } } diff --git a/crates/signed_app/src/inbox/helpers.rs b/crates/signed_app/src/inbox/helpers.rs index d3a5df8..4249edb 100644 --- a/crates/signed_app/src/inbox/helpers.rs +++ b/crates/signed_app/src/inbox/helpers.rs @@ -1,6 +1,8 @@ +use std::sync::Arc; + use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, Div, Entity, InteractiveElement as _, IntoElement, ParentElement as _, + App, Div, Entity, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, SharedString, Stateful, Styled as _, div, }; use metadata::ProfileDirectory; @@ -8,146 +10,114 @@ use nostr::prelude::{Event, Kind, PublicKey}; use ui::avatar::Avatar; use ui::badge::Badge; use ui::common::{Sizable as _, h_flex, v_flex}; -use ui::icons::{Icon, IconRole}; use ui::status_dot::{StatusDot, StatusDotVariant}; use ui::theme::ActiveTheme as _; use utils::relative_time; -pub fn repo_header(id: SharedString, name: SharedString, unread: usize) -> AnyElement { - h_flex() - .h_12() - .w_full() - .gap_2() - .child( - div() - .min_w_0() - .text_sm() - .whitespace_nowrap() - .text_ellipsis() - .child(name), - ) - .when(unread > 0, |this| { - this.child(Badge::new(id.clone(), unread.to_string())) - }) - .into_any_element() -} +use super::{EntryRow, InboxSection}; -pub fn empty_section_row(cx: &App) -> AnyElement { - h_flex() - .h_12() - .w_full() - .px_3() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .bg(cx.theme().colors.secondary) - .rounded(cx.theme().radius.control) - .child(SharedString::from("No activity yet.")) - .into_any_element() -} - -#[expect(clippy::too_many_arguments, reason = "one per column")] -pub fn thread( - prefix: &'static str, - ix: usize, - title: SharedString, - unread: bool, - first: bool, - last: bool, - events: Vec, - me: Option, - directory: &Entity, - cx: &App, -) -> Stateful
{ - let mut timeline = v_flex().gap_2().w_full(); - for event in events { - timeline = timeline.child(sub_activity(&event, me, directory, cx)); +impl InboxSection { + /// The section's header row: its repository name and unread count. + pub(super) fn header(&self, _cx: &App) -> Stateful
{ + h_flex() + .id(( + gpui::ElementId::from(self.badge_id.clone()), + SharedString::from("header"), + )) + .h_12() + .w_full() + .gap_2() + .child( + div() + .min_w_0() + .text_sm() + .whitespace_nowrap() + .text_ellipsis() + .child(self.name.clone()), + ) + .when(self.unread > 0, |this| { + this.child(Badge::new(self.badge_id.clone(), self.unread.to_string())) + }) } - v_flex() - .id((prefix, ix)) - .w_full() - .px_3() - .py_2() - .gap_2() - .bg(cx.theme().colors.secondary) - .when(first, |this| this.rounded_t(cx.theme().radius.control)) - .when(last, |this| this.rounded_b(cx.theme().radius.control)) - .when(!last, |this| { - this.border_b_1().border_color(cx.theme().colors.background) - }) - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .child( - h_flex() - .gap_2() - .text_sm() - .child( - h_flex() - .size_6() - .flex_shrink_0() - .items_center() - .justify_center() - .child( - Icon::named(IconRole::Inbox) - .small() - .color(cx.theme().colors.muted_foreground), - ), - ) - .child( - div() - .min_w_0() - .whitespace_nowrap() - .text_ellipsis() - .child(title), - ) - .child(div().flex_1()) - .when(unread, |this| { - this.child( - StatusDot::new(("inbox-unread", ix)).variant(StatusDotVariant::Accent), - ) - }), - ) - .child(timeline) + /// The placeholder shown when the section has no threads. + pub(super) fn empty_row(cx: &App) -> Stateful
{ + h_flex() + .id("inbox-empty") + .h_12() + .w_full() + .px_3() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .bg(cx.theme().colors.secondary) + .rounded(cx.theme().radius.control) + .child(SharedString::from("No activity yet.")) + } } -fn sub_activity( - event: &Event, +/// One sub-activity line under a thread's title. +#[derive(IntoElement)] +pub(super) struct ActivityRow { + events: Arc<[Event]>, + ix: usize, me: Option, - directory: &Entity, - cx: &App, -) -> AnyElement { - let profile = directory.read(cx).profile(&event.pubkey, cx); - let name = if Some(event.pubkey) == me { - SharedString::from("You") - } else { - profile.name() - }; + directory: Entity, +} - h_flex() - .w_full() - .gap_2() - .child(div().w_6().flex_shrink_0()) - .child( - h_flex() - .flex_1() - .min_w_0() - .gap_1() - .text_xs() - .child( - Avatar::new(event.pubkey) - .name(name.clone()) - .picture(profile.picture()) - .small(), - ) - .child(name) - .child(SharedString::from(activity_phrase(event.kind))) - .child(div().flex_1()) - .child( - div() - .text_color(cx.theme().colors.muted_foreground) - .child(SharedString::from(relative_time(event.created_at))), - ), - ) - .into_any_element() +impl ActivityRow { + pub(super) fn new( + events: &Arc<[Event]>, + ix: usize, + me: Option, + directory: &Entity, + ) -> Self { + Self { + events: Arc::clone(events), + ix, + me, + directory: directory.clone(), + } + } +} + +impl RenderOnce for ActivityRow { + fn render(self, _window: &mut gpui::Window, cx: &mut App) -> impl IntoElement { + let Some(event) = self.events.get(self.ix) else { + return div(); + }; + let profile = self.directory.read(cx).profile(&event.pubkey, cx); + let name = if Some(event.pubkey) == self.me { + SharedString::from("You") + } else { + profile.name() + }; + + h_flex() + .w_full() + .gap_2() + .child(div().w_6().flex_shrink_0()) + .child( + h_flex() + .flex_1() + .min_w_0() + .gap_1() + .text_xs() + .child( + Avatar::new(event.pubkey) + .name(name.clone()) + .picture(profile.picture()) + .small(), + ) + .child(name) + .child(SharedString::from(activity_phrase(event.kind))) + .child(div().flex_1()) + .child( + div() + .text_color(cx.theme().colors.muted_foreground) + .child(SharedString::from(relative_time(event.created_at))), + ), + ) + } } fn activity_phrase(kind: Kind) -> &'static str { @@ -164,3 +134,60 @@ fn activity_phrase(kind: Kind) -> &'static str { _ => "did something", } } + +impl super::InboxView { + /// One thread row, keyed by its thread root. + pub(super) fn thread(&self, row: &EntryRow, me: Option, cx: &App) -> Stateful
{ + v_flex() + // Keyed by the thread, not its position: rows reorder by latest activity. + .id(( + gpui::ElementId::from("inbox-row"), + SharedString::from(row.root.to_hex()), + )) + .w_full() + .px_3() + .py_2() + .gap_2() + .bg(cx.theme().colors.secondary) + .when(row.first, |this| this.rounded_t(cx.theme().radius.control)) + .when(row.last, |this| this.rounded_b(cx.theme().radius.control)) + .when(!row.last, |this| { + this.border_b_1().border_color(cx.theme().colors.background) + }) + .hover(|this| this.bg(cx.theme().colors.muted_hover)) + .child( + h_flex() + .gap_2() + .text_sm() + .child( + h_flex() + .size_6() + .flex_shrink_0() + .items_center() + .justify_center() + .child( + ui::icons::Icon::named(ui::icons::IconRole::Inbox) + .small() + .color(cx.theme().colors.muted_foreground), + ), + ) + .child( + div() + .min_w_0() + .whitespace_nowrap() + .text_ellipsis() + .child(row.title.clone()), + ) + .child(div().flex_1()) + .when(row.unread, |this| { + this.child(StatusDot::new().variant(StatusDotVariant::Accent)) + }), + ) + .child( + v_flex().gap_2().w_full().children( + (0..row.timeline.len()) + .map(|ix| ActivityRow::new(&row.timeline, ix, me, &self.directory)), + ), + ) + } +} diff --git a/crates/signed_app/src/inbox/mod.rs b/crates/signed_app/src/inbox/mod.rs index 35fd648..6c0d7a2 100644 --- a/crates/signed_app/src/inbox/mod.rs +++ b/crates/signed_app/src/inbox/mod.rs @@ -1,12 +1,13 @@ use std::collections::HashMap; +use std::rc::Rc; use std::sync::Arc; use anyhow::Error; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, - SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity, - Window, div, + AnyElement, App, AppContext as _, Context, Entity, IntoElement, ListAlignment, ListState, + ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, + Subscription, Task, WeakEntity, Window, div, list, px, }; use metadata::ProfileDirectory; use nostr::prelude::{Event, EventId, Kind, PublicKey, Timestamp}; @@ -18,27 +19,43 @@ 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; mod helpers; -use helpers::{empty_section_row, repo_header, thread}; - -use crate::app::AppRoot; -use crate::repo::actions::{RepoItem, open_repo_item}; -use crate::repo::helpers::announcement_display_name; +use crate::app::{AppRoot, RepoItem}; +use crate::shared::labels::AnnouncementExt; +use crate::shared::log_dropped; const MAX_SUB_ACTIVITIES: usize = 5; +/// Opens a thread's root event in its repository. +type OpenHandler = Rc, Option, &mut Window, &mut App)>; + #[derive(Clone, Copy)] enum InboxRow { Repo(usize), - Entry(usize, usize), + Entry(usize), Empty, } +/// One thread row's display data, built when the inbox regroups. +struct EntryRow { + root: EventId, + kind: Option, + address: Option, + title: SharedString, + unread: bool, + first: bool, + last: bool, + timeline: Arc<[Event]>, +} + struct InboxSection { address: Option, + /// The section's display name. + name: SharedString, + /// The unread badge's element id. + badge_id: SharedString, unread: usize, entries: Vec, latest: Timestamp, @@ -49,6 +66,10 @@ pub struct InboxView { threads: Arc>, sections: Arc>, rows: Arc>, + /// The thread rows, indexed by `InboxRow::Entry`. + entry_rows: Arc>, + /// Scroll state of the flattened rows. + rows_scroll: ListState, state: InboxReadState, state_loaded: bool, refresh: RefreshGate, @@ -65,7 +86,7 @@ impl InboxView { let inbox = backend.read(cx).inbox(); let repos = RepoListStore::global(cx); - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); let mut subscriptions = vec![]; @@ -93,6 +114,8 @@ impl InboxView { threads: Arc::new(Vec::new()), sections: Arc::new(Vec::new()), rows: Arc::new(Vec::new()), + entry_rows: Arc::new(Vec::new()), + rows_scroll: ListState::new(0, ListAlignment::Top, px(48.)), state: InboxReadState::default(), state_loaded: false, refresh: RefreshGate::default(), @@ -171,12 +194,6 @@ impl InboxView { self.run_refresh(cx); } - /// Reaps finished tasks, then queues another. - fn push_task(&mut self, task: Task>) { - self.tasks.retain(|task| !task.is_ready()); - self.tasks.push(task); - } - fn run_refresh(&mut self, cx: &mut Context) { self.refresh.begin(); let backend = Backend::global(cx); @@ -191,7 +208,7 @@ impl InboxView { let state = self.state.clone(); let work = cx.background_spawn(async move { Inbox::query(&client, me, &state).await }); - self.push_task(cx.spawn(async move |this, cx| { + self.tasks.push(cx.spawn(async move |this, cx| { let (threads, _unread_count) = match work.await { Ok(results) => results, Err(error) => { @@ -246,6 +263,8 @@ impl InboxView { if !known { sections.push(InboxSection { address: Some(address), + name: SharedString::default(), + badge_id: SharedString::default(), unread: 0, entries: Vec::new(), latest: Timestamp::default(), @@ -255,8 +274,37 @@ impl InboxView { } sections.sort_by_key(|section| std::cmp::Reverse(section.latest)); + + let mut entry_rows = Vec::new(); + for section in &mut sections { + let name = repo_name(section.address.as_ref(), cx); + section.badge_id = SharedString::from(match §ion.address { + Some(address) => format!("inbox-unread:{address}"), + None => String::from("inbox-unread:local"), + }); + section.name = name; + + let last = section.entries.len().saturating_sub(1); + for (entry_ix, thread_ix) in section.entries.iter().enumerate() { + let Some(item) = self.threads.get(*thread_ix) else { + continue; + }; + entry_rows.push(EntryRow { + root: item.root, + kind: item.root_event.as_ref().map(|event| event.kind), + address: section.address.clone(), + title: SharedString::from(item.title()), + unread: item.is_unread(), + first: entry_ix == 0, + last: entry_ix == last, + timeline: item.timeline(MAX_SUB_ACTIVITIES).into(), + }); + } + } + let rows = self.flatten_rows(§ions); self.sections = Arc::new(sections); + self.entry_rows = Arc::new(entry_rows); self.rows = Arc::new(rows); let mut keys: Vec = self @@ -281,6 +329,8 @@ impl InboxView { .entry(address.clone()) .or_insert_with(move || InboxSection { address, + name: SharedString::default(), + badge_id: SharedString::default(), unread: 0, entries: Vec::new(), latest: Timestamp::default(), @@ -312,9 +362,7 @@ impl InboxView { rows.push(InboxRow::Empty); continue; } - rows.extend( - (0..section.entries.len()).map(|entry_ix| InboxRow::Entry(section_ix, entry_ix)), - ); + rows.extend((0..section.entries.len()).map(InboxRow::Entry)); } rows } @@ -345,65 +393,40 @@ impl InboxView { Some(Kind::GitPatch) => RepoItem::Patch, _ => return, }; - open_repo_item(&self.workspace, &address, None, item, window, cx); + let result = self.workspace.update(cx, |root, cx| { + root.open_repo_item(&address, None, item, window, cx); + }); + log_dropped(result); } - fn render_entry(&self, ix: usize, cx: &mut Context) -> AnyElement { + fn render_entry(&self, ix: usize, on_open: &OpenHandler, cx: &App) -> AnyElement { let Some(row) = self.rows.get(ix) else { return div().into_any_element(); }; match *row { - InboxRow::Empty => empty_section_row(cx), + InboxRow::Empty => InboxSection::empty_row(cx).into_any_element(), InboxRow::Repo(section_ix) => { let Some(section) = self.sections.get(section_ix) else { return div().into_any_element(); }; - let name = repo_name(section.address.as_ref(), cx); - let id = SharedString::from(format!( - "inbox-unread:{}", - section - .address - .as_ref() - .map(ToString::to_string) - .unwrap_or_default() - )); - repo_header(id, name, section.unread) + section.header(cx).into_any_element() } - InboxRow::Entry(section_ix, entry_ix) => { - let Some(section) = self.sections.get(section_ix) else { + InboxRow::Entry(entry_ix) => { + let Some(row) = self.entry_rows.get(entry_ix) else { return div().into_any_element(); }; - let Some(&thread_ix) = section.entries.get(entry_ix) else { - return div().into_any_element(); - }; - let Some(item) = self.threads.get(thread_ix) else { - return div().into_any_element(); - }; - - let root = item.root; - let kind = item.root_event.as_ref().map(|event| event.kind); - let address = section.address.clone(); - let first = entry_ix == 0; - let last = entry_ix + 1 == section.entries.len(); let me = Backend::global(cx).read(cx).current_user(); - thread( - "inbox-row", - ix, - SharedString::from(item.title()), - item.is_unread(), - first, - last, - item.timeline(MAX_SUB_ACTIVITIES), - me, - &self.directory, - cx, - ) - .on_click(cx.listener(move |this, _ev, window, cx| { - this.open(root, kind, address.clone(), window, cx) - })) - .into_any_element() + self.thread(row, me, cx) + .on_click({ + let on_open = on_open.clone(); + let root = row.root; + let kind = row.kind; + let address = row.address.clone(); + move |_, window, cx| on_open(root, kind, address.clone(), window, cx) + }) + .into_any_element() } } } @@ -417,11 +440,11 @@ impl Panel for InboxView { impl Render for InboxView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let rows = self.rows.clone(); - let mut children = Vec::with_capacity(rows.len()); - for ix in 0..rows.len() { - children.push(self.render_entry(ix, cx)); + let count = self.rows.len(); + if self.rows_scroll.item_count() != count { + self.rows_scroll.reset(count); } + let weak = cx.weak_entity(); v_flex() .size_full() @@ -446,7 +469,7 @@ impl Render for InboxView { ), ) .when_some(self.error.clone(), |this, error| { - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); this.child( Alert::new("inbox-error") .severity(AlertSeverity::Danger) @@ -464,19 +487,41 @@ impl Render for InboxView { ) }) .child( - div() - .relative() - .flex_1() - .min_h_0() - .px_4() - .child(if rows.is_empty() { - EmptyState::centered("You're all caught up.") - } else { - ScrollArea::new("inbox-scroll") - .flex_1() - .child(v_flex().gap_2().py_2().children(children)) - .into_any_element() - }), + div().relative().flex_1().min_h_0().px_4().child( + v_flex() + .flex_1() + .py_2() + .when(count == 0, |this| { + this.child(EmptyState::centered("You're all caught up.")) + }) + .when(count > 0, |this| { + this.child(list(self.rows_scroll.clone(), { + let weak = weak.clone(); + let open = cx.processor( + |this, + (root, kind, address): ( + EventId, + Option, + Option, + ), + window, + cx| { + this.open(root, kind, address, window, cx); + }, + ); + let on_open: OpenHandler = + Rc::new(move |root, kind, address, window, cx| { + open((root, kind, address), window, cx); + }); + move |ix, _window, cx| { + weak.read_with(cx, |view, cx| { + view.render_entry(ix, &on_open, cx) + }) + .unwrap_or_else(|_| div().into_any_element()) + } + })) + }), + ), ) .into_any_element() } @@ -491,6 +536,6 @@ fn repo_name(addr: Option<&RepoAddr>, cx: &App) -> SharedString { .announcements .iter() .find(|announcement| announcement.addr() == *addr) - .map(announcement_display_name) + .map(AnnouncementExt::display_name) .unwrap_or_else(|| SharedString::from("Untitled")) } diff --git a/crates/signed_app/src/issues/detail.rs b/crates/signed_app/src/issues/detail.rs index 940415c..c588a0b 100644 --- a/crates/signed_app/src/issues/detail.rs +++ b/crates/signed_app/src/issues/detail.rs @@ -2,9 +2,9 @@ use std::sync::Arc; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, - ParentElement as _, Pixels, Render, ScrollHandle, SharedString, Styled as _, Subscription, - WeakEntity, Window, div, px, + AnyElement, App, AppContext as _, Context, ElementId, Entity, IntoElement, ListAlignment, + ListSizingBehavior, ListState, ParentElement as _, Pixels, Render, ScrollHandle, SharedString, + Styled as _, Subscription, Window, div, list, px, rems, }; use metadata::ProfileDirectory; use nostr::prelude::EventId; @@ -12,19 +12,21 @@ use signed_core::GitEvent; use signed_state::RepoStore; use ui::avatar::Avatar; use ui::badge::{Badge, BadgeVariant}; +use ui::button::Button; 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, PanelSlot, SplitSide}; +use ui::icons::{Icon, IconRole}; +use ui::input::{Input, InputState}; +use ui::layout::panel::{Panel, PanelSlot, PanelStack, SplitSide}; use ui::scroll_area::ScrollArea; use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; +use ui::tooltip::Tooltip; use utils::relative_time; -use crate::app::AppRoot; -use crate::issues::helpers::{comment_form, comments_section}; +use crate::shared::labels::ProfileDirectoryExt as _; +use crate::shared::log_dropped; use crate::shared::widgets::status_badge; -use crate::shared::{log_dropped, track_event_participants}; /// The split pane showing the issue's participants and labels. const SIDEBAR_ID: &str = "Issue details"; @@ -37,6 +39,7 @@ pub struct IssueDetailView { /// Profiles for the author, commenters and the repository owner. directory: Entity, scroll_handle: ScrollHandle, + comments_scroll: ListState, _subscription: Subscription, } @@ -44,7 +47,7 @@ impl IssueDetailView { pub fn new(store: Entity, issue_id: EventId, cx: &mut Context) -> Self { let comment_input = InputState::builder().multiline().build(cx); let directory = ProfileDirectory::new(cx); - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); let subscription = cx.observe(&store, |this, _store, cx| { this.track_participants(cx); @@ -63,13 +66,14 @@ impl IssueDetailView { comment_input, directory, scroll_handle: ScrollHandle::new(), + comments_scroll: ListState::new(0, ListAlignment::Top, px(48.)), _subscription: subscription, } } /// Opens the issue's detail as the main panel and its sidebar in the split pane. pub fn open( - workspace: &WeakEntity, + panels: &Entity, store: Entity, issue_id: EventId, window: &mut Window, @@ -78,35 +82,33 @@ impl IssueDetailView { let id = SharedString::from(format!("issue:{issue_id}")); let sidebar_store = store.clone(); - log_dropped(workspace.update(cx, |root, cx| { - root.panels().update(cx, |panels, cx| { - panels.open( - PanelSlot::Main, - id, - { - let store = store.clone(); - move |_, cx| cx.new(|cx| IssueDetailView::new(store.clone(), issue_id, cx)) - }, - window, - cx, - ); + panels.update(cx, |panels, cx| { + panels.open( + PanelSlot::Main, + id, + { + let store = store.clone(); + move |_, cx| cx.new(|cx| IssueDetailView::new(store.clone(), issue_id, cx)) + }, + window, + cx, + ); - let sidebar = cx.new(|cx| IssueSidebarView { - store: sidebar_store.clone(), - issue_id, - directory: ProfileDirectory::new(cx), - scroll_handle: ScrollHandle::new(), - }); + let sidebar = cx.new(|cx| IssueSidebarView { + store: sidebar_store.clone(), + issue_id, + directory: ProfileDirectory::new(cx), + scroll_handle: ScrollHandle::new(), + }); - panels.insert_split_at( - SIDEBAR_ID, - SIDEBAR_WIDTH, - SplitSide::Trailing, - Arc::new(sidebar), - cx, - ); - }) - })); + panels.insert_split_at( + SIDEBAR_ID, + SIDEBAR_WIDTH, + SplitSide::Trailing, + Arc::new(sidebar), + cx, + ); + }); } /// Track the issue author, everyone who commented and the repository owner. @@ -125,7 +127,81 @@ impl IssueDetailView { .map(|comment| comment.pubkey) .collect(); - track_event_participants(author, owner, comments.into_iter(), &self.directory, cx); + self.directory + .track_participants(author, owner, comments.into_iter(), cx); + } + + /// One comment card of the issue's discussion. + fn render_comment(&self, ix: usize, cx: &App) -> AnyElement { + let Some(comment) = self.store.read(cx).comments_of(&self.issue_id).nth(ix) else { + return div().into_any_element(); + }; + + let profile = self.directory.read(cx).profile(&comment.pubkey, cx); + let author = profile.name(); + let age = relative_time(comment.created_at); + let content = SharedString::from(comment.content.as_str()); + + v_flex() + .gap_1() + .p_3() + .border_1() + .border_color(cx.theme().colors.border) + .rounded(cx.theme().radius.control) + .child( + h_flex() + .gap_2() + .text_sm() + .child( + h_flex() + .gap_1() + .child( + Avatar::new(comment.pubkey) + .name(author.clone()) + .picture(profile.picture()) + .small(), + ) + .child(author), + ) + .child( + div() + .text_color(cx.theme().colors.muted_foreground) + .child("commented"), + ) + .child( + div() + .text_color(cx.theme().colors.muted_foreground) + .child(SharedString::from(age)), + ), + ) + .child(div().text_sm().child(content)) + .into_any_element() + } + + /// Posts the composer's text as a comment on this issue. + fn submit_comment(&mut self, window: &mut Window, cx: &mut Context) { + let content = self.comment_input.read(cx).value().trim().to_string(); + if content.is_empty() { + return; + } + + let event = self + .store + .read(cx) + .issues + .iter() + .find(|event| event.id == self.issue_id) + .cloned(); + + if let Some(event) = event { + self.store.update(cx, |store, cx| { + store.comment(&event, content, cx); + }); + } + + self.comment_input.update(cx, |input, cx| { + input.set_value("", window, cx); + }); } } @@ -174,9 +250,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 { - EmptyState::centered("Issue not found") + EmptyState::centered("Issue not found").into_any_element() } else { - Spinner::centered("issue-loading") + Spinner::centered("issue-loading").into_any_element() }; }; @@ -199,75 +275,125 @@ impl Render for IssueDetailView { }; let picture = self.directory.read(cx).profile(&pubkey, cx).picture(); - div() - .id("issue-detail") + ScrollArea::new("issue-detail-scroll") + .handle(self.scroll_handle.clone()) .size_full() .child( - ScrollArea::new("issue-detail-scroll") - .handle(self.scroll_handle.clone()) - .size_full() + v_flex() + .p_4() + .gap_6() + .child( + h_flex() + .gap_2() + .child(status_badge(status)) + .child(div().flex_1().min_w_0().font_semibold().child(title)), + ) .child( v_flex() - .p_4() - .gap_6() - .child( - h_flex() - .gap_2() - .child(status_badge(status)) - .child(div().flex_1().min_w_0().font_semibold().child(title)), - ) + .gap_8() .child( v_flex() - .gap_8() + .gap_4() .child( - v_flex() - .gap_4() + h_flex() + .gap_2() + .text_sm() .child( h_flex() - .gap_2() - .text_sm() + .gap_1() .child( - h_flex() - .gap_1() - .child( - Avatar::new(pubkey) - .name(author.clone()) - .picture(picture) - .small(), - ) - .child(author), + Avatar::new(pubkey) + .name(author.clone()) + .picture(picture) + .small(), ) - .child( - div() - .text_color( - cx.theme().colors.muted_foreground, - ) - .child("opened"), - ) - .child( - div() - .text_color( - cx.theme().colors.muted_foreground, - ) - .child(SharedString::from(age)), - ), + .child(author), ) - .child(content), + .child( + div() + .text_color(cx.theme().colors.muted_foreground) + .child("opened"), + ) + .child( + div() + .text_color(cx.theme().colors.muted_foreground) + .child(SharedString::from(age)), + ), ) - .child(comments_section( - &self.store, - issue_id, - &self.directory, - cx, - )) - .child(comment_form( - &self.store, - issue_id, - &store.issues, - &self.comment_input, - "comment", - cx, - )), + .child(content), + ) + .child({ + let comments = self.store.read(cx).comments_of(&issue_id).count(); + + if self.comments_scroll.item_count() != comments { + self.comments_scroll.reset(comments); + } + + v_flex() + .gap_4() + .child( + h_flex() + .gap_2() + .child(Icon::named(IconRole::Message)) + .child( + div() + .text_sm() + .font_semibold() + .child("Discussions"), + ) + .child(Badge::new( + format!("discussion-count:{issue_id}"), + comments.to_string(), + )), + ) + .child( + v_flex().max_h(rems(24.)).min_h_0().child( + list( + self.comments_scroll.clone(), + cx.processor(|this, ix, _, cx| { + this.render_comment(ix, cx) + }), + ) + .with_sizing_behavior(ListSizingBehavior::Infer), + ), + ) + }) + .child( + v_flex() + .gap_2() + .child( + Input::new("comment-input", self.comment_input.clone()) + .placeholder("Leave a comment...") + .rows(4), + ) + .child( + h_flex() + .justify_between() + .child( + h_flex() + .gap_1() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child( + Icon::named(IconRole::Markdown) + .size(px(12.)) + .color( + cx.theme().colors.muted_foreground, + ), + ) + .child("Markdown is supported"), + ) + .child( + Button::new("comment") + .label("Comment") + .tooltip(Tooltip::text("Post comment")) + .on_click(cx.listener( + |this, _, window, cx| { + this.submit_comment(window, cx) + }, + )), + ), + ), ), ), ) @@ -292,78 +418,79 @@ impl Panel for IssueSidebarView { impl Render for IssueSidebarView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let store = self.store.read(cx); + let root = store.issues.iter().find(|issue| issue.id == self.issue_id); - let details = store - .issues - .iter() - .find(|issue| issue.id == self.issue_id) - .map(|root| { + ScrollArea::new("issue-sidebar-scroll") + .handle(self.scroll_handle.clone()) + .size_full() + .child(v_flex().w_full().p_4().when_some(root, |this, root| { let mut participants = vec![root.pubkey]; participants.extend(store.comments_of(&root.id).map(|comment| comment.pubkey)); - participants.sort_by_key(|key| key.to_hex()); + participants.sort_by_key(|key| key.to_bytes()); participants.dedup(); - let labels: Vec = root.tags.hashtags().map(|tag| tag.to_string()).collect(); + let labels: Vec = + root.tags.hashtags().map(SharedString::from).collect(); - v_flex() - .gap_4() - .child( - v_flex() - .gap_2() - .child( - div() - .text_xs() - .font_medium() - .text_color(cx.theme().colors.muted_foreground) - .child("Participants"), - ) - .children(participants.iter().map(|pubkey| { - let profile = self.directory.read(cx).profile(pubkey, cx); - let name = profile.name(); + this.child( + v_flex() + .gap_4() + .child( + v_flex() + .gap_2() + .child( + div() + .text_xs() + .font_medium() + .text_color(cx.theme().colors.muted_foreground) + .child("Participants"), + ) + .children(participants.iter().map(|pubkey| { + let profile = self.directory.read(cx).profile(pubkey, cx); + let name = profile.name(); - h_flex() - .gap_1() - .child( - Avatar::new(*pubkey) - .name(name.clone()) - .picture(profile.picture()) - .small(), - ) - .child( - div() - .flex_1() - .min_w_0() - .whitespace_nowrap() - .text_sm() - .text_ellipsis() - .child(name), - ) - .into_any_element() - })), - ) - .child( - v_flex() - .gap_2() - .child( - div() - .text_xs() - .font_medium() - .text_color(cx.theme().colors.muted_foreground) - .child("Labels"), - ) - .map(|this| { - if labels.is_empty() { + h_flex() + .gap_1() + .child( + Avatar::new(*pubkey) + .name(name.clone()) + .picture(profile.picture()) + .small(), + ) + .child( + div() + .flex_1() + .min_w_0() + .whitespace_nowrap() + .text_sm() + .text_ellipsis() + .child(name), + ) + })), + ) + .child( + v_flex() + .gap_2() + .child( + div() + .text_xs() + .font_medium() + .text_color(cx.theme().colors.muted_foreground) + .child("Labels"), + ) + .when(labels.is_empty(), |this| { this.child( div() .text_sm() .text_color(cx.theme().colors.muted_foreground) .child("None yet."), ) - } else { + }) + .when(!labels.is_empty(), |this| { this.child(v_flex().gap_1().items_start().children( labels.iter().map(|label| { Badge::new( - SharedString::from(format!("label:{label}")), + (ElementId::from("label"), label.clone()), label.clone(), ) .variant(BadgeVariant::Outline) @@ -371,16 +498,9 @@ impl Render for IssueSidebarView { .flex_none() }), )) - } - }), - ) - .into_any_element() - }) - .unwrap_or_else(|| div().into_any_element()); - - ScrollArea::new("issue-sidebar-scroll") - .handle(self.scroll_handle.clone()) - .size_full() - .child(v_flex().w_full().p_4().child(details)) + }), + ), + ) + })) } } diff --git a/crates/signed_app/src/issues/helpers.rs b/crates/signed_app/src/issues/helpers.rs index f5ab0a2..b7aa094 100644 --- a/crates/signed_app/src/issues/helpers.rs +++ b/crates/signed_app/src/issues/helpers.rs @@ -1,19 +1,4 @@ -use gpui::{ - AnyElement, App, Entity, IntoElement, ParentElement as _, SharedString, Styled as _, div, px, -}; -use metadata::ProfileDirectory; -use nostr::prelude::{Event, EventId}; use signed_core::RepoStatus; -use signed_state::RepoStore; -use ui::avatar::Avatar; -use ui::badge::Badge; -use ui::button::Button; -use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; -use ui::icons::{Icon, IconRole}; -use ui::input::{Input, InputState}; -use ui::theme::ActiveTheme as _; -use ui::tooltip::Tooltip; -use utils::relative_time; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum IssueFilter { @@ -31,168 +16,3 @@ impl IssueFilter { } } } - -/// Root events counted by their resolved status. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct StatusCounts { - pub(crate) total: usize, - pub(crate) open: usize, - pub(crate) closed: usize, - pub(crate) draft: usize, - pub(crate) applied: usize, -} - -impl StatusCounts { - fn record(&mut self, status: RepoStatus) { - self.total += 1; - match status { - RepoStatus::Open => self.open += 1, - RepoStatus::Closed => self.closed += 1, - RepoStatus::Draft => self.draft += 1, - RepoStatus::Applied => self.applied += 1, - } - } -} - -/// Indices of `roots` whose status `keep` accepts, counting every root's status. -pub(crate) fn filter_by_status<'a>( - roots: impl IntoIterator, - status_of: impl Fn(&Event) -> RepoStatus, - keep: impl Fn(RepoStatus) -> bool, -) -> (Vec, StatusCounts) { - let mut counts = StatusCounts::default(); - - let visible = roots - .into_iter() - .enumerate() - .filter_map(|(index, root)| { - let status = status_of(root); - counts.record(status); - keep(status).then_some(index) - }) - .collect(); - - (visible, counts) -} - -pub(crate) fn comments_section( - store: &Entity, - root: EventId, - directory: &Entity, - cx: &App, -) -> AnyElement { - let store = store.read(cx); - let comments: Vec<&Event> = store.comments_of(&root).collect(); - let count = comments.len(); - - v_flex() - .gap_4() - .child( - h_flex() - .gap_2() - .child(Icon::named(IconRole::Message)) - .child(div().text_sm().font_semibold().child("Discussions")) - .child(Badge::new( - format!("discussion-count:{root}"), - count.to_string(), - )), - ) - .children(comments.iter().map(|comment| { - let profile = directory.read(cx).profile(&comment.pubkey, cx); - let author = profile.name(); - let age = relative_time(comment.created_at); - let content = SharedString::from(comment.content.as_str()); - - v_flex() - .gap_1() - .p_3() - .border_1() - .border_color(cx.theme().colors.border) - .rounded(cx.theme().radius.control) - .child( - h_flex() - .gap_2() - .text_sm() - .child( - h_flex() - .gap_1() - .child( - Avatar::new(comment.pubkey) - .name(author.clone()) - .picture(profile.picture()) - .small(), - ) - .child(author), - ) - .child( - div() - .text_color(cx.theme().colors.muted_foreground) - .child("commented"), - ) - .child( - div() - .text_color(cx.theme().colors.muted_foreground) - .child(SharedString::from(age)), - ), - ) - .child(div().text_sm().child(content)) - })) - .into_any_element() -} - -pub(crate) fn comment_form( - store: &Entity, - root: EventId, - 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(); - - v_flex() - .gap_2() - .child( - Input::new("comment-input", comment_input.clone()) - .placeholder("Leave a comment...") - .rows(4), - ) - .child( - h_flex() - .justify_between() - .child( - h_flex() - .gap_1() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .child( - Icon::named(IconRole::Markdown) - .size(px(12.)) - .color(cx.theme().colors.muted_foreground), - ) - .child("Markdown is supported"), - ) - .child( - Button::new(button_id) - .label("Comment") - .tooltip(Tooltip::text("Post comment")) - .on_click(move |_, window, cx| { - let content = comment_input.read(cx).value().trim().to_string(); - if content.is_empty() { - return; - } - store.update(cx, |store, cx| { - store.comment(&root, content, cx); - }); - comment_input.update(cx, |input, cx| { - input.set_value("", window, cx); - }); - }), - ), - ) - .into_any_element() -} diff --git a/crates/signed_app/src/issues/mod.rs b/crates/signed_app/src/issues/mod.rs index 6b5ebbe..20a0375 100644 --- a/crates/signed_app/src/issues/mod.rs +++ b/crates/signed_app/src/issues/mod.rs @@ -1,13 +1,16 @@ +use std::ops::Range; +use std::sync::Arc; + use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div, uniform_list, }; -use helpers::{IssueFilter, StatusCounts, filter_by_status}; +use helpers::IssueFilter; use metadata::ProfileDirectory; -use nostr::prelude::PublicKey; -use signed_core::GitEvent; +use nostr::prelude::{EventId, PublicKey}; +use signed_core::{GitEvent, RepoStatus}; use signed_state::RepoStore; use ui::avatar::Avatar; use ui::button::Button; @@ -23,19 +26,31 @@ use utils::relative_time; use self::detail::IssueDetailView; use crate::app::AppRoot; use crate::issues::new_issue::NewIssueView; -use crate::repo::helpers::short_id; +use crate::shared::labels::ShortIdExt as _; use crate::shared::log_dropped; -use crate::shared::widgets::status_badge; +use crate::shared::widgets::{StatusCounts, status_badge}; pub mod detail; pub(crate) mod helpers; pub mod new_issue; +/// One issue row, with its display strings built on rebuild. +struct IssueRow { + id: EventId, + /// The row's element id. + element_id: SharedString, + status: RepoStatus, + subject: SharedString, + author: PublicKey, + age: SharedString, + short: SharedString, +} + pub struct IssuesView { workspace: WeakEntity, store: Entity, filter: IssueFilter, - visible_issues: Vec, + rows: Arc>, counts: StatusCounts, // A filter change notifies even when the visible rows are unchanged. synced_filter: IssueFilter, @@ -51,7 +66,7 @@ impl IssuesView { store: Entity, cx: &mut Context, ) -> Self { - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); let subscription = cx.observe(&store, |this, _store, cx| { this.rebuild(cx); }); @@ -66,7 +81,7 @@ impl IssuesView { workspace, store: store.clone(), filter: IssueFilter::Open, - visible_issues: Vec::new(), + rows: Arc::new(Vec::new()), counts: StatusCounts::default(), synced_filter: IssueFilter::Open, scroll_handle: UniformListScrollHandle::new(), @@ -117,48 +132,150 @@ impl IssuesView { let (visible_issues, counts) = { let store = self.store.read(cx); - filter_by_status( + StatusCounts::filter( &store.issues, |issue| store.status_of(issue), |status| filter.matches(status), ) }; - let store = self.store.read(cx); - let mut keys: Vec = store.issues.iter().map(|issue| issue.pubkey).collect(); + let (keys, rows) = { + let store = self.store.read(cx); + let mut keys: Vec = store.issues.iter().map(|issue| issue.pubkey).collect(); - if let Some(owner) = store - .announcement - .as_ref() - .map(|announcement| announcement.owner) - { - keys.push(owner); - } + if let Some(owner) = store + .announcement + .as_ref() + .map(|announcement| announcement.owner) + { + keys.push(owner); + } + + let rows: Vec = visible_issues + .iter() + .filter_map(|index| { + let issue = store.issues.get(*index)?; + Some(IssueRow { + id: issue.id, + element_id: SharedString::from(format!("issue:{}", issue.id.to_hex())), + status: store.status_of(issue), + subject: SharedString::from(issue.activity_subject()), + author: issue.pubkey, + age: SharedString::from(relative_time(issue.created_at)), + short: issue.id.to_hex().short_id(), + }) + }) + .collect(); + + (keys, rows) + }; self.directory.update(cx, |directory, cx| { directory.track(keys, cx); }); let filter_changed = self.synced_filter != filter; - let visible_issues_changed = self.visible_issues != visible_issues; let counts_changed = self.counts != counts; + let rows_changed = self.rows.len() != rows.len(); - if !filter_changed && !visible_issues_changed && !counts_changed { + if !filter_changed && !counts_changed && !rows_changed { return; } self.synced_filter = filter; - self.visible_issues = visible_issues; + self.rows = Arc::new(rows); self.counts = counts; cx.notify(); } - fn render_header(&self, cx: &mut Context) -> AnyElement { + /// One issue row of the list. + fn render_issue(&mut self, ix: usize, cx: &mut Context) -> AnyElement { + let Some(row) = self.rows.get(ix) else { + return div().into_any_element(); + }; + + let profile = self.directory.read(cx).profile(&row.author, cx); + let issue_id = row.id; + let status = row.status; + + h_flex() + .id(row.element_id.clone()) + .w_full() + .h_16() + .px_2() + .border_b_1() + .border_color(cx.theme().colors.border) + .hover(|this| this.bg(cx.theme().colors.muted_hover)) + .on_click(cx.listener(move |this, _, window, cx| { + this.open_issue(issue_id, window, cx); + })) + .child( + h_flex() + .w_full() + .items_start() + .gap_2() + .child(h_flex().w_20().child(status_badge(status))) + .child( + v_flex() + .flex_1() + .min_w_0() + .gap_1() + .child( + div() + .text_sm() + .text_ellipsis() + .whitespace_nowrap() + .child(row.subject.clone()), + ) + .child( + h_flex() + .gap_2() + .text_xs() + .child( + h_flex() + .min_w_0() + .gap_1() + .child( + Avatar::new(row.author) + .name(profile.name()) + .picture(profile.picture()) + .small(), + ) + .child( + div().min_w_0().truncate().child(profile.name()), + ), + ) + .child("opened") + .child( + div() + .text_color(cx.theme().colors.muted_foreground) + .child(row.short.clone()), + ) + .child(row.age.clone()), + ), + ), + ) + .into_any_element() + } + + /// Opens this issue's detail panel in the split stack. + fn open_issue(&mut self, issue_id: EventId, window: &mut Window, cx: &mut Context) { + let panels = self + .workspace + .read_with(cx, |root, _| root.panels().clone()); + let Ok(panels) = panels else { + log::warn!("issue list outlived the app shell"); + return; + }; + + IssueDetailView::open(&panels, self.store.clone(), issue_id, window, cx); + } + + fn render_header(&self, cx: &mut Context) -> impl IntoElement { let counts = self.counts; let colors = cx.theme().colors; let muted = colors.muted_foreground; - let weak = cx.entity().downgrade(); h_flex() .px_2() @@ -181,14 +298,10 @@ impl IssuesView { .label(format!("Closed ({})", counts.closed)) .icon(Icon::named(IconRole::GitIssueClosed).color(muted)), ]) - .on_change(move |filter, _, cx| { - if let Err(error) = weak.update(cx, |this, cx| { - this.filter = filter; - this.rebuild(cx); - }) { - log::warn!("failed to switch issue filter: {error}"); - } - }), + .on_change(cx.processor(|this, filter: IssueFilter, _, cx| { + this.filter = filter; + this.rebuild(cx); + })), ) .child(div().flex_1()) .child( @@ -200,7 +313,6 @@ impl IssuesView { this.open_new_issue(window, cx); })), ) - .into_any_element() } } @@ -213,12 +325,8 @@ impl Panel for IssuesView { impl Render for IssuesView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let filter = self.filter; - let visible_issues = self.visible_issues.clone(); - let directory = self.directory.clone(); - let store = self.store.clone(); - let workspace = self.workspace.clone(); let scroll_handle = self.scroll_handle.clone(); - let count = visible_issues.len(); + let count = self.rows.len(); let empty_message = match filter { IssueFilter::All => "No issues", @@ -237,96 +345,13 @@ impl Render for IssuesView { .child(self.render_header(cx)) .when(count > 0, |this| { this.child( - uniform_list("issues", count, move |range, _, cx| { - range - .map(|ix| { - // The store re-read per frame can shrink below a captured index. - let Some(issue) = - visible_issues.get(ix).and_then(|issue_ix| { - store.read(cx).issues.get(*issue_ix) - }) - else { - return div().into_any_element(); - }; - let profile = directory.read(cx).profile(&issue.pubkey, cx); - let issue_id = issue.id; - let id_hex = issue.id.to_hex(); - let status = store.read(cx).status_of(issue); - let store = store.clone(); - let workspace = workspace.clone(); - - h_flex() - .id(SharedString::from(format!("issue:{id_hex}"))) - .w_full() - .h_16() - .px_2() - .border_b_1() - .border_color(cx.theme().colors.border) - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .on_click(move |_, window, cx| { - IssueDetailView::open( - &workspace, - store.clone(), - issue_id, - window, - cx, - ); - }) - .child( - h_flex() - .w_full() - .items_start() - .gap_2() - .child(h_flex().w_20().child(status_badge(status))) - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_1() - .child( - div() - .text_sm() - .text_ellipsis() - .whitespace_nowrap() - .child(issue.activity_subject()), - ) - .child( - h_flex() - .gap_2() - .text_xs() - .child( - h_flex() - .gap_1() - .child( - Avatar::new(issue.pubkey) - .name(profile.name()) - .picture( - profile.picture(), - ) - .small(), - ) - .child( - div().child(profile.name()), - ), - ) - .child("opened") - .child( - div() - .text_color( - cx.theme() - .colors - .muted_foreground, - ) - .child(short_id(&id_hex)), - ) - .child(relative_time(issue.created_at)), - ), - ), - ) - .into_any_element() - }) - .collect() - }) + uniform_list( + "issues", + count, + cx.processor(|this, range: Range, _, cx| { + range.map(|ix| this.render_issue(ix, cx)).collect() + }), + ) .track_scroll(&scroll_handle) .size_full(), ) @@ -334,8 +359,7 @@ impl Render for IssuesView { }) .when(count == 0, |this| { this.child(EmptyState::centered(empty_message)) - }) - .into_any_element(), + }), ) .into_any_element() } diff --git a/crates/signed_app/src/issues/new_issue.rs b/crates/signed_app/src/issues/new_issue.rs index bbce422..a871d17 100644 --- a/crates/signed_app/src/issues/new_issue.rs +++ b/crates/signed_app/src/issues/new_issue.rs @@ -13,7 +13,6 @@ use ui::theme::ActiveTheme as _; use crate::app::AppRoot; use crate::shared::log_dropped; -use crate::shared::progress::error_row; pub struct NewIssueView { workspace: WeakEntity, @@ -64,9 +63,11 @@ impl NewIssueView { let workspace = self.workspace.clone(); let panel_id = self.panel_id.clone(); + let task = self .store .update(cx, |store, cx| store.open_issue(subject, content, cx)); + self.submit_task = Some(cx.spawn(async move |this, cx| match task.await { Ok(()) => { log_dropped(workspace.update(cx, |root, cx| { @@ -86,8 +87,6 @@ impl NewIssueView { } fn render_footer(&self, cx: &Context) -> AnyElement { - let weak = cx.entity().downgrade(); - h_flex() .px_4() .py_2() @@ -100,9 +99,7 @@ impl NewIssueView { .label("Create issue") .loading(self.submitting) .disabled(self.submitting) - .on_click(move |_, _, cx| { - log_dropped(weak.update(cx, |this, cx| this.submit(cx))); - }), + .on_click(cx.listener(|this, _, _, cx| this.submit(cx))), ) .into_any_element() } @@ -124,6 +121,8 @@ impl Panel for NewIssueView { impl Render for NewIssueView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + const HINT: &str = "Report a bug, ask a question, or propose a change."; + v_flex() .id("new-issue") .size_full() @@ -137,7 +136,7 @@ impl Render for NewIssueView { .pr_16() .text_sm() .text_color(cx.theme().colors.muted_foreground) - .child("Report a bug, ask a question, or propose a change."), + .child(HINT), ) .child( Field::new("issue-title", "Title") @@ -147,7 +146,14 @@ impl Render for NewIssueView { Field::new("issue-content", "Content") .child(Input::new("issue-content-input", self.content.clone()).rows(6)), ) - .when_some(error_row(&self.error, cx), |this, error| this.child(error)), + .when_some(self.error.clone(), |this, error| { + this.child( + div() + .text_sm() + .text_color(cx.theme().ramps.destructive.base) + .child(error), + ) + }), ) .child(self.render_footer(cx)) } diff --git a/crates/signed_app/src/lib.rs b/crates/signed_app/src/lib.rs index 6df52ba..439e7cc 100644 --- a/crates/signed_app/src/lib.rs +++ b/crates/signed_app/src/lib.rs @@ -11,14 +11,3 @@ mod shared; mod titlebar; pub use app::AppRoot; -pub use app::helpers::apply_appearance_mode; -use gpui::{App, AppContext as _, Entity, Window}; -use ui::layout::root::Root; - -pub fn root(window: &mut Window, cx: &mut App) -> Entity { - let root = cx.new(|cx| Root::new(window, cx)); - let content: Entity = cx.new(|cx| AppRoot::new(window, cx)); - - root.update(cx, |root, cx| root.set_content(content, cx)); - root -} diff --git a/crates/signed_app/src/pull_requests/detail.rs b/crates/signed_app/src/pull_requests/detail.rs index 707a5e5..4aadee6 100644 --- a/crates/signed_app/src/pull_requests/detail.rs +++ b/crates/signed_app/src/pull_requests/detail.rs @@ -1,11 +1,13 @@ +use std::ops::Range; use std::path::PathBuf; use std::sync::Arc; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, - ParentElement as _, Pixels, Render, ScrollHandle, SharedString, - StatefulInteractiveElement as _, Styled as _, Subscription, WeakEntity, Window, div, px, + AnyElement, App, AppContext as _, Context, ElementId, Entity, InteractiveElement as _, + IntoElement, ListAlignment, ListSizingBehavior, ListState, ParentElement as _, Pixels, Render, + ScrollHandle, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, + WeakEntity, Window, div, list, px, rems, uniform_list, }; use metadata::ProfileDirectory; use nostr::prelude::{EventId, Kind, Url}; @@ -18,21 +20,21 @@ use ui::button::Button; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; -use ui::input::InputState; -use ui::layout::panel::{Panel, PanelSlot, SplitSide}; +use ui::input::{Input, InputState}; +use ui::layout::panel::{Panel, PanelSlot, PanelStack, SplitSide}; use ui::layout::root::RootContext as _; use ui::scroll_area::ScrollArea; use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; +use ui::tooltip::Tooltip; use utils::relative_time; use crate::app::AppRoot; -use crate::issues::helpers::{comment_form, comments_section}; use crate::pull_requests::dialogs::update::UpdatePrDialog; -use crate::repo::commit_diff::{CommitDiffView, DiffPane}; -use crate::repo::helpers::short_id; +use crate::shared::commit_diff::{CommitDiffView, DiffPane}; +use crate::shared::labels::{ProfileDirectoryExt as _, ShortIdExt as _}; +use crate::shared::log_dropped; use crate::shared::widgets::status_badge; -use crate::shared::{log_dropped, track_event_participants}; const NOT_FOUND: &str = "Pull request not found"; const SIDEBAR_ID: &str = "Discussion"; @@ -41,7 +43,7 @@ const SIDEBAR_WIDTH: Pixels = px(320.); #[derive(Clone, PartialEq, Eq)] struct PrBinding { description: String, - patch: String, + patch: Arc, tip: Option, base: Option, clone_urls: Vec, @@ -51,10 +53,33 @@ struct PrBinding { struct CommitRow { commit: FileCommit, + /// The row's element id. + id: SharedString, + /// The abbreviated commit id shown in the row. + short: SharedString, + /// The stats badge's element id. + stats_id: SharedString, insertions: usize, deletions: usize, } +impl CommitRow { + fn new(commit: FileCommit, insertions: usize, deletions: usize) -> Self { + let id = SharedString::from(commit.id.clone()); + let short = commit.id.short_id(); + let stats_id = SharedString::from(format!("pr-commit-stats:{}", commit.id)); + + Self { + commit, + id, + short, + stats_id, + insertions, + deletions, + } + } +} + pub struct PullRequestDetailView { workspace: WeakEntity, store: Entity, @@ -68,9 +93,10 @@ pub struct PullRequestDetailView { error: Option, bound: Option, load_generation: u64, + _store_subscription: Subscription, pane: Entity, scroll_handle: ScrollHandle, - tasks: Vec>>, + load_task: Option>>, } impl PullRequestDetailView { @@ -82,7 +108,12 @@ impl PullRequestDetailView { window: &mut Window, cx: &mut Context, ) -> Self { - let pane = cx.new(DiffPane::new); + let pane = cx.new(|cx| DiffPane::new(false, cx)); + + // A new revision or a rebind must reach the panel without reopening it. + let store_subscription = cx.observe(&store, |this, _store, cx| { + this.sync(cx); + }); cx.defer_in(window, move |this, _window, cx| { this.sync(cx); @@ -101,14 +132,16 @@ impl PullRequestDetailView { error: None, bound: None, load_generation: 0, + _store_subscription: store_subscription, pane, scroll_handle: ScrollHandle::new(), - tasks: Vec::new(), + load_task: None, } } /// Opens the pull request in the main panel and its discussion in the split pane. pub fn open( + panels: &Entity, workspace: &WeakEntity, store: Entity, pr_id: EventId, @@ -120,47 +153,61 @@ impl PullRequestDetailView { let detail_store = store.clone(); let directory = ProfileDirectory::new(cx); - log_dropped(workspace.update(cx, |root, cx| { - root.panels().update(cx, |panels, cx| { - panels.open( - PanelSlot::Main, - id, - { - let directory = directory.clone(); - move |window, cx| { - cx.new(|cx| { - Self::new( - workspace_for_build.clone(), - detail_store.clone(), - pr_id, - directory.clone(), - window, - cx, - ) - }) - } - }, - window, - cx, - ); + panels.update(cx, |panels, cx| { + panels.open( + PanelSlot::Main, + id, + { + let directory = directory.clone(); + move |window, cx| { + cx.new(|cx| { + Self::new( + workspace_for_build.clone(), + detail_store.clone(), + pr_id, + directory.clone(), + window, + cx, + ) + }) + } + }, + window, + cx, + ); - let sidebar = cx.new(|cx| { - PullRequestSidebarView::new(store.clone(), pr_id, directory.clone(), cx) - }); + let sidebar = cx + .new(|cx| PullRequestSidebarView::new(store.clone(), pr_id, directory.clone(), cx)); - panels.insert_split_at( - SIDEBAR_ID, - SIDEBAR_WIDTH, - SplitSide::Trailing, - Arc::new(sidebar), - cx, - ); - }) - })); + panels.insert_split_at( + SIDEBAR_ID, + SIDEBAR_WIDTH, + SplitSide::Trailing, + Arc::new(sidebar), + cx, + ); + }); + } + + /// Opens the update dialog for the pull request's current revision. + fn open_update_dialog(&mut self, cx: &mut Context) { + let root = self + .store + .read(cx) + .pull_requests + .iter() + .find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest) + .cloned(); + + if let Some(root) = root { + let dialog = UpdatePrDialog::new(self.store.clone(), root, cx); + cx.open_dialog(dialog); + } } fn sync(&mut self, cx: &mut Context) { let loaded = self.store.read(cx).loaded; + let binding = { let store = self.store.read(cx); store.addr().and_then(|addr| { @@ -185,7 +232,7 @@ impl PullRequestDetailView { PrBinding { description: root.content.clone(), - patch: PullRequest::new(root).patch(store.patches.iter()), + patch: PullRequest::new(root).patch(store.patches.iter()).into(), tip, base, clone_urls, @@ -237,24 +284,22 @@ impl PullRequestDetailView { .. } = binding; - let task: gpui::Task> = cx.spawn(async move |this, cx| { + let task: Task> = cx.spawn(async move |this, cx| { let nostr_diff = cx .background_spawn({ - let patch = patch.clone(); + let patch = Arc::clone(&patch); async move { PatchParser::patch_diffs(&patch) } }) .await; let nostr_commits = cx .background_spawn({ - let patch = patch.clone(); + let patch = Arc::clone(&patch); async move { PatchParser::patch_commits_with_stats(&patch) .into_iter() - .map(|(commit, insertions, deletions)| CommitRow { - commit, - insertions, - deletions, + .map(|(commit, insertions, deletions)| { + CommitRow::new(commit, insertions, deletions) }) .collect::>() } @@ -273,6 +318,7 @@ impl PullRequestDetailView { let clone_urls = clone_urls.clone(); let base = base.clone(); let tip = tip.clone(); + Some( cx.background_spawn(async move { let repo = Mirrors::ensure(&addr, &clone_urls)?; @@ -315,11 +361,7 @@ impl PullRequestDetailView { (0, 0) } }; - CommitRow { - insertions, - deletions, - commit, - } + CommitRow::new(commit, insertions, deletions) }) .collect::>(); @@ -354,7 +396,8 @@ impl PullRequestDetailView { Ok(()) }); - self.tasks.push(task); + // Assigning drops the previous load task, cancelling superseded work. + self.load_task = Some(task); } fn open_commit_diff( @@ -395,9 +438,9 @@ impl PullRequestDetailView { })); } - fn render_body(&self, cx: &mut Context) -> AnyElement { + fn render_body(&self, cx: &mut Context) -> impl IntoElement { if self.bound.is_none() { - return div().into_any_element(); + return div(); } let description = if self.description.is_empty() { @@ -413,13 +456,10 @@ impl PullRequestDetailView { .p_2() .text_sm() .child(description) - .into_any_element() } - fn render_commits(&self, cx: &mut Context) -> AnyElement { + fn render_commits(&self, cx: &mut Context) -> impl IntoElement { let count = self.commits.len(); - let worktree = self.worktree.clone(); - let view = cx.entity().downgrade(); v_flex() .w_full() @@ -445,60 +485,68 @@ impl PullRequestDetailView { .child("No commits found"), ) }) - .children(self.commits.iter().map(|row| { - let commit = &row.commit; - let row_id = commit.id.clone(); - let worktree = worktree.clone(); - let view = view.clone(); + .when(count > 0, |this| { + this.child(v_flex().max_h(px(320.)).min_h_0().child(uniform_list( + "pr-commits", + count, + cx.processor(|this, range: Range, _window, cx| { + range.map(|index| this.render_commit(index, cx)).collect() + }), + ))) + }) + } - h_flex() - .id(commit.id.clone()) - .px_2() - .h_12() - .w_full() - .gap_3() - .border_b_1() - .border_color(cx.theme().colors.border) - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .child( - div() - .w_20() - .flex_none() - .text_sm() - .text_color(cx.theme().colors.muted_foreground) - .child(short_id(&commit.id)), - ) - .child( - div() - .flex_1() - .min_w_0() - .text_sm() - .text_ellipsis() - .whitespace_nowrap() - .child(commit.summary.clone()), - ) - .child(GroupedBadge::new( - format!("pr-commit-stats:{}", commit.id), - row.insertions, - row.deletions, - )) - .on_click(move |_, window, cx| { - if let Some(worktree) = worktree.clone() { - log_dropped(view.update(cx, |this, cx| { - this.open_commit_diff(worktree, &row_id, window, cx); - })); - } - }) - .into_any_element() + /// One commit row of the patch series. + fn render_commit(&mut self, index: usize, cx: &mut Context) -> AnyElement { + let Some(row) = self.commits.get(index) else { + return div().into_any_element(); + }; + + let commit = &row.commit; + let row_id = row.id.clone(); + let worktree = self.worktree.clone(); + let theme = cx.theme(); + + h_flex() + .id(row.id.clone()) + .px_2() + .h_12() + .w_full() + .gap_3() + .border_b_1() + .border_color(theme.colors.border) + .hover(|this| this.bg(theme.colors.muted_hover)) + .child( + div() + .w_20() + .flex_none() + .text_sm() + .text_color(theme.colors.muted_foreground) + .child(row.short.clone()), + ) + .child( + div() + .flex_1() + .min_w_0() + .text_sm() + .text_ellipsis() + .whitespace_nowrap() + .child(commit.summary.clone()), + ) + .child(GroupedBadge::new( + row.stats_id.clone(), + row.insertions, + row.deletions, + )) + .on_click(cx.listener(move |this, _, window, cx| { + if let Some(worktree) = worktree.clone() { + this.open_commit_diff(worktree, &row_id, window, cx); + } })) .into_any_element() } - fn render_changes(&self, cx: &App) -> AnyElement { - self.pane.read(cx).render_flow(self.pane.downgrade(), cx) - } - - fn render_header(&self, cx: &mut Context) -> AnyElement { + fn render_header(&self, cx: &mut Context) -> impl IntoElement { let (title, status, branch, author, created_at, target_branch) = { let store = self.store.read(cx); let Some(root) = store @@ -506,7 +554,7 @@ impl PullRequestDetailView { .iter() .find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest) else { - return div().into_any_element(); + return div(); }; ( root.activity_subject(), @@ -524,7 +572,6 @@ impl PullRequestDetailView { let backend = Backend::global(cx); let can_update = backend.read(cx).current_user() == Some(author); - let weak = cx.entity().downgrade(); let muted = cx.theme().colors.muted_foreground; v_flex() @@ -548,6 +595,7 @@ impl PullRequestDetailView { .child(div().text_color(muted).child("opened by")) .child( h_flex() + .min_w_0() .gap_1() .child( Avatar::new(author) @@ -555,7 +603,7 @@ impl PullRequestDetailView { .picture(author_picture) .small(), ) - .child(author_name), + .child(div().min_w_0().truncate().child(author_name)), ) .child( div() @@ -565,46 +613,41 @@ impl PullRequestDetailView { .when_some(target_branch, |this, target| { this.child(div().text_color(muted).child("targeting")) .child( - Badge::new(format!("target-branch:{target}"), target) - .variant(BadgeVariant::Outline) - .small() - .flex_none(), + Badge::new( + ( + ElementId::from("target-branch"), + SharedString::from(target.clone()), + ), + target.clone(), + ) + .variant(BadgeVariant::Outline) + .small() + .flex_none(), ) }) .when_some(branch, |this, branch| { this.child(div().text_color(muted).child("from")).child( - Badge::new(format!("source-branch:{branch}"), branch) - .variant(BadgeVariant::Outline) - .small() - .flex_none(), + Badge::new( + ( + ElementId::from("source-branch"), + SharedString::from(branch.clone()), + ), + branch.clone(), + ) + .variant(BadgeVariant::Outline) + .small() + .flex_none(), ) }) .child(div().flex_1()) .when(can_update, |this| { this.child(Button::new("update-pr").label("Update").small().on_click( - move |_, _, cx| { - log_dropped(weak.update(cx, |this, cx| { - let root = this - .store - .read(cx) - .pull_requests - .iter() - .find(|pr| { - pr.id == this.pr_id && pr.kind == Kind::GitPullRequest - }) - .cloned(); - - if let Some(root) = root { - let dialog = - UpdatePrDialog::new(this.store.clone(), root, cx); - cx.open_dialog(dialog); - } - })); - }, + cx.listener(|this, _, _, cx| { + this.open_update_dialog(cx); + }), )) }), ) - .into_any_element() } } @@ -615,6 +658,7 @@ struct PullRequestSidebarView { comment_input: Entity, directory: Entity, scroll_handle: ScrollHandle, + comments_scroll: ListState, _subscription: Subscription, } @@ -626,7 +670,7 @@ impl PullRequestSidebarView { cx: &mut Context, ) -> Self { let comment_input = InputState::builder().multiline().build(cx); - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); let subscription = cx.observe(&store, |this, _store, cx| { this.track_participants(cx); @@ -645,6 +689,7 @@ impl PullRequestSidebarView { comment_input, directory, scroll_handle: ScrollHandle::new(), + comments_scroll: ListState::new(0, ListAlignment::Top, px(48.)), _subscription: subscription, } } @@ -664,7 +709,79 @@ impl PullRequestSidebarView { .map(|comment| comment.pubkey) .collect(); - track_event_participants(author, owner, comments.into_iter(), &self.directory, cx); + self.directory + .track_participants(author, owner, comments.into_iter(), cx); + } + + /// One comment card of the pull request's discussion. + fn render_comment(&self, ix: usize, cx: &App) -> AnyElement { + let Some(comment) = self.store.read(cx).comments_of(&self.pr_id).nth(ix) else { + return div().into_any_element(); + }; + + let profile = self.directory.read(cx).profile(&comment.pubkey, cx); + let author = profile.name(); + let age = relative_time(comment.created_at); + let content = SharedString::from(comment.content.as_str()); + + v_flex() + .gap_1() + .p_3() + .border_1() + .border_color(cx.theme().colors.border) + .rounded(cx.theme().radius.control) + .child( + h_flex() + .gap_2() + .text_sm() + .child( + h_flex() + .gap_1() + .child( + Avatar::new(comment.pubkey) + .name(author.clone()) + .picture(profile.picture()) + .small(), + ) + .child(author), + ) + .child( + div() + .text_color(cx.theme().colors.muted_foreground) + .child("commented"), + ) + .child( + div() + .text_color(cx.theme().colors.muted_foreground) + .child(SharedString::from(age)), + ), + ) + .child(div().text_sm().child(content)) + .into_any_element() + } + + /// Posts the sidebar composer's text as a comment on this pull request. + fn submit_comment(&mut self, window: &mut Window, cx: &mut Context) { + let content = self.comment_input.read(cx).value().trim().to_string(); + if content.is_empty() { + return; + } + + let event = self + .store + .read(cx) + .pull_requests + .iter() + .find(|event| event.id == self.pr_id) + .cloned(); + + if let Some(event) = event { + self.store + .update(cx, |store, cx| store.comment(&event, content, cx)); + } + + self.comment_input + .update(cx, |input, cx| input.set_value("", window, cx)); } } @@ -684,37 +801,89 @@ impl Render for PullRequestSidebarView { .find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest) else { return if store.loaded { - EmptyState::centered(NOT_FOUND) + EmptyState::centered(NOT_FOUND).into_any_element() } else { - Spinner::centered("pr-loading") + Spinner::centered("pr-loading").into_any_element() }; }; - let root_id = root.id; - let discussion = ScrollArea::new("pr-discussion-scroll") - .handle(self.scroll_handle.clone()) - .flex_1() - .min_h_0() - .child(v_flex().p_2().child(comments_section( - &self.store, - root_id, - &self.directory, - cx, - ))) - .into_any_element(); + let root_id = root.id; + let comments = self.store.read(cx).comments_of(&root_id).count(); + + if self.comments_scroll.item_count() != comments { + self.comments_scroll.reset(comments); + } v_flex() .size_full() .min_h_0() - .child(discussion) - .child(div().flex_none().p_2().child(comment_form( - &self.store, - root_id, - &store.pull_requests, - &self.comment_input, - "pr-comment", - cx, - ))) + .child( + ScrollArea::new("pr-discussion-scroll") + .handle(self.scroll_handle.clone()) + .flex_1() + .min_h_0() + .child( + v_flex() + .p_2() + .gap_4() + .child( + h_flex() + .gap_2() + .child(Icon::named(IconRole::Message)) + .child(div().text_sm().font_semibold().child("Discussion")) + .child(Badge::new( + format!("discussion-count:{root_id}"), + comments.to_string(), + )), + ) + .child( + v_flex().max_h(rems(24.)).min_h_0().child( + list( + self.comments_scroll.clone(), + cx.processor(|this, ix: usize, _window, cx| { + this.render_comment(ix, cx) + }), + ) + .with_sizing_behavior(ListSizingBehavior::Infer), + ), + ), + ), + ) + .child( + div().flex_none().p_2().child( + v_flex() + .gap_2() + .child( + Input::new("pr-comment-input", self.comment_input.clone()) + .placeholder("Leave a comment...") + .rows(4), + ) + .child( + h_flex() + .justify_between() + .child( + h_flex() + .gap_1() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child( + Icon::named(IconRole::Markdown) + .size(px(12.)) + .color(cx.theme().colors.muted_foreground), + ) + .child("Markdown is supported"), + ) + .child( + Button::new("pr-comment") + .label("Comment") + .tooltip(Tooltip::text("Post comment")) + .on_click(cx.listener(|this, _, window, cx| { + this.submit_comment(window, cx) + })), + ), + ), + ), + ) .into_any_element() } } @@ -780,7 +949,7 @@ impl Render for PullRequestDetailView { .child(self.render_header(cx)) .child(self.render_body(cx)) .child(self.render_commits(cx)) - .child(self.render_changes(cx)), + .child(self.pane.read(cx).render_flow(self.pane.downgrade(), cx)), ) .into_any_element() } diff --git a/crates/signed_app/src/pull_requests/dialogs/update.rs b/crates/signed_app/src/pull_requests/dialogs/update.rs index 6d3edd5..332599e 100644 --- a/crates/signed_app/src/pull_requests/dialogs/update.rs +++ b/crates/signed_app/src/pull_requests/dialogs/update.rs @@ -1,48 +1,51 @@ use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, - Styled as _, Window, div, + App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, + Window, div, }; use nostr::prelude::Event; use signed_state::RepoStore; +use ui::button::Button; use ui::common::v_flex; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; -use crate::shared::progress::{DialogProgress, dialog_submit_button}; +use crate::shared::log_dropped; pub struct UpdatePrDialog { handle: DialogHandle, store: Entity, root: Event, patch: Entity, - state: Entity, + busy: bool, } impl UpdatePrDialog { pub fn new(store: Entity, root: Event, cx: &mut App) -> Entity { let patch = InputState::builder().multiline().build(cx); - let state = cx.new(|_| DialogProgress::default()); + cx.new(|_| Self { handle: DialogHandle::new(true), store, root, patch, - state, + busy: false, }) } fn submit(&mut self, cx: &mut Context) { // The publish runs detached in the store; one submission per dialog. - if self.state.read(cx).busy { + if self.busy { return; } + let patch = self.patch.read(cx).value().to_string(); if patch.trim().is_empty() { return; } - self.state.update(cx, |state, _| state.begin()); + + self.busy = true; self.store.update(cx, |store, cx| { store.update_pull_request(&self.root, patch, cx); }); @@ -52,9 +55,11 @@ impl UpdatePrDialog { impl Render for UpdatePrDialog { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + const PATCH_HINT: &str = "Publish a new revision with the output of `git format-patch`."; + let patch = self.patch.clone(); - let this = cx.entity().downgrade(); - let action_state = self.state.clone(); + let this = cx.weak_entity(); + let busy = self.busy; Dialog::new("update-pr-dialog") .handle(self.handle.clone()) @@ -67,7 +72,7 @@ impl Render for UpdatePrDialog { div() .text_sm() .text_color(cx.theme().colors.muted_foreground) - .child("Publish a new revision with the output of `git format-patch`."), + .child(PATCH_HINT), ) .child( Field::new("update-patch", "Patch") @@ -75,22 +80,17 @@ impl Render for UpdatePrDialog { ) .into_any_element() }) - .actions(move |_, cx| { + .actions(move |_, _cx| { let this = this.clone(); - let busy = action_state.read(cx).busy; vec![ - dialog_submit_button( - "submit-update", - "Update pull request", - None, - busy, - &this, - |this, _window, cx| { - this.submit(cx); - Ok(()) - }, - ) - .into_any_element() as AnyElement, + Button::new("submit-update") + .label("Update pull request") + .loading(busy) + .disabled(busy) + .on_click(move |_, _, cx| { + log_dropped(this.update(cx, |this, cx| this.submit(cx))); + }) + .into_any_element(), ] }) } diff --git a/crates/signed_app/src/pull_requests/helpers.rs b/crates/signed_app/src/pull_requests/helpers.rs index 23fbe60..b87b9c8 100644 --- a/crates/signed_app/src/pull_requests/helpers.rs +++ b/crates/signed_app/src/pull_requests/helpers.rs @@ -8,7 +8,7 @@ use ui::menu::MenuItem; use utils::middle_truncate; use super::NewPullRequestView; -use crate::repo::helpers::announcement_display_name; +use crate::shared::labels::AnnouncementExt as _; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PullRequestFilter { @@ -90,9 +90,9 @@ pub fn source_menu_items( let Some(path) = associated.get(index).cloned() else { return; }; - if let Err(error) = - target.update(cx, |this, cx| this.apply_folder_path(path, window, cx)) - { + if let Err(error) = target.update(cx, |this, cx| { + this.apply_folder_path(path, window, cx); + }) { log::warn!("failed to apply checkout: {error}"); } }), @@ -102,8 +102,9 @@ pub fn source_menu_items( let folder_view = view.clone(); items.push( MenuItem::new("Choose another folder…").handler(move |window, cx| { - if let Err(error) = folder_view.update(cx, |this, cx| this.choose_checkout(window, cx)) - { + if let Err(error) = folder_view.update(cx, |this, cx| { + this.choose_checkout(window, cx); + }) { log::warn!("failed to choose checkout: {error}"); } }), @@ -120,7 +121,7 @@ pub fn source_menu_items( SharedString::from(format!("by {}", shorten_owner(&candidate.owner))) }; - let title = format!("{} — {}", announcement_display_name(candidate), subtitle); + let title = format!("{} — {}", candidate.display_name(), subtitle); let target = view.clone(); let candidates = Arc::clone(&candidates); let checked = active_fork == Some(candidate.addr()); @@ -132,9 +133,9 @@ pub fn source_menu_items( let Some(announcement) = candidates.get(index).cloned() else { return; }; - if let Err(error) = - target.update(cx, |this, cx| this.choose_fork(announcement, window, cx)) - { + if let Err(error) = target.update(cx, |this, cx| { + this.choose_fork(announcement, window, cx); + }) { log::warn!("failed to choose fork: {error}"); } }), diff --git a/crates/signed_app/src/pull_requests/mod.rs b/crates/signed_app/src/pull_requests/mod.rs index caf4527..0b029b6 100644 --- a/crates/signed_app/src/pull_requests/mod.rs +++ b/crates/signed_app/src/pull_requests/mod.rs @@ -1,3 +1,6 @@ +use std::ops::Range; +use std::sync::Arc; + use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, @@ -5,8 +8,8 @@ use gpui::{ Subscription, UniformListScrollHandle, WeakEntity, Window, div, uniform_list, }; use metadata::ProfileDirectory; -use nostr::prelude::{Kind, PublicKey}; -use signed_core::GitEvent; +use nostr::prelude::{EventId, Kind, PublicKey}; +use signed_core::{GitEvent, RepoStatus}; use signed_state::RepoStore; use ui::alert::{Alert, AlertSeverity}; use ui::avatar::Avatar; @@ -33,16 +36,27 @@ pub use new::NewPullRequestView; pub use send_patch::SendPatchView; use crate::app::AppRoot; -use crate::issues::helpers::{StatusCounts, filter_by_status}; -use crate::repo::helpers::short_id; +use crate::shared::labels::ShortIdExt as _; use crate::shared::log_dropped; -use crate::shared::widgets::status_badge; +use crate::shared::widgets::{StatusCounts, status_badge}; + +/// One pull request row, with its display strings built on rebuild. +struct PrRow { + id: EventId, + /// The row's element id. + element_id: SharedString, + status: RepoStatus, + subject: SharedString, + author: PublicKey, + age: SharedString, + short: SharedString, +} pub struct PullRequestsView { workspace: WeakEntity, store: Entity, filter: PullRequestFilter, - visible_prs: Vec, + rows: Arc>, counts: StatusCounts, synced_filter: PullRequestFilter, scroll_handle: UniformListScrollHandle, @@ -57,7 +71,7 @@ impl PullRequestsView { store: Entity, cx: &mut Context, ) -> Self { - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); let subscription = cx.observe(&store, |this, _store, cx| { this.rebuild(cx); }); @@ -72,7 +86,7 @@ impl PullRequestsView { workspace, store, filter: PullRequestFilter::Open, - visible_prs: Vec::new(), + rows: Arc::new(Vec::new()), counts: StatusCounts::default(), synced_filter: PullRequestFilter::Open, scroll_handle: UniformListScrollHandle::new(), @@ -97,13 +111,29 @@ impl PullRequestsView { .iter() .filter(|pr| pr.kind == Kind::GitPullRequest); - filter_by_status( + StatusCounts::filter( roots, |pr| store.status_of(pr), |status| filter.matches(status), ) }; + let rows: Vec = visible_prs + .iter() + .filter_map(|index| { + let pr = store.pull_requests.get(*index)?; + Some(PrRow { + id: pr.id, + element_id: SharedString::from(format!("pr:{}", pr.id.to_hex())), + status: store.status_of(pr), + subject: SharedString::from(pr.activity_subject()), + author: pr.pubkey, + age: SharedString::from(relative_time(pr.created_at)), + short: pr.id.to_hex().short_id(), + }) + }) + .collect(); + let mut keys: Vec = store .pull_requests .iter() @@ -124,12 +154,14 @@ impl PullRequestsView { }); let filter_changed = self.synced_filter != filter; - if !filter_changed && self.visible_prs == visible_prs && self.counts == counts { + if !filter_changed && self.rows.len() == rows.len() && self.counts == counts { return; } + self.synced_filter = filter; - self.visible_prs = visible_prs; + self.rows = Arc::new(rows); self.counts = counts; + cx.notify(); } @@ -199,14 +231,102 @@ impl PullRequestsView { })); } - fn render_header(&self, cx: &mut Context) -> AnyElement { + /// One pull request row of the list. + fn render_pr(&mut self, ix: usize, cx: &mut Context) -> AnyElement { + let Some(row) = self.rows.get(ix) else { + return div().into_any_element(); + }; + + let profile = self.directory.read(cx).profile(&row.author, cx); + let pr_id = row.id; + let status = row.status; + + h_flex() + .id(row.element_id.clone()) + .w_full() + .h_16() + .px_2() + .border_b_1() + .border_color(cx.theme().colors.border) + .hover(|this| this.bg(cx.theme().colors.muted_hover)) + .on_click(cx.listener(move |this, _, window, cx| { + this.open_pr(pr_id, window, cx); + })) + .child( + h_flex() + .w_full() + .items_start() + .gap_2() + .child(h_flex().w_20().child(status_badge(status))) + .child( + v_flex() + .flex_1() + .min_w_0() + .gap_1() + .child( + div() + .text_sm() + .text_ellipsis() + .whitespace_nowrap() + .child(row.subject.clone()), + ) + .child( + h_flex() + .gap_2() + .text_xs() + .child( + h_flex() + .min_w_0() + .gap_1() + .child( + Avatar::new(row.author) + .name(profile.name()) + .picture(profile.picture()) + .small(), + ) + .child( + div().min_w_0().truncate().child(profile.name()), + ), + ) + .child("opened") + .child( + div() + .text_color(cx.theme().colors.muted_foreground) + .child(row.short.clone()), + ) + .child(row.age.clone()), + ), + ), + ) + .into_any_element() + } + + /// Opens this pull request's detail panel in the split stack. + fn open_pr(&mut self, pr_id: EventId, window: &mut Window, cx: &mut Context) { + let panels = self + .workspace + .read_with(cx, |root, _| root.panels().clone()); + + let Ok(panels) = panels else { + log::warn!("pull request list outlived the app shell"); + return; + }; + + PullRequestDetailView::open( + &panels, + &self.workspace, + self.store.clone(), + pr_id, + window, + cx, + ); + } + + fn render_header(&self, cx: &mut Context) -> impl IntoElement { let counts = self.counts; let colors = cx.theme().colors; let muted = colors.muted_foreground; - let weak = cx.entity().downgrade(); - let open_weak = cx.entity().downgrade(); - let menu_open_weak = cx.entity().downgrade(); - let patch_weak = cx.entity().downgrade(); + let patch_weak = cx.weak_entity(); h_flex() .px_2() @@ -235,14 +355,10 @@ impl PullRequestsView { .label(format!("Merged ({})", counts.applied)) .icon(Icon::named(IconRole::GitPullRequestMerged).color(muted)), ]) - .on_change(move |filter, _, cx| { - if let Err(error) = weak.update(cx, |this, cx| { - this.filter = filter; - this.rebuild(cx); - }) { - log::warn!("failed to switch PR filter: {error}"); - } - }), + .on_change(cx.processor(|this, filter: PullRequestFilter, _, cx| { + this.filter = filter; + this.rebuild(cx); + })), ) .child(div().flex_1()) .child( @@ -251,19 +367,11 @@ impl PullRequestsView { .icon(Icon::named(IconRole::GitPullRequest)) .small() .open(self.new_pr_menu_open) - .on_click(move |_, window, cx| { - if let Err(error) = - open_weak.update(cx, |this, cx| this.open_new(window, cx)) - { - log::warn!("failed to open new PR: {error}"); - } - }) - .on_open_change(move |open, _, cx| { - log_dropped(menu_open_weak.update(cx, |this, cx| { - this.new_pr_menu_open = open; - cx.notify(); - })); - }) + .on_click(cx.listener(|this, _, window, cx| this.open_new(window, cx))) + .on_open_change(cx.processor(|this, open: bool, _, cx| { + this.new_pr_menu_open = open; + cx.notify(); + })) .items(move |_, _| { vec![MenuItem::new("Send Patch").handler({ let weak = patch_weak.clone(); @@ -275,7 +383,6 @@ impl PullRequestsView { })] }), ) - .into_any_element() } } @@ -288,11 +395,6 @@ impl Panel for PullRequestsView { impl Render for PullRequestsView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let filter = self.filter; - let visible = self.visible_prs.clone(); - let directory = self.directory.clone(); - let store = self.store.clone(); - let workspace = self.workspace.clone(); - let (last_error, last_warning) = { let store = self.store.read(cx); (store.last_error.clone(), store.last_warning.clone()) @@ -302,7 +404,7 @@ impl Render for PullRequestsView { let dismiss_error_store = self.store.clone(); let scroll_handle = self.scroll_handle.clone(); - let count = visible.len(); + let count = self.rows.len(); v_flex() .size_full() @@ -345,95 +447,13 @@ impl Render for PullRequestsView { .child(self.render_header(cx)) .when(count > 0, |this| { this.child( - uniform_list("prl", count, move |range, _, cx| { - range - .map(|ix| { - // The store re-read per frame can shrink below a captured index. - let Some(pr) = visible.get(ix).and_then(|pr_ix| { - store.read(cx).pull_requests.get(*pr_ix) - }) else { - return div().into_any_element(); - }; - - let profile = directory.read(cx).profile(&pr.pubkey, cx); - let pr_id = pr.id; - let id_hex = pr.id.to_hex(); - let status = store.read(cx).status_of(pr); - let workspace = workspace.clone(); - let store = store.clone(); - - h_flex() - .id(SharedString::from(format!("pr:{id_hex}"))) - .w_full() - .h_16() - .px_2() - .border_b_1() - .border_color(cx.theme().colors.border) - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .on_click(move |_, window, cx| { - PullRequestDetailView::open( - &workspace, - store.clone(), - pr_id, - window, - cx, - ); - }) - .child( - h_flex() - .w_full() - .items_start() - .gap_2() - .child(h_flex().w_20().child(status_badge(status))) - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_1() - .child( - div() - .text_sm() - .text_ellipsis() - .whitespace_nowrap() - .child(pr.activity_subject()), - ) - .child( - h_flex() - .gap_2() - .text_xs() - .child( - h_flex() - .gap_1() - .child( - Avatar::new(pr.pubkey) - .name(profile.name()) - .picture( - profile.picture(), - ) - .small(), - ) - .child( - div().child(profile.name()), - ), - ) - .child("opened") - .child( - div() - .text_color( - cx.theme() - .colors - .muted_foreground, - ) - .child(short_id(&id_hex)), - ) - .child(relative_time(pr.created_at)), - ), - ), - ) - .into_any_element() - }) - .collect() - }) + uniform_list( + "prl", + count, + cx.processor(|this, range: Range, _window, cx| { + range.map(|ix| this.render_pr(ix, cx)).collect() + }), + ) .track_scroll(&scroll_handle) .size_full(), ) diff --git a/crates/signed_app/src/pull_requests/new.rs b/crates/signed_app/src/pull_requests/new.rs index 81778e1..3768bc0 100644 --- a/crates/signed_app/src/pull_requests/new.rs +++ b/crates/signed_app/src/pull_requests/new.rs @@ -1,4 +1,5 @@ use std::path::{Path, PathBuf}; +use std::rc::Rc; use std::sync::Arc; use gpui::prelude::FluentBuilder as _; @@ -28,10 +29,9 @@ use utils::relative_time_secs; use super::helpers::{ForkCompare, truncate_label}; use crate::app::AppRoot; -use crate::repo::commit_diff::{CommitDiffView, DiffPane}; -use crate::repo::helpers::{announcement_display_name, short_id}; +use crate::shared::commit_diff::{CommitDiffView, DiffPane}; +use crate::shared::labels::{AnnouncementExt as _, ShortIdExt as _}; use crate::shared::log_dropped; -use crate::shared::progress::error_row; pub struct NewPullRequestView { workspace: WeakEntity, @@ -58,6 +58,8 @@ pub struct NewPullRequestView { scroll_handle: UniformListScrollHandle, pub(super) tasks: Vec>>, source_open: bool, + /// The compare bar's source label, derived from `fork`/`repo_path`. + source_label: SharedString, /// The checkouts, forks, and user the source menu lists. checkouts: Arc>, forks: Arc>, @@ -80,8 +82,8 @@ impl NewPullRequestView { let subject = InputState::new(cx); let description = InputState::builder().multiline().build(cx); - let pane = cx.new(DiffPane::new); - let weak = cx.entity().downgrade(); + let pane = cx.new(|cx| DiffPane::new(false, cx)); + let weak = cx.weak_entity(); let base_select = cx.new(|cx| { ComboboxState::new( @@ -188,6 +190,7 @@ impl NewPullRequestView { scroll_handle: UniformListScrollHandle::new(), tasks: Vec::new(), source_open: false, + source_label: SharedString::from("No source"), checkouts: Arc::default(), forks: Arc::default(), user: None, @@ -195,22 +198,19 @@ impl NewPullRequestView { } } - /// Reaps finished tasks, then queues another. - pub(super) fn push_task(&mut self, task: gpui::Task>) { - self.tasks.retain(|task| !task.is_ready()); - self.tasks.push(task); - } - fn submit(&mut self, _window: &mut Window, cx: &mut Context) { if self.submitting || self.loading { return; } + let Some(merge_base) = self.merge_base.clone() else { return; }; + let Some(repo_path) = self.work_path() else { return; }; + let subject = self.subject.read(cx).value().to_string(); let description = self.description.read(cx).value().to_string(); let branch_name = self.compare.to_string(); @@ -236,6 +236,7 @@ impl NewPullRequestView { cx, ) }); + if let Err(error) = publish.await { this.update(cx, |this, cx| { this.submitting = false; @@ -244,29 +245,36 @@ impl NewPullRequestView { })?; return Ok(()); } + this.update(cx, |this, _cx| { this.submitting = false; })?; + log_dropped(workspace.update(cx, |root, cx| { root.panels().clone().update(cx, |panels, cx| { panels.close(PanelSlot::Split, &panel_id, cx) }) })); + Ok(()) }); - self.push_task(task); + + self.tasks.push(task); } fn open_commit_diff(&mut self, commit_id: &str, window: &mut Window, cx: &mut Context) { let Some(repo_path) = self.work_path() else { return; }; + let id = match self.store.read(cx).addr() { Some(addr) => SharedString::from(format!("commit:{addr}:{commit_id}")), None => SharedString::from(format!("commit:{}:{commit_id}", repo_path.display())), }; + let workspace = self.workspace.clone(); let commit_id = commit_id.to_owned(); + log_dropped(workspace.update(cx, |root, cx| { root.panels().clone().update(cx, |panels, cx| { panels.open( @@ -303,9 +311,7 @@ impl NewPullRequestView { } fn render_compare_bar(&self, cx: &mut Context) -> AnyElement { - let weak = cx.entity().downgrade(); - let weak_menu = cx.entity().downgrade(); - let source_view = cx.entity().downgrade(); + let source_view = cx.weak_entity(); let associated = Arc::clone(&self.checkouts); let active_path = (self.fork.is_none()) @@ -313,17 +319,11 @@ impl NewPullRequestView { .flatten(); let candidates = Arc::clone(&self.forks); - let user = signed_state::Backend::global(cx).read(cx).current_user(); + let user = self.user; let active_fork = self.fork.as_ref().map(|fork| fork.announcement.addr()); let can_submit = self.submit_enabled(cx); - let source_label = match &self.fork { - Some(fork) => truncate_label(&announcement_display_name(&fork.announcement)), - None => self.repo_path.as_ref().map_or_else( - || SharedString::from("No source"), - |path| truncate_label(&path.display().to_string()), - ), - }; + let source_label = self.source_label.clone(); let refresh_fork = self.fork.as_ref().map(|fork| fork.announcement.clone()); h_flex() @@ -352,12 +352,10 @@ impl NewPullRequestView { .child( Menu::new("pr-source") .open(self.source_open) - .on_change(move |open, _, cx| { - log_dropped(weak_menu.update(cx, |this, cx| { - this.source_open = open; - cx.notify(); - })); - }) + .on_change(cx.processor(|this, open: bool, _, cx| { + this.source_open = open; + cx.notify(); + })) .trigger(move |_, _| { Button::new("compare-source") .label(source_label.clone()) @@ -392,9 +390,9 @@ impl NewPullRequestView { .icon(Icon::named(IconRole::Plus)) .loading(self.submitting) .disabled(!can_submit) - .on_click(move |_, window, cx| { - log_dropped(weak.update(cx, |this, cx| this.submit(window, cx))); - }), + .on_click(cx.listener(|this, _, window, cx| { + this.submit(window, cx); + })), ) .into_any_element() } @@ -402,7 +400,6 @@ impl NewPullRequestView { fn render_tabs(&self, cx: &mut Context) -> AnyElement { let files = self.pane.read(cx).diff().map_or(0, |diff| diff.files.len()); let commits = self.commits.as_ref().map_or(0, |commits| commits.len()); - let weak = cx.entity().downgrade(); Tabs::new("new-pr-tabs") .selected(self.active_tab) @@ -413,26 +410,25 @@ impl NewPullRequestView { .lead(Icon::named(IconRole::GitCommit)), ] }) - .on_change(move |index, _, cx| { - log_dropped(weak.update(cx, |this, cx| { - this.active_tab = index; - cx.notify(); - })); - }) + .on_change(cx.processor(|this, index: usize, _, cx| { + this.active_tab = index; + cx.notify(); + })) .into_any_element() } fn render_content(&self, cx: &mut Context) -> AnyElement { if self.loading { - return Spinner::centered("new-pr-loading"); + return Spinner::centered("new-pr-loading").into_any_element(); } if !self.has_source() { - return EmptyState::centered("Choose a local checkout or an announced fork to compare"); + return EmptyState::centered("Choose a local checkout or an announced fork to compare") + .into_any_element(); } if self.commits.is_none() && self.error.is_some() { - return EmptyState::centered("Nothing to compare"); + return EmptyState::centered("Nothing to compare").into_any_element(); } match self.active_tab { @@ -447,17 +443,20 @@ impl NewPullRequestView { fn render_commits(&self, cx: &mut Context) -> AnyElement { let Some(commits) = self.commits.as_ref() else { - return EmptyState::centered("No commits"); + return EmptyState::centered("No commits").into_any_element(); }; if commits.is_empty() { - return EmptyState::centered("No commits between the branches"); + return EmptyState::centered("No commits between the branches").into_any_element(); } let commits = Arc::clone(commits); - let view = cx.entity().downgrade(); let scroll_handle = self.scroll_handle.clone(); + let open_commit = Rc::new(cx.processor(|this, commit_id: String, window, cx| { + this.open_commit_diff(&commit_id, window, cx); + })); + v_flex() .relative() .flex_1() @@ -470,7 +469,7 @@ impl NewPullRequestView { return div().into_any_element(); }; let row_id = commit.id.clone(); - let view = view.clone(); + let open_commit = open_commit.clone(); h_flex() .id(commit.id.clone()) @@ -489,6 +488,7 @@ impl NewPullRequestView { .justify_center() .child( h_flex() + .min_w_0() .gap_2() .overflow_hidden() .child( @@ -498,7 +498,7 @@ impl NewPullRequestView { .text_color( cx.theme().colors.muted_foreground, ) - .child(short_id(&commit.id)), + .child(commit.id.short_id()), ) .child( div() @@ -520,9 +520,7 @@ impl NewPullRequestView { ), ) .on_click(move |_, window, cx| { - log_dropped(view.update(cx, |this, cx| { - this.open_commit_diff(&row_id, window, cx); - })); + open_commit(row_id.clone(), window, cx); }) .into_any_element() }) @@ -581,7 +579,8 @@ impl NewPullRequestView { })?; Ok(()) }); - self.push_task(task); + + self.tasks.push(task); } pub(crate) fn apply_folder_path( @@ -593,6 +592,7 @@ impl NewPullRequestView { self.fork_generation = self.fork_generation.wrapping_add(1); let generation = self.fork_generation; let path_string = path.to_string_lossy().to_string(); + let task: gpui::Task> = cx.spawn_in(window, async move |this, cx| { let info = cx @@ -618,7 +618,8 @@ impl NewPullRequestView { })?; Ok(()) }); - self.push_task(task); + + self.tasks.push(task); } fn apply_checkout( @@ -661,6 +662,7 @@ impl NewPullRequestView { self.repo_path = Some(PathBuf::from(&path)); self.error = None; + self.refresh_source_label(); self.branches = branches.into_iter().map(SharedString::from).collect(); if let Some(addr) = self.store.read(cx).addr().cloned() { @@ -681,6 +683,7 @@ impl NewPullRequestView { .iter() .map(|branch| (branch.clone(), branch.clone())) .collect(); + let base = self.base.clone(); let compare = self.compare.clone(); @@ -688,6 +691,7 @@ impl NewPullRequestView { state.set_options(options.clone(), cx); state.set_selected(Some(base), window, cx); }); + self.compare_select.update(cx, |state, cx| { state.set_options(options, cx); state.set_selected(Some(compare), window, cx); @@ -709,8 +713,10 @@ impl NewPullRequestView { let checkouts = CheckoutsStore::global(cx); let repositories = RepoListStore::global(cx); + let backend = Backend::global(cx); let user = backend.read(cx).current_user(); + let checkouts = addr .as_ref() .map_or_else(Vec::new, |addr| checkouts.read(cx).associations_of(addr)); @@ -750,9 +756,11 @@ impl NewPullRequestView { let Some(base) = self.store.read(cx).addr().cloned() else { return; }; + let mirror_path = Mirrors::path(&base); let namespace = GitCache::fork_namespace(&announcement); let clone_urls: Vec = announcement.clone.clone(); + let base_clone_urls: Vec = self .store .read(cx) @@ -760,6 +768,7 @@ impl NewPullRequestView { .as_ref() .map(|a| a.clone.clone()) .unwrap_or_default(); + self.fork_generation = self.fork_generation.wrapping_add(1); let generation = self.fork_generation; let handle = window.window_handle(); @@ -775,12 +784,14 @@ impl NewPullRequestView { let mirror_path = mirror_path.clone(); async move { Mirrors::ensure(&base, &base_clone_urls)?; + let repo = Repo::open(&mirror_path)?; repo.delete_refs_with_prefix("refs/fork")?; repo.fetch_refs( &clone_urls, &format!("+refs/heads/*:refs/fork/{namespace}/*"), )?; + let strip = |refs: Vec, prefix: &str| { let mut names: Vec = refs .into_iter() @@ -793,14 +804,17 @@ impl NewPullRequestView { names.sort(); names }; + let base_branches = strip( repo.refs_with_prefix("refs/remotes/origin")?, "refs/remotes/origin", ); + let compare_branches = strip( repo.refs_with_prefix(&format!("refs/fork/{namespace}"))?, &format!("refs/fork/{namespace}"), ); + Ok::<_, anyhow::Error>((base_branches, compare_branches)) } }) @@ -816,9 +830,11 @@ impl NewPullRequestView { }) { log::warn!("failed to apply fork: {error}"); } + Ok(()) }); - self.push_task(task); + + self.tasks.push(task); } fn apply_fork( @@ -868,6 +884,7 @@ impl NewPullRequestView { mirror_path, }); self.error = None; + self.refresh_source_label(); self.base = SharedString::from(base); self.compare = compare; self.branches = base_branches.into_iter().map(SharedString::from).collect(); @@ -875,23 +892,28 @@ impl NewPullRequestView { self.reload_compare(cx); } + /// Recomputes the compare bar's source label after a fork or checkout change. + fn refresh_source_label(&mut self) { + self.source_label = match &self.fork { + Some(fork) => truncate_label(&fork.announcement.display_name()), + None => self.repo_path.as_ref().map_or_else( + || SharedString::from("No source"), + |path| truncate_label(&path.display().to_string()), + ), + }; + } + pub(super) fn reload_compare(&mut self, cx: &mut Context) { let Some(repo_path) = self.work_path() else { return; }; + let base = self.base_ref(); let compare = self.compare_ref(); let base_name = self.base.to_string(); let compare_name = self.compare.to_string(); - self.loading = true; - self.error = None; - self.compare_generation = self.compare_generation.wrapping_add(1); - let generation = self.compare_generation; - cx.notify(); - if base == compare { - self.loading = false; self.merge_base = None; self.commits = None; self.pane.update(cx, |pane, cx| pane.clear(cx)); @@ -900,6 +922,13 @@ impl NewPullRequestView { return; } + self.loading = true; + self.error = None; + self.compare_generation = self.compare_generation.wrapping_add(1); + + let generation = self.compare_generation; + cx.notify(); + let task: gpui::Task> = cx.spawn(async move |this, cx| { let result = cx .background_spawn({ @@ -922,6 +951,7 @@ impl NewPullRequestView { return; } this.loading = false; + match result { Ok((merge_base, commits, diff)) => { this.merge_base = Some(merge_base); @@ -935,11 +965,14 @@ impl NewPullRequestView { this.error = Some(error.to_string().into()); } } + cx.notify(); })?; + Ok(()) }); - self.push_task(task); + + self.tasks.push(task); } } @@ -978,7 +1011,14 @@ impl Render for NewPullRequestView { .rows(3) .placeholder("Describe..."), ) - .when_some(error_row(&self.error, cx), |this, error| this.child(error)), + .when_some(self.error.clone(), |this, error| { + this.child( + div() + .text_sm() + .text_color(cx.theme().ramps.destructive.base) + .child(error), + ) + }), ) .child(self.render_tabs(cx)), ) diff --git a/crates/signed_app/src/pull_requests/send_patch.rs b/crates/signed_app/src/pull_requests/send_patch.rs index ded9d02..2d7899b 100644 --- a/crates/signed_app/src/pull_requests/send_patch.rs +++ b/crates/signed_app/src/pull_requests/send_patch.rs @@ -1,7 +1,7 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, - Render, SharedString, Styled as _, WeakEntity, Window, div, + App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, + SharedString, Styled as _, Task, WeakEntity, Window, div, }; use signed_state::RepoStore; use ui::button::Button; @@ -13,7 +13,6 @@ use ui::theme::ActiveTheme as _; use crate::app::AppRoot; use crate::shared::log_dropped; -use crate::shared::progress::error_row; pub struct SendPatchView { workspace: WeakEntity, @@ -24,6 +23,8 @@ pub struct SendPatchView { patch: Entity, submitting: bool, error: Option, + /// Holds the submit so a closed panel cancels it. + task: Option>, } impl SendPatchView { @@ -47,6 +48,7 @@ impl SendPatchView { patch, submitting: false, error: None, + task: None, } } @@ -57,8 +59,8 @@ impl SendPatchView { let subject = self.subject.read(cx).value().to_string(); let description = self.description.read(cx).value().to_string(); - let patch = self.patch.read(cx).value().to_string(); + if patch.is_empty() { return; } @@ -79,10 +81,11 @@ impl SendPatchView { cx, ) }); + let workspace = self.workspace.clone(); let panel_id = self.panel_id.clone(); - cx.spawn(async move |this, cx| match task.await { + self.task = Some(cx.spawn(async move |this, cx| match task.await { Ok(()) => { log_dropped(workspace.update(cx, |root, cx| { root.panels().clone().update(cx, |panels, cx| { @@ -98,17 +101,16 @@ impl SendPatchView { }) .log_err(); } - }) - .detach(); + })); } - fn render_footer(&self, cx: &Context) -> AnyElement { + fn render_footer(&self, cx: &Context) -> impl IntoElement { let can_submit = !self.submitting && !self.subject.read(cx).value().is_empty() && !self.patch.read(cx).value().is_empty(); - let weak = cx.entity().downgrade(); h_flex() + .flex_none() .px_4() .py_2() .w_full() @@ -121,11 +123,8 @@ impl SendPatchView { .icon(Icon::named(IconRole::ArrowUp)) .loading(self.submitting) .disabled(!can_submit) - .on_click(move |_, _, cx| { - log_dropped(weak.update(cx, |this, cx| this.submit(cx))); - }), + .on_click(cx.listener(|this, _, _, cx| this.submit(cx))), ) - .into_any_element() } } @@ -152,6 +151,7 @@ impl Render for SendPatchView { v_flex() .p_4() .flex_1() + .min_h_0() .gap_2() .child(div().pr_16().child( Input::new("patch-subject", self.subject.clone()).placeholder("Title"), @@ -174,7 +174,14 @@ impl Render for SendPatchView { .rows(12) .placeholder("diff --git a/file.txt b/file.txt"), ) - .when_some(error_row(&self.error, cx), |this, error| this.child(error)), + .when_some(self.error.clone(), |this, error| { + this.child( + div() + .text_sm() + .text_color(cx.theme().ramps.destructive.base) + .child(error), + ) + }), ) .child(self.render_footer(cx)) } diff --git a/crates/signed_app/src/repo/dialogs/create.rs b/crates/signed_app/src/repo/dialogs/create.rs index 99059fd..4bc6301 100644 --- a/crates/signed_app/src/repo/dialogs/create.rs +++ b/crates/signed_app/src/repo/dialogs/create.rs @@ -2,8 +2,8 @@ use std::path::PathBuf; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, - PathPromptOptions, Render, Styled as _, Task, WeakEntity, Window, div, px, + App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, PathPromptOptions, + Render, SharedString, Styled as _, Task, WeakEntity, Window, div, px, }; use settings::SettingsStore; use signed_state::{Backend, CheckoutsStore}; @@ -13,14 +13,12 @@ use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState}; +use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; use crate::app::AppRoot; -use crate::repo::actions::open_repo_panel; -use crate::shared::progress::{ - DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task_with, -}; +use crate::shared::log_dropped; /// Progress of the create-repository flow, so async results can be rendered. pub struct CreateRepoDialog { @@ -30,10 +28,13 @@ pub struct CreateRepoDialog { desc_input: Entity, folder_input: Entity, relay_input: Entity, - state: Entity, + busy: bool, + error: Option, grasp_state: Entity, /// Held so the grasp-server load is cancelled when the dialog drops. task: Option>, + /// Holds the folder prompt so it is cancelled when the dialog drops. + folder_task: Option>, } impl CreateRepoDialog { @@ -58,7 +59,6 @@ impl CreateRepoDialog { .build(cx); let relay_input = InputState::new(cx); - let state = cx.new(|_| DialogProgress::default()); let grasp_state = cx.new(|_| GraspServersState::new_default(&grasp_settings)); cx.new(|cx| { @@ -74,90 +74,82 @@ impl CreateRepoDialog { desc_input, folder_input, relay_input, - state, + busy: false, + error: None, grasp_state, task: None, + folder_task: None, } }) } fn create(&mut self, window: &mut Window, cx: &mut Context) { - if self.state.read(cx).busy { + if self.busy { return; } + let backend = Backend::global(cx); let name = self.name_input.read(cx).value().trim().to_owned(); let description = self.desc_input.read(cx).value().trim().to_owned(); let folder = PathBuf::from(self.folder_input.read(cx).value().trim()); let servers = self.grasp_state.read(cx).grasp_servers.clone(); - if name.is_empty() { - self.state.update(cx, |state, cx| { - state.fail("Repository name is required"); - cx.notify(); - }); - return; - } - if servers.is_empty() { - self.state.update(cx, |state, cx| { - state.fail("Add at least one grasp server"); - cx.notify(); - }); - return; - } - - let backend = Backend::global(cx); - let Some(user) = backend.read(cx).current_user() else { - self.state.update(cx, |state, cx| { - state.fail("Sign in to create a repository"); - cx.notify(); - }); + let Some(_user) = backend.read(cx).current_user() else { + self.error = Some("Sign in to create a repository".into()); + cx.notify(); return; }; - let addr = - signed_core::RepoAddr::new(user, signed_core::RepoAddr::identifier_from_name(&name)); - self.state.update(cx, |state, cx| { - state.begin_push(addr, cx); + if name.is_empty() { + self.error = Some("Repository name is required".into()); cx.notify(); - }); + return; + } + + if servers.is_empty() { + self.error = Some("Add at least one grasp server".into()); + cx.notify(); + return; + } + + self.busy = true; + self.error = None; + cx.notify(); let task = backend.update(cx, |backend, cx| { backend.create_repository(&name, &description, folder, servers, cx) }); - let state = self.state.clone(); + let workspace = self.workspace.clone(); let close = self.handle.clone(); let handle = window.window_handle(); - run_dialog_task_with( - task, - cx, - move |(announcement, local_path), cx| { + self.task = Some(cx.spawn(async move |this, cx| match task.await { + Ok((announcement, local_path)) => { cx.update_window(handle, |_, window, cx| { let checkouts = CheckoutsStore::global(cx); checkouts.update(cx, |store, cx| { store.record(local_path.clone(), announcement.addr(), cx); }); + cx.open_with_system(&local_path); - open_repo_panel( - &workspace, - &announcement.addr(), - Some(&announcement), - window, - cx, - ); + let result = workspace.update(cx, |root, cx| { + root.open_repo_panel(&announcement.addr(), Some(&announcement), window, cx); + }); + + log_dropped(result); close.close(cx); }) .log_err(); - }, - move |error, cx| { - state.update(cx, |state, cx| { - state.fail(error.to_string()); + } + Err(error) => { + log_dropped(this.update(cx, |this, cx| { + this.busy = false; + this.error = Some(error.to_string().into()); cx.notify(); - }); - }, - ); + })); + } + })); } } @@ -168,12 +160,11 @@ impl Render for CreateRepoDialog { let folder_input = self.folder_input.clone(); let relay_input = self.relay_input.clone(); - let state = self.state.clone(); - let busy = state.read(cx).busy; + let busy = self.busy; + let error = self.error.clone(); let grasp_state = self.grasp_state.clone(); - let action_state = state.clone(); - let this = cx.entity().downgrade(); + let this = cx.weak_entity(); Dialog::new("create-repo-dialog") .handle(self.handle.clone()) @@ -181,106 +172,113 @@ impl Render for CreateRepoDialog { .close_on_backdrop(!busy) .min_width(px(520.)) .title("Create Repository") - .content(move |_window, cx| { - let progress = state.read(cx); - - v_flex() - .gap_3() - .child( - Field::new("repo-name", "Repository Name") - .description("Max 100 characters") - .child(Input::new("repo-name-input", name_input.clone())), - ) - .child( - Field::new("repo-description", "Description").child( + .content({ + let this = this.clone(); + move |_window, cx| { + v_flex() + .gap_3() + .child( + Field::new("repo-name", "Repository Name") + .description("Max 100 characters") + .child(Input::new("repo-name-input", name_input.clone())), + ) + .child(Field::new("repo-description", "Description").child( Input::new("repo-description-input", desc_input.clone()).rows(3), - ), - ) - .child( - Field::new("repo-folder", "Folder") - .description("Where the repository's working copy is created.") - .child( - h_flex() - .gap_1() - .w_full() - .child(div().flex_1().child(Input::new( - "repo-folder-input", - folder_input.clone(), - ))) - .child( - Button::new("choose-folder") - .icon(Icon::named(IconRole::Folder)) - .variant(ButtonVariant::Ghost) - .tooltip(Tooltip::text("Choose folder")) - .on_click({ - let folder_input = folder_input.clone(); - move |_, window, cx| { - choose_folder(&folder_input, window, cx); - } - }), - ), - ), - ) - .child(grasp_servers_field(&grasp_state, &relay_input, cx)) - .when_some(push_steps_row(&progress.push_steps, cx), |el, steps| { - el.child(steps) - }) - .when_some(error_row(&progress.error, cx), |el, error| el.child(error)) - .into_any_element() + )) + .child( + Field::new("repo-folder", "Folder") + .description("Where the repository's working copy is created.") + .child( + h_flex() + .gap_1() + .w_full() + .child(div().flex_1().min_w_0().child(Input::new( + "repo-folder-input", + folder_input.clone(), + ))) + .child( + Button::new("choose-folder") + .icon(Icon::named(IconRole::Folder)) + .variant(ButtonVariant::Ghost) + .tooltip(Tooltip::text("Choose folder")) + .on_click({ + let this = this.clone(); + move |_, window, cx| { + log_dropped(this.update(cx, |this, cx| { + this.choose_folder(window, cx) + })); + } + }), + ), + ), + ) + .child(grasp_servers_field(&grasp_state, &relay_input, cx)) + .when_some(error.clone(), |el, error| { + el.child( + div() + .text_sm() + .text_color(cx.theme().ramps.destructive.base) + .child(error), + ) + }) + .into_any_element() + } }) - .actions(move |_, cx| { - let busy = action_state.read(cx).busy; + .actions(move |_, _cx| { let this = this.clone(); - 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] + vec![ + Button::new("create-repository") + .label("Create repository") + .icon(Icon::named(IconRole::Plus)) + .loading(busy) + .disabled(busy) + .on_click(move |_, window, cx| { + log_dropped(this.update(cx, |this, cx| { + this.create(window, cx); + })); + }) + .into_any_element(), + ] }) } } -fn choose_folder(folder_input: &Entity, window: &mut Window, cx: &mut App) { - let store = SettingsStore::global(cx); +impl CreateRepoDialog { + /// Prompts for the repository's folder and remembers it as the default. + fn choose_folder(&mut self, window: &mut Window, cx: &mut Context) { + let store = SettingsStore::global(cx); - let prompt = cx.prompt_for_paths(PathPromptOptions { - files: false, - directories: true, - multiple: false, - prompt: Some("Choose folder".into()), - }); + let prompt = cx.prompt_for_paths(PathPromptOptions { + files: false, + directories: true, + multiple: false, + prompt: Some("Choose folder".into()), + }); - let handle = window.window_handle(); - let folder_input = folder_input.clone(); + let handle = window.window_handle(); + let folder_input = self.folder_input.clone(); - cx.spawn(async move |cx| { - if let Ok(Ok(Some(mut paths))) = prompt.await - && let Some(path) = paths.pop() - && let Err(error) = cx.update_window(handle, |_, window, cx| { - let text = path.to_string_lossy().to_string(); - store.update(cx, |store, cx| { - store.edit( - |settings| { - settings.create_repository.default_folder = Some(path.clone()); - }, - cx, - ); - }); - folder_input.update(cx, |input, cx| input.set_value(text, window, cx)); - }) - { - log::warn!("failed to apply selected folder: {error}"); - } - }) - .detach(); + self.folder_task = Some(cx.spawn(async move |_, cx| { + if let Ok(Ok(Some(mut paths))) = prompt.await + && let Some(path) = paths.pop() + && let Err(error) = cx.update_window(handle, |_, window, cx| { + let text = path.to_string_lossy().to_string(); + store.update(cx, |store, cx| { + store.edit( + |settings| { + settings.create_repository.default_folder = Some(path.clone()); + }, + cx, + ); + }); + folder_input.update(cx, |input, cx| { + input.set_value(text, window, cx); + }); + }) + { + log::warn!("failed to apply selected folder: {error}"); + } + })); + } } diff --git a/crates/signed_app/src/repo/dialogs/grasp_servers.rs b/crates/signed_app/src/repo/dialogs/grasp_servers.rs index bb8142a..dc713c5 100644 --- a/crates/signed_app/src/repo/dialogs/grasp_servers.rs +++ b/crates/signed_app/src/repo/dialogs/grasp_servers.rs @@ -13,7 +13,7 @@ use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; -use crate::shared::progress::error_row; +use crate::shared::labels::{RelayHostExt as _, ServerInputExt as _}; /// State of the grasp-server section of a publish dialog, so async results can be rendered. #[derive(Default)] @@ -37,6 +37,7 @@ impl GraspServersState { } else { settings.default_servers.clone() }; + Self { loading_servers: true, servers_enabled: false, @@ -138,7 +139,14 @@ pub fn grasp_servers_field( .child("Loading your grasp servers..."), ) }) - .when_some(error_row(&error, cx), |section, error| section.child(error)) + .when_some(error, |section, error| { + section.child( + div() + .text_sm() + .text_color(cx.theme().ramps.destructive.base) + .child(error), + ) + }) }) .into_any_element() } @@ -152,13 +160,14 @@ fn render_server_row(relay: &RelayUrl, state: Entity, cx: &Ap .child( h_flex() .flex_1() + .min_w_0() .h_8() .px_2() .bg(cx.theme().colors.muted) .text_color(cx.theme().colors.muted_foreground) .text_xs() .rounded(cx.theme().radius.control) - .child(server_host(&relay)), + .child(relay.host_label()), ) .child( Button::new(SharedString::from(format!("remove-relay:{relay}"))) @@ -187,7 +196,7 @@ fn add_relay( return; } - match normalize_server(&value) { + match value.normalize_server() { Some((_, relay)) => { state.update(cx, |state, cx| { state.error = None; @@ -196,7 +205,10 @@ fn add_relay( } cx.notify(); }); - input.update(cx, |input, cx| input.set_value("", window, cx)); + + input.update(cx, |input, cx| { + input.set_value("", window, cx); + }); } None => { state.update(cx, |state, cx| { @@ -220,7 +232,10 @@ pub fn load_user_grasp_servers( }; let Some(user) = user else { - state.update(cx, |state, _| state.loading_servers = false); + state.update(cx, |state, cx| { + state.loading_servers = false; + cx.notify(); + }); return Task::ready(()); }; @@ -248,21 +263,3 @@ pub fn load_user_grasp_servers( } }) } - -/// Normalize a user-typed grasp server, adding a `wss://` scheme when none is given. -pub fn normalize_server(input: &str) -> Option<(String, RelayUrl)> { - let text = if input.contains("://") { - input.to_owned() - } else { - format!("wss://{input}") - }; - RelayUrl::parse(&text).ok().map(|relay| (text, relay)) -} - -/// The host of a relay URL, which is what the server lists show; the scheme is implied. -pub fn server_host(relay: &RelayUrl) -> SharedString { - relay - .domain() - .map(SharedString::from) - .unwrap_or_else(|| SharedString::from(relay.to_string())) -} diff --git a/crates/signed_app/src/repo/dialogs/init.rs b/crates/signed_app/src/repo/dialogs/init.rs index fbe6100..5636964 100644 --- a/crates/signed_app/src/repo/dialogs/init.rs +++ b/crates/signed_app/src/repo/dialogs/init.rs @@ -2,17 +2,17 @@ use std::path::PathBuf; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, - SharedString, Styled as _, Task, WeakEntity, Window, div, px, + App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, + Styled as _, Task, WeakEntity, Window, div, px, }; use settings::SettingsStore; -use signed_core::RepoAddr; use signed_git::Repo; use signed_state::Backend; +use ui::button::Button; use ui::common::{ResultLogErr as _, v_flex}; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; -use ui::icons::IconRole; +use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState}; use ui::layout::h_flex; use ui::select::{Select, SelectOption}; @@ -20,9 +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, dialog_submit_button, error_row, push_steps_row, run_dialog_task_with, -}; +use crate::shared::log_dropped; pub struct InitRepoDialog { handle: DialogHandle, @@ -30,13 +28,20 @@ pub struct InitRepoDialog { name_input: Entity, desc_input: Entity, relay_input: Entity, - state: Entity, + busy: bool, + error: Option, grasp_state: Entity, branches: Vec, + /// `Select` options for `branches`, rebuilt when they load. + branch_options: Vec>, + /// The folder shown in the form, formatted once. + folder_label: SharedString, selected_branch: Option, view: WeakEntity, /// Held so the grasp-server load is cancelled when the dialog drops. task: Option>, + /// Holds the default-branch load so it is cancelled when the dialog drops. + branches_task: Option>, } impl InitRepoDialog { @@ -46,18 +51,15 @@ impl InitRepoDialog { window: &mut Window, cx: &mut App, ) -> Entity { + let settings = SettingsStore::global(cx); + let grasp_settings = settings.read(cx).settings().grasp_servers.clone(); + let grasp_state = cx.new(|_| GraspServersState::new_default(&grasp_settings)); + let local_path_label = local_path.display().to_string(); + let default_name = local_path .file_name() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_default(); - let grasp_settings = SettingsStore::global(cx) - .read(cx) - .settings() - .grasp_servers - .clone(); - - let state = cx.new(|_| DialogProgress::default()); - let grasp_state = cx.new(|_| GraspServersState::new_default(&grasp_settings)); let name_input = InputState::builder() .text(default_name) @@ -67,10 +69,12 @@ impl InitRepoDialog { let desc_input = InputState::builder().multiline().build(cx); let relay_input = InputState::new(cx); - let dialog = cx.new(|cx| { + cx.new(|cx| { cx.defer_in(window, move |this: &mut Self, window, cx| { let task = load_user_grasp_servers(this.grasp_state.clone(), window, cx); this.task = Some(task); + + this.load_branches(cx); }); Self { @@ -79,27 +83,29 @@ impl InitRepoDialog { name_input, desc_input, relay_input, - state, + busy: false, + error: None, grasp_state, branches: Vec::new(), + branch_options: Vec::new(), + folder_label: SharedString::from(local_path_label), selected_branch: None, view, task: None, + branches_task: None, } - }); - - load_branches(dialog.clone(), cx); - dialog + }) } fn init_repository(&mut self, window: &mut Window, cx: &mut Context) { - if self.state.read(cx).busy { + if self.busy { return; } let name = self.name_input.read(cx).value().trim().to_owned(); let description = self.desc_input.read(cx).value().trim().to_owned(); let servers = self.grasp_state.read(cx).grasp_servers.clone(); + let default_branch = self .selected_branch .as_ref() @@ -107,48 +113,39 @@ impl InitRepoDialog { .filter(|branch| !branch.is_empty()); if name.is_empty() { - self.state.update(cx, |state, cx| { - state.fail("Repository name is required"); - cx.notify(); - }); + self.error = Some("Repository name is required".into()); + cx.notify(); return; } + if servers.is_empty() { - self.state.update(cx, |state, cx| { - state.fail("Add at least one grasp server"); - cx.notify(); - }); + self.error = Some("Add at least one grasp server".into()); + cx.notify(); return; } let backend = Backend::global(cx); - let Some(user) = backend.read(cx).current_user() else { - self.state.update(cx, |state, cx| { - state.fail("Sign in to publish a repository"); - cx.notify(); - }); + let Some(_user) = backend.read(cx).current_user() else { + self.error = Some("Sign in to publish a repository".into()); + cx.notify(); return; }; - let addr = RepoAddr::new(user, RepoAddr::identifier_from_name(&name)); - self.state.update(cx, |state, cx| { - state.begin_push(addr, cx); - cx.notify(); - }); + self.busy = true; + self.error = None; + cx.notify(); let local_path = self.local_path.clone(); let task = backend.update(cx, |backend, cx| { backend.publish_local_repo(local_path, &name, &description, servers, default_branch, cx) }); - let state = self.state.clone(); + let view = self.view.clone(); let close = self.handle.clone(); let handle = window.window_handle(); - run_dialog_task_with( - task, - cx, - move |announcement, cx| { + self.task = Some(cx.spawn(async move |this, cx| match task.await { + Ok(announcement) => { cx.update_window(handle, |_, _window, cx| { close.close(cx); if let Some(view) = view.upgrade() { @@ -156,14 +153,54 @@ impl InitRepoDialog { } }) .log_err(); - }, - move |error, cx| { - state.update(cx, |state, cx| { - state.fail(error.to_string()); + } + Err(error) => { + log_dropped(this.update(cx, |this, cx| { + this.busy = false; + this.error = Some(error.to_string().into()); cx.notify(); - }); - }, - ); + })); + } + })); + } + + /// Lists the repository's branches for the default-branch selector. + fn load_branches(&mut self, cx: &mut Context) { + let local_path = self.local_path.clone(); + + self.branches_task = Some(cx.spawn(async move |this, cx| { + let loaded = cx + .background_spawn(async move { + let repo = Repo::open(&local_path)?; + let current: Option = repo.current_branch().map(Into::into); + Ok::<_, anyhow::Error>((repo.branches()?, current)) + }) + .await; + + let (branches, current) = match loaded { + Ok(loaded) => loaded, + Err(error) => { + log::warn!("failed to list branches for the default branch selector: {error}"); + let _ = this.update(cx, |this, cx| { + this.error = Some("Could not list the repository's branches".into()); + cx.notify(); + }); + return; + } + }; + + let _ = this.update(cx, |this, cx| { + this.branches = branches.into_iter().map(Into::into).collect(); + this.branch_options = this + .branches + .iter() + .cloned() + .map(|branch| SelectOption::new(branch.clone(), branch)) + .collect(); + this.selected_branch = current; + cx.notify(); + }); + })); } } @@ -172,14 +209,14 @@ impl Render for InitRepoDialog { let name_input = self.name_input.clone(); let desc_input = self.desc_input.clone(); let relay_input = self.relay_input.clone(); - let state = self.state.clone(); + let error = self.error.clone(); let grasp_state = self.grasp_state.clone(); - let action_state = state.clone(); - let this = cx.entity().downgrade(); - let folder = self.local_path.display().to_string(); - let branches = self.branches.clone(); + let folder = self.folder_label.clone(); + let branch_options = self.branch_options.clone(); let selected_branch = self.selected_branch.clone(); - let busy = state.read(cx).busy; + let busy = self.busy; + + let this = cx.weak_entity(); Dialog::new("init-repo-dialog") .handle(self.handle.clone()) @@ -188,8 +225,6 @@ impl Render for InitRepoDialog { .min_width(px(520.)) .title("Initialize repository") .content(move |_, cx| { - let progress = state.read(cx); - v_flex() .gap_3() .child( @@ -220,7 +255,9 @@ impl Render for InitRepoDialog { .text_sm() .text_color(cx.theme().colors.muted_foreground) .rounded(cx.theme().radius.control) - .child(folder.clone()), + .child( + div().flex_1().min_w_0().truncate().child(folder.clone()), + ), ), ) .child( @@ -228,77 +265,38 @@ impl Render for InitRepoDialog { .description("The local branch to announce as the default") .child( Select::new("init-branch-select") - .options( - branches - .iter() - .cloned() - .map(|branch| SelectOption::new(branch.clone(), branch)) - .collect::>(), - ) + .options(branch_options.clone()) .selected(selected_branch.clone()) .placeholder("Select branch"), ), ) .child(grasp_servers_field(&grasp_state, &relay_input, cx)) - .when_some(push_steps_row(&progress.push_steps, cx), |el, steps| { - el.child(steps) + .when_some(error.clone(), |el, error| { + el.child( + div() + .text_sm() + .text_color(cx.theme().ramps.destructive.base) + .child(error), + ) }) - .when_some(error_row(&progress.error, cx), |el, error| el.child(error)) .into_any_element() }) - .actions(move |_, cx| { - let busy = action_state.read(cx).busy; + .actions(move |_, _cx| { let this = this.clone(); - 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] + vec![ + Button::new("initialize-repository") + .label("Initialize") + .icon(Icon::named(IconRole::Plus)) + .loading(busy) + .disabled(busy) + .on_click(move |_, window, cx| { + log_dropped(this.update(cx, |this, cx| { + this.init_repository(window, cx); + })); + }) + .into_any_element(), + ] }) } } - -fn load_branches(dialog: Entity, cx: &mut App) { - let local_path = dialog.read(cx).local_path.clone(); - - cx.spawn(async move |cx| { - let loaded = cx - .background_spawn(async move { - let repo = Repo::open(&local_path)?; - let current: Option = repo.current_branch().map(Into::into); - Ok::<_, anyhow::Error>((repo.branches()?, current)) - }) - .await; - - let (branches, current) = match loaded { - Ok(loaded) => loaded, - Err(error) => { - log::warn!("failed to list branches for the default branch selector: {error}"); - dialog.update(cx, |dialog, cx| { - dialog.state.update(cx, |state, cx| { - state.fail("Could not list the repository's branches"); - cx.notify(); - }); - }); - return; - } - }; - - dialog.update(cx, |dialog, cx| { - dialog.branches = branches.into_iter().map(Into::into).collect(); - dialog.selected_branch = current; - cx.notify(); - }); - }) - .detach(); -} diff --git a/crates/signed_app/src/repo/dialogs/mod.rs b/crates/signed_app/src/repo/dialogs/mod.rs index 22e9ea5..04b279f 100644 --- a/crates/signed_app/src/repo/dialogs/mod.rs +++ b/crates/signed_app/src/repo/dialogs/mod.rs @@ -5,8 +5,8 @@ pub mod init; pub mod reset; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, - SharedString, Styled as _, WeakEntity, Window, div, + App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, + Styled as _, WeakEntity, Window, div, }; use ui::button::{Button, ButtonVariant}; use ui::dialog::{Dialog, DialogHandle}; @@ -96,25 +96,25 @@ impl Render for DeleteRepositoryDialog { .actions(move |_, _| { let cancel_close = cancel_close.clone(); let confirm_close = confirm_close.clone(); - let cancel: AnyElement = Button::new("cancel-delete") - .label("Cancel") - .variant(ButtonVariant::Secondary) - .on_click(move |_, _, cx| cancel_close.close(cx)) - .into_any_element(); - let delete: AnyElement = Button::new("confirm-delete") - .label("Delete") - .variant(ButtonVariant::Destructive) - .on_click({ - let view = view.clone(); - move |_, _, cx| { - confirm_close.close(cx); - log_dropped(view.update(cx, |this, cx| this.delete_repository(cx))); - } - }) - .into_any_element(); - - vec![cancel, delete] + vec![ + Button::new("cancel-delete") + .label("Cancel") + .variant(ButtonVariant::Secondary) + .on_click(move |_, _, cx| cancel_close.close(cx)) + .into_any_element(), + Button::new("confirm-delete") + .label("Delete") + .variant(ButtonVariant::Destructive) + .on_click({ + let view = view.clone(); + move |_, _, cx| { + confirm_close.close(cx); + log_dropped(view.update(cx, |this, cx| this.delete_repository(cx))); + } + }) + .into_any_element(), + ] }) } } diff --git a/crates/signed_app/src/repo/dialogs/reset.rs b/crates/signed_app/src/repo/dialogs/reset.rs index e7a5979..e67dd4e 100644 --- a/crates/signed_app/src/repo/dialogs/reset.rs +++ b/crates/signed_app/src/repo/dialogs/reset.rs @@ -1,7 +1,11 @@ +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + use gpui::prelude::FluentBuilder as _; use gpui::{ - App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, - Window, div, px, + App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, + Styled as _, Task, Window, div, px, }; use signed_state::RepoStore; use ui::button::{Button, ButtonVariant}; @@ -9,15 +13,17 @@ use ui::common::{ResultLogErr as _, v_flex}; use ui::dialog::{Dialog, DialogHandle}; use ui::theme::ActiveTheme as _; -use crate::shared::progress::{DialogProgress, error_row}; +use crate::shared::log_dropped; pub struct ResetRemoteDialog { handle: DialogHandle, store: Entity, - deleted: Vec, + deleted: Arc<[SharedString]>, /// Servers that could not be listed, so their refs are missing from `deleted`. - unreachable: Vec, - state: Entity, + unreachable: Arc<[SharedString]>, + busy: bool, + error: Option, + task: Rc>>>, } impl ResetRemoteDialog { @@ -27,13 +33,14 @@ impl ResetRemoteDialog { unreachable: Vec, cx: &mut App, ) -> Entity { - let state = cx.new(|_| DialogProgress::default()); cx.new(|_| Self { handle: DialogHandle::new(true), store, - deleted, - unreachable, - state, + deleted: deleted.into_iter().map(SharedString::from).collect(), + unreachable: unreachable.into_iter().map(SharedString::from).collect(), + busy: false, + error: None, + task: Rc::new(RefCell::new(None)), }) } } @@ -43,15 +50,18 @@ impl Render for ResetRemoteDialog { const WARNING: &str = "Grasp servers are overwritten to match the local mirror. Refs that do not exist locally are deleted from the servers. This cannot be undone."; const ERROR: &str = "Could not reach some grasp servers, their refs are not listed:"; - let deleted = self.deleted.clone(); - let unreachable = self.unreachable.clone(); + let deleted = Arc::clone(&self.deleted); + let unreachable = Arc::clone(&self.unreachable); + let action_unreachable = unreachable.clone(); let store = self.store.clone(); let cancel_close = self.handle.clone(); let confirm_close = self.handle.clone(); - let content_state = self.state.clone(); - let action_state = self.state.clone(); - let busy = self.state.read(cx).busy; + let confirm_task = self.task.clone(); + let busy = self.busy; + let error = self.error.clone(); + + let this = cx.weak_entity(); Dialog::new("reset-remote-dialog") .handle(self.handle.clone()) @@ -60,8 +70,6 @@ impl Render for ResetRemoteDialog { .min_width(px(480.)) .title("Reset remote to local") .content(move |_, cx| { - let progress = content_state.read(cx); - v_flex() .gap_2() .child( @@ -84,68 +92,98 @@ impl Render for ResetRemoteDialog { .child(url.clone()) })) }) - .child(if deleted.is_empty() { - div() - .text_sm() - .text_color(cx.theme().colors.muted_foreground) - .child("No server refs will be deleted.") - .into_any_element() - } else { - v_flex() - .gap_1() - .children(deleted.iter().map(|name| { + .map(|this| { + if deleted.is_empty() { + this.child( + div() + .text_sm() + .text_color(cx.theme().colors.muted_foreground) + .child("No server refs will be deleted."), + ) + } else { + this.child(v_flex().gap_1().children(deleted.iter().map(|name| { div() .text_sm() .font_family(cx.theme().mono_font) .child(name.clone()) - })) - .into_any_element() + }))) + } + }) + .when_some(error.clone(), |el, error| { + el.child( + div() + .text_sm() + .text_color(cx.theme().ramps.destructive.base) + .child(error), + ) }) - .when_some(error_row(&progress.error, cx), |el, error| el.child(error)) .into_any_element() }) - .actions(move |_, cx| { - let busy = action_state.read(cx).busy; + .actions(move |_, _cx| { let store = store.clone(); let cancel_close = cancel_close.clone(); let confirm_close = confirm_close.clone(); - let confirm_state = action_state.clone(); - - let cancel = Button::new("cancel-reset-remote") - .label("Cancel") - .variant(ButtonVariant::Secondary) - .disabled(busy) - .on_click(move |_, _, cx| cancel_close.close(cx)) - .into_any_element(); + let confirm_task = confirm_task.clone(); + let action_this = this.clone(); let confirm = Button::new("confirm-reset-remote") .label("Reset remote") .variant(ButtonVariant::Destructive) .loading(busy) .disabled(busy || !action_unreachable.is_empty()) - .on_click(move |_, window, cx| { - let task = store.update(cx, |store, cx| store.reset_repository(cx)); - let state = confirm_state.clone(); - let close = confirm_close.clone(); - let handle = window.window_handle(); + .on_click({ + let this = action_this.clone(); + move |_, window, cx| { + if busy { + return; + } - cx.spawn(async move |cx| match task.await { - Ok(()) => { - cx.update_window(handle, |_, _, cx| close.close(cx)) - .log_err(); - } - Err(error) => { - state.update(cx, |state, cx| { - state.fail(error.to_string()); - cx.notify(); - }); - } - }) - .detach(); + log_dropped(this.update(cx, |this, cx| { + this.busy = true; + this.error = None; + cx.notify(); + })); + + let task = store.update(cx, |store, cx| store.reset_repository(cx)); + let close = confirm_close.clone(); + let handle = window.window_handle(); + let task_this = this.clone(); + + let spawned = cx.spawn(async move |cx| match task.await { + Ok(()) => { + cx.update_window(handle, |_, _, cx| close.close(cx)) + .log_err(); + task_this + .update(cx, |this, cx| { + this.busy = false; + cx.notify(); + }) + .log_err(); + } + Err(error) => { + task_this + .update(cx, |this, cx| { + this.busy = false; + this.error = Some(error.to_string().into()); + cx.notify(); + }) + .log_err(); + } + }); + *confirm_task.borrow_mut() = Some(spawned); + } }) .into_any_element(); - vec![cancel, confirm] + vec![ + Button::new("cancel-reset-remote") + .label("Cancel") + .variant(ButtonVariant::Secondary) + .disabled(busy) + .on_click(move |_, _, cx| cancel_close.close(cx)) + .into_any_element(), + confirm, + ] }) } } diff --git a/crates/signed_app/src/repo/files.rs b/crates/signed_app/src/repo/files.rs index 5a6f944..c074202 100644 --- a/crates/signed_app/src/repo/files.rs +++ b/crates/signed_app/src/repo/files.rs @@ -6,20 +6,19 @@ use anyhow::Error; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, EventEmitter, IntoElement, - ParentElement as _, Render, SharedString, StyleRefinement, Styled as _, Task, WeakEntity, - Window, div, px, + ParentElement as _, Render, SharedString, StyleRefinement, Styled as _, Task, Window, div, px, }; use signed_git::{FileCommit, Repo, WorktreeSnapshot}; use ui::code::CodeViewState; use ui::common::{StyledExt as _, h_flex, v_flex}; use ui::empty_state::EmptyState; +use ui::highlight::Language; use ui::markdown::MarkdownViewState; use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; use ui::tree::{Tree, TreeItem, TreeItemSeed}; -use super::helpers::{code_language, is_markdown_path, source_hash}; -use crate::repo::helpers::short_id; +use crate::shared::labels::{ShortIdExt as _, StrExt as _}; const MAX_PREVIEW_BYTES: usize = 1024 * 1024; const MAX_PREVIEWED_FILES: usize = 32; @@ -163,8 +162,8 @@ impl RepoFilesView { /// Point the README pane at `path`/`bytes`, or clear it when absent. pub fn set_readme( &mut self, - path: Option, - bytes: Option>, + path: Option<&Path>, + bytes: Option<&[u8]>, cx: &mut Context, ) -> bool { let Some((path, bytes)) = path.zip(bytes) else { @@ -179,8 +178,8 @@ impl RepoFilesView { self.readme_name = Some(name); self.load_commit(&path.to_string_lossy(), cx); - if let Ok(text) = String::from_utf8(bytes) { - changed |= self.set_markdown(None, &text, cx); + if let Ok(text) = std::str::from_utf8(bytes) { + changed |= self.set_markdown(None, text, cx); } changed @@ -246,7 +245,11 @@ impl RepoFilesView { } if self.selected_file.is_none() { - changed |= self.set_readme(snapshot.readme_path.clone(), snapshot.readme.clone(), cx); + changed |= self.set_readme( + snapshot.readme_path.as_deref(), + snapshot.readme.as_deref(), + cx, + ); } changed @@ -276,69 +279,12 @@ impl RepoFilesView { cx.notify(); } - pub fn render_tree(&self, view: WeakEntity) -> AnyElement { - let rows = Arc::clone(&self.rows); - let selected = self.selected_index; - let change_view = view.clone(); - let disclosure_view = view; - - Tree::new("repo-tree") - .pr_2() - .selected(selected) - .items(move |_, _| Arc::clone(&rows)) - .on_change({ - let view = change_view; - move |index, window, cx| { - if let Some(index) = index - && let Err(error) = view.update(cx, |this, cx| { - this.activate_row(index, window, cx); - }) - { - log::warn!("failed to activate tree row: {error}"); - } - } - }) - .on_disclosure({ - let view = disclosure_view; - move |index, _, cx| { - if let Err(error) = view.update(cx, |this, cx| { - let id = this.rows.get(index).map(|row| row.key().to_string()); - if let Some(id) = id { - this.toggle_folder(&id); - cx.emit(RepoFilesEvent::Activated); - cx.notify(); - } - }) { - log::warn!("failed to toggle folder: {error}"); - } - } - }) - .into_any_element() - } - pub fn render_content(&self, cx: &App) -> AnyElement { + const BINARY: &str = "Binary file - preview not supported"; + const TOO_LARGE: &str = "File is too large to preview"; + const NO_README: &str = "No README found"; + let pane_title = self.pane_title(); - let body: AnyElement = if let Some(path) = self.selected_file.clone() { - match self.files.get(path.as_ref()) { - Some(FileContent::Text(_)) => { - if is_markdown_path(path.as_ref()) { - self.markdown_element(Some(path.as_ref())) - } else { - self.code_element(path.as_ref()) - } - } - Some(FileContent::Binary) => { - 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 { - EmptyState::centered("No README found") - }; let commit = match &self.selected_file { Some(path) => self.commits.get(path.as_ref()), @@ -366,8 +312,7 @@ impl RepoFilesView { .min_w_0() .text_xs() .font_medium() - .text_ellipsis() - .whitespace_nowrap() + .truncate() .child(pane_title), ) .when_some(commit, |this, commit| { @@ -379,20 +324,50 @@ impl RepoFilesView { div() .text_xs() .font_family(cx.theme().mono_font) - .child(short_id(&commit.id)), + .child(commit.id.short_id()), ) .child( div() .max_w(px(250.)) + .min_w_0() .text_xs() - .text_ellipsis() - .whitespace_nowrap() + .truncate() .child(commit.summary.clone()), ), ) }), ) - .child(div().flex_1().min_h_0().child(body)) + .child( + div() + .flex_1() + .min_h_0() + .when_some(self.selected_file.clone(), |this, path| { + this.child(match self.files.get(path.as_ref()) { + Some(FileContent::Text(_)) if path.as_ref().is_markdown_path() => { + self.markdown_element(Some(path.as_ref())) + } + Some(FileContent::Text(_)) => self.code_element(path.as_ref()), + Some(FileContent::Binary) => { + EmptyState::centered(BINARY).into_any_element() + } + Some(FileContent::TooLarge) => { + EmptyState::centered(TOO_LARGE).into_any_element() + } + Some(FileContent::Failed(message)) => { + EmptyState::centered(message).into_any_element() + } + None => Spinner::centered("repo-preview-spinner").into_any_element(), + }) + }) + .when( + self.selected_file.is_none() && self.readme_name.is_some(), + |this| this.child(self.markdown_element(None)), + ) + .when( + self.selected_file.is_none() && self.readme_name.is_none(), + |this| this.child(EmptyState::centered(NO_README)), + ), + ) .into_any_element() } @@ -402,7 +377,7 @@ impl RepoFilesView { text: &str, cx: &mut Context, ) -> bool { - let hash = source_hash(text); + let hash = text.source_hash(); if let Some(md) = &self.md && md.path == path @@ -425,7 +400,7 @@ impl RepoFilesView { return true; } - let state = cx.new(|_| MarkdownViewState::new("repo-readme", text)); + let state = cx.new(|cx| MarkdownViewState::new("repo-readme", text, cx)); self.md = Some(MarkdownView { path, state, @@ -437,7 +412,7 @@ impl RepoFilesView { fn markdown_element(&self, path: Option<&str>) -> AnyElement { let Some(md) = &self.md else { - return Spinner::centered("repo-preview-spinner"); + return Spinner::centered("repo-preview-spinner").into_any_element(); }; let ready = match path { @@ -446,7 +421,7 @@ impl RepoFilesView { }; if !ready { - return Spinner::centered("repo-preview-spinner"); + return Spinner::centered("repo-preview-spinner").into_any_element(); } div() @@ -462,8 +437,8 @@ impl RepoFilesView { } fn set_code(&mut self, path: SharedString, text: &str, cx: &mut Context) { - let hash = source_hash(text); - let language = code_language(path.as_ref()); + let hash = text.source_hash(); + let language = Language::from_path(path.as_ref()); if let Some(code) = &self.code && code.path == path @@ -496,10 +471,11 @@ impl RepoFilesView { fn code_element(&self, path: &str) -> AnyElement { let Some(code) = &self.code else { - return Spinner::centered("repo-preview-spinner"); + return Spinner::centered("repo-preview-spinner").into_any_element(); }; + if code.path.as_ref() != path { - return Spinner::centered("repo-preview-spinner"); + return Spinner::centered("repo-preview-spinner").into_any_element(); } div() @@ -513,19 +489,14 @@ impl RepoFilesView { .into_any_element() } - /// Reaps finished tasks, then queues another. - fn push_task(&mut self, task: Task>) { - self.tasks.retain(|task| !task.is_ready()); - self.tasks.push(task); - } - fn open_file(&mut self, path: &str, window: &mut Window, cx: &mut Context) { self.selected_file = Some(path.into()); if self.files.contains_key(path) { if let Some(FileContent::Text(text)) = self.files.get(path) { let text = text.clone(); - if is_markdown_path(path) { + + if path.is_markdown_path() { if self.md.as_ref().map(|md| md.path.as_deref()) != Some(Some(path)) { self.set_markdown(Some(path.into()), &text, cx); } @@ -533,11 +504,10 @@ impl RepoFilesView { self.set_code(path.into(), &text, cx); } } - cx.notify(); return; } + if self.loading_files.contains(path) { - cx.notify(); return; } @@ -617,7 +587,7 @@ impl RepoFilesView { match content { Ok(kind) => { if let FileContent::Text(text) = &kind { - if is_markdown_path(&path) { + if path.is_markdown_path() { let same = this.md.as_ref().map(|md| md.path.as_deref()) == Some(Some(path.as_str())); if !same { @@ -641,13 +611,14 @@ impl RepoFilesView { .insert(path, FileContent::Failed(error.to_string())); } } + cx.notify(); })?; Ok(()) }); - self.push_task(task); + self.tasks.push(task); } fn drop_preview_of(&mut self, path: &str) { @@ -660,9 +631,11 @@ impl RepoFilesView { if self.selected_file.as_deref() == Some(path) { self.selected_file = None; } + if self.md.as_ref().and_then(|md| md.path.as_deref()) == Some(path) { self.md = None; } + if self.code.as_ref().map(|code| code.path.as_ref()) == Some(path) { self.code = None; } @@ -685,9 +658,11 @@ impl RepoFilesView { if let Some(FileContent::Text(text)) = self.files.remove(&path) { self.preview_bytes -= text.len(); } + if self.md.as_ref().and_then(|md| md.path.as_deref()) == Some(path.as_str()) { self.md = None; } + if self .code .as_ref() @@ -766,12 +741,31 @@ impl RepoFilesView { Ok(()) }); - self.push_task(task); + self.tasks.push(task); } } impl Render for RepoFilesView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - self.render_tree(cx.entity().downgrade()) + let rows = Arc::clone(&self.rows); + let selected = self.selected_index; + + Tree::new("repo-tree") + .pr_2() + .selected(selected) + .items(move |_, _| Arc::clone(&rows)) + .on_change(cx.processor(|this, index: Option, window, cx| { + if let Some(index) = index { + this.activate_row(index, window, cx); + } + })) + .on_disclosure(cx.processor(|this, index: usize, _window, cx| { + 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); + cx.notify(); + } + })) } } diff --git a/crates/signed_app/src/repo/helpers.rs b/crates/signed_app/src/repo/helpers.rs index 8662035..ca73c65 100644 --- a/crates/signed_app/src/repo/helpers.rs +++ b/crates/signed_app/src/repo/helpers.rs @@ -1,78 +1,13 @@ use std::path::{Path, PathBuf}; use anyhow::Error; -use gpui::prelude::FluentBuilder as _; -use gpui::{ - AnyElement, App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, - SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, px, -}; -use metadata::ProfileDirectory; -use nostr::prelude::{RelayUrl, ToBech32}; -use signed_core::{Announcement, RepoAddr}; -use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo, WorktreeSnapshot}; -use signed_state::{Nip34Binding, RepoListStore, RepoStore}; -use ui::avatar::Avatar; +use gpui::{Div, ParentElement as _, SharedString, Styled as _, div}; +use signed_git::{FileCommit, Repo, WorktreeSnapshot}; 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 ui::common::{StyledExt as _, v_flex}; use ui::tree::TreeItemSeed; -use super::RepoDetailView; - -const GUTTER_WIDTH: f32 = 44.; -pub const DIFF_ROW_HEIGHT: f32 = 20.; - -#[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(), - } - } - } - } -} - +/// The worktree-derived data the repository panel is built from. pub(super) struct RepoData { pub(super) tree: Vec, pub(super) entries: Vec, @@ -85,6 +20,37 @@ pub(super) struct RepoData { pub(super) head_commit: Option, } +impl RepoData { + /// Snapshots the repository and derives the explorer's tree rows. + pub(super) fn load(repo: &Repo) -> Result { + let snapshot = repo.snapshot()?; + let worktree = repo.workdir().map(Path::to_path_buf); + let tree = TreeItemSeed::from_paths(&snapshot.entries); + + Ok(Self { + tree, + entries: snapshot.entries, + readme_path: snapshot.readme_path, + readme: snapshot.readme, + worktree, + branches: snapshot.branches, + tags: snapshot.tags, + current_branch: snapshot.current_branch, + head_commit: snapshot.head_commit, + }) + } + + /// Snapshots the worktree and derives the explorer's tree rows and paths. + pub(super) fn snapshot( + worktree: PathBuf, + ) -> Result<(WorktreeSnapshot, Vec, Vec), Error> { + let snapshot = Repo::open(&worktree)?.snapshot()?; + let tree = TreeItemSeed::from_paths(&snapshot.entries); + let paths = CommitTree::sorted_paths(&snapshot.entries); + Ok((snapshot, tree, paths)) + } +} + /// A commit's tree and README, as the file explorer shows them. pub(super) struct CommitTree { pub(super) tree: Vec, @@ -93,82 +59,37 @@ pub(super) struct CommitTree { pub(super) readme: 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 -} +impl CommitTree { + /// Sorted relative paths of a snapshot's entries. + pub(super) fn sorted_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 { - announcement - .name - .as_deref() - .map(SharedString::from) - .unwrap_or_else(|| SharedString::from(announcement.id.clone())) -} + /// Lists the tree and README of `commit` in the repository at `worktree`. + pub(super) fn snapshot(worktree: &Path, commit: &str) -> Result { + let repo = Repo::open_cached(worktree)?; + let entries = repo.entries_at(commit)?; + let readme_path = Repo::pick_readme(&entries); + let readme = match &readme_path { + Some(path) => repo.read_at(commit, path)?, + None => None, + }; -/// The first eight hex characters of an object id, for row labels. -pub fn short_id(hex: &str) -> SharedString { - SharedString::from(hex.get(..8).unwrap_or(hex).to_owned()) -} - -/// The co-author names credited in a commit body, deduplicated in order. -pub(super) fn co_authors(description: &str) -> Vec { - let mut names: Vec = Vec::new(); - for line in description.lines() { - let trimmed = line.trim(); - if !trimmed.to_lowercase().starts_with("co-authored-by:") { - continue; - } - let name = trimmed - .split_once(':') - .map(|(_, value)| value.trim()) - .unwrap_or_default() - .split('<') - .next() - .unwrap_or_default() - .trim(); - if !name.is_empty() && !names.iter().any(|existing| existing.as_ref() == name) { - names.push(SharedString::from(name.to_owned())); - } + Ok(Self { + tree: TreeItemSeed::from_paths(&entries), + paths: Self::sorted_paths(&entries), + readme_path, + readme, + }) } - names } -/// Snapshots the worktree and derives the explorer's tree rows and paths. -pub(super) fn snapshot_worktree( - worktree: PathBuf, -) -> Result<(WorktreeSnapshot, Vec, Vec), Error> { - let snapshot = Repo::open(&worktree)?.snapshot()?; - let tree = TreeItemSeed::from_paths(&snapshot.entries); - let paths = sorted_worktree_paths(&snapshot.entries); - Ok((snapshot, tree, paths)) -} - -/// Lists the tree and README of `commit` in the repository at `worktree`. -pub(super) fn snapshot_commit(worktree: &Path, commit: &str) -> Result { - let repo = Repo::open_cached(worktree)?; - let entries = repo.entries_at(commit)?; - let readme_path = Repo::pick_readme(&entries); - let readme = match &readme_path { - Some(path) => repo.read_at(commit, path)?, - None => None, - }; - - Ok(CommitTree { - tree: TreeItemSeed::from_paths(&entries), - paths: sorted_worktree_paths(&entries), - readme_path, - readme, - }) -} - -pub(super) fn clone_group(label: &str, id: SharedString, command: &SharedString) -> AnyElement { +pub(super) fn clone_group(label: &str, id: SharedString, command: &SharedString) -> Div { v_flex() .gap_1() .min_w_0() @@ -179,300 +100,4 @@ pub(super) fn clone_group(label: &str, id: SharedString, command: &SharedString) .child(SharedString::from(label)), ) .child(CopyRow::new(id, command.clone())) - .into_any_element() -} - -pub(super) fn nostr_clone_url(announcement: &Announcement, nip05: Option<&str>) -> SharedString { - let owner = announcement.owner; - let user = nip05 - .map(str::to_owned) - .unwrap_or_else(|| owner.to_bech32().unwrap_or_else(|_| owner.to_string())); - - let mut url = format!("nostr://{user}"); - if let Some(hint) = announcement.relays.first().and_then(RelayUrl::domain) { - url.push('/'); - url.push_str(hint); - } - url.push('/'); - url.push_str(&announcement.id); - - SharedString::from(url) -} - -/// 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, -) -> Option { - let upstream = announcement.upstream.as_ref()?; - - let (label, clickable) = match &upstream.addr { - Some(addr) => { - 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), - }; - - let row = h_flex() - .gap_1() - .min_w_0() - .text_sm() - .text_color(cx.theme().colors.muted_foreground) - .child(Icon::named(IconRole::GitBranch).small()) - .child( - div() - .min_w_0() - .whitespace_nowrap() - .text_ellipsis() - .child(label), - ); - - Some(if clickable { - row.id("fork-upstream") - .cursor_pointer() - .on_click(cx.listener(|this, _, window, cx| this.open_upstream(window, cx))) - .into_any_element() - } else { - row.into_any_element() - }) -} - -pub(super) fn load_repo_data(repo: &Repo) -> Result { - let snapshot = repo.snapshot()?; - let worktree = repo.workdir().map(Path::to_path_buf); - let tree = TreeItemSeed::from_paths(&snapshot.entries); - - Ok(RepoData { - tree, - entries: snapshot.entries, - readme_path: snapshot.readme_path, - readme: snapshot.readme, - worktree, - branches: snapshot.branches, - tags: snapshot.tags, - current_branch: snapshot.current_branch, - head_commit: snapshot.head_commit, - }) -} - -/// The announcement's name or ID for announced repositories, the directory name for local ones. -pub fn repo_display_name(store: &RepoStore) -> SharedString { - if store.addr().is_none() { - return store - .path - .as_ref() - .map(|path| { - SharedString::from( - path.file_name() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_else(|| path.display().to_string()), - ) - }) - .unwrap_or_default(); - } - - store - .announcement - .as_ref() - .map(announcement_display_name) - .unwrap_or_default() -} - -/// The owner and identifier a local repository is already bound to. -pub(super) fn bound_repo_label( - binding: &Nip34Binding, - directory: &Entity, - cx: &App, -) -> AnyElement { - let profile = binding.owner.map(|pk| directory.read(cx).profile(&pk, cx)); - - h_flex() - .flex_shrink_0() - .gap_2() - .text_sm() - .child("Initialized by") - .text_color(cx.theme().colors.muted_foreground) - .when_some(profile, |this, profile| { - let name = profile.name(); - this.child( - h_flex() - .gap_1() - .text_color(cx.theme().colors.foreground) - .child( - Avatar::new(profile.public_key()) - .name(name.clone()) - .picture(profile.picture()) - .small(), - ) - .child(name), - ) - }) - .when_some(binding.identifier.as_deref(), |this, ident| { - this.child( - div() - .text_xs() - .font_medium() - .child(SharedString::from(format!("/{ident}"))), - ) - }) - .into_any_element() -} - -/// Computes a source hash from the given text. -pub(super) fn source_hash(text: &str) -> u64 { - use std::hash::{Hash, Hasher}; - - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - text.hash(&mut hasher); - hasher.finish() -} - -/// The kit grammar for a path; only four languages are supported. -pub(super) fn code_language(path: &str) -> ui::highlight::Language { - use ui::highlight::Language; - match Path::new(path) - .extension() - .and_then(|ext| ext.to_str()) - .map(|ext| ext.to_ascii_lowercase()) - .as_deref() - { - Some("rs") => Language::Rust, - Some("ts" | "mts" | "cts" | "tsx") => Language::TypeScript, - Some("js" | "mjs" | "cjs" | "jsx") => Language::JavaScript, - Some("py") => Language::Python, - _ => Language::Plain, - } -} - -/// Whether a file path has a markdown extension. -pub(super) fn is_markdown_path(path: &str) -> bool { - Path::new(path) - .extension() - .and_then(|ext| ext.to_str()) - .is_some_and(|ext| { - matches!( - ext.to_ascii_lowercase().as_str(), - "md" | "markdown" | "mdown" | "mkdn" - ) - }) -} - -pub(super) fn diff_rows(file: &FileDiff) -> Vec { - let mut rows = Vec::new(); - for (hunk_ix, hunk) in file.hunks.iter().enumerate() { - rows.push(DiffRow::Hunk { - old_start: hunk.old_start, - old_lines: hunk.old_lines, - new_start: hunk.new_start, - new_lines: hunk.new_lines, - }); - rows.extend((0..hunk.lines.len()).map(|line| DiffRow::Line { - hunk: hunk_ix, - line, - })); - } - rows -} - -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)), - DiffLineKind::Deletion => Some(cx.theme().ramps.destructive.base.opacity(0.2)), - DiffLineKind::Context => None, - }; - let gutter = cx.theme().colors.muted_foreground; - - h_flex() - .w_full() - .when(wrap, |row| row.min_h(px(DIFF_ROW_HEIGHT))) - .when(!wrap, |row| row.h(px(DIFF_ROW_HEIGHT))) - .font_family(cx.theme().mono_font) - .text_xs() - .when_some(bg, |this, bg| this.bg(bg)) - .child( - div() - .w(px(GUTTER_WIDTH)) - .flex_none() - .pr_2() - .text_right() - .text_color(gutter) - .child(line.old.map(|n| n.to_string()).unwrap_or_default()), - ) - .child( - div() - .w(px(GUTTER_WIDTH)) - .flex_none() - .pr_2() - .text_right() - .text_color(gutter) - .child(line.new.map(|n| n.to_string()).unwrap_or_default()), - ) - .child( - div() - .flex_1() - .min_w_0() - .text_color(cx.theme().colors.foreground) - .when(!wrap, |content| { - content.overflow_hidden().whitespace_nowrap() - }) - .child(line.text.clone()), - ) - .into_any_element() -} - -pub(super) fn sync_selector( - select: &Entity>, - cached: &mut Vec, - items: Vec, - selected: Option, - window: &mut Window, - cx: &mut App, -) -> bool { - let items_changed = *cached != items; - - let selection_changed = selected - .as_ref() - .is_some_and(|value| select.read(cx).selected() != Some(value)); - - if !items_changed && !selection_changed { - return false; - } - - select.update(cx, |state, cx| { - if items_changed { - state.set_options( - items - .iter() - .map(|item| (item.clone(), item.clone())) - .collect(), - cx, - ); - } - if let Some(value) = selected - && (items_changed || selection_changed) - { - state.set_selected_silent(Some(value), window, cx); - } - }); - *cached = items; - - true } diff --git a/crates/signed_app/src/repo/history.rs b/crates/signed_app/src/repo/history.rs index fb5429f..6900741 100644 --- a/crates/signed_app/src/repo/history.rs +++ b/crates/signed_app/src/repo/history.rs @@ -1,17 +1,18 @@ use std::path::{Path, PathBuf}; +use std::rc::Rc; use std::sync::Arc; use anyhow::Error; use gpui::prelude::FluentBuilder as _; use gpui::{ - App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, + App, AppContext as _, Context, ElementId, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Task, UniformListScrollHandle, WeakEntity, Window, div, uniform_list, }; use signed_git::{CommitList, FileCommit, Repo}; use signed_state::{Backend, RepoStore, SyncStatusDirectory}; use ui::alert::{Alert, AlertSeverity, AlertStyle}; -use ui::avatar::IdentityRow; +use ui::avatar::Avatar; use ui::button::{Button, ButtonVariant}; use ui::common::{Sizable as _, h_flex, v_flex}; use ui::empty_state::EmptyState; @@ -24,11 +25,24 @@ use ui::tooltip::Tooltip; use utils::relative_time_secs; use super::RepoDetailView; -use super::commit_diff::CommitDiffView; -use super::helpers::short_id; use crate::app::AppRoot; +use crate::shared::commit_diff::CommitDiffView; +use crate::shared::labels::ShortIdExt as _; use crate::shared::log_dropped; +/// One commit row, with its display strings built when the list loads. +struct HistoryRow { + commit: FileCommit, + /// The commit's hex id. + id: SharedString, + /// The abbreviated id shown on the browse button. + short: SharedString, + /// The browse button's element id. + browse: ElementId, + /// The row's age label. + age: SharedString, +} + pub struct RepoHistoryView { store: Entity, workspace: WeakEntity, @@ -39,6 +53,7 @@ pub struct RepoHistoryView { loading_all_commits: bool, /// The loaded commit list, shared with the render without a per-frame copy. commits: Arc>, + rows: Arc>, /// The last load failure, shown instead of the empty list. error: Option, scroll_handle: UniformListScrollHandle, @@ -62,6 +77,7 @@ impl RepoHistoryView { all_commits: None, loading_all_commits: false, commits: Arc::new(Vec::new()), + rows: Arc::new(Vec::new()), error: None, scroll_handle: UniformListScrollHandle::new(), load_task: None, @@ -92,13 +108,12 @@ impl RepoHistoryView { if self.loading_all_commits || self.all_commits.is_some() { return; } + self.loading_all_commits = true; let Some(worktree) = self.worktree.clone() else { return; }; - self.loading_all_commits = true; - let task: Task> = cx.spawn(async move |this, cx| { let result = cx .background_spawn(async move { @@ -110,6 +125,21 @@ impl RepoHistoryView { match result { Ok(list) => { this.commits = Arc::new(list.commits.clone()); + this.rows = Arc::new( + list.commits + .iter() + .map(|commit| HistoryRow { + id: SharedString::from(commit.id.clone()), + short: commit.id.short_id(), + browse: ElementId::from(( + ElementId::from("browse-commit"), + SharedString::from(commit.id.clone()), + )), + age: SharedString::from(relative_time_secs(commit.time)), + commit: commit.clone(), + }) + .collect(), + ); this.all_commits = Some(Arc::new(list)); this.error = None; } @@ -196,9 +226,10 @@ 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 { - Spinner::centered("commits-loading") + Spinner::centered("commits-loading").into_any_element() } else if let Some(error) = self.error.clone() { - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); + v_flex() .size_full() .items_center() @@ -220,19 +251,25 @@ impl Render for RepoHistoryView { ) .into_any_element() } else { - EmptyState::centered("Failed to load commits") + EmptyState::centered("Failed to load commits").into_any_element() }; }; if self.commits.is_empty() { - return EmptyState::centered("No commits found"); + return EmptyState::centered("No commits found").into_any_element(); } - let commits = Arc::clone(&self.commits); + let commits = Arc::clone(&self.rows); let shown = commits.len(); let total = list.total; - let view = cx.entity().downgrade(); + let open_commit = Rc::new(cx.processor(|this, commit_id: SharedString, window, cx| { + this.open_commit_diff(&commit_id, window, cx); + })); + + let browse_commit = Rc::new(cx.processor(|this, commit_id: SharedString, window, cx| { + this.browse_commit(&commit_id, window, cx); + })); let detail = self.detail.clone(); let backend = Backend::global(cx); @@ -277,15 +314,15 @@ impl Render for RepoHistoryView { let row_id = commit.id.clone(); let browse_id = commit.id.clone(); - let view = view.clone(); - let browse_view = view.clone(); + let open_commit = open_commit.clone(); + let browse_commit = browse_commit.clone(); let ahead = ahead .iter() .find(|(id, _)| id.starts_with(commit.id.as_str())); h_flex() - .id(commit.id.clone()) + .id(row_id.clone()) .px_4() .h_12() .w_full() @@ -294,23 +331,31 @@ impl Render for RepoHistoryView { .border_color(cx.theme().colors.border) .hover(|this| this.bg(cx.theme().colors.muted)) .child( - IdentityRow::new( - commit.author.clone(), - commit.author.clone(), - None, - ) - .small() - .truncate() - .gap_2() - .flex_none() - .w_40() - .text_xs() - .text_color(cx.theme().colors.muted_foreground), + h_flex() + .gap_2() + .flex_none() + .w_40() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child( + Avatar::new(commit.commit.author.clone()) + .name(commit.commit.author.clone()) + .small(), + ) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .child(commit.commit.author.clone()), + ), ) .child( h_flex().w_20().child( - Button::new(format!("browse-commit:{}", commit.id)) - .label(short_id(&commit.id)) + Button::new(commit.browse.clone()) + .label(commit.short.clone()) .variant(ButtonVariant::Ghost) .small() .tooltip(Tooltip::text( @@ -318,14 +363,11 @@ impl Render for RepoHistoryView { )) .on_click(move |_, window, cx| { cx.stop_propagation(); - log_dropped(browse_view.update( + browse_commit( + browse_id.clone(), + window, cx, - |this, cx| { - this.browse_commit( - &browse_id, window, cx, - ); - }, - )); + ); }), ), ) @@ -336,7 +378,7 @@ impl Render for RepoHistoryView { .text_ellipsis() .text_sm() .whitespace_nowrap() - .child(commit.summary.clone()), + .child(commit.commit.summary.clone()), ) .child( div() @@ -344,14 +386,16 @@ impl Render for RepoHistoryView { .text_xs() .text_color(cx.theme().colors.muted_foreground) .whitespace_nowrap() - .child(relative_time_secs(commit.time)), + .child(commit.age.clone()), ) .when_some(ahead, |row, (ahead_id, path)| { let path = path.clone(); let target = ahead_id.clone(); let detail = detail.clone(); - let tooltip = - format!("Sync up to {}", short_id(&commit.id)); + let tooltip = SharedString::from(format!( + "Sync up to {}", + commit.short + )); row.child( Button::new(("sync-commit", ix)) @@ -364,25 +408,22 @@ impl Render for RepoHistoryView { .tooltip(Tooltip::text(tooltip)) .on_click(move |_, window, cx| { cx.stop_propagation(); - if let Some(detail) = detail.upgrade() { - detail.update(cx, |this, cx| { + log_dropped(detail.update( + cx, + |this, cx| { this.sync_checkout_commit( path.clone(), target.clone(), window, cx, ); - }); - } + }, + )); }), ) }) .on_click(move |_, window, cx| { - if let Err(error) = view.update(cx, |this, cx| { - this.open_commit_diff(&row_id, window, cx); - }) { - log::warn!("failed to open commit diff: {error}"); - } + open_commit(row_id.clone(), window, cx); }) .into_any_element() }) diff --git a/crates/signed_app/src/repo/mod.rs b/crates/signed_app/src/repo/mod.rs index 886f981..0c2317d 100644 --- a/crates/signed_app/src/repo/mod.rs +++ b/crates/signed_app/src/repo/mod.rs @@ -5,9 +5,10 @@ use std::sync::Arc; use anyhow::Error; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, - ParentElement as _, PathPromptOptions, Render, SharedString, StyleRefinement, Styled as _, - Subscription, SystemNotification, Task, WeakEntity, Window, div, px, + AnyElement, App, AppContext as _, Context, Div, ElementId, Entity, InteractiveElement as _, + IntoElement, ParentElement as _, PathPromptOptions, Render, SharedString, Stateful, + StatefulInteractiveElement as _, StyleRefinement, Styled as _, Subscription, + SystemNotification, Task, WeakEntity, Window, div, px, }; use metadata::ProfileDirectory; use nostr::prelude::{PublicKey, Url}; @@ -15,7 +16,7 @@ use signed_core::{Announcement, RepoAddr}; use signed_git::{FileCommit, GitCache, Repo}; use signed_state::{ Backend, BackendEvent, LocalReposStore, Mirrors, Nip34Binding, Nip34Kind, PushStepStatus, - RefreshGate, RefreshRequest, RepoStore, SyncStatusDirectory, + RefreshGate, RefreshRequest, RepoListStore, RepoStore, SyncStatusDirectory, }; use ui::alert::{Alert, AlertSeverity}; use ui::avatar::Avatar; @@ -34,8 +35,6 @@ 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; pub mod helpers; @@ -43,20 +42,17 @@ pub mod history; pub mod refs; use files::RepoFilesView; -use helpers::{ - RepoData, announcement_display_name, bound_repo_label, clone_group, fork_row, load_repo_data, - nostr_clone_url, repo_display_name, snapshot_commit, snapshot_worktree, -}; +use helpers::{CommitTree, RepoData, clone_group}; use history::RepoHistoryView; use refs::RefSwitcher; use utils::relative_time_secs; -use crate::app::AppRoot; -use crate::issues::IssuesView; -use crate::pull_requests::PullRequestsView; +use crate::app::{AppRoot, RepoTabs}; use crate::repo::dialogs::DeleteRepositoryDialog; use crate::repo::dialogs::init::InitRepoDialog; -use crate::repo::helpers::{short_id, sorted_worktree_paths}; +use crate::shared::labels::{ + AnnouncementExt, AnnouncementsExt as _, RepoStoreExt as _, ShortIdExt as _, +}; use crate::shared::log_dropped; #[derive(Clone, Copy, PartialEq, Eq)] @@ -78,19 +74,43 @@ pub enum RefKind { /// The announcement and clone commands the repository header renders. struct AboutModel { announcement: Arc, - git_commands: Arc>, + /// The owner's nip05 at the time the clone URL was built. + nip05: Option, + ngit_command: SharedString, + nak_command: SharedString, + avatar_seed: SharedString, } impl AboutModel { - /// Rebuilds the model only when the store's announcement changed. - fn sync(header: &mut Option, store: &Entity, cx: &App) { + /// Rebuilds the model only when the announcement or the owner's nip05 changed. + fn sync(header: &mut Option, store: &Entity, nip05: Option<&str>, cx: &App) { let announcement = store.read(cx).announcement.as_ref(); - if header.as_ref().map(|header| header.announcement.as_ref()) == announcement { + let unchanged = match (header.as_ref(), announcement) { + (None, None) => true, + (Some(header), Some(announcement)) => { + header.announcement.as_ref() == announcement && header.nip05.as_deref() == nip05 + } + _ => false, + }; + + if unchanged { return; } - *header = announcement.map(|announcement| Self { - announcement: Arc::new(announcement.clone()), - git_commands: Arc::new(announcement.clone_urls()), + + *header = announcement.map(|announcement| { + let clone_url = announcement.clone_url(nip05); + let ngit_command = SharedString::from(format!("git clone {clone_url}")); + let nak_command = SharedString::from(format!("nak git clone {clone_url}")); + let avatar_seed = + SharedString::from(format!("{}:{}", announcement.owner, announcement.id)); + + Self { + announcement: Arc::new(announcement.clone()), + nip05: nip05.map(SharedString::from), + ngit_command, + nak_command, + avatar_seed, + } }); } } @@ -106,10 +126,11 @@ pub struct RepoDetailView { files: Entity, /// The commit history section. pub(super) history: Entity, - /// The issues list shown in the repository panel. - issues: Entity, - /// The pull request list shown in the repository panel. - pulls: Entity, + /// The issue and pull-request tab views shown in the repository panel. + tabs: RepoTabs, + /// The tab totals shown in the repository sidebar. + pub(crate) issue_count: usize, + pub(crate) pull_count: usize, /// The section selected in the repository sidebar. active_section: RepoSection, /// The checked-out worktree path. @@ -177,13 +198,12 @@ impl RepoDetailView { cx: &mut Context, ) -> Self { let backend = Backend::global(cx); - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); let sync_directory = SyncStatusDirectory::new(cx); let files = cx.new(RepoFilesView::new); - let issues = cx.new(|cx| IssuesView::new(workspace.clone(), store.clone(), cx)); - let pulls = cx.new(|cx| PullRequestsView::new(workspace.clone(), store.clone(), cx)); + let tabs = AppRoot::repo_tabs(&store, &workspace, cx); let refs = RefSwitcher::new(weak.clone(), window, cx); let history = cx.new(|_| { @@ -230,7 +250,7 @@ impl RepoDetailView { let store_for_attach = store.clone(); let mut header = None; - AboutModel::sync(&mut header, &store, cx); + AboutModel::sync(&mut header, &store, None, cx); cx.defer_in(window, move |this, window, cx| { this.attach_store(&store_for_attach, window, cx); @@ -244,8 +264,9 @@ impl RepoDetailView { repo_started: false, files, history, - issues, - pulls, + tabs, + issue_count: 0, + pull_count: 0, active_section: RepoSection::Files, worktree: None, loading: true, @@ -272,11 +293,15 @@ impl RepoDetailView { let path = self.store.read(cx).path.clone(); if let Some(path) = path { - LocalReposStore::global(cx).update(cx, |store, cx| store.remove(&path, cx)); + let store = LocalReposStore::global(cx); + store.update(cx, |store, cx| { + store.remove(&path, cx); + }); } - self.store - .update(cx, |store, cx| store.announce(announcement, cx)); + self.store.update(cx, |store, cx| { + store.announce(announcement, cx); + }); cx.notify(); } @@ -289,9 +314,10 @@ impl RepoDetailView { ) { self._subscriptions .push(cx.observe_in(store, window, |this, store, window, cx| { - AboutModel::sync(&mut this.header, &store, cx); + this.sync_header(cx); this.track_profiles(cx); this.track_sync_status(cx); + if !this.repo_started && store.read(cx).announcement.is_some() { this.load_repo(window, cx); } else if this.loading @@ -303,6 +329,7 @@ impl RepoDetailView { this.loading = false; this.error = Some("Repository announcement not found".into()); } + cx.notify(); })); } @@ -430,7 +457,7 @@ impl RepoDetailView { let data = cx .background_spawn(async move { let repo = Repo::open(&local_path)?; - load_repo_data(&repo) + RepoData::load(&repo) }) .await; @@ -446,7 +473,7 @@ impl RepoDetailView { Ok(()) }); - self.push_task(task); + self.tasks.push(task); return; } @@ -463,7 +490,7 @@ impl RepoDetailView { let addr = addr.clone(); cx.background_spawn(async move { match Mirrors::open(&addr)? { - Some(repo) => Ok(Some(load_repo_data(&repo)?)), + Some(repo) => Ok(Some(RepoData::load(&repo)?)), None => Ok(None), } }) @@ -480,7 +507,7 @@ impl RepoDetailView { let clone_urls = clone_urls.clone(); cx.background_spawn(async move { let repo = Mirrors::ensure(&addr, &clone_urls)?; - load_repo_data(&repo) + RepoData::load(&repo) }) .await } @@ -505,7 +532,7 @@ impl RepoDetailView { Ok(()) }); - self.push_task(task); + self.tasks.push(task); } /// Fetches the mirror and fast-forwards its branches, showing the caught-up state. @@ -548,6 +575,7 @@ impl RepoDetailView { if let Ok(Some((moved, snapshot))) = refresh { let branches: Vec = snapshot.branches.iter().map(Into::into).collect(); + let tags: Vec = snapshot.tags.iter().map(Into::into).collect(); let current_branch = snapshot.current_branch.clone(); let head_commit = snapshot.head_commit.clone(); @@ -558,10 +586,11 @@ impl RepoDetailView { window, cx, ); - let tags_changed = this.refs.set_tags(tags, window, cx); + let tags_changed = this.refs.set_tags(tags, window, cx); let new_head_commit = head_commit.as_ref().map(|c| &c.id); let current_head_commit = this.head_commit.as_ref().map(|c| &c.id); + head_changed = new_head_commit != current_head_commit; this.head_commit = head_commit; @@ -584,7 +613,7 @@ impl RepoDetailView { Ok(()) }); - self.push_task(task); + self.tasks.push(task); } fn apply_repo_data(&mut self, data: RepoData, window: &mut Window, cx: &mut Context) { @@ -613,8 +642,8 @@ impl RepoDetailView { self.files.update(cx, |files, cx| { files.set_worktree(worktree.clone()); files.pin_commit(None); - files.apply_entries(tree, sorted_worktree_paths(&entries), cx); - files.set_readme(readme_path, readme, cx); + files.apply_entries(tree, CommitTree::sorted_paths(&entries), cx); + files.set_readme(readme_path.as_deref(), readme.as_deref(), cx); }); let history_source = self.history_source(&worktree, cx); @@ -642,7 +671,7 @@ impl RepoDetailView { ) { self.active_section = RepoSection::Files; self.browsed_commit = Some(commit.clone()); - self.refs.show_commit(short_id(&commit.id), window, cx); + self.refs.show_commit(commit.id.short_id(), window, cx); cx.notify(); let loaded_id = commit.id.clone(); @@ -650,7 +679,7 @@ impl RepoDetailView { let task: Task> = cx.spawn_in(window, async move |this, cx| { let result = cx - .background_spawn(async move { snapshot_commit(&source, &loaded_id) }) + .background_spawn(async move { CommitTree::snapshot(&source, &loaded_id) }) .await; this.update_in(cx, |this, window, cx| { @@ -659,6 +688,7 @@ impl RepoDetailView { .browsed_commit .as_ref() .is_some_and(|current| current.id == commit.id); + if !current { return; } @@ -669,20 +699,21 @@ impl RepoDetailView { files.clear_previews(); files.apply_entries(tree.tree, tree.paths, cx); files.pin_commit(Some(commit)); - files.set_readme(tree.readme_path, tree.readme, cx); + files.set_readme(tree.readme_path.as_deref(), tree.readme.as_deref(), cx); }), Err(error) => { this.error = Some(error.to_string().into()); this.reload_worktree(window, cx); } } + cx.notify(); })?; Ok(()) }); - self.push_task(task); + self.tasks.push(task); } fn clone_to_folder(&mut self, window: &mut Window, cx: &mut Context) { @@ -692,6 +723,7 @@ impl RepoDetailView { let Some(announcement) = self.announcement(cx) else { return; }; + let addr = announcement.addr(); let name = announcement .name @@ -699,8 +731,8 @@ impl RepoDetailView { .map(|name| name.to_string()) .filter(|name| !name.trim().is_empty()) .unwrap_or_else(|| addr.identifier().to_owned()); - let name = GitCache::sanitize_path_component(&name); + let name = GitCache::sanitize_path_component(&name); if name.is_empty() { "repository".to_owned() } else { @@ -720,6 +752,7 @@ impl RepoDetailView { Ok(Ok(Some(mut paths))) => paths.pop(), _ => None, }; + let Some(folder) = picked else { return Ok(()); }; @@ -740,7 +773,7 @@ impl RepoDetailView { Ok(()) }); - self.push_task(task); + self.tasks.push(task); } fn switch_ref(&mut self, kind: RefKind, name: T, window: &mut Window, cx: &mut Context) @@ -754,6 +787,7 @@ impl RepoDetailView { let Some(worktree) = self.worktree.clone() else { return; }; + let name = name.into(); let browsing = self.browsed_commit.is_some(); self.refs.commit_label = None; @@ -778,7 +812,6 @@ impl RepoDetailView { } self.refs.switching_ref = true; - cx.notify(); let checkout_name = name.clone(); let task: Task> = cx.spawn_in(window, async move |this, cx| { @@ -788,8 +821,6 @@ impl RepoDetailView { // A failed checkout leaves HEAD alone; report the branch it is still on. let current = repo.as_ref().ok().and_then(|repo| repo.current_branch()); let checkout = match kind { - // Browsing a commit leaves HEAD alone, so picking its branch again only - // returns to the worktree. RefKind::Branch if browsing && current.as_deref() == Some(checkout_name.as_ref()) => { @@ -807,37 +838,35 @@ impl RepoDetailView { }) .await; - this.update_in(cx, |this, window, cx| { - match outcome { - Ok(_) => this.reload_worktree(window, cx), - Err((error, current)) => { - this.error = Some(format!("Failed to check out {name}: {error}").into()); - this.refs.switching_ref = false; + this.update_in(cx, |this, window, cx| match outcome { + Ok(_) => this.reload_worktree(window, cx), + Err((error, current)) => { + this.error = Some(format!("Failed to check out {name}: {error}").into()); + this.refs.switching_ref = false; - let detached = current.is_none(); - this.refs.restore_selection( - &this.refs.branch_select, - ¤t.map(Into::into), - window, - cx, - ); + let detached = current.is_none(); + this.refs.restore_selection( + &this.refs.branch_select, + ¤t.map(Into::into), + window, + cx, + ); - let tag = if detached { previous_tag } else { None }; - this.refs - .restore_selection(&this.refs.tag_select, &tag, window, cx); + let tag = if detached { previous_tag } else { None }; + this.refs + .restore_selection(&this.refs.tag_select, &tag, window, cx); - if browsing { - this.reload_worktree(window, cx); - } + if browsing { + this.reload_worktree(window, cx); } + cx.notify(); } - cx.notify(); })?; Ok(()) }); - self.push_task(task); + self.tasks.push(task); } /// Reloads the worktree, ending a browsed commit. @@ -850,7 +879,7 @@ impl RepoDetailView { let task: Task> = cx.spawn_in(window, async move |this, cx| { let result = cx - .background_spawn(async move { snapshot_worktree(worktree) }) + .background_spawn(async move { RepoData::snapshot(worktree) }) .await; this.update_in(cx, |this, window, cx| { @@ -869,7 +898,7 @@ impl RepoDetailView { files.set_worktree(displayed); files.clear_previews(); files.apply_entries(tree, paths, cx); - files.set_readme(readme_path, readme, cx); + files.set_readme(readme_path.as_deref(), readme.as_deref(), cx); }); this.refs.restore_selection( &this.refs.branch_select, @@ -885,16 +914,15 @@ impl RepoDetailView { this.files.update(cx, |files, cx| { files.apply_entries(Vec::new(), Vec::new(), cx); }); + cx.notify(); } } - - cx.notify(); })?; Ok(()) }); - self.push_task(task); + self.tasks.push(task); } /// Refresh the file explorer and previews after the mirror caught up with the remote. @@ -905,7 +933,7 @@ impl RepoDetailView { let task: Task> = cx.spawn(async move |this, cx| { let result = cx - .background_spawn(async move { snapshot_worktree(worktree) }) + .background_spawn(async move { RepoData::snapshot(worktree) }) .await; this.update(cx, |this, cx| match result { @@ -928,12 +956,6 @@ impl RepoDetailView { Ok(()) }); - self.push_task(task); - } - - /// Reaps finished tasks, then queues another. - fn push_task(&mut self, task: Task>) { - self.tasks.retain(|task| !task.is_ready()); self.tasks.push(task); } @@ -942,7 +964,7 @@ impl RepoDetailView { cx.notify(); let task = self.store.update(cx, |store, cx| store.push_repository(cx)); - self.push_task(task); + self.tasks.push(task); } fn sync_notification_tag(addr: &RepoAddr) -> SharedString { @@ -1012,7 +1034,7 @@ impl RepoDetailView { match result { Ok(()) => { if let Some(tag) = &tag { - let short = short_id(&commit); + let short = commit.short_id(); 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}")), @@ -1030,7 +1052,11 @@ impl RepoDetailView { if let Some(tag) = &tag { cx.dismiss_system_notification(tag.as_ref()).detach(); } - store.update(cx, |store, _| store.last_error = None); + + store.update(cx, |store, _| { + store.last_error = None; + }); + let dialog = dialogs::SyncErrorDialog::new(format!("{error:#}").into(), cx); cx.open_dialog(dialog); } @@ -1042,7 +1068,7 @@ impl RepoDetailView { Ok(()) }); - self.push_task(task); + self.tasks.push(task); } fn reset_remote(&mut self, window: &mut Window, cx: &mut Context) { @@ -1052,6 +1078,7 @@ impl RepoDetailView { let store = self.store.clone(); let mirror = Mirrors::path(&announcement.addr()); + let urls: Vec = announcement .clone .iter() @@ -1088,7 +1115,7 @@ impl RepoDetailView { Ok::<_, Error>((deleted, unreachable)) }); - cx.spawn_in(window, async move |this, cx| { + let task = cx.spawn_in(window, async move |this, cx| { let probe = probe.await; this.update_in(cx, |this, _window, cx| match probe { @@ -1104,8 +1131,9 @@ impl RepoDetailView { })?; Ok::<(), Error>(()) - }) - .detach(); + }); + + self.tasks.push(task); } /// Delete the repository from nostr, announcement, state and activity. @@ -1113,7 +1141,7 @@ impl RepoDetailView { let task = self .store .update(cx, |store, cx| store.delete_repository(cx)); - self.push_task(task); + self.tasks.push(task); } fn render_files_tab(&self, cx: &App) -> AnyElement { @@ -1123,6 +1151,7 @@ impl RepoDetailView { } else { "Cloning repository..." }; + return v_flex() .flex_1() .size_full() @@ -1146,32 +1175,30 @@ impl RepoDetailView { let files = self.files.clone(); let commit_count = self.history.read(cx).commit_count(); let include_issues = self.store.read(cx).addr().is_some(); - let issue_count = include_issues.then(|| self.issues.read(cx).total_count()); - let pull_count = include_issues.then(|| self.pulls.read(cx).total_count()); + let issue_count = include_issues.then_some(self.issue_count); + let pull_count = include_issues.then_some(self.pull_count); + let selected = match self.active_section { RepoSection::Commits => Some(0), RepoSection::Issues if include_issues => Some(1), RepoSection::PullRequests if include_issues => Some(2), _ => None, }; - let weak = cx.entity().downgrade(); Sidebar::new("repo-sidebar") .selected(selected) .border_right(true) .transparent(false) - .on_change(move |index, _, cx| { + .on_change(cx.processor(move |this, index: Option, _, cx| { let section = match (index, include_issues) { (Some(0), _) => RepoSection::Commits, (Some(1), true) => RepoSection::Issues, (Some(2), true) => RepoSection::PullRequests, _ => return, }; - log_dropped(weak.update(cx, |this, cx| { - this.active_section = section; - cx.notify(); - })); - }) + this.active_section = section; + cx.notify(); + })) .entries(move |_, _| { let mut entries = vec![ SidebarEntry::row("repo-nav-commits", "Commits") @@ -1216,11 +1243,90 @@ impl RepoDetailView { match self.active_section { RepoSection::Files => self.render_files_tab(cx), RepoSection::Commits => self.history.clone().into_any_element(), - RepoSection::Issues => self.issues.clone().into_any_element(), - RepoSection::PullRequests => self.pulls.clone().into_any_element(), + RepoSection::Issues => self.tabs.issues.clone().into_any_element(), + RepoSection::PullRequests => self.tabs.pulls.clone().into_any_element(), } } + /// The "forked from" row of the announcement, clickable when its upstream is announced here. + fn fork_row( + &self, + announcement: &Announcement, + cx: &mut Context, + ) -> Option> { + let upstream = announcement.upstream.as_ref()?; + + let (label, clickable) = match &upstream.addr { + Some(addr) => { + let name = RepoListStore::global(cx) + .read(cx) + .announcements + .as_slice() + .upstream_display_name(addr); + (SharedString::from(format!("Forked from {name}")), true) + } + None => (SharedString::from(upstream.display().as_str()), false), + }; + + Some( + h_flex() + .gap_1() + .min_w_0() + .text_sm() + .text_color(cx.theme().colors.muted_foreground) + .child(Icon::named(IconRole::GitBranch).small()) + .child( + div() + .min_w_0() + .whitespace_nowrap() + .text_ellipsis() + .child(label), + ) + .id("fork-upstream") + .when(clickable, |row| { + row.cursor_pointer() + .on_click(cx.listener(|this, _, window, cx| this.open_upstream(window, cx))) + }), + ) + } + + /// The owner and identifier a local repository is already bound to. + fn bound_repo_label(&self, binding: &Nip34Binding, cx: &App) -> Div { + let profile = binding + .owner + .map(|pk| self.directory.read(cx).profile(&pk, cx)); + + h_flex() + .flex_shrink_0() + .gap_2() + .text_sm() + .child("Initialized by") + .text_color(cx.theme().colors.muted_foreground) + .when_some(profile, |this, profile| { + let name = profile.name(); + this.child( + h_flex() + .gap_2() + .text_color(cx.theme().colors.foreground) + .child( + Avatar::new(profile.public_key()) + .name(name.clone()) + .picture(profile.picture()) + .small(), + ) + .child(name), + ) + }) + .when_some(binding.identifier.as_deref(), |this, ident| { + this.child( + div() + .text_xs() + .font_medium() + .child(SharedString::from(format!("/{ident}"))), + ) + }) + } + pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context) { let Some(addr) = self .announcement(cx) @@ -1229,17 +1335,27 @@ impl RepoDetailView { else { return; }; - actions::open_repo_panel(&self.workspace, &addr, None, window, cx); + + log_dropped(self.workspace.update(cx, |root, cx| { + root.open_repo_panel(&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; - }; - let view = cx.entity().downgrade(); - let dialog = InitRepoDialog::new(local_path, view, window, cx); - cx.open_dialog(dialog); + /// Rebuilds the header model when the announcement or the owner's nip05 changed. + fn sync_header(&mut self, cx: &App) { + let owner = self + .store + .read(cx) + .announcement + .as_ref() + .map(|announcement| announcement.owner); + + let nip05 = owner + .map(|owner| self.directory.read(cx).profile(&owner, cx)) + .and_then(|profile| profile.metadata().nip05.clone()) + .filter(|nip05| !nip05.trim().is_empty()); + + AboutModel::sync(&mut self.header, &self.store, nip05.as_deref(), cx); } pub(super) fn render_about(&mut self, cx: &mut Context) -> AnyElement { @@ -1247,6 +1363,8 @@ impl RepoDetailView { return self.render_init_banner(cx); } + self.sync_header(cx); + let backend = Backend::global(cx); let store = self.store.read(cx); let pushing = store.pushing; @@ -1255,33 +1373,22 @@ impl RepoDetailView { let Some(header) = &self.header else { return div().into_any_element(); }; - let announcement = header.announcement.as_ref(); - let nip05 = self - .directory - .read(cx) - .profile(&announcement.owner, cx) - .metadata() - .nip05 - .clone() - .filter(|nip05| !nip05.trim().is_empty()); + let announcement = Arc::clone(&header.announcement); + let ngit_command = header.ngit_command.clone(); + let nak_command = header.nak_command.clone(); - 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 name = repo_display_name(self.store.read(cx)); + let name = self.store.read(cx).display_name(); let description = announcement.description(); - let avatar = Avatar::new(format!("{}:{}", announcement.owner, announcement.id)); let announcement_for_menu = Arc::clone(&header.announcement); - 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 weak_menu_open = cx.weak_entity(); + let weak_menu_items = cx.weak_entity(); + let weak_clone = cx.weak_entity(); + let weak_download = cx.weak_entity(); let ngit_for_popover = ngit_command.clone(); let nak_for_popover = nak_command.clone(); - let git_for_popover = Arc::clone(&header.git_commands); + let git_for_popover = Arc::new(announcement.clone_urls()); h_flex() .p_6() @@ -1299,7 +1406,7 @@ impl RepoDetailView { .gap_2() .text_sm() .font_semibold() - .child(avatar) + .child(Avatar::new(header.avatar_seed.clone())) .child( div() .min_w_0() @@ -1316,7 +1423,9 @@ impl RepoDetailView { .line_clamp(3) .child(description), ) - .when_some(fork_row(announcement, cx), |this, row| this.child(row)), + .when_some(self.fork_row(&announcement, cx), |this, row| { + this.child(row) + }), ) .child( h_flex() @@ -1378,16 +1487,12 @@ impl RepoDetailView { .child("No git clone urls."), ) }) - .children(git_for_popover.iter().enumerate().map( - |(ix, command)| { - CopyRow::new( - SharedString::from(format!( - "copy-git-{ix}" - )), - command.clone(), - ) - }, - )), + .children(git_for_popover.iter().map(|command| { + CopyRow::new( + (ElementId::from("copy-git"), command.as_str()), + command.clone(), + ) + })), ) .child( h_flex().justify_end().child( @@ -1474,7 +1579,7 @@ impl RepoDetailView { let weak = weak_menu_items.clone(); move |_window, cx| { if let Err(error) = weak.update(cx, |_, cx| { - let view = cx.entity().downgrade(); + let view = cx.weak_entity(); let dialog = DeleteRepositoryDialog::new(view, cx); cx.open_dialog(dialog); @@ -1518,14 +1623,19 @@ impl RepoDetailView { .justify_center() .gap_2() .map(|this| match binding { - Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)), + Some(binding) => this.child(self.bound_repo_label(binding, 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); + let Some(local_path) = this.store.read(cx).path.clone() else { + return; + }; + let view = cx.weak_entity(); + let dialog = InitRepoDialog::new(local_path, view, window, cx); + cx.open_dialog(dialog); })), ), }) @@ -1565,7 +1675,7 @@ impl RepoDetailView { .into_any_element() } - fn render_last_commit(&self, cx: &mut Context) -> Option { + fn render_last_commit(&self, cx: &mut Context) -> Option { let commit = self.browsed_commit.as_ref().or(self.head_commit.as_ref())?; let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned(); let history = self.history.clone(); @@ -1615,14 +1725,13 @@ impl RepoDetailView { .child(SharedString::from(relative_time_secs(commit.time))), ), ) - .flex_1() - .into_any_element(), + .flex_1(), ) } - fn render_maintainers(&self, cx: &mut Context) -> AnyElement { + fn render_maintainers(&self, cx: &mut Context) -> impl IntoElement { let Some(announcement) = self.announcement(cx) else { - return div().into_any_element(); + return div(); }; let mut seen = HashSet::new(); @@ -1642,6 +1751,7 @@ impl RepoDetailView { .gap_2() .child( h_flex() + .min_w_0() .gap_2() .child( Avatar::new(announcement.owner) @@ -1649,7 +1759,7 @@ impl RepoDetailView { .picture(owner.picture()) .small(), ) - .child(div().text_xs().whitespace_nowrap().child(owner_name)), + .child(div().min_w_0().text_xs().truncate().child(owner_name)), ) .when(!rest.is_empty(), |this| { this.child( @@ -1659,7 +1769,6 @@ impl RepoDetailView { .child(SharedString::from(format!("+{}", rest.len()))), ) }) - .into_any_element() } } @@ -1670,7 +1779,7 @@ impl Panel for RepoDetailView { return SharedString::from(name.to_string_lossy().into_owned()); } if let Some(announcement) = store.announcement.as_ref() { - return announcement_display_name(announcement); + return announcement.display_name(); } SharedString::from("Repository") } @@ -1679,7 +1788,7 @@ impl Panel for RepoDetailView { let store = self.store.read(cx); let key = match (store.announcement.as_ref(), store.path.as_ref()) { - (Some(announcement), _) => SharedString::from(format!("repo:{}", announcement.addr())), + (Some(announcement), _) => announcement.panel_key(), (None, Some(path)) => SharedString::from(format!("repo-local:{}", path.display())), (None, None) => SharedString::from("repo"), }; @@ -1725,7 +1834,7 @@ impl Render for RepoDetailView { .child(self.render_about(cx)) .child(self.render_metadata(cx)) .when_some(error, |this, error| { - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); this.child( Alert::new("repo-error") .severity(AlertSeverity::Danger) diff --git a/crates/signed_app/src/repo/refs.rs b/crates/signed_app/src/repo/refs.rs index 3217f20..89cd273 100644 --- a/crates/signed_app/src/repo/refs.rs +++ b/crates/signed_app/src/repo/refs.rs @@ -1,9 +1,8 @@ use gpui::{App, AppContext as _, Entity, SharedString, WeakEntity, Window}; use ui::combobox::{Combobox, ComboboxState}; -use ui::icons::{IconRole, icon}; +use ui::icons::IconRole; -use super::RepoDetailView; -use super::helpers::sync_selector; +use super::{RefKind, RepoDetailView}; pub(super) struct RefSwitcher { pub(super) branch_select: Entity>, @@ -22,7 +21,7 @@ impl RefSwitcher { ComboboxState::new( Combobox::new("branch-select", "Branch", Vec::new()) .placeholder("Branch") - .selected_icon(icon(IconRole::GitBranch)) + .selected_icon(IconRole::GitBranch.into()) .on_change(move |value, window, cx| { if let Some(name) = value && let Err(error) = branch_view.update(cx, |this, cx| { @@ -80,14 +79,59 @@ impl RefSwitcher { selected }; - sync_selector( - &self.branch_select, - &mut self.ref_branches, - branches, - selected, - window, - cx, - ) + self.sync_select(RefKind::Branch, branches, selected, window, cx) + } + + /// Pushes `items`/`selected` into a selector, reporting whether it changed. + fn sync_select( + &mut self, + kind: RefKind, + items: Vec, + selected: Option, + window: &mut Window, + cx: &mut App, + ) -> bool { + let select = match kind { + RefKind::Branch => self.branch_select.clone(), + RefKind::Tag => self.tag_select.clone(), + }; + + let cached = match kind { + RefKind::Branch => &mut self.ref_branches, + RefKind::Tag => &mut self.ref_tags, + }; + + let select = &select; + let items_changed = *cached != items; + + let selection_changed = selected + .as_ref() + .is_some_and(|value| select.read(cx).selected() != Some(value)); + + if !items_changed && !selection_changed { + return false; + } + + select.update(cx, |state, cx| { + if items_changed { + state.set_options( + items + .iter() + .map(|item| (item.clone(), item.clone())) + .collect(), + cx, + ); + } + + if let Some(value) = selected + && (items_changed || selection_changed) + { + state.set_selected_silent(Some(value), window, cx); + } + }); + + *cached = items; + true } pub(super) fn set_tags( @@ -96,14 +140,15 @@ impl RefSwitcher { window: &mut Window, cx: &mut App, ) -> bool { - sync_selector(&self.tag_select, &mut self.ref_tags, tags, None, window, cx) + self.sync_select(RefKind::Tag, tags, None, window, cx) } /// Shows `label` in the branch selector until a ref is picked. pub(super) fn show_commit(&mut self, label: SharedString, window: &mut Window, cx: &mut App) { self.commit_label = Some(label.clone()); - self.branch_select - .update(cx, |state, cx| state.set_display_label(label, window, cx)); + self.branch_select.update(cx, |state, cx| { + state.set_display_label(label, window, cx); + }); } pub(super) fn restore_selection( diff --git a/crates/signed_app/src/settings/helpers.rs b/crates/signed_app/src/settings/helpers.rs index d945fc1..965bddb 100644 --- a/crates/signed_app/src/settings/helpers.rs +++ b/crates/signed_app/src/settings/helpers.rs @@ -1,8 +1,8 @@ use std::path::PathBuf; use gpui::{ - AnyElement, App, AppContext as _, Div, Entity, IntoElement, ParentElement as _, - PathPromptOptions, SharedString, Styled as _, Window, div, px, + AnyElement, App, AppContext as _, Div, ElementId, Entity, IntoElement, ParentElement as _, + PathPromptOptions, SharedString, Styled as _, WeakEntity, Window, div, px, }; use settings::{AppearanceMode, EventFetchingStrategy, SettingsStore}; use ui::button::{Button, ButtonVariant}; @@ -13,7 +13,8 @@ use ui::select::{Select, SelectOption}; use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; -use crate::repo::dialogs::grasp_servers::{normalize_server, server_host}; +use crate::settings::{PathRow, ServerRow, SettingsDialog}; +use crate::shared::labels::ServerInputExt as _; /// The title and description a settings row or block opens with. fn setting_header( @@ -83,30 +84,38 @@ pub fn appearance_select(cx: &App) -> Select { } pub fn event_fetching_select(cx: &App) -> Select { - let current = SettingsStore::global(cx).read(cx).settings().event_fetching; + let store = SettingsStore::global(cx); + let current = store.read(cx).settings().event_fetching; + Select::new("settings-event-fetching") .options(vec![ SelectOption::new(EventFetchingStrategy::Curated, "Curated"), SelectOption::new(EventFetchingStrategy::Uncensored, "Uncensored"), ]) .selected(Some(current)) - .on_change(|value, _, cx| { + .on_change(move |value, _, cx| { let Some(strategy) = value else { return; }; - SettingsStore::global(cx).update(cx, |store, cx| { - store.edit(|settings| settings.event_fetching = strategy, cx); + + store.update(cx, |store, cx| { + store.edit( + |settings| { + settings.event_fetching = strategy; + }, + cx, + ); }); }) } /// One editable value: a muted row with a trailing remove button. fn editor_value_row( - id: String, + id: ElementId, text: SharedString, on_remove: impl Fn(&mut App) + 'static, cx: &App, -) -> AnyElement { +) -> Div { h_flex() .gap_1() .child( @@ -125,27 +134,25 @@ fn editor_value_row( .icon(Icon::named(IconRole::Close)) .variant(ButtonVariant::Ghost) .tooltip(Tooltip::text("Remove")) - .on_click(move |_, _, cx| on_remove(cx)), + .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 - .read(cx) - .settings() - .grasp_servers - .default_servers - .clone(); - +pub fn grasp_servers_editor( + input: &Entity, + servers: &[ServerRow], + cx: &App, +) -> AnyElement { v_flex() .gap_2() .children(servers.iter().map(|server| { - let server = server.clone(); + let url = server.url.clone(); + editor_value_row( - format!("settings-remove-server:{server}"), - display_server(&server), + server.id.clone(), + server.host.clone(), move |cx| { let store = SettingsStore::global(cx); store.update(cx, |store, cx| { @@ -154,7 +161,7 @@ pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement settings .grasp_servers .default_servers - .retain(|known| known != &server); + .retain(|known| known != &url); }, cx, ); @@ -187,52 +194,18 @@ pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement .into_any_element() } -fn display_server(server: &str) -> SharedString { - match normalize_server(server) { - Some((_, relay)) => server_host(&relay), - None => SharedString::from(server.to_owned()), - } -} - -fn add_server(input: &Entity, window: &mut Window, cx: &mut App) { - let settings = SettingsStore::global(cx); - let value = input.read(cx).value().trim().to_owned(); - - if value.is_empty() { - return; - } - - let Some((normalized, _)) = normalize_server(&value) else { - return; - }; - - settings.update(cx, |store, cx| { - store.edit( - |settings| { - if !settings.grasp_servers.default_servers.contains(&normalized) { - settings - .grasp_servers - .default_servers - .push(normalized.clone()); - } - }, - cx, - ); - }); - input.update(cx, |input, cx| input.set_value("", window, cx)); -} - -pub fn scan_paths_editor(cx: &App) -> AnyElement { - let store = SettingsStore::global(cx); - let scan_paths = store.read(cx).settings().local_repos.scan_paths.clone(); - +pub fn scan_paths_editor( + this: &WeakEntity, + scan_paths: &[PathRow], + cx: &App, +) -> AnyElement { v_flex() .gap_2() - .children(scan_paths.iter().map(|path| { - let path = path.clone(); + .children(scan_paths.iter().map(|row| { + let path = row.path.clone(); editor_value_row( - format!("settings-remove-path:{}", path.display()), - SharedString::from(path.display().to_string()), + row.id.clone(), + row.label.clone(), move |cx| { let store = SettingsStore::global(cx); store.update(cx, |store, cx| { @@ -255,20 +228,79 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement { Button::new("settings-add-path") .icon(Icon::named(IconRole::Plus)) .label("Add directory") - .on_click(|_, _, cx| add_scan_path(cx)), + .on_click({ + let this = this.clone(); + move |_, _, cx| { + add_scan_path(&this, cx); + } + }), ), ) .into_any_element() } -fn add_scan_path(cx: &mut App) { +pub fn default_folder_selector( + default_folder: &Entity, + this: &WeakEntity, +) -> AnyElement { + let folder = default_folder.clone(); + h_flex() + .gap_1() + .child( + div() + .flex_1() + .child(Input::new("settings-default-folder", folder.clone())), + ) + .child( + Button::new("settings-choose-folder") + .icon(Icon::named(IconRole::Folder)) + .variant(ButtonVariant::Ghost) + .tooltip(Tooltip::text("Choose folder")) + .on_click({ + let this = this.clone(); + move |_, window, cx| choose_default_folder(&folder, &this, window, cx) + }), + ) + .into_any_element() +} + +fn add_server(input: &Entity, window: &mut Window, cx: &mut App) { + let settings = SettingsStore::global(cx); + let value = input.read(cx).value().trim().to_owned(); + + if value.is_empty() { + return; + } + + let Some((normalized, _)) = value.normalize_server() else { + return; + }; + + settings.update(cx, |store, cx| { + store.edit( + |settings| { + if !settings.grasp_servers.default_servers.contains(&normalized) { + settings + .grasp_servers + .default_servers + .push(normalized.clone()); + } + }, + cx, + ); + }); + input.update(cx, |input, cx| input.set_value("", window, cx)); +} + +fn add_scan_path(this: &WeakEntity, cx: &mut App) { let prompt = cx.prompt_for_paths(PathPromptOptions { files: false, directories: true, multiple: true, prompt: Some("Choose directories".into()), }); - cx.spawn(async move |cx| { + + let task = cx.spawn(async move |cx| { if let Ok(Ok(Some(paths))) = prompt.await { cx.update(|cx| { let store = SettingsStore::global(cx); @@ -292,41 +324,31 @@ fn add_scan_path(cx: &mut App) { }); }); } + }); + + this.update(cx, |dialog, _cx| { + dialog.tasks.push(task); }) - .detach(); + .ok(); } -pub fn default_folder_selector(default_folder: &Entity) -> AnyElement { - let folder = default_folder.clone(); - h_flex() - .gap_1() - .child( - div() - .flex_1() - .child(Input::new("settings-default-folder", folder.clone())), - ) - .child( - Button::new("settings-choose-folder") - .icon(Icon::named(IconRole::Folder)) - .variant(ButtonVariant::Ghost) - .tooltip(Tooltip::text("Choose folder")) - .on_click(move |_, window, cx| { - choose_default_folder(&folder, window, cx); - }), - ) - .into_any_element() -} - -fn choose_default_folder(default_folder: &Entity, window: &mut Window, cx: &mut App) { +fn choose_default_folder( + default_folder: &Entity, + this: &WeakEntity, + window: &mut Window, + cx: &mut App, +) { let handle = window.window_handle(); let default_folder = default_folder.clone(); + let prompt = cx.prompt_for_paths(PathPromptOptions { files: false, directories: true, multiple: false, prompt: Some("Choose default folder".into()), }); - cx.spawn(async move |cx| { + + let task = cx.spawn(async move |cx| { if let Ok(Ok(Some(mut paths))) = prompt.await && let Some(path) = paths.pop() { @@ -344,6 +366,10 @@ fn choose_default_folder(default_folder: &Entity, window: &mut Windo log::warn!("failed to apply default folder: {error}"); } } + }); + + this.update(cx, |dialog, _cx| { + dialog.tasks.push(task); }) - .detach(); + .ok(); } diff --git a/crates/signed_app/src/settings/mod.rs b/crates/signed_app/src/settings/mod.rs index 95fbb7f..fba0dc6 100644 --- a/crates/signed_app/src/settings/mod.rs +++ b/crates/signed_app/src/settings/mod.rs @@ -1,9 +1,11 @@ mod helpers; +use std::path::PathBuf; + use gpui::prelude::FluentBuilder as _; use gpui::{ - App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, - Window, px, + App, AppContext as _, Context, ElementId, Entity, IntoElement, ParentElement as _, Render, + SharedString, Styled as _, Subscription, Task, Window, px, }; use helpers::{ appearance_select, default_folder_selector, event_fetching_select, grasp_servers_editor, @@ -16,10 +18,38 @@ use ui::dialog::{Dialog, DialogHandle}; use ui::input::InputState; use ui::separator::Separator; +use crate::shared::labels::{RelayHostExt as _, ServerInputExt as _}; + +/// One grasp server row, with its display strings built when settings change. +#[derive(Clone)] +pub(crate) struct ServerRow { + pub(crate) id: ElementId, + /// The stored server URL. + pub(crate) url: String, + /// The host shown on the row. + pub(crate) host: SharedString, +} + +/// One scan path row, with its label built when settings change. +#[derive(Clone)] +pub(crate) struct PathRow { + pub(crate) id: ElementId, + pub(crate) path: PathBuf, + pub(crate) label: SharedString, +} + pub struct SettingsDialog { handle: DialogHandle, grasp_input: Entity, default_folder: Entity, + /// Grasp server rows, rebuilt when the settings change. + servers: Vec, + /// Scan path rows, rebuilt when the settings change. + scan_paths: Vec, + /// Prompts this dialog started, cancelled when it drops. + tasks: Vec>, + /// Rebuilds the rows when the settings change. + _subscription: Option, } impl SettingsDialog { @@ -39,16 +69,70 @@ impl SettingsDialog { .read_only() .build(cx); - cx.new(|_| Self { - handle: DialogHandle::new(true), - grasp_input, - default_folder, - }) + let dialog = cx.new(|cx| { + let mut dialog = Self { + handle: DialogHandle::new(true), + grasp_input, + default_folder, + servers: Vec::new(), + scan_paths: Vec::new(), + tasks: Vec::new(), + _subscription: None, + }; + dialog.rebuild_rows(cx); + dialog + }); + + dialog.update(cx, |dialog, cx| { + dialog._subscription = Some(cx.observe(&store, |this, _store, cx| { + this.rebuild_rows(cx); + cx.notify(); + })); + }); + + dialog + } + + /// Rebuilds the row caches from the current settings. + fn rebuild_rows(&mut self, cx: &App) { + let store = SettingsStore::global(cx); + let settings = store.read(cx).settings(); + + self.servers = settings + .grasp_servers + .default_servers + .iter() + .map(|url| ServerRow { + id: ElementId::from(( + ElementId::from("settings-remove-server"), + SharedString::from(url.clone()), + )), + url: url.clone(), + host: url.normalize_server().map_or_else( + || SharedString::from(url.clone()), + |(_, relay)| relay.host_label(), + ), + }) + .collect(); + + self.scan_paths = settings + .local_repos + .scan_paths + .iter() + .map(|path| PathRow { + id: ElementId::from(( + ElementId::from("settings-remove-path"), + SharedString::from(path.display().to_string()), + )), + path: path.clone(), + label: SharedString::from(path.display().to_string()), + }) + .collect(); } } impl Render for SettingsDialog { - fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { const APPEARANCE_DESC: &str = "Choose whether the app follows the system theme or uses a light/dark theme."; const FETCH_DESC: &str = "Curated fetches events from relays in the repository's announcement. Uncensored also fetches from every maintainer's relays."; @@ -59,6 +143,9 @@ impl Render for SettingsDialog { let grasp_input = self.grasp_input.clone(); let default_folder = self.default_folder.clone(); + let servers = self.servers.clone(); + let scan_paths = self.scan_paths.clone(); + let this = cx.weak_entity(); Dialog::new("settings-dialog") .handle(self.handle.clone()) @@ -66,7 +153,8 @@ impl Render for SettingsDialog { .height(px(560.)) .title("Settings") .content(move |_, cx| { - let error = SettingsStore::global(cx).read(cx).error.clone(); + let store = SettingsStore::global(cx); + let error = store.read(cx).error.clone(); v_flex() .gap_4() @@ -97,20 +185,20 @@ impl Render for SettingsDialog { cx, "Grasp Servers", GRASP_DESC, - grasp_servers_editor(&grasp_input, cx), + grasp_servers_editor(&grasp_input, &servers, cx), )) .child(Separator::horizontal()) .child(setting_block( cx, "Scan Directories", SCAN_DESC, - scan_paths_editor(cx), + scan_paths_editor(&this, &scan_paths, cx), )) .child(setting_block( cx, "Default Folder", FOLDER_DESC, - default_folder_selector(&default_folder), + default_folder_selector(&default_folder, &this), )) .into_any_element() }) diff --git a/crates/signed_app/src/repo/commit_diff.rs b/crates/signed_app/src/shared/commit_diff.rs similarity index 64% rename from crates/signed_app/src/repo/commit_diff.rs rename to crates/signed_app/src/shared/commit_diff.rs index dd5a658..fac8c37 100644 --- a/crates/signed_app/src/repo/commit_diff.rs +++ b/crates/signed_app/src/shared/commit_diff.rs @@ -7,9 +7,9 @@ use gpui::{ AnyElement, App, AppContext as _, Axis, Context, Entity, EventEmitter, InteractiveElement as _, IntoElement, ListAlignment, ListState, ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity, Window, div, - list, px, + list, px, rems, }; -use signed_git::{CommitDiff, FileCommit, FileDiff, Repo}; +use signed_git::{CommitDiff, DiffLineKind, FileCommit, FileDiff, Repo}; use ui::avatar::Avatar; use ui::badge::GroupedBadge; use ui::button::{Button, ButtonVariant}; @@ -29,15 +29,97 @@ use ui::tooltip::Tooltip; use ui::tree::{Tree, TreeItem, TreeItemSeed}; use utils::relative_time_secs; -use super::helpers::{DiffRow, co_authors, diff_rows, short_id}; +use crate::shared::labels::ShortIdExt as _; + +const GUTTER_WIDTH: f32 = 44.; +pub const DIFF_ROW_HEIGHT: f32 = 20.; + +/// One virtualized row of a single file's diff. +#[derive(Clone)] +enum DiffRow { + Hunk { + old_start: u32, + old_lines: u32, + new_start: u32, + new_lines: u32, + }, + Line { + kind: DiffLineKind, + /// The old-side line number, empty for additions. + old: SharedString, + /// The new-side line number, empty for deletions. + new: SharedString, + text: SharedString, + }, +} + +impl DiffRow { + /// The rows of `file`, hunks interleaved with their lines. + fn from_file(file: &FileDiff) -> Vec { + let mut rows = Vec::new(); + for hunk in file.hunks.iter() { + rows.push(Self::Hunk { + old_start: hunk.old_start, + old_lines: hunk.old_lines, + new_start: hunk.new_start, + new_lines: hunk.new_lines, + }); + rows.extend(hunk.lines.iter().map(|line| { + Self::Line { + kind: line.kind, + old: line + .old + .map(|number| SharedString::from(number.to_string())) + .unwrap_or_default(), + new: line + .new + .map(|number| SharedString::from(number.to_string())) + .unwrap_or_default(), + text: SharedString::from(line.text.clone()), + } + })); + } + rows + } + + /// Renders one diff row against the file's hunks. + fn render(&self, wrap: bool, cx: &App) -> AnyElement { + match self { + Self::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(), + Self::Line { + kind, + old, + new, + text, + } => render_diff_line(*kind, old, new, text, wrap, cx), + } + } +} /// Emitted when the user activates the Download commit button. pub enum DiffPaneEvent { DownloadCommit, } -impl EventEmitter for DiffPane {} - /// One virtualized row of the multi-file diff list. #[derive(Clone)] enum PaneRow { @@ -51,12 +133,19 @@ enum PaneRow { last: bool, }, Line { - file_index: usize, row: DiffRow, last: bool, }, } +/// The commit's header strings, built once when the commit loads. +struct CommitHeader { + /// `(label, shown)` for the date's day label. + date_label: SharedString, + relative: SharedString, + co_authors: Vec, +} + pub struct DiffPane { diff: Option>, seeds: Vec, @@ -67,13 +156,16 @@ pub struct DiffPane { split: Entity, expanded_files: HashSet, pane_rows: Arc>, + files: Arc<[FileDiff]>, list: ListState, + /// Scroll state of the inline flow rows. + flow: ListState, wrap: bool, downloadable: bool, } impl DiffPane { - pub fn new(cx: &mut Context) -> Self { + pub fn new(downloadable: bool, cx: &mut Context) -> Self { let split = ResizableState::new(cx); split.update(cx, |split, cx| { split.set_sizes([px(260.)], cx); @@ -89,9 +181,11 @@ impl DiffPane { split, expanded_files: HashSet::new(), pane_rows: Arc::default(), + files: Arc::default(), list: ListState::new(0, ListAlignment::Top, px(320.)), + flow: ListState::new(0, ListAlignment::Top, px(24.)), wrap: false, - downloadable: false, + downloadable, } } @@ -111,6 +205,7 @@ impl DiffPane { self.expanded = TreeItemSeed::collect_expanded(&self.seeds); self.rows = Arc::new(TreeItemSeed::flatten_all(&self.seeds, &self.expanded)); self.selected_index = None; + self.files = diff.files.clone().into(); self.diff = Some(Arc::new(diff)); self.expanded_files.clear(); @@ -121,6 +216,7 @@ impl DiffPane { pub fn clear(&mut self, cx: &mut Context) { self.diff = None; + self.files = Arc::default(); self.seeds.clear(); self.expanded.clear(); self.rows = Arc::default(); @@ -136,14 +232,8 @@ impl DiffPane { cx.notify(); } - pub fn set_downloadable(&mut self, downloadable: bool, cx: &mut Context) { - self.downloadable = downloadable; - cx.notify(); - } - pub fn toggle_wrap(&mut self, cx: &mut Context) { self.wrap = !self.wrap; - self.rebuild_rows(); cx.notify(); } @@ -180,6 +270,7 @@ impl DiffPane { .rows .iter() .position(|row| row.key().to_string() == path); + if self.expanded_files.insert(path.to_owned()) { self.rebuild_rows(); } @@ -192,9 +283,11 @@ impl DiffPane { .is_some_and(|file| file.path == path), _ => false, }); + if let Some(header_index) = header_index { self.list.scroll_to_reveal_item(header_index); } + cx.notify(); } @@ -234,14 +327,13 @@ impl DiffPane { continue; } - let rows = diff_rows(file); + let rows = DiffRow::from_file(file); let last_row = rows.len().saturating_sub(1); pane_rows.extend( rows.into_iter() .enumerate() .map(|(row_index, row)| PaneRow::Line { - file_index, row, last: row_index == last_row, }), @@ -250,6 +342,7 @@ impl DiffPane { self.pane_rows = Arc::new(pane_rows); self.list.reset(self.pane_rows.len()); + self.flow.reset(self.pane_rows.len()); } fn toggle_folder(&mut self, id: &str, cx: &mut Context) { @@ -268,7 +361,7 @@ impl DiffPane { fn render_tree_column(&self, cx: &mut Context) -> AnyElement { let rows = Arc::clone(&self.rows); let selected = self.selected_index; - let view = cx.entity().downgrade(); + let view = cx.weak_entity(); let change_view = view.clone(); v_flex() @@ -309,6 +402,7 @@ impl DiffPane { let Some(row) = self.rows.get(index) else { return; }; + let id = row.key().to_string(); let expandable = row.is_expandable(); self.selected_index = Some(index); @@ -332,6 +426,7 @@ impl DiffPane { diff.files.iter().map(|file| file.deletions).sum(), ) }); + let files = self.diff().map_or(0, |diff| diff.files.len()); let all_expanded = self.all_expanded(); @@ -371,7 +466,7 @@ impl DiffPane { div() .text_xs() .text_color(cx.theme().colors.muted_foreground) - .child(format!("{files} changed files")), + .child(SharedString::from(format!("{files} changed files"))), ) .child(div().flex_1()) .child( @@ -430,14 +525,9 @@ impl DiffPane { } fn render_file_list(&self, cx: &mut Context) -> AnyElement { - let Some(diff) = self.diff.as_ref() else { - return EmptyState::centered("No changes"); - }; - - let diff = Arc::clone(diff); - let pane_rows = Arc::clone(&self.pane_rows); - let wrap = self.wrap; - let view = cx.entity().downgrade(); + if self.diff.is_none() { + return EmptyState::centered("No changes").into_any_element(); + } div() .relative() @@ -446,12 +536,10 @@ impl DiffPane { .h_full() .debug_selector(|| "commit-diff-files-list".to_owned()) .child( - list(self.list.clone(), move |ix, _, cx| { - match pane_rows.get(ix) { - Some(row) => render_pane_row(row, &diff.files, &view, wrap, cx), - None => div().into_any_element(), - } - }) + list( + self.list.clone(), + cx.processor(|this, ix: usize, _window, cx| this.render_pane_row(ix, cx)), + ) .size_full() .p_2(), ) @@ -459,6 +547,16 @@ impl DiffPane { .into_any_element() } + /// One virtualized row of the file list. + fn render_pane_row(&mut self, ix: usize, cx: &mut Context) -> AnyElement { + let Some(row) = self.pane_rows.get(ix) else { + return div().into_any_element(); + }; + + let view = cx.weak_entity(); + row.render(&self.files, &view, self.wrap, cx) + } + /// Renders every diff row inline, for embedding in a page that scrolls as a whole. pub fn render_flow(&self, view: WeakEntity, cx: &App) -> AnyElement { let Some(diff) = self.diff.as_ref() else { @@ -469,6 +567,7 @@ impl DiffPane { .child("No changes") .into_any_element(); }; + if diff.files.is_empty() { return div() .p_4() @@ -479,128 +578,133 @@ impl DiffPane { } let wrap = self.wrap; - let rows = self - .pane_rows - .iter() - .map(|row| render_pane_row(row, &diff.files, &view, wrap, cx)) - .collect::>(); + let rows = Arc::clone(&self.pane_rows); + let files = Arc::clone(&self.files); v_flex() .w_full() - .child(self.render_toolbar(false, view, cx)) - .child(v_flex().w_full().p_2().children(rows)) + .child(self.render_toolbar(false, view.clone(), cx)) + .child( + v_flex() + .w_full() + .p_2() + .max_h(rems(24.)) + .min_h_0() + .occlude() + .child(list(self.flow.clone(), move |ix, _window, cx| { + rows.get(ix) + .map(|row| row.render(&files, &view, wrap, cx)) + .unwrap_or_else(|| div().into_any_element()) + })), + ) .into_any_element() } } -fn render_pane_row( - row: &PaneRow, - files: &[FileDiff], - pane: &WeakEntity, - wrap: bool, - cx: &App, -) -> AnyElement { - let border = cx.theme().colors.border; - let surface = cx.theme().colors.surface; +impl EventEmitter for DiffPane {} - match row { - PaneRow::Header { - file_index, - gap, - expanded, - } => { - let Some(file) = files.get(*file_index) else { - return div().into_any_element(); - }; - let path = file.path.clone(); - let title = match &file.old_path { - Some(old) => SharedString::from(format!("{old} → {}", file.path)), - None => SharedString::from(file.path.clone()), - }; +impl PaneRow { + /// Renders one row of the inline flow. + fn render( + &self, + files: &[FileDiff], + pane: &WeakEntity, + wrap: bool, + cx: &App, + ) -> AnyElement { + let border = cx.theme().colors.border; + let surface = cx.theme().colors.surface; - div() - .w_full() - .when(*gap, |this| this.pt_2()) - .child( - h_flex() - .id(("file-header", *file_index)) - .debug_selector(move || format!("commit-diff-file-card-{file_index}")) - .h_10() - .px_2() - .gap_2() - .bg(surface) - .border_1() - .border_color(border) - .cursor_pointer() - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .when(*expanded, |this| this.rounded_t_lg().border_b_0()) - .when(!*expanded, |this| this.rounded_lg()) - .child( - Icon::named(if *expanded { - IconRole::ChevronDown - } else { - IconRole::ChevronRight + match self { + PaneRow::Header { + file_index, + gap, + expanded, + } => { + let Some(file) = files.get(*file_index) else { + return div().into_any_element(); + }; + let path = file.path.clone(); + let title = match &file.old_path { + Some(old) => SharedString::from(format!("{old} → {}", file.path)), + None => SharedString::from(file.path.clone()), + }; + + div() + .w_full() + .when(*gap, |this| this.pt_2()) + .child( + h_flex() + .id(("file-header", *file_index)) + .debug_selector(move || format!("commit-diff-file-card-{file_index}")) + .h_10() + .px_2() + .gap_2() + .bg(surface) + .border_1() + .border_color(border) + .cursor_pointer() + .hover(|this| this.bg(cx.theme().colors.muted_hover)) + .when(*expanded, |this| this.rounded_t_lg().border_b_0()) + .when(!*expanded, |this| this.rounded_lg()) + .child( + Icon::named(if *expanded { + IconRole::ChevronDown + } else { + IconRole::ChevronRight + }) + .color(cx.theme().colors.muted_foreground), + ) + .child(div().min_w_0().truncate().text_sm().child(title)) + .when(file.insertions > 0 || file.deletions > 0, |this| { + this.child(GroupedBadge::new( + ("file-diff-stats", *file_index), + file.insertions, + file.deletions, + )) }) - .color(cx.theme().colors.muted_foreground), - ) - .child(div().min_w_0().truncate().text_sm().child(title)) - .when(file.insertions > 0 || file.deletions > 0, |this| { - this.child(GroupedBadge::new( - ("file-diff-stats", *file_index), - file.insertions, - file.deletions, - )) - }) - .child(div().flex_1()) - .child( - Button::new(("view-file", *file_index)) - .label("View file") - .icon(Icon::named(IconRole::Eye)) - .variant(ButtonVariant::Ghost) - .small() - .on_click(|_, _, cx| cx.stop_propagation()), - ) - .on_click({ - let pane = pane.clone(); - move |_, _, cx| { - if let Err(error) = - pane.update(cx, |this, cx| this.toggle_file(&path, cx)) - { - log::warn!("failed to toggle diff file: {error}"); + .child(div().flex_1()) + .child( + Button::new(("view-file", *file_index)) + .label("View file") + .icon(Icon::named(IconRole::Eye)) + .variant(ButtonVariant::Ghost) + .small() + .on_click(|_, _, cx| cx.stop_propagation()), + ) + .on_click({ + let pane = pane.clone(); + move |_, _, cx| { + if let Err(error) = + pane.update(cx, |this, cx| this.toggle_file(&path, cx)) + { + log::warn!("failed to toggle diff file: {error}"); + } } - } - }), - ) - .into_any_element() - } - PaneRow::Note { message, last, .. } => div() - .w_full() - .border_x_1() - .border_color(border) - .bg(surface) - .px_3() - .py_2() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .when(*last, |this| this.border_b_1().rounded_b_lg()) - .child(message.clone()) - .into_any_element(), - PaneRow::Line { - file_index, - row, - last, - } => { - let Some(file) = files.get(*file_index) else { - return div().into_any_element(); - }; - div() + }), + ) + .into_any_element() + } + PaneRow::Note { message, last, .. } => div() + .w_full() + .border_x_1() + .border_color(border) + .bg(surface) + .px_3() + .py_2() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .when(*last, |this| this.border_b_1().rounded_b_lg()) + .child(message.clone()) + .into_any_element(), + PaneRow::Line { row, last, .. } => div() .w_full() .border_x_1() .border_color(border) .bg(surface) .when(*last, |this| this.border_b_1().rounded_b_lg()) - .child(row.render(&file.hunks, wrap, cx)) - .into_any_element() + .child(row.render(wrap, cx)) + .into_any_element(), } } } @@ -608,14 +712,14 @@ fn render_pane_row( impl Render for DiffPane { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let Some(diff) = self.diff.as_ref() else { - return EmptyState::centered("No changes"); + return EmptyState::centered("No changes").into_any_element(); }; if diff.files.is_empty() { - return EmptyState::centered("No files changed"); + return EmptyState::centered("No files changed").into_any_element(); } - let toolbar = self.render_toolbar(true, cx.entity().downgrade(), cx); + let toolbar = self.render_toolbar(true, cx.weak_entity(), cx); let file_list = self.render_file_list(cx); let content = if self.tree_visible { @@ -655,6 +759,7 @@ impl Render for DiffPane { pub struct CommitDiffView { worktree: PathBuf, commit: FileCommit, + header: CommitHeader, /// The diff is being computed on a background task. loading: bool, error: Option, @@ -671,24 +776,23 @@ impl CommitDiffView { window: &mut Window, cx: &mut Context, ) -> Self { - let pane = cx.new(|cx| { - let mut pane = DiffPane::new(cx); - pane.set_downloadable(downloadable, cx); - pane - }); + let pane = cx.new(|cx| DiffPane::new(downloadable, cx)); + let subscription = cx.subscribe(&pane, |this, _, DiffPaneEvent::DownloadCommit, cx| { this.download_patch(cx); }); - let weak = cx.entity().downgrade(); - window.defer(cx, move |window, cx| { - if let Err(error) = weak.update(cx, |this, cx| this.load(window, cx)) { - log::warn!("failed to load commit diff: {error}"); - } + cx.defer_in(window, |this, window, cx| { + this.load(window, cx); }); Self { worktree, + header: CommitHeader { + date_label: SharedString::default(), + relative: SharedString::default(), + co_authors: Vec::new(), + }, commit: FileCommit { id: commit_id, summary: String::new(), @@ -706,12 +810,6 @@ impl CommitDiffView { } } - /// Reaps finished tasks, then queues another. - fn push_task(&mut self, task: Task>) { - self.tasks.retain(|task| !task.is_ready()); - self.tasks.push(task); - } - fn load(&mut self, window: &mut Window, cx: &mut Context) { self.loading = true; self.error = None; @@ -728,6 +826,7 @@ impl CommitDiffView { async move { Repo::open(&worktree).and_then(|repo| repo.commit(&id)) } }) .await; + let diff = cx .background_spawn({ let worktree = worktree.clone(); @@ -738,9 +837,24 @@ impl CommitDiffView { this.update_in(cx, |this, _window, cx| { this.loading = false; + if let Ok(Some(commit)) = commit { + this.header = CommitHeader { + date_label: if commit.date_label.is_empty() { + SharedString::default() + } else { + SharedString::from(format!("({})", commit.date_label)) + }, + relative: SharedString::from(relative_time_secs(commit.time)), + co_authors: commit + .description + .as_deref() + .map(co_authors) + .unwrap_or_default(), + }; this.commit = commit; } + match diff { Ok(diff) => { this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx)); @@ -749,20 +863,21 @@ impl CommitDiffView { this.error = Some(error.to_string().into()); } } + cx.notify(); })?; Ok(()) }); - self.push_task(task); + self.tasks.push(task); } fn download_patch(&mut self, cx: &mut Context) { let worktree = self.worktree.clone(); let id = self.commit.id.clone(); - let suggested_name = format!("{}.patch", short_id(&id)); + let suggested_name = format!("{}.patch", id.short_id()); let prompt = cx.prompt_for_new_path(&worktree, Some(suggested_name.as_str())); let task: Task> = cx.spawn(async move |this, cx| { @@ -790,10 +905,11 @@ impl CommitDiffView { cx.notify(); })?; } + Ok(()) }); - self.push_task(task); + self.tasks.push(task); } fn render_header(&self, cx: &mut Context) -> AnyElement { @@ -825,7 +941,6 @@ impl CommitDiffView { .pr_16() .font_semibold() .truncate() - .text_ellipsis() .child(SharedString::from(commit.summary.clone())), ) .when_some(commit.description.as_ref(), |this, description| { @@ -854,37 +969,32 @@ impl CommitDiffView { .into_any_element(), )) .children( - commit - .description - .as_ref() - .map_or_else(Vec::new, |description| { - co_authors(description) - .into_iter() - .map(|name| { - row( - "Co-author", - h_flex() - .gap_2() - .child(Avatar::new(name.clone()).name(name.clone()).small()) - .child( - div().min_w_0().truncate().text_ellipsis().child(name), - ) - .into_any_element(), - ) - }) - .collect::>() - }), + self.header + .co_authors + .iter() + .cloned() + .map(|name| { + row( + "Co-author", + h_flex() + .gap_2() + .child(Avatar::new(name.clone()).name(name.clone()).small()) + .child(div().min_w_0().truncate().child(name)) + .into_any_element(), + ) + }) + .collect::>(), ) .child(row( "Date", h_flex() .gap_2() - .child(relative_time_secs(commit.time)) - .when(!commit.date_label.is_empty(), |this| { + .child(self.header.relative.clone()) + .when(!self.header.date_label.is_empty(), |this| { this.child( div() .text_color(muted) - .child(SharedString::from(format!("({})", commit.date_label))), + .child(self.header.date_label.clone()), ) }) .into_any_element(), @@ -896,7 +1006,6 @@ impl CommitDiffView { .child( div() .min_w_0() - .text_ellipsis() .truncate() .child(SharedString::from(commit.id.clone())), ) @@ -911,7 +1020,6 @@ impl CommitDiffView { .child( div() .min_w_0() - .text_ellipsis() .truncate() .child(SharedString::from(parent.clone())), ) @@ -940,18 +1048,104 @@ 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 { - Spinner::centered("commit-diff-loading") - } else if let Some(error) = self.error.clone() { - EmptyState::centered(error) - } else { - self.pane.clone().into_any_element() - }; - v_flex() .size_full() .min_h_0() .child(self.render_header(cx)) - .child(div().flex_1().min_h_0().child(body)) + .child( + div() + .flex_1() + .min_h_0() + .when(self.loading, |this| { + this.child(Spinner::centered("commit-diff-loading")) + }) + .when(!self.loading, |this| { + this.when_some(self.error.clone(), |this, error| { + this.child(EmptyState::centered(error)) + }) + .when(self.error.is_none(), |this| this.child(self.pane.clone())) + }), + ) } } + +/// The co-author names credited in a commit body, deduplicated in order. +fn co_authors(description: &str) -> Vec { + let mut names: Vec = Vec::new(); + + for line in description.lines() { + let trimmed = line.trim(); + if !trimmed.to_lowercase().starts_with("co-authored-by:") { + continue; + } + + let name = trimmed + .split_once(':') + .map(|(_, value)| value.trim()) + .unwrap_or_default() + .split('<') + .next() + .unwrap_or_default() + .trim(); + + if !name.is_empty() && !names.iter().any(|existing| existing.as_ref() == name) { + names.push(SharedString::from(name.to_owned())); + } + } + + names +} + +/// Renders one diff line with its old and new gutter numbers. +fn render_diff_line( + kind: DiffLineKind, + old: &SharedString, + new: &SharedString, + text: &SharedString, + wrap: bool, + cx: &App, +) -> AnyElement { + let bg = match kind { + DiffLineKind::Addition => Some(cx.theme().ramps.success.base.opacity(0.2)), + DiffLineKind::Deletion => Some(cx.theme().ramps.destructive.base.opacity(0.2)), + DiffLineKind::Context => None, + }; + let gutter = cx.theme().colors.muted_foreground; + + h_flex() + .w_full() + .when(wrap, |row| row.min_h(px(DIFF_ROW_HEIGHT))) + .when(!wrap, |row| row.h(px(DIFF_ROW_HEIGHT))) + .font_family(cx.theme().mono_font) + .text_xs() + .when_some(bg, |this, bg| this.bg(bg)) + .child( + div() + .w(px(GUTTER_WIDTH)) + .flex_none() + .pr_2() + .text_right() + .text_color(gutter) + .child(old.clone()), + ) + .child( + div() + .w(px(GUTTER_WIDTH)) + .flex_none() + .pr_2() + .text_right() + .text_color(gutter) + .child(new.clone()), + ) + .child( + div() + .flex_1() + .min_w_0() + .text_color(cx.theme().colors.foreground) + .when(!wrap, |content| { + content.overflow_hidden().whitespace_nowrap() + }) + .child(text.clone()), + ) + .into_any_element() +} diff --git a/crates/signed_app/src/shared/labels.rs b/crates/signed_app/src/shared/labels.rs new file mode 100644 index 0000000..382cb77 --- /dev/null +++ b/crates/signed_app/src/shared/labels.rs @@ -0,0 +1,208 @@ +use std::hash::{Hash, Hasher}; +use std::path::Path; + +use gpui::{App, Entity, SharedString}; +use metadata::ProfileDirectory; +use nostr::prelude::{PublicKey, RelayUrl, ToBech32}; +use signed_core::{Announcement, RepoAddr}; +use signed_state::{RepoStore, ResolvedLocalRepo}; + +/// Display labels for repository announcements. +pub trait AnnouncementExt { + /// The announcement's name, falling back to its id. + fn display_name(&self) -> SharedString; + + /// The `nostr://` clone URL of the announcement, crediting `nip05` when known. + fn clone_url(&self, nip05: Option<&str>) -> SharedString; + + /// The panel-stack key that identifies this repository. + fn panel_key(&self) -> SharedString; +} + +impl AnnouncementExt for Announcement { + fn panel_key(&self) -> SharedString { + SharedString::from(format!("repo:{}", self.addr())) + } + + fn display_name(&self) -> SharedString { + self.name + .as_deref() + .map(SharedString::from) + .unwrap_or_else(|| SharedString::from(self.id.clone())) + } + + fn clone_url(&self, nip05: Option<&str>) -> SharedString { + let owner = self.owner; + let user = nip05 + .map(str::to_owned) + .unwrap_or_else(|| owner.to_bech32().unwrap_or_else(|_| owner.to_string())); + + let mut url = format!("nostr://{user}"); + if let Some(hint) = self.relays.first().and_then(RelayUrl::domain) { + url.push('/'); + url.push_str(hint); + } + url.push('/'); + url.push_str(&self.id); + + SharedString::from(url) + } +} + +/// The label of a repository's upstream, when its address is in this list. +pub trait AnnouncementsExt { + /// The display name of the announcement addressing `addr`, falling back to its identifier. + fn upstream_display_name(&self, addr: &RepoAddr) -> SharedString; +} + +impl AnnouncementsExt for [Announcement] { + fn upstream_display_name(&self, addr: &RepoAddr) -> SharedString { + self.iter() + .find(|announcement| announcement.addr() == *addr) + .map(AnnouncementExt::display_name) + .unwrap_or_else(|| SharedString::from(addr.identifier().to_owned())) + } +} + +/// Short hex ids for display. +pub trait ShortIdExt { + /// The first eight hex characters of an object id, for row labels. + fn short_id(&self) -> SharedString; +} + +impl ShortIdExt for str { + fn short_id(&self) -> SharedString { + SharedString::from(self.get(..8).unwrap_or(self).to_owned()) + } +} + +/// The panel-stack key of a locally resolved repository. +pub trait ResolvedLocalRepoExt { + /// The announced repository's key, or the local path's when unannounced. + fn panel_key(&self) -> SharedString; +} + +impl ResolvedLocalRepoExt for ResolvedLocalRepo { + fn panel_key(&self) -> SharedString { + match self.announcement.as_ref() { + Some(announcement) => announcement.panel_key(), + None => SharedString::from(format!("repo-local:{}", self.path.display())), + } + } +} + +/// Text and path helpers shared by the repository views. +pub trait StrExt { + /// Whether a file path has a markdown extension. + fn is_markdown_path(&self) -> bool; + + /// Computes a source hash from the given text. + fn source_hash(&self) -> u64; +} + +impl StrExt for str { + fn is_markdown_path(&self) -> bool { + Path::new(self) + .extension() + .and_then(|ext| ext.to_str()) + .is_some_and(|ext| { + matches!( + ext.to_ascii_lowercase().as_str(), + "md" | "markdown" | "mdown" | "mkdn" + ) + }) + } + + fn source_hash(&self) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + self.hash(&mut hasher); + hasher.finish() + } +} + +/// The display name of a repository store. +pub trait RepoStoreExt { + /// The announcement's name or ID for announced repositories, the directory name for local ones. + fn display_name(&self) -> SharedString; +} + +impl RepoStoreExt for RepoStore { + fn display_name(&self) -> SharedString { + if self.addr().is_none() { + return self + .path + .as_ref() + .map(|path| { + SharedString::from( + path.file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| path.display().to_string()), + ) + }) + .unwrap_or_default(); + } + + self.announcement + .as_ref() + .map(AnnouncementExt::display_name) + .unwrap_or_default() + } +} + +/// Normalises a relay URL typed by the user. +pub trait ServerInputExt { + /// Returns the typed text, with a `wss://` scheme added when none is given, and the parsed relay. + fn normalize_server(&self) -> Option<(String, RelayUrl)>; +} + +impl ServerInputExt for str { + fn normalize_server(&self) -> Option<(String, RelayUrl)> { + let text = if self.contains("://") { + self.to_owned() + } else { + format!("wss://{self}") + }; + RelayUrl::parse(&text).ok().map(|relay| (text, relay)) + } +} + +/// The host label shown for a relay. +pub trait RelayHostExt { + /// The host of a relay URL, which is what the server lists show; the scheme is implied. + fn host_label(&self) -> SharedString; +} + +impl RelayHostExt for RelayUrl { + fn host_label(&self) -> SharedString { + self.domain() + .map(SharedString::from) + .unwrap_or_else(|| SharedString::from(self.to_string())) + } +} + +/// Tracks a detail view's author, commenters, and owner for profile prefetch. +pub trait ProfileDirectoryExt { + /// Prefetches the profiles of `author`, `comments`, and `owner`. + fn track_participants( + &self, + author: Option, + owner: Option, + comments: impl Iterator, + cx: &mut App, + ); +} + +impl ProfileDirectoryExt for Entity { + fn track_participants( + &self, + author: Option, + owner: Option, + comments: impl Iterator, + cx: &mut App, + ) { + let mut keys: Vec = author.into_iter().collect(); + keys.extend(comments); + keys.extend(owner); + self.update(cx, |directory, cx| directory.track(keys, cx)); + } +} diff --git a/crates/signed_app/src/shared/mod.rs b/crates/signed_app/src/shared/mod.rs index f893910..fa96b82 100644 --- a/crates/signed_app/src/shared/mod.rs +++ b/crates/signed_app/src/shared/mod.rs @@ -1,9 +1,5 @@ -use gpui::{App, Entity}; -use metadata::ProfileDirectory; -use nostr::prelude::PublicKey; - -pub mod progress; - +pub mod commit_diff; +pub mod labels; pub mod widgets; /// Logs a discarded `Result` with its source location instead of dropping it silently. @@ -18,17 +14,3 @@ pub fn log_dropped(result: Result) { ); } } - -/// Tracks a detail view's author, commenters, and owner for profile prefetch. -pub fn track_event_participants( - author: Option, - owner: Option, - comments: impl Iterator, - directory: &Entity, - cx: &mut App, -) { - let mut keys: Vec = author.into_iter().collect(); - keys.extend(comments); - keys.extend(owner); - directory.update(cx, |directory, cx| directory.track(keys, cx)); -} diff --git a/crates/signed_app/src/shared/progress.rs b/crates/signed_app/src/shared/progress.rs deleted file mode 100644 index 253185b..0000000 --- a/crates/signed_app/src/shared/progress.rs +++ /dev/null @@ -1,196 +0,0 @@ -use gpui::{ - AnyElement, App, AsyncApp, Context, Entity, IntoElement as _, ParentElement as _, SharedString, - 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 { - pub busy: bool, - pub error: Option, - // The repository whose push checklist is shown; `None` outside a publish. - push_addr: Option, - pub push_steps: Vec, - _push_subscription: Option, -} - -impl DialogProgress { - /// Marks an action as started, disabling the form and clearing the previous error. - pub fn begin(&mut self) { - self.busy = true; - self.error = None; - } - - /// Starts a publish for the repository at `addr` and listens for its push steps. - pub fn begin_push(&mut self, addr: RepoAddr, cx: &mut Context) { - self.begin(); - self.push_addr = Some(addr); - self.push_steps.clear(); - - if self._push_subscription.is_none() { - let backend = Backend::global(cx); - self._push_subscription = Some(cx.subscribe(&backend, |this, _backend, event, cx| { - let BackendEvent::PushProgress { addr, status } = event else { - return; - }; - - if this.push_addr.as_ref() != Some(addr) { - return; - } - - match this - .push_steps - .iter_mut() - .find(|step| step.step() == status.step()) - { - Some(step) => *step = status.clone(), - None => this.push_steps.push(status.clone()), - } - - cx.notify(); - })); - } - } - - /// Marks an action as failed, enabling the form and showing `message`. - pub fn fail(&mut self, message: impl Into) { - self.busy = false; - self.error = Some(message.into()); - } -} - -/// The shared error line under a dialog form, `None` when there is no error. -pub fn error_row(error: &Option, cx: &App) -> Option { - error.as_ref().map(|message| { - div() - .text_sm() - .text_color(cx.theme().ramps.destructive.base) - .child(message.clone()) - .into_any_element() - }) -} - -/// The push checklist of a running publish, `None` before any step is reported. -pub fn push_steps_row(steps: &[PushStepStatus], cx: &App) -> Option { - if steps.is_empty() { - return None; - } - - let rows = steps - .iter() - .map(|status| { - let label = SharedString::from(status.step().label()); - - match status { - PushStepStatus::Running(_) => h_flex() - .gap_2() - .text_sm() - .text_color(cx.theme().colors.muted_foreground) - .child(Spinner::new("push-step")) - .child(label) - .into_any_element(), - PushStepStatus::Done(_) => h_flex() - .gap_2() - .text_sm() - .text_color(cx.theme().colors.foreground) - .child( - Icon::named(IconRole::Check) - .small() - .color(cx.theme().colors.foreground), - ) - .child(label) - .into_any_element(), - PushStepStatus::Failed(_, reason) => h_flex() - .gap_2() - .text_sm() - .text_color(cx.theme().ramps.destructive.base) - .child( - Icon::named(IconRole::Close) - .small() - .color(cx.theme().ramps.destructive.base), - ) - .child(SharedString::from(format!( - "{}: {reason}", - status.step().label() - ))) - .into_any_element(), - } - }) - .collect::>(); - - Some(v_flex().gap_1().children(rows).into_any_element()) -} - -/// Runs a dialog task to completion. -pub fn run_dialog_task( - task: Task>, - state: &Entity, - handle: &DialogHandle, - cx: &mut App, -) { - let state = state.clone(); - let handle = handle.clone(); - - run_dialog_task_with( - task, - cx, - move |_, cx| cx.update(|cx| handle.close(cx)), - move |error, cx| { - state.update(cx, |state, cx| { - state.fail(error.to_string()); - cx.notify(); - }); - }, - ); -} - -/// Runs a dialog task to completion, with explicit success and failure sinks. -pub fn run_dialog_task_with( - task: Task>, - cx: &mut App, - on_success: impl FnOnce(T, &mut AsyncApp) + 'static, - on_error: impl FnOnce(anyhow::Error, &mut AsyncApp) + 'static, -) { - cx.spawn(async move |cx| match task.await { - Ok(value) => on_success(value, cx), - Err(error) => on_error(error, cx), - }) - .detach(); -} diff --git a/crates/signed_app/src/shared/widgets.rs b/crates/signed_app/src/shared/widgets.rs index 022aec4..9a59d38 100644 --- a/crates/signed_app/src/shared/widgets.rs +++ b/crates/signed_app/src/shared/widgets.rs @@ -1,9 +1,53 @@ +use nostr::prelude::Event; use signed_core::RepoStatus; use ui::badge::{Badge, BadgeVariant}; use ui::common::Sizable; use ui::icons::{Icon, IconRole}; use ui::tooltip::Tooltip; +/// Root events counted by their resolved status. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct StatusCounts { + pub(crate) total: usize, + pub(crate) open: usize, + pub(crate) closed: usize, + pub(crate) draft: usize, + pub(crate) applied: usize, +} + +impl StatusCounts { + fn record(&mut self, status: RepoStatus) { + self.total += 1; + match status { + RepoStatus::Open => self.open += 1, + RepoStatus::Closed => self.closed += 1, + RepoStatus::Draft => self.draft += 1, + RepoStatus::Applied => self.applied += 1, + } + } + + /// Indices of `roots` whose status `keep` accepts, counting every root's status. + pub(crate) fn filter<'a>( + roots: impl IntoIterator, + status_of: impl Fn(&Event) -> RepoStatus, + keep: impl Fn(RepoStatus) -> bool, + ) -> (Vec, Self) { + let mut counts = Self::default(); + + let visible = roots + .into_iter() + .enumerate() + .filter_map(|(index, root)| { + let status = status_of(root); + counts.record(status); + keep(status).then_some(index) + }) + .collect(); + + (visible, counts) + } +} + /// The status pill shown on issue and pull-request rows. pub fn status_badge(status: RepoStatus) -> Badge { let (label, variant, icon) = match status { diff --git a/crates/signed_app/src/titlebar/mod.rs b/crates/signed_app/src/titlebar/mod.rs index a724815..b2a1605 100644 --- a/crates/signed_app/src/titlebar/mod.rs +++ b/crates/signed_app/src/titlebar/mod.rs @@ -2,8 +2,8 @@ use std::rc::Rc; use std::sync::Arc; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, IntoElement, KeyBinding, - KeyBindingContextPredicate, ParentElement as _, SharedString, Subscription, WeakEntity, Window, + App, AppContext as _, Context, Entity, IntoElement, KeyBinding, KeyBindingContextPredicate, + ParentElement as _, SharedString, Subscription, WeakEntity, Window, }; use metadata::{Profile, ProfileDirectory}; use nostr::prelude::PublicKey; @@ -23,8 +23,10 @@ use ui::tooltip::Tooltip; use crate::app::AppRoot; use crate::explore::ExploreView; use crate::identity::exit::ExitDialog; -use crate::repo::{RepoDetailView, actions, dialogs}; +use crate::repo::RepoDetailView; +use crate::repo::dialogs::create::CreateRepoDialog; use crate::settings::SettingsDialog; +use crate::shared::labels::{AnnouncementExt as _, ResolvedLocalRepoExt as _}; use crate::shared::log_dropped; mod repository_switcher; @@ -76,9 +78,7 @@ impl TitlebarView { let repos = RepoListStore::global(cx); let local = LocalReposStore::global(cx); let directory = ProfileDirectory::new(cx); - - let entity = cx.entity(); - let weak = entity.downgrade(); + let weak = cx.weak_entity(); let palette = Self::new_palette(weak.clone(), window, cx); cx.open_palette(palette); @@ -115,10 +115,15 @@ impl TitlebarView { }); subscriptions.push(cx.subscribe(&backend, |this, _backend, event, cx| { - let signer_changed = matches!(event, BackendEvent::SignerChanged); - let signer_required = matches!(event, BackendEvent::SignerRequired); + // Push progress and sync events cannot change the titlebar's data. + if !matches!( + event, + BackendEvent::SignerChanged | BackendEvent::SignerRequired + ) { + return; + } - if this.refresh(cx) || signer_changed || signer_required { + if this.refresh(cx) { cx.notify(); } })); @@ -135,16 +140,14 @@ impl TitlebarView { } })); - cx.defer(move |cx| { - entity.update(cx, |this, cx| { - if this.refresh(cx) { - cx.notify(); - } - }); + cx.defer_in(window, move |this, _window, cx| { + if this.refresh(cx) { + cx.notify(); + } }); Self { - weak: cx.entity().downgrade(), + weak, app, announcements: Arc::new(Vec::new()), local_repos: Arc::new(Vec::new()), @@ -269,7 +272,8 @@ impl TitlebarView { entries.push(RepositoryEntry { index, - key: announcement_key(announcement), + key: announcement.panel_key(), + label_lower: SharedString::from(label.to_lowercase()), label, owner: Some(announcement.owner), }); @@ -277,11 +281,13 @@ impl TitlebarView { for (local_index, entry) in self.local_repos.iter().enumerate() { let owner = entry.nip34.as_ref().and_then(|binding| binding.owner); + let label = entry.name(); entries.push(RepositoryEntry { index: self.announcements.len() + local_index, - key: local_key(entry), - label: entry.name(), + key: entry.panel_key(), + label_lower: SharedString::from(label.to_lowercase()), + label, owner, }); } @@ -299,39 +305,41 @@ impl TitlebarView { window: &mut Window, cx: &mut Context, ) { - self.repository_switcher - .update(cx, |switcher, cx| switcher.close(cx)); + self.repository_switcher.update(cx, |switcher, cx| { + switcher.close(cx); + }); self.activate(index, window, cx); } pub(crate) fn create_repository(&mut self, window: &mut Window, cx: &mut Context) { - self.repository_switcher - .update(cx, |switcher, cx| switcher.close(cx)); + self.repository_switcher.update(cx, |switcher, cx| { + switcher.close(cx); + }); self.open_create(window, cx); } fn open_settings(&mut self, cx: &mut Context) { let dialog = SettingsDialog::new(cx); cx.open_dialog(dialog); - cx.notify(); } fn open_exit(&mut self, cx: &mut Context) { let dialog = ExitDialog::new(cx); cx.open_dialog(dialog); - cx.notify(); } fn open_create(&mut self, window: &mut Window, cx: &mut Context) { - let view = dialogs::create::CreateRepoDialog::new(self.app.clone(), window, cx); + let view = CreateRepoDialog::new(self.app.clone(), window, cx); cx.open_dialog(view); - cx.notify(); } fn activate(&mut self, index: usize, window: &mut Window, cx: &mut Context) { if let Some(announcement) = self.announcements.get(index) { let addr = announcement.addr(); - actions::open_repo_panel(&self.app, &addr, Some(announcement), window, cx); + let result = self.app.update(cx, |root, cx| { + root.open_repo_panel(&addr, Some(announcement), window, cx); + }); + log_dropped(result); return; } @@ -342,6 +350,7 @@ impl TitlebarView { else { return; }; + self.open_local_entry(entry, window, cx); } @@ -414,7 +423,7 @@ impl TitlebarView { })); } - pub fn render_user_menu(&self, cx: &App) -> Option { + pub fn render_user_menu(&self, cx: &App) -> Option { let profile = Backend::global(cx) .read(cx) .current_user() @@ -423,7 +432,7 @@ impl TitlebarView { Some(self.render_user(&profile, cx).into_any_element()) } - pub fn render_explore(&self) -> AnyElement { + pub fn render_explore(&self) -> Button { let workspace = self.app.clone(); Button::new("open-explore") @@ -432,12 +441,15 @@ impl TitlebarView { .fully_rounded(true) .tooltip(Tooltip::text("Explore repositories")) .on_click(move |_, window, cx| { - ExploreView::open(&workspace, window, cx); + let panels = workspace.read_with(cx, |root, _| root.panels().clone()); + let Ok(panels) = panels else { + return; + }; + ExploreView::open(&panels, workspace.clone(), window, cx); }) - .into_any_element() } - pub fn render_new_repository(&self) -> AnyElement { + pub fn render_new_repository(&self) -> Button { let weak = self.weak.clone(); Button::new("add-repo") @@ -448,7 +460,6 @@ impl TitlebarView { .on_click(move |_, window, cx| { log_dropped(weak.update(cx, |this, cx| this.open_create(window, cx))); }) - .into_any_element() } fn render_user(&self, profile: &Profile, _cx: &App) -> impl IntoElement { @@ -506,56 +517,48 @@ impl TitlebarView { } } -fn announcement_key(announcement: &Announcement) -> SharedString { - SharedString::from(format!("repo:{}", announcement.addr())) -} +impl TitlebarView { + /// Binds the repository shortcuts that the shell and the switcher share. + pub(crate) fn bind_keys(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; + } + }; -fn local_key(entry: &ResolvedLocalRepo) -> SharedString { - match entry.announcement.as_ref() { - Some(announcement) => announcement_key(announcement), - None => SharedString::from(format!("repo-local:{}", entry.path.display())), - } -} - -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 }), + 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, - ) - }) - .chain(std::iter::once(KeyBinding::load( - CREATE_KEYSTROKE, - Box::new(CreateRepository), - context.clone(), - false, - None, - cx, - ))) - .collect::, _>>(); + ))) + .collect::, _>>(); - let bindings = match bindings { - Ok(bindings) => bindings, - Err(error) => { - log::error!("failed to parse repository shortcut keystrokes: {error}"); - return; - } - }; + let bindings = match bindings { + Ok(bindings) => bindings, + Err(error) => { + log::error!("failed to parse repository shortcut keystrokes: {error}"); + return; + } + }; - cx.bind_keys(bindings); + cx.bind_keys(bindings); + } } diff --git a/crates/signed_app/src/titlebar/repository_switcher.rs b/crates/signed_app/src/titlebar/repository_switcher.rs index f4e1dc2..4af30f8 100644 --- a/crates/signed_app/src/titlebar/repository_switcher.rs +++ b/crates/signed_app/src/titlebar/repository_switcher.rs @@ -33,6 +33,8 @@ pub(super) struct RepositoryEntry { pub(super) index: usize, pub(super) key: SharedString, pub(super) label: SharedString, + /// `label` lowercased, for the search filter. + pub(super) label_lower: SharedString, pub(super) owner: Option, } @@ -96,8 +98,9 @@ impl RepositorySwitcher { impl Render for RepositorySwitcher { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let theme = *cx.theme(); - let weak = cx.entity().downgrade(); + let colors = cx.theme().colors; + let avatar_radius = cx.theme().radius.full; + let weak = cx.weak_entity(); let entries = Arc::clone(&self.entries); let search = self.search.clone(); let directory = self.directory.clone(); @@ -151,9 +154,7 @@ impl Render for RepositorySwitcher { let visible: Arc> = Arc::new( entries .iter() - .filter(|entry| { - query.is_empty() || entry.label.to_lowercase().contains(&query) - }) + .filter(|entry| query.is_empty() || entry.label_lower.contains(&query)) .cloned() .collect(), ); @@ -163,6 +164,8 @@ impl Render for RepositorySwitcher { let list_entries = Arc::clone(&visible); let list_directory = directory.clone(); let list_weak = row_weak.clone(); + let list_radius = avatar_radius; + let list_muted = colors.muted; let list_on_open = on_open.clone(); let list_scroll_handle = scroll_handle.clone(); v_flex() @@ -176,17 +179,17 @@ impl Render for RepositorySwitcher { .prefix( Icon::named(IconRole::Search) .small() - .color(theme.colors.muted_foreground), + .color(colors.muted_foreground), ) - .bg(theme.colors.muted) - .border_color(theme.colors.muted), + .bg(colors.muted) + .border_color(colors.muted), ) .map(|this| { if visible.is_empty() { this.child( div() .p_3() - .text_color(theme.colors.muted_foreground) + .text_color(colors.muted_foreground) .text_center() .text_sm() .child("No repositories found"), @@ -217,9 +220,9 @@ impl Render for RepositorySwitcher { .h(row_height) .px_3() .gap_2() - .rounded(theme.radius.full) + .rounded(list_radius) .text_sm() - .hover(|row| row.bg(theme.colors.muted)) + .hover(|row| row.bg(list_muted)) .child(entry.avatar(&list_directory, cx)) .child( div() diff --git a/crates/signed_state/src/backend.rs b/crates/signed_state/src/backend.rs index 0946a12..46b1705 100644 --- a/crates/signed_state/src/backend.rs +++ b/crates/signed_state/src/backend.rs @@ -79,7 +79,7 @@ impl Backend { } pub(crate) fn new(client: Client, signer: UniversalSigner, cx: &mut Context) -> Self { - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); let pump_client = client.clone(); let pump: Task> = cx.spawn(async move |this, cx| { diff --git a/crates/signed_state/src/checkouts.rs b/crates/signed_state/src/checkouts.rs index 08f158f..cc5da86 100644 --- a/crates/signed_state/src/checkouts.rs +++ b/crates/signed_state/src/checkouts.rs @@ -162,7 +162,7 @@ impl CheckoutsStore { } if !cfg!(target_arch = "wasm32") { - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); cx.defer(move |cx| { weak.update(cx, |this, cx| { this.refresh(cx); diff --git a/crates/signed_state/src/local_repos.rs b/crates/signed_state/src/local_repos.rs index 9ea0db3..3eccd6f 100644 --- a/crates/signed_state/src/local_repos.rs +++ b/crates/signed_state/src/local_repos.rs @@ -28,7 +28,7 @@ impl LocalReposStore { } pub fn new(roots: Vec, cx: &mut Context) -> Self { - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); cx.defer(move |cx| { if let Err(error) = weak.update(cx, |this, cx| this.rescan(cx)) { log::warn!("local repos store dropped before initial scan could run: {error}"); diff --git a/crates/signed_state/src/repo.rs b/crates/signed_state/src/repo.rs index 778fde6..14faf20 100644 --- a/crates/signed_state/src/repo.rs +++ b/crates/signed_state/src/repo.rs @@ -64,7 +64,7 @@ pub struct RepoStore { impl RepoStore { pub fn new(addr: RepoAddr, hint: Option, cx: &mut Context) -> Self { - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); let subscription = Self::subscribe_backend(cx); let announced_relays = hint diff --git a/crates/signed_state/src/repos.rs b/crates/signed_state/src/repos.rs index fd45735..93717d5 100644 --- a/crates/signed_state/src/repos.rs +++ b/crates/signed_state/src/repos.rs @@ -50,7 +50,7 @@ impl RepoListStore { pub fn new(cx: &mut Context) -> Self { let backend = Backend::global(cx); - let weak = cx.entity().downgrade(); + let weak = cx.weak_entity(); let subscription = cx.subscribe(&backend, |this, _backend, event, cx| { let relevant = match event { diff --git a/crates/ui/src/components/alert.rs b/crates/ui/src/components/alert.rs index 6f4ce9f..1703eab 100644 --- a/crates/ui/src/components/alert.rs +++ b/crates/ui/src/components/alert.rs @@ -28,8 +28,7 @@ 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, + DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, v_flex, }; use crate::icons::{Icon, IconRole}; use crate::theme::{ALERT_EDGE_WIDTH, ALERT_STACK_WIDTH, ActiveTheme as _, ENTER_SLIDE_DISTANCE}; @@ -195,33 +194,29 @@ impl RenderOnce for Alert { }); match self.presentation { - AlertStyle::Overlay => floating_panel( - cx, - theme.radius.overlay, - div() - .id(self.id.clone()) - .role(Role::Alert) - .w_full() - .flex() - .items_start() - .gap_2() - .px_3() - .py_2(), - theme.elevations.popover.shadows(), - ) - .refine_style(&self.style) - .when_some(self.icon.clone(), |alert, icon_glyph| { - alert.child( - div() - .flex_none() - .flex() - .items_center() - .h(window.line_height()) - .child(icon_glyph.size(rems(1.0)).color(ramp.base)), - ) - }) - .child(content) - .when_some(dismiss, |alert, dismiss| alert.child(dismiss)), + AlertStyle::Overlay => div() + .id(self.id.clone()) + .role(Role::Alert) + .w_full() + .flex() + .items_start() + .gap_2() + .px_3() + .py_2() + .floating_panel(cx, theme.radius.overlay, theme.elevations.popover.shadows()) + .refine_style(&self.style) + .when_some(self.icon.clone(), |alert, icon_glyph| { + alert.child( + div() + .flex_none() + .flex() + .items_center() + .h(window.line_height()) + .child(icon_glyph.size(rems(1.0)).color(ramp.base)), + ) + }) + .child(content) + .when_some(dismiss, |alert, dismiss| alert.child(dismiss)), AlertStyle::Inline => div() .id(self.id.clone()) .role(Role::Alert) @@ -291,7 +286,7 @@ impl Alerts { self.next_id += 1; let on_dismiss = alert.on_dismiss.take(); - let stack = cx.entity().downgrade(); + let stack = cx.weak_entity(); alert.on_dismiss = Some(Rc::new(move |cx: &mut App| { stack diff --git a/crates/ui/src/components/avatar.rs b/crates/ui/src/components/avatar.rs index 22279da..f4573d8 100644 --- a/crates/ui/src/components/avatar.rs +++ b/crates/ui/src/components/avatar.rs @@ -11,13 +11,15 @@ //! .picture(Some("https://example.com/ada.png")); //! ``` +use std::cell::RefCell; 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, + App, Bounds, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, Pixels, + RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, + Window, canvas, div, fill, img, point, size, }; use crate::components::common::{ControlSizing, Sizable, StyledExt, h_flex}; @@ -37,6 +39,12 @@ const SHADE_PROBABILITY: f32 = 0.25; /// Minimum number of filled left-half cells. const MIN_FILLED: usize = 5; +// Computed identicon patterns per seed, so avatars do not reroll their PRNG every frame. +thread_local! { + static PATTERN_CACHE: RefCell> = + RefCell::new(HashMap::new()); +} + /// An avatar for a user or other entity. #[derive(IntoElement)] #[must_use] @@ -98,8 +106,8 @@ impl Sizable for Avatar { } } -impl gpui::Styled for Avatar { - fn style(&mut self) -> &mut gpui::StyleRefinement { +impl Styled for Avatar { + fn style(&mut self) -> &mut StyleRefinement { &mut self.style } } @@ -116,7 +124,11 @@ impl RenderOnce for Avatar { theme.radius.sm }; - let base = h_flex() + let has_picture = self.picture.is_some(); + let picture = self.picture; + let seed = PixelAvatar::seed(&self.id); + + h_flex() .id(ElementId::from(self.id.clone())) .flex_none() .justify_center() @@ -126,90 +138,16 @@ impl RenderOnce for Avatar { .rounded(radius) .role(Role::Image) .aria_label(self.name.clone().unwrap_or_else(|| self.id.clone())) - .refine_style(&self.style); - - match self.picture { - Some(url) => base.child(gpui::img(url).size_full().rounded(radius)), - None => base.child(PixelAvatar { - seed: fnv1a(self.id.as_bytes()), - side, - radius, - fully_rounded: self.fully_rounded, - }), - } - .into_any_element() - } -} - -/// 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), - ) + .children(picture.map(|url| img(url).size_full().rounded(radius))) + .when(!has_picture, |avatar| { + avatar.child(PixelAvatar { + seed, + side, + radius, + fully_rounded: self.fully_rounded, + }) + }) } } @@ -217,16 +155,39 @@ impl RenderOnce for IdentityRow { #[derive(IntoElement)] struct PixelAvatar { seed: u64, - side: gpui::Pixels, - radius: gpui::Pixels, + side: Pixels, + radius: Pixels, fully_rounded: bool, } +impl PixelAvatar { + /// Hashes `id` into the pattern seed. + fn seed(id: &str) -> u64 { + // FNV-1a 64-bit hash, stable across platforms and runs. + let mut hash = 0xcbf2_9ce4_8422_2325u64; + for &byte in id.as_bytes() { + hash ^= byte as u64; + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + hash + } + + /// The pattern for `seed`, computed once. + fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] { + let cached = PATTERN_CACHE.with(|cache| cache.borrow().get(&seed).copied()); + if let Some(cached) = cached { + return cached; + } + let computed = PixelRng::new(seed).pattern(); + PATTERN_CACHE.with(|cache| cache.borrow_mut().insert(seed, computed)); + computed + } +} + impl RenderOnce for PixelAvatar { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); - let pattern = pattern(self.seed); - let mut cells = Vec::new(); + let pattern = Self::pattern(self.seed); let hue = (self.seed as f32 / u64::MAX as f32) * 360.0; let accent = Oklch::from_hsla(theme.colors.accent); @@ -249,48 +210,48 @@ impl RenderOnce for PixelAvatar { let inset = if self.fully_rounded { self.side / GRID_SIZE as f32 } else { - gpui::Pixels::ZERO + Pixels::ZERO }; - for row in 0..GRID_SIZE { - for col in 0..GRID_SIZE { - let value = pattern[row * GRID_SIZE + col]; - if value != 0 { - let color = if value == 2 { shade } else { main }; - cells.push( - div() - .row_start(row as i16 + 1) - .row_end(row as i16 + 2) - .col_start(col as i16 + 1) - .col_end(col as i16 + 2) - .bg(color), - ); - } - } - } - div() - .grid() - .grid_cols(GRID_SIZE as u16) - .grid_rows(GRID_SIZE as u16) - .size(self.side) .flex_none() + .size(self.side) .p(inset) .rounded(self.radius) - .bg(gpui::Hsla { + .bg(Hsla { a: PIXEL_AVATAR_TINT_ALPHA, ..main }) - .children(cells) + .child( + canvas( + |bounds, _, _| bounds.size, + move |bounds, area, window, _| { + let cell = area.width / GRID_SIZE as f32; + for (index, value) in pattern.iter().enumerate() { + if *value == 0 { + continue; + } + let color = if *value == 2 { shade } else { main }; + let top_left = bounds.origin + + point( + (index % GRID_SIZE) as f32 * cell, + (index / GRID_SIZE) as f32 * cell, + ); + window.paint_quad(fill( + Bounds { + origin: top_left, + size: size(cell, cell), + }, + color, + )); + } + }, + ) + .size_full(), + ) } } -// Computed identicon patterns per seed, so avatars do not reroll their PRNG every frame. -thread_local! { - static PATTERN_CACHE: std::cell::RefCell> = - std::cell::RefCell::new(HashMap::new()); -} - /// Tiny xorshift64* PRNG for deriving the pattern from the seed. struct PixelRng(u64); @@ -299,6 +260,53 @@ impl PixelRng { Self(seed.max(1)) } + /// Fills the left half of the art area at random and mirrors it. + fn pattern(&mut self) -> [u8; GRID_SIZE * GRID_SIZE] { + /// Fill `cell (row, col)` and its horizontal mirror. + fn set_cell(pattern: &mut [u8; GRID_SIZE * GRID_SIZE], row: usize, col: usize, value: u8) { + pattern[row * GRID_SIZE + col] = value; + pattern[row * GRID_SIZE + (GRID_SIZE - 1 - col)] = value; + } + + let mut pattern = [0u8; GRID_SIZE * GRID_SIZE]; + let mut filled = 0usize; + + let art_rows = GRID_SIZE - 2 * MARGIN; + let art_columns = GRID_SIZE / 2 - MARGIN; + + for row in MARGIN..GRID_SIZE - MARGIN { + for col in MARGIN..GRID_SIZE / 2 { + if self.chance(FILL_PROBABILITY) { + let shade = self.chance(SHADE_PROBABILITY); + set_cell(&mut pattern, row, col, if shade { 2 } else { 1 }); + filled += 1; + } + } + } + + if filled < MIN_FILLED { + let total = art_rows * art_columns; + let start = (self.next() % total as u64) as usize; + + for offset in 0..total { + if filled >= MIN_FILLED { + break; + } + + let flat_index = (start + offset) % total; + let row = MARGIN + flat_index / art_columns; + let col = MARGIN + flat_index % art_columns; + + if pattern[row * GRID_SIZE + col] == 0 { + set_cell(&mut pattern, row, col, 1); + filled += 1; + } + } + } + + pattern + } + fn next(&mut self) -> u64 { let mut x = self.0; x ^= x >> 12; @@ -312,70 +320,3 @@ impl PixelRng { 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 { - return cached; - } - let computed = compute_pattern(seed); - PATTERN_CACHE.with(|cache| cache.borrow_mut().insert(seed, computed)); - computed -} - -fn compute_pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] { - let mut rng = PixelRng::new(seed); - let mut pattern = [0u8; GRID_SIZE * GRID_SIZE]; - let mut filled = 0usize; - - let art_rows = GRID_SIZE - 2 * MARGIN; - let art_columns = GRID_SIZE / 2 - MARGIN; - - for row in MARGIN..GRID_SIZE - MARGIN { - for col in MARGIN..GRID_SIZE / 2 { - if rng.chance(FILL_PROBABILITY) { - let shade = rng.chance(SHADE_PROBABILITY); - set_cell(&mut pattern, row, col, if shade { 2 } else { 1 }); - filled += 1; - } - } - } - - if filled < MIN_FILLED { - let total = art_rows * art_columns; - let start = (rng.next() % total as u64) as usize; - - for offset in 0..total { - if filled >= MIN_FILLED { - break; - } - - let flat_index = (start + offset) % total; - let row = MARGIN + flat_index / art_columns; - let col = MARGIN + flat_index % art_columns; - - if pattern[row * GRID_SIZE + col] == 0 { - set_cell(&mut pattern, row, col, 1); - filled += 1; - } - } - } - - pattern -} - -/// Fill `cell (row, col)` and its horizontal mirror. -fn set_cell(pattern: &mut [u8; GRID_SIZE * GRID_SIZE], row: usize, col: usize, value: u8) { - pattern[row * GRID_SIZE + col] = value; - pattern[row * GRID_SIZE + (GRID_SIZE - 1 - col)] = value; -} - -/// FNV-1a 64-bit hash, stable across platforms and runs. -fn fnv1a(bytes: &[u8]) -> u64 { - let mut hash = 0xcbf2_9ce4_8422_2325u64; - for &byte in bytes { - hash ^= byte as u64; - hash = hash.wrapping_mul(0x0000_0100_0000_01b3); - } - hash -} diff --git a/crates/ui/src/components/badge.rs b/crates/ui/src/components/badge.rs index 3fb3b21..c6a298b 100644 --- a/crates/ui/src/components/badge.rs +++ b/crates/ui/src/components/badge.rs @@ -13,17 +13,14 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyView, App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, - RenderOnce, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, - Window, relative, transparent_black, + RenderOnce, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, + relative, transparent_black, }; -use crate::components::common::{ControlSizing, Sizable, StyledExt, h_flex}; +use crate::components::common::{ControlSizing, Sizable, StyledExt, TooltipBuilder, h_flex}; use crate::icons::Icon; use crate::theme::{ActiveTheme as _, Size, Theme}; -/// The tooltip view builder gpui's `.tooltip(...)` expects. -type TooltipBuilder = Rc AnyView>; - /// The visual treatment of a [`Badge`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum BadgeVariant { @@ -141,8 +138,8 @@ impl Sizable for Badge { } } -impl gpui::Styled for Badge { - fn style(&mut self) -> &mut gpui::StyleRefinement { +impl Styled for Badge { + fn style(&mut self) -> &mut StyleRefinement { &mut self.style } } @@ -206,8 +203,8 @@ impl GroupedBadge { } } -impl gpui::Styled for GroupedBadge { - fn style(&mut self) -> &mut gpui::StyleRefinement { +impl Styled for GroupedBadge { + fn style(&mut self) -> &mut StyleRefinement { &mut self.style } } diff --git a/crates/ui/src/components/button.rs b/crates/ui/src/components/button.rs index bf3ce6a..bebd172 100644 --- a/crates/ui/src/components/button.rs +++ b/crates/ui/src/components/button.rs @@ -17,18 +17,16 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, AnyView, App, ClickEvent, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, Window, relative, transparent_black, + StyleRefinement, Styled, Window, relative, transparent_black, }; -use crate::components::common::{ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex}; +use crate::components::common::{ControlSizing, Sizable, StyledExt as _, TooltipBuilder, h_flex}; use crate::components::spinner::Spinner; use crate::icons::Icon; use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; /// The single activation handler, shared by pointer, Enter, and Space. type ClickHandler = Box; -/// The tooltip view builder gpui's `.tooltip(...)` expects. -type TooltipBuilder = Rc AnyView>; /// Which visual treatment a button uses. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -278,7 +276,7 @@ impl ParentElement for Button { } } -impl gpui::Styled for Button { +impl Styled for Button { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } @@ -302,13 +300,13 @@ impl RenderOnce for Button { pressed_border, } = self.variant.chrome(cx); + let theme = cx.theme(); let radius = if self.fully_rounded { - let theme = cx.theme(); theme.radius.full } else { - let theme = cx.theme(); theme.radius.control }; + let ring = theme.focus_ring(); let on_click = self.on_click; let a11y_label = self.a11y_label.or_else(|| self.label.clone()); @@ -320,7 +318,6 @@ impl RenderOnce for Button { let is_round_child = is_child_only && self.fully_rounded; let icon_trailing = self.side == ButtonSide::Right; - let ring = cx.theme().colors.ring; h_flex() .id(self.id.clone()) @@ -395,10 +392,8 @@ impl RenderOnce for Button { .tab_stop(self.tab_stop) .hover(move |style| style.bg(hover).border_color(hover_border)) .active(move |style| style.bg(pressed).border_color(pressed_border)) - .focus_visible(|style| style.shadow(focus_ring(ring))) - .when_some(on_click, |button, on_click| { - button.on_click(move |event, window, cx| on_click(event, window, cx)) - }) + .focus_visible(|style| style.shadow(ring)) + .when_some(on_click, |button, on_click| button.on_click(on_click)) }) } } diff --git a/crates/ui/src/components/checkbox.rs b/crates/ui/src/components/checkbox.rs index cb6b631..f6e527c 100644 --- a/crates/ui/src/components/checkbox.rs +++ b/crates/ui/src/components/checkbox.rs @@ -16,11 +16,11 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder as _; use gpui::{ App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, - SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Toggled, Window, }; -use crate::components::common::{ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex}; -use crate::icons::{IconRole, icon}; +use crate::components::common::{ControlSizing, Sizable, StyledExt as _, h_flex}; +use crate::icons::{Icon, IconRole}; use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; /// The change reporter, fired with the next value by pointer, Enter, and Space. @@ -109,7 +109,7 @@ impl Checkbox { } } -impl gpui::Styled for Checkbox { +impl Styled for Checkbox { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } @@ -125,6 +125,7 @@ impl RenderOnce for Checkbox { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let colors = theme.colors; + let ring = theme.focus_ring(); let ramps = theme.ramps; let size = self.size; let on_change = self.on_change; @@ -148,7 +149,7 @@ impl RenderOnce for Checkbox { .cursor_pointer() .focusable() .tab_stop(true) - .focus_visible(|style| style.shadow(focus_ring(colors.ring))) + .focus_visible(|style| style.shadow(ring)) .when_some(on_change, |checkbox, on_change| { checkbox.on_click(move |_, window, cx| on_change(next, window, cx)) }) @@ -170,7 +171,7 @@ impl RenderOnce for Checkbox { .border_color(ramps.primary.hover) }) .child( - icon(IconRole::Check) + Icon::from(IconRole::Check) .size(size.dense_icon_rems()) .color(colors.primary_foreground), ) diff --git a/crates/ui/src/components/clipboard.rs b/crates/ui/src/components/clipboard.rs index aa3db11..246e37c 100644 --- a/crates/ui/src/components/clipboard.rs +++ b/crates/ui/src/components/clipboard.rs @@ -16,19 +16,19 @@ use std::time::Duration; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyView, App, ClipboardItem, ElementId, IntoElement, ParentElement as _, RenderOnce, - SharedString, StyleRefinement, Styled as _, Task, Window, div, + SharedString, StyleRefinement, Styled, Task, Window, div, }; use crate::components::button::{Button, ButtonVariant}; -use crate::components::common::{ResultLogErr as _, Sizable, StyledExt as _, h_flex}; +use crate::components::common::{ + ResultLogErr as _, Sizable, StyledExt as _, TooltipBuilder, h_flex, +}; use crate::icons::IconRole; use crate::theme::{ActiveTheme as _, Size}; /// How long the check mark shows before reverting to the copy icon. 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; @@ -46,6 +46,12 @@ pub struct ClipboardButton { style: StyleRefinement, } +/// The transient copied marker keyed per button. +struct CopiedState { + generation: u64, + task: Option>, +} + impl ClipboardButton { /// Creates a copy button for this value. pub fn new(id: I, value: V) -> Self @@ -105,10 +111,10 @@ impl Sizable for ClipboardButton { } } -/// The transient copied marker keyed per button. -struct CopiedState { - generation: u64, - task: Option>, +impl Styled for ClipboardButton { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } } impl RenderOnce for ClipboardButton { @@ -143,9 +149,10 @@ impl RenderOnce for ClipboardButton { button.tooltip(move |window, cx| tooltip(window, cx)) }) .on_click({ + let weak = copied.downgrade(); let value = self.value; - let copied = copied.clone(); let on_copied = self.on_copied; + move |_, window, cx| { cx.write_to_clipboard(ClipboardItem::new_string(value.to_string())); @@ -155,17 +162,18 @@ impl RenderOnce for ClipboardButton { state.generation }); - let weak = copied.downgrade(); + let task_weak = weak.clone(); let task = window.spawn(cx, async move |cx| { cx.background_executor().timer(COPIED_DURATION).await; cx.update(|_, cx| { - weak.update(cx, |state, cx| { - if state.generation == generation { - state.generation = 0; - cx.notify(); - } - }) - .log_err(); + task_weak + .update(cx, |state, cx| { + if state.generation == generation { + state.generation = 0; + cx.notify(); + } + }) + .log_err(); }) .log_err(); }); @@ -174,7 +182,6 @@ impl RenderOnce for ClipboardButton { state.task = Some(task); }); - // Invoke the callback after copying if let Some(on_copied) = &on_copied { on_copied(cx); } @@ -187,7 +194,7 @@ impl RenderOnce for ClipboardButton { #[derive(IntoElement)] #[must_use] pub struct CopyRow { - id: SharedString, + id: ElementId, value: SharedString, large_text: bool, } @@ -196,7 +203,7 @@ impl CopyRow { /// Monospace `value` in a secondary-background row (the clone-command look). pub fn new(id: ID, value: V) -> Self where - ID: Into, + ID: Into, V: Into, { Self { @@ -238,12 +245,9 @@ impl RenderOnce for CopyRow { }) .child(self.value.clone()), ) - .child(if self.large_text { - ClipboardButton::new(self.id, self.value).into_any_element() - } else { + .child( ClipboardButton::new(self.id, self.value) - .xsmall() - .into_any_element() - }) + .when(!self.large_text, |button| button.xsmall()), + ) } } diff --git a/crates/ui/src/components/code.rs b/crates/ui/src/components/code.rs index f7e01b4..970c3ae 100644 --- a/crates/ui/src/components/code.rs +++ b/crates/ui/src/components/code.rs @@ -5,24 +5,25 @@ //! //! The view is the state: build a [`CodeViewState`] in a [`gpui::Entity`] //! and render the entity, then mutate the state to update the view. -//! [`bind_code_view_keys`] installs the selection copy chord once at +//! [`CodeViewState::bind_keys`] installs the selection copy chord once at //! startup. //! //! # Examples //! //! ```no_run //! use gpui::{App, AppContext as _}; -//! use ui::code::{CodeViewState, bind_code_view_keys}; +//! use ui::code::CodeViewState; //! use ui::highlight::Language; //! //! fn source_pane(cx: &mut App) -> gpui::Entity { -//! bind_code_view_keys(cx); +//! CodeViewState::bind_keys(cx); //! let view = cx.new(|cx| CodeViewState::new("source", "fn main() {}\n", Language::Rust, cx)); //! view.update(cx, |state, cx| state.set_source("fn hello() {}\n", Language::Rust, cx)); //! view //! } //! ``` +use std::cell::RefCell; use std::rc::Rc; use gpui::prelude::FluentBuilder as _; @@ -42,11 +43,11 @@ use crate::theme::{ WASH_ALPHA_SOFT, }; -actions!(code_view, [Copy]); - /// The key context the code view declares while it holds focus. pub const CODE_VIEW_CONTEXT: &str = "CodeView"; +actions!(code_view, [Copy]); + /// A point in the source, in lines and characters (not bytes). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] struct SelectionPoint { @@ -66,7 +67,8 @@ impl SelectionPoint { /// The source-derived part of one rendered line, cached between frames. struct CodeLineLayout { text: String, - roles: Vec, + /// Byte ranges of same-role runs, built once per source change. + runs: Vec<(std::ops::Range, Role)>, } /// Retained state for a code view. @@ -170,22 +172,26 @@ impl CodeViewState { .iter() .map(|line| { let mut text = String::new(); + let mut runs: Vec<(std::ops::Range, Role)> = Vec::new(); + for span in &line.spans { + let start = text.len(); text.push_str(&span.text); - } + let end = text.len(); - let char_count = text.chars().count(); - let mut roles = vec![Role::Text; char_count]; - let mut offset = 0usize; - for span in &line.spans { - let chars = span.text.chars().count(); - for slot in &mut roles[offset..offset + chars] { - *slot = span.role; + if start == end { + continue; + } + + match runs.last_mut() { + Some((range, role)) if *role == span.role && range.end == start => { + range.end = end; + } + _ => runs.push((start..end, span.role)), } - offset += chars; } - CodeLineLayout { text, roles } + CodeLineLayout { text, runs } }) .collect() } @@ -200,8 +206,7 @@ impl CodeViewState { &self.code } - /// Scrolls `line` to the top of the view; past-the-end lines clamp to - /// the last line. + /// Scrolls `line` to the top of the view; past-the-end lines clamp to the last line. pub fn scroll_to_line(&self, line: usize) { self.handle.scroll_to_item( line.min(self.code.lines.len().saturating_sub(1)), @@ -305,60 +310,69 @@ impl CodeViewState { ) -> 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 runs = layout.map_or(&[][..], |layout| layout.runs.as_slice()); - 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; + // The selection is in char columns; convert once to byte offsets on this line. + let selected = selection.and_then(|(start, end)| { + if line_ix < start.row || line_ix > end.row { + return None; } - } + + let start_col = if line_ix == start.row { start.col } else { 0 }; + let end_col = if line_ix == end.row { + end.col + } else { + usize::MAX + }; + + Some(( + byte_offset_of_char(text, start_col), + byte_offset_of_char(text, end_col), + )) + }); 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 (range, role) in runs { + match selected { + None => push_highlight(&mut highlights, range.clone(), *role, false, colors, ramps), + Some((start, end)) => { + if range.end <= start || range.start >= end { + push_highlight(&mut highlights, range.clone(), *role, false, colors, ramps); + continue; + } - 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), - )); + if range.start < start { + push_highlight( + &mut highlights, + range.start..start, + *role, + false, + colors, + ramps, + ); + } + + push_highlight( + &mut highlights, + range.start.max(start)..range.end.min(end), + *role, + true, + colors, + ramps, + ); + + if range.end > end { + push_highlight( + &mut highlights, + end..range.end, + *role, + false, + 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 { @@ -410,6 +424,30 @@ impl CodeViewState { ) .into_any_element() } + + /// 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_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]); + } } impl gpui::Focusable for CodeViewState { @@ -434,8 +472,7 @@ impl Render for CodeViewState { let selection = self.selection(); let gutter_width = CODE_GUTTER_WIDTH; - let bounds_cell: std::rc::Rc>>> = - std::rc::Rc::new(std::cell::RefCell::new(None)); + let bounds_cell: Rc>>> = Rc::new(RefCell::new(None)); div() .id((id.clone(), "view")) @@ -607,23 +644,23 @@ impl Render for CodeViewState { } } -/// 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]); +/// The byte offset of a char column, clamped to the text length. +fn byte_offset_of_char(text: &str, column: usize) -> usize { + text.char_indices() + .nth(column) + .map_or(text.len(), |(offset, _)| offset) +} + +/// Appends one styled run, skipping empty ranges. +fn push_highlight( + highlights: &mut Vec<(std::ops::Range, HighlightStyle)>, + range: std::ops::Range, + role: Role, + selected: bool, + colors: ColorTokens, + ramps: Ramps, +) { + if !range.is_empty() { + highlights.push((range, role.run_style(selected, colors, ramps))); + } } diff --git a/crates/ui/src/components/combobox.rs b/crates/ui/src/components/combobox.rs index c4c8e5a..7ef9fa9 100644 --- a/crates/ui/src/components/combobox.rs +++ b/crates/ui/src/components/combobox.rs @@ -29,26 +29,22 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder; use gpui::{ - App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, - MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, SharedString, - StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task, - UniformListScrollHandle, Window, actions, canvas, div, uniform_list, + AnyElement, App, Bounds, ClickEvent, Context, DispatchPhase, ElementId, Entity, + InteractiveElement as _, IntoElement, KeyBinding, MouseButton, MouseDownEvent, + ParentElement as _, Pixels, Render, Role, SharedString, StatefulInteractiveElement as _, + StyleRefinement, Styled, Subscription, Task, UniformListScrollHandle, Window, actions, canvas, + div, uniform_list, }; use crate::components::common::{ - ControlSizing, ResultLogErr as _, Sizable, StyledExt as _, floating_panel, h_flex, - paint_highlighted_row, v_flex, wrapping_adjacent_selectable, + ControlSizing, ResultLogErr as _, SelectableRows as _, Sizable, StyledExt as _, h_flex, v_flex, }; use crate::components::empty_state::EmptyState; use crate::components::input::{Input, InputState, InputStateEvent}; -use crate::icons::{Icon, IconRole, icon}; +use crate::components::menu::anchored_overlay; +use crate::icons::{Icon, IconRole}; use crate::theme::{ActiveTheme as _, COMBOBOX_MIN_WIDTH, COMBOBOX_WIDTH, POPUP_MAX_HEIGHT, Size}; -actions!( - combobox, - [HighlightNext, HighlightPrevious, Choose, Dismiss] -); - /// The key context the combobox's wrapper declares. pub const COMBOBOX_CONTEXT: &str = "Combobox"; @@ -56,6 +52,13 @@ pub const COMBOBOX_CONTEXT: &str = "Combobox"; pub type ComboboxOption = (T, SharedString); /// Reports the value whenever it changes. pub type ComboboxHandler = Rc, &mut Window, &mut App)>; +/// A popup row's pointer handler, told which row it fired on. +type RowHandler = Rc; + +actions!( + combobox, + [HighlightNext, HighlightPrevious, Choose, Dismiss] +); /// Builder for a combobox, consumed by [`ComboboxState::new`]. #[must_use] @@ -138,6 +141,21 @@ where self.name = label.into(); self } + + /// Binds the combobox's four keys: down, up, enter, and escape. + pub fn bind_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)), + ]); + } } /// Style refinements set the combobox's width. @@ -178,6 +196,8 @@ where name: SharedString, placeholder: SharedString, options: Vec>, + /// Each option's label lowercased, so filtering skips no work on labels. + option_labels: Vec, /// The chosen value. `None` while the text names nothing. selected: Option, /// A label shown in the field in place of a chosen option. @@ -195,7 +215,7 @@ where selected_icon: Option, /// The row list's scroll, kept across frames while the popup is open. rows_scroll: UniformListScrollHandle, - /// The most recent handler report in flight; a newer report replaces it. + /// The most recent handler report in flight; a newer report waits for it. task: Option>, /// Keeps the query-event subscription tied to the state's lifetime. _subscription: Subscription, @@ -218,8 +238,7 @@ where pub fn new(combobox: Combobox, window: &mut Window, cx: &mut Context) -> Self { let query = InputState::new(cx); - // The field starts showing the label of whatever was chosen, - // so text and value agree from the first frame. + // The field starts showing the label of whatever was chosen. if let Some(selected) = &combobox.selected && let Some((_, label)) = combobox.options.iter().find(|(value, _)| value == selected) { @@ -236,12 +255,14 @@ where }); let visible = (0..combobox.options.len()).collect(); + let option_labels = Self::lowercased_labels(&combobox.options); Self { id: combobox.id, name: combobox.name, placeholder: combobox.placeholder, options: combobox.options, + option_labels, selected: combobox.selected, display_label: None, query, @@ -266,13 +287,17 @@ where pub fn set_selected(&mut self, value: Option, window: &mut Window, cx: &mut Context) { let changed = self.selected != value; self.display_label = None; - self.set_value(value, window, cx); + + let reported = self.set_value(value, window, cx); + if changed { let label = self.selected_label().unwrap_or_default(); self.query .update(cx, |query, cx| query.set_value_silent(label, window, cx)); self.refilter(""); - cx.notify(); + if !reported { + cx.notify(); + } } } @@ -317,9 +342,12 @@ where /// Replaces the choice list and re-runs the current filter. pub fn set_options(&mut self, options: Vec>, cx: &mut Context) { + self.option_labels = Self::lowercased_labels(&options); self.options = options; + let query = self.query.read(cx).value().to_string(); self.refilter(&query); + cx.notify(); } @@ -335,14 +363,21 @@ where self.display_label.clone() } + fn lowercased_labels(options: &[ComboboxOption]) -> Vec { + options + .iter() + .map(|(_, label)| label.to_lowercase()) + .collect() + } + /// Recomputes `visible` for `query` and clamps the highlight onto it. fn refilter(&mut self, query: &str) { let needle = query.to_lowercase(); self.visible = self - .options + .option_labels .iter() .enumerate() - .filter(|(_, (_, label))| label.to_lowercase().contains(&needle)) + .filter(|(_, label)| label.contains(&needle)) .map(|(index, _)| index) .collect(); self.highlight = self.highlight.filter(|row| *row < self.visible.len()); @@ -352,22 +387,32 @@ where self.query.read(cx).value().trim().to_string() } - /// Sets the value and reports it, including when it is `None`. - fn set_value(&mut self, value: Option, window: &mut Window, cx: &mut Context) { + /// Sets the value and reports it, including when it is `None`; returns whether it notified. + fn set_value(&mut self, value: Option, window: &mut Window, cx: &mut Context) -> bool { if self.selected == value { - return; + return false; } + self.display_label = None; self.selected = value.clone(); + if let Some(on_change) = self.on_change.clone() { - let value = value.clone(); + // Dropping the previous task would cancel a report that has not run yet. + let previous = self.task.take(); let task = window.spawn(cx, async move |cx| { - cx.update(|window, cx| on_change(value, window, cx)) - .log_err(); + if let Some(previous) = previous { + previous.await; + } + + cx.update(|window, cx| { + on_change(value, window, cx); + }) + .log_err(); }); - self.task.replace(task); + self.task = Some(task); } cx.notify(); + true } /// Commits the option at popup *row*. @@ -393,8 +438,10 @@ where let query = self.query_text(cx); self.refilter(&query); self.highlight = Some(0); - self.set_value(None, window, cx); - cx.notify(); + + if !self.set_value(None, window, cx) { + cx.notify(); + } } /// Gaining focus. @@ -431,7 +478,7 @@ where } let current = self.highlight.filter(|row| *row < self.visible.len()); let rows: Vec = (0..self.visible.len()).collect(); - let next = wrapping_adjacent_selectable(&rows, current, delta > 0); + let next = rows.wrapping_adjacent(current, delta > 0); self.highlight = next; cx.notify(); } @@ -454,6 +501,73 @@ where self.highlight = None; cx.notify(); } + + /// One popup row, highlighted and checked from the current state. + fn render_row( + &self, + row: usize, + row_height: Pixels, + on_move: RowHandler, + on_click: RowHandler, + cx: &App, + ) -> AnyElement { + let Some(option_index) = self.visible.get(row).copied() else { + return div().into_any_element(); + }; + + let Some((value, label)) = self.options.get(option_index) else { + return div().into_any_element(); + }; + + let highlighted = self.highlight == Some(row); + let checked = self.selected.as_ref() == Some(value); + let theme = cx.theme(); + let size = self.size; + + div() + .id(("option", option_index)) + .debug_selector({ + let id = self.id.clone(); + move || format!("{id}-option-{row}") + }) + .role(Role::ListBoxOption) + .aria_label(label.clone()) + .w_full() + .flex() + .items_center() + .gap_2() + .px_2() + .py_1() + .h(row_height) + .control_text(size) + .rounded(theme.radius.full) + .highlighted_row(cx, highlighted, false) + .on_mouse_move({ + let on_move = on_move.clone(); + move |_, window, cx| on_move(&row, window, cx) + }) + .on_click({ + let on_click = on_click.clone(); + move |_, window, cx| on_click(&row, window, cx) + }) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .child(label.clone()), + ) + .when(checked, |row| { + row.child( + Icon::from(IconRole::Check) + .size(size.dense_icon_rems()) + .color(theme.colors.foreground), + ) + }) + .into_any_element() + } } impl Render for ComboboxState @@ -472,9 +586,8 @@ where }; let id = self.id.clone(); - let state = cx.entity(); let open = self.highlight.is_some(); - + let weak = cx.weak_entity(); let wrapper_bounds: Rc>>> = Rc::new(RefCell::new(None)); div() @@ -487,30 +600,18 @@ where .role(Role::ComboBox) .aria_expanded(open) .aria_label(self.name.clone()) - .on_action({ - let state = state.clone(); - move |_: &HighlightNext, _window, cx| { - state.update(cx, |state, cx| state.move_highlight(1, cx)); - } - }) - .on_action({ - let state = state.clone(); - move |_: &HighlightPrevious, _window, cx| { - state.update(cx, |state, cx| state.move_highlight(-1, cx)); - } - }) - .on_action({ - let state = state.clone(); - move |_: &Choose, window, cx| { - state.update(cx, |state, cx| state.choose(window, cx)); - } - }) - .on_action({ - let state = state.clone(); - move |_: &Dismiss, _window, cx| { - state.update(cx, |state, cx| state.dismiss(_window, cx)); - } - }) + .on_action(cx.listener(|state, _: &HighlightNext, _window, cx| { + state.move_highlight(1, cx); + })) + .on_action(cx.listener(|state, _: &HighlightPrevious, _window, cx| { + state.move_highlight(-1, cx); + })) + .on_action(cx.listener(|state, _: &Choose, window, cx| { + state.choose(window, cx); + })) + .on_action(cx.listener(|state, _: &Dismiss, window, cx| { + state.dismiss(window, cx); + })) .child( canvas( { @@ -546,135 +647,55 @@ where .id((id.clone(), "chevron")) .cursor_pointer() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click({ - let state = state.clone(); - move |_, window, cx| { - let focus = state.read(cx).query.read(cx).focus_handle(); - window.focus(&focus, cx); - state.update(cx, |state, cx| { - if state.highlight.is_some() { - state.highlight = None; - } else { - if state.selected.is_some() - || state.display_label.is_some() - { - state.refilter(""); - } else { - let query = - state.query.read(cx).value().to_string(); - state.refilter(&query); - } - state.highlight = Some(0); - } - cx.notify(); - }); + .on_click(cx.listener(|state, _: &ClickEvent, window, cx| { + let focus = state.query.read(cx).focus_handle(); + window.focus(&focus, cx); + + if state.highlight.is_some() { + state.highlight = None; + } else { + if state.selected.is_some() || state.display_label.is_some() { + state.refilter(""); + } else { + let query = state.query.read(cx).value().to_string(); + state.refilter(&query); + } + state.highlight = Some(0); } - }) + + cx.notify(); + })) .child( - icon(IconRole::ChevronDown) + Icon::from(IconRole::ChevronDown) .size(self.size.dense_icon_rems()) .color(colors.muted_foreground), ), ), ) .when(open, |wrapper| { - let visible = self.visible.clone(); - let options = self.options.clone(); - let highlight = self.highlight; - let selected = self.selected.clone(); - let size = self.size; - let list_state = state.clone(); let rows_id = id.clone(); - let radius_full = radius.full; - let foreground = colors.foreground; + let size = self.size; + let rows_scroll = self.rows_scroll.clone(); + let count = self.visible.len(); // Rows are `control_height`, so the row height follows the size. let row_height = size.control_height_rems().to_pixels(window.rem_size()); - let count = visible.len(); - let list_height = (row_height * count as f32) .max(row_height) .min(POPUP_MAX_HEIGHT); - let rows: gpui::AnyElement = if count == 0 { - EmptyState::compact("No matches", cx).into_any_element() - } else { - uniform_list((rows_id.clone(), "rows"), count, move |range, _, cx| { - range - .map(|row| { - let Some(option_index) = visible.get(row).copied() else { - return div().into_any_element(); - }; - let Some((value, label)) = options.get(option_index) else { - return div().into_any_element(); - }; + let on_move: RowHandler = + Rc::new(cx.listener(|state, row: &usize, _window, cx| { + if state.highlight != Some(*row) { + state.highlight = Some(*row); + cx.notify(); + } + })); - let highlighted = highlight == Some(row); - let checked = selected.as_ref() == Some(value); - let state = list_state.clone(); - let row_index = row; - - div() - .id(("option", option_index)) - .debug_selector({ - let id = rows_id.clone(); - move || format!("{id}-option-{row}") - }) - .role(Role::ListBoxOption) - .aria_label(label.clone()) - .w_full() - .flex() - .items_center() - .gap_2() - .px_2() - .py_1() - .h(row_height) - .control_text(size) - .rounded(radius_full) - .map(|row| paint_highlighted_row(cx, row, highlighted, false)) - .on_mouse_move({ - let state = state.clone(); - move |_, _window, cx| { - if state.read(cx).highlight != Some(row_index) { - state.update(cx, |state, cx| { - state.highlight = Some(row_index); - cx.notify(); - }); - } - } - }) - .on_click({ - let state = state.clone(); - move |_, window, cx| { - state.update(cx, |state, cx| { - state.choose_row(row_index, window, cx) - }); - } - }) - .child( - div() - .flex_1() - .min_w_0() - .overflow_hidden() - .whitespace_nowrap() - .text_ellipsis() - .child(label.clone()), - ) - .when(checked, |row| { - row.child( - icon(IconRole::Check) - .size(size.dense_icon_rems()) - .color(foreground), - ) - }) - .into_any_element() - }) - .collect() - }) - .track_scroll(&self.rows_scroll) - .h(list_height) - .into_any_element() - }; + let on_click: RowHandler = + Rc::new(cx.listener(|state, row: &usize, window, cx| { + state.choose_row(*row, window, cx); + })); let panel_bounds: Rc>>> = Rc::new(RefCell::new(None)); @@ -683,84 +704,94 @@ where .map(|bounds| bounds.size.width) .unwrap_or(COMBOBOX_WIDTH); - wrapper.child(crate::components::menu::anchored_overlay( + let on_outside = Rc::new(cx.listener({ + let panel_bounds = panel_bounds.clone(); + let wrapper_bounds = wrapper_bounds.clone(); + + move |state, event: &MouseDownEvent, _window, cx| { + let on_panel = panel_bounds + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)); + let on_wrapper = wrapper_bounds + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)); + if on_panel || on_wrapper { + return; + } + state.highlight = None; + cx.notify(); + } + })); + + wrapper.child(anchored_overlay( None, - floating_panel( - cx, - radius.overlay, - v_flex() - .id((id.clone(), "panel")) - .debug_selector({ - let id = id.clone(); - move || format!("{id}-panel") - }) - .w(popup_width) - .p_1() - .text_color(colors.foreground), - shadows, - ) - .overflow_hidden() - .child(rows) - .child( - canvas( - { - let cell = panel_bounds.clone(); - move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) - }, - { - let state = state.clone(); - let panel_bounds = panel_bounds.clone(); - let wrapper_bounds = wrapper_bounds.clone(); - move |_, _, window, _cx| { - window.on_mouse_event({ - let state = state.clone(); - let panel_bounds = panel_bounds.clone(); - let wrapper_bounds = wrapper_bounds.clone(); - move |event: &MouseDownEvent, phase, _window, cx| { - if phase != gpui::DispatchPhase::Bubble { - return; - } - let on_panel = - panel_bounds.borrow().is_some_and(|bounds| { - bounds.contains(&event.position) - }); - let on_wrapper = - wrapper_bounds.borrow().is_some_and(|bounds| { - bounds.contains(&event.position) - }); - if on_panel || on_wrapper { - return; - } - state.update(cx, |state, cx| { - state.highlight = None; - cx.notify(); - }); - } - }); - } - }, + v_flex() + .id((id.clone(), "panel")) + .debug_selector({ + let id = id.clone(); + move || format!("{id}-panel") + }) + .w(popup_width) + .p_1() + .text_color(colors.foreground) + .floating_panel(cx, radius.overlay, shadows) + .overflow_hidden() + .when(count == 0, |panel| { + panel.child(EmptyState::compact("No matches", cx)) + }) + .when(count > 0, |panel| { + panel.child( + uniform_list( + (rows_id.clone(), "rows"), + count, + move |range, _window, cx| { + range + .map(|row| { + // Paint-time read: the state is not leased here. + weak.read_with(cx, |state, cx| { + state.render_row( + row, + row_height, + on_move.clone(), + on_click.clone(), + cx, + ) + }) + .unwrap_or_else(|_| div().into_any_element()) + }) + .collect() + }, + ) + .track_scroll(&rows_scroll) + .h(list_height), + ) + }) + .child( + canvas( + { + let cell = panel_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + { + move |_, _, window, _cx| { + let on_outside = on_outside.clone(); + window.on_mouse_event( + move |event: &MouseDownEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble { + return; + } + on_outside(event, window, cx); + }, + ); + } + }, + ) + .absolute() + .inset_0(), ) - .absolute() - .inset_0(), - ) - .into_any_element(), + .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 5dd709a..a245b4a 100644 --- a/crates/ui/src/components/command_palette.rs +++ b/crates/ui/src/components/command_palette.rs @@ -35,19 +35,14 @@ use gpui::{ }; use crate::components::common::{ - DIALOG_LAYER, StyledExt as _, floating_panel, h_flex, paint_highlighted_row, v_flex, - wrapping_adjacent_selectable, + DIALOG_LAYER, ElementIdExt as _, SelectableRows as _, StyledExt as _, h_flex, v_flex, }; use crate::components::empty_state::EmptyState; use crate::components::input::{Input, InputState, InputStateEvent}; +use crate::components::menu::focus_capture; use crate::icons::Icon; use crate::theme::{ActiveTheme as _, POPUP_MAX_HEIGHT}; -actions!( - command_palette, - [HighlightNext, HighlightPrevious, Choose, Dismiss] -); - /// The key context the palette's panel declares. pub const COMMAND_PALETTE_CONTEXT: &str = "CommandPalette"; @@ -56,6 +51,11 @@ pub type CommandMatcher = Rc Vec>; /// Runs the chosen command. pub type CommandHandler = Rc; +actions!( + command_palette, + [HighlightNext, HighlightPrevious, Choose, Dismiss] +); + /// A command the palette can run: a stable id and the label the matcher sees. #[derive(Clone)] #[must_use] @@ -311,8 +311,10 @@ impl CommandPaletteState { if self.matches.is_empty() { return; } + let rows: Vec = (0..self.matches.len()).collect(); - let next = wrapping_adjacent_selectable(&rows, self.highlight, delta > 0); + let next = rows.wrapping_adjacent(self.highlight, delta > 0); + self.highlight = next; cx.notify(); } @@ -346,10 +348,30 @@ impl CommandPaletteState { } self.close(cx); } + + /// Binds the palette's four keys: down, up, enter, and escape. + pub fn bind_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)), + ]); + } } impl Render for CommandPaletteState { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + // Restores the trigger's focus when the palette closes. + let overlay_focus = self.query.read(cx).focus_handle(); + self.id + .track_overlay_focus(&overlay_focus, self.open, window, cx); + if !self.open { return div().into_any_element(); } @@ -409,7 +431,7 @@ impl Render for CommandPaletteState { .text_sm() .line_height(relative(1.0)) .rounded(radius_sm) - .map(|row| paint_highlighted_row(cx, row, highlighted, false)) + .highlighted_row(cx, highlighted, false) .on_mouse_move({ let state = state.clone(); move |_, _window, cx| { @@ -482,79 +504,59 @@ impl Render for CommandPaletteState { }), ) .child( - floating_panel( - cx, - radius.overlay, - v_flex() - .id((id.clone(), "panel")) - .debug_selector({ - let id = id.clone(); - move || format!("{id}-panel") - }) - .key_context(COMMAND_PALETTE_CONTEXT) - .role(Role::Dialog) - .aria_label(self.name.clone()) - .w_full() - .max_w(relative(0.6)) - .p_2() - .gap_2() - .text_color(colors.foreground), - shadows, - ) - .overflow_hidden() - .refine_style(&self.style) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_action({ - let state = state.clone(); - move |_: &HighlightNext, _window, cx| { - state.update(cx, |state, cx| state.move_highlight(1, cx)); - } - }) - .on_action({ - let state = state.clone(); - move |_: &HighlightPrevious, _window, cx| { - state.update(cx, |state, cx| state.move_highlight(-1, cx)); - } - }) - .on_action({ - let state = state.clone(); - move |_: &Choose, window, cx| { - state.update(cx, |state, cx| state.choose(window, cx)); - } - }) - .on_action({ - let state = state.clone(); - move |_: &Dismiss, window, cx| { - state.update(cx, |state, cx| state.dismiss(window, cx)); - } - }) - .child( - Input::new((id.clone(), "query"), self.query.clone()) - .placeholder(self.placeholder.clone()), - ) - .child(rows) - .child(crate::components::menu::focus_capture( - query_focus.clone(), - move |window, cx| !query_focus.contains_focused(window, cx), - )), + v_flex() + .id((id.clone(), "panel")) + .debug_selector({ + let id = id.clone(); + move || format!("{id}-panel") + }) + .key_context(COMMAND_PALETTE_CONTEXT) + .role(Role::Dialog) + .aria_label(self.name.clone()) + .w_full() + .max_w(relative(0.6)) + .p_2() + .gap_2() + .text_color(colors.foreground) + .floating_panel(cx, radius.overlay, shadows) + .overflow_hidden() + .refine_style(&self.style) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_action({ + let state = state.clone(); + move |_: &HighlightNext, _window, cx| { + state.update(cx, |state, cx| state.move_highlight(1, cx)); + } + }) + .on_action({ + let state = state.clone(); + move |_: &HighlightPrevious, _window, cx| { + state.update(cx, |state, cx| state.move_highlight(-1, cx)); + } + }) + .on_action({ + let state = state.clone(); + move |_: &Choose, window, cx| { + state.update(cx, |state, cx| state.choose(window, cx)); + } + }) + .on_action({ + let state = state.clone(); + move |_: &Dismiss, window, cx| { + state.update(cx, |state, cx| state.dismiss(window, cx)); + } + }) + .child( + Input::new((id.clone(), "query"), self.query.clone()) + .placeholder(self.placeholder.clone()), + ) + .child(rows) + .child(focus_capture(query_focus.clone(), move |window, cx| { + !query_focus.contains_focused(window, cx) + })), ), ) .with_priority(DIALOG_LAYER) .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 0291b73..76a9e49 100644 --- a/crates/ui/src/components/common.rs +++ b/crates/ui/src/components/common.rs @@ -10,14 +10,15 @@ //! let column = v_flex().gap_2().child(row); //! ``` -use gpui::prelude::FluentBuilder as _; +use std::rc::Rc; +use std::sync::Arc; + use gpui::{ - App, BoxShadow, Div, ElementId, FocusHandle, FontWeight, Hsla, IntoElement, Pixels, - Refineable as _, Rems, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, - Window, div, px, rems, + AnyView, App, BoxShadow, Div, ElementId, FocusHandle, FontWeight, Pixels, Refineable as _, + Rems, StatefulInteractiveElement, StyleRefinement, Styled, Window, div, rems, }; -use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD, Size}; +use crate::theme::{ActiveTheme as _, 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; @@ -27,19 +28,9 @@ pub const OVERLAY_LAYER: usize = 2; pub const TOAST_LAYER: usize = 3; /// A handler told to clean up after a dismissed surface. -pub type DismissHandler = std::rc::Rc; - -/// A row whose children center on the cross axis. -#[must_use] -pub fn h_flex() -> Div { - div().flex().flex_row().items_center() -} - -/// A column whose children stack on the main axis. -#[must_use] -pub fn v_flex() -> Div { - div().flex().flex_col() -} +pub type DismissHandler = Rc; +/// Builds a tooltip's view once its hover delay elapses. +pub type TooltipBuilder = Rc AnyView>; /// Logs the error and yields the success value, if any. pub trait ResultLogErr { @@ -80,191 +71,184 @@ pub trait StyledExt: Styled + Sized { self.text_style().font_weight = Some(FontWeight::SEMIBOLD); self } + + /// The shared floating-panel stack. + #[must_use] + fn floating_panel( + self, + cx: &App, + radius: Pixels, + shadows: impl Into>, + ) -> Self { + let theme = cx.theme(); + let mut panel = self + .bg(theme.colors.surface) + .rounded(radius) + .border_1() + .border_color(theme.colors.border); + let shadow = StyleRefinement::default().shadow(shadows.into().to_vec()); + panel.style().refine(&shadow); + panel + } + + /// A selectable row's background. + #[must_use] + fn selectable_row(self, cx: &App, selected: bool, disabled: bool) -> Self + where + Self: StatefulInteractiveElement, + { + let theme = cx.theme(); + if disabled { + self + } else if selected { + self.bg(theme.ramps.primary.base) + } else { + self.hover(|row| row.bg(theme.colors.muted)) + } + } + + /// A row that highlights under the pointer, for lists driven by mouse move + /// instead of selection. + #[must_use] + fn highlighted_row(self, cx: &App, highlighted: bool, disabled: bool) -> Self + where + Self: StatefulInteractiveElement, + { + let theme = cx.theme(); + if disabled { + self + } else if highlighted { + self.bg(theme.colors.muted) + } else { + self.hover(|row| row.bg(theme.colors.muted)) + } + } } impl StyledExt for E {} -/// Returns a focus handle for the given element ID. -pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusHandle { - window - .with_element_namespace(id.clone(), |window| { - window.use_keyed_state("focus-handle", cx, |_, cx| cx.focus_handle()) - }) - .read(cx) - .clone() -} +/// Per-element-id focus and overlay state. +pub trait ElementIdExt { + /// Returns a focus handle for the element ID. + fn focus_handle(&self, window: &mut Window, cx: &mut App) -> FocusHandle; -/// Saves the focused handle while an overlay is open and restores it when the -/// overlay closes, unless another surface already took focus. -pub(crate) fn track_overlay_focus( - id: &ElementId, - overlay_focus: &FocusHandle, - open: bool, - window: &mut Window, - cx: &mut App, -) { - let was_open = window.use_keyed_state( - SharedString::from(format!("overlay-was-open:{id}")), - cx, - |_, _| false, - ); - let previous = window.use_keyed_state( - SharedString::from(format!("overlay-previous-focus:{id}")), - cx, - |_, _| None::, + /// Saves the focused handle while an overlay is open and restores it when the overlay closes. + fn track_overlay_focus( + &self, + overlay_focus: &FocusHandle, + open: bool, + window: &mut Window, + cx: &mut App, ); +} - let was_open_now = *was_open.read(cx); - if open && !was_open_now { - let focused = window.focused(cx); - previous.update(cx, |previous, _| *previous = focused); - was_open.update(cx, |was_open, _| *was_open = true); - } else if !open && was_open_now { - was_open.update(cx, |was_open, _| *was_open = false); - let Some(restore) = previous.update(cx, |previous, _| previous.take()) else { - return; - }; - // Only take focus back from the closing overlay itself; a surface that - // replaced it owns focus now. - let overlay_focus = overlay_focus.clone(); - window.defer(cx, move |window, cx| { - let holds_focus = window - .focused(cx) - .is_none_or(|current| current == overlay_focus); - if holds_focus && restore.is_rendered(window) { - window.focus(&restore, cx); - } - }); +impl ElementIdExt for ElementId { + fn focus_handle(&self, window: &mut Window, cx: &mut App) -> FocusHandle { + window + .with_element_namespace(self.clone(), |window| { + window.use_keyed_state("focus-handle", cx, |_, cx| cx.focus_handle()) + }) + .read(cx) + .clone() + } + + fn track_overlay_focus( + &self, + overlay_focus: &FocusHandle, + open: bool, + window: &mut Window, + cx: &mut App, + ) { + let was_open = window.use_keyed_state((self.clone(), "overlay-was-open"), cx, |_, _| false); + let previous = + window.use_keyed_state((self.clone(), "overlay-previous-focus"), cx, |_, _| { + None:: + }); + + let was_open_now = *was_open.read(cx); + + if open && !was_open_now { + let focused = window.focused(cx); + previous.update(cx, |previous, _| *previous = focused); + was_open.update(cx, |was_open, _| *was_open = true); + } else if !open && was_open_now { + was_open.update(cx, |was_open, _| *was_open = false); + + let Some(restore) = previous.update(cx, |previous, _| previous.take()) else { + return; + }; + + // Only take focus back from the closing overlay itself. + let overlay_focus = overlay_focus.clone(); + window.defer(cx, move |window, cx| { + let holds_focus = window + .focused(cx) + .is_none_or(|current| current == overlay_focus); + + if holds_focus && restore.is_rendered(window) { + window.focus(&restore, cx); + } + }); + } } } -/// Returns a focus ring shadow with the given color at half ink. -pub fn focus_ring(color: Hsla) -> Vec { - vec![ - BoxShadow::new(px(0.), px(0.), color.alpha(FOCUS_RING_ALPHA)) - .spread_radius(FOCUS_RING_SPREAD), - ] +/// Row selection stepping over the rows that cannot be selected. +pub trait SelectableRows { + /// The next selectable row in the direction. + fn wrapping_adjacent(&self, selected: Option, forward: bool) -> Option; + + /// The next selectable row in the direction, or `None` at the ends. + fn adjacent(&self, selected: Option, forward: bool) -> Option; + + /// Whether the given key is a vertical navigation key. + fn nav_key(&self, selected: Option, key: &str, select: S) -> bool + where + S: FnOnce(Option); } -/// The shared floating-panel stack. -#[must_use] -pub fn floating_panel(cx: &App, radius: Pixels, panel: R, shadows: Vec) -> R -where - R: Styled + IntoElement, -{ - let theme = cx.theme(); - panel.map(|panel| { - panel - .bg(theme.colors.surface) - .rounded(radius) - .border_1() - .border_color(theme.colors.border) - .shadow(shadows) - }) -} +impl SelectableRows for [usize] { + fn wrapping_adjacent(&self, selected: Option, forward: bool) -> Option { + if self.is_empty() { + return None; + } -/// The next selectable row in the direction. -pub fn wrapping_adjacent_selectable( - selectable: &[usize], - selected: Option, - forward: bool, -) -> Option { - if selectable.is_empty() { - return None; + self.adjacent(selected, forward) + .or_else(|| forward.then(|| self.first().copied()).flatten()) + .or_else(|| (!forward).then(|| self.last().copied()).flatten()) } - adjacent_selectable(selectable, selected, forward) - .or_else(|| forward.then(|| selectable.first().copied()).flatten()) - .or_else(|| (!forward).then(|| selectable.last().copied()).flatten()) -} - -/// The next selectable row in the direction, or `None` at the ends. -pub fn adjacent_selectable( - selectable: &[usize], - selected: Option, - forward: bool, -) -> Option { - if forward { - selectable - .iter() - .copied() - .find(|index| Some(*index) > selected) - } else { - selectable - .iter() - .copied() - .rev() - .find(|index| Some(*index) < selected) + fn adjacent(&self, selected: Option, forward: bool) -> Option { + if forward { + self.iter().copied().find(|index| Some(*index) > selected) + } else { + self.iter() + .copied() + .rev() + .find(|index| Some(*index) < selected) + } } -} -/// Whether the given key is a vertical navigation key. -pub fn nav_key(selectable: &[usize], selected: Option, key: &str, select: S) -> bool -where - S: FnOnce(Option), -{ - let target = match key { - "down" => adjacent_selectable(selectable, selected, true), - "up" => adjacent_selectable(selectable, selected, false), - "home" => selectable.first().copied(), - "end" => selectable.last().copied(), - _ => return false, - }; - if let Some(next) = target - && Some(next) != selected + fn nav_key(&self, selected: Option, key: &str, select: S) -> bool + where + S: FnOnce(Option), { - select(Some(next)); - } - true -} + let target = match key { + "down" => self.adjacent(selected, true), + "up" => self.adjacent(selected, false), + "home" => self.first().copied(), + "end" => self.last().copied(), + _ => return false, + }; -/// A selectable row's label and icon color. -pub fn selectable_label_color(cx: &App, selected: bool, disabled: bool) -> Hsla { - let theme = cx.theme(); - if disabled { - theme.colors.muted_foreground - } else if selected { - theme.colors.primary_foreground - } else { - theme.colors.foreground - } -} - -/// A selectable row's background. -#[must_use] -pub fn paint_selectable_row(cx: &App, row: R, selected: bool, disabled: bool) -> R -where - R: IntoElement + Styled + StatefulInteractiveElement, -{ - let theme = cx.theme(); - row.map(|row| { - if disabled { - row - } else if selected { - row.bg(theme.ramps.primary.base) - } else { - row.hover(|row| row.bg(theme.colors.muted)) + if let Some(next) = target + && Some(next) != selected + { + select(Some(next)); } - }) -} -/// A row that highlights under the pointer, for lists driven by mouse move -/// instead of selection. -#[must_use] -pub fn paint_highlighted_row(cx: &App, row: R, highlighted: bool, disabled: bool) -> R -where - R: IntoElement + Styled + StatefulInteractiveElement, -{ - let theme = cx.theme(); - row.map(|row| { - if disabled { - row - } else if highlighted { - row.bg(theme.colors.muted) - } else { - row.hover(|row| row.bg(theme.colors.muted)) - } - }) + true + } } /// A component that can be told which size to render at. @@ -582,3 +566,15 @@ impl Size { } } } + +/// A row whose children center on the cross axis. +#[must_use] +pub fn h_flex() -> Div { + div().flex().flex_row().items_center() +} + +/// A column whose children stack on the main axis. +#[must_use] +pub fn v_flex() -> Div { + div().flex().flex_col() +} diff --git a/crates/ui/src/components/dialog.rs b/crates/ui/src/components/dialog.rs index a283992..b3d0a67 100644 --- a/crates/ui/src/components/dialog.rs +++ b/crates/ui/src/components/dialog.rs @@ -27,21 +27,27 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder as _; use gpui::{ Animation, AnimationExt as _, AnyElement, App, DefiniteLength, ElementId, InteractiveElement, - IntoElement, KeyDownEvent, MouseButton, ParentElement as _, RenderOnce, Role, ScrollHandle, - SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas, + IntoElement, KeyBinding, MouseButton, ParentElement as _, RenderOnce, Role, ScrollHandle, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, actions, deferred, div, ease_out_quint, relative, }; use crate::components::button::{Button, ButtonVariant}; use crate::components::common::{ - DIALOG_LAYER, Sizable, StyledExt as _, floating_panel, focus_handle, h_flex, - track_overlay_focus, v_flex, + DIALOG_LAYER, ElementIdExt as _, Sizable, StyledExt as _, h_flex, v_flex, }; -use crate::components::grain::grain; +use crate::components::grain::Grain; +use crate::components::menu::focus_capture; +use crate::components::popover::POPOVER_CONTEXT; use crate::components::scroll_area::ScrollArea; use crate::icons::IconRole; use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH}; +actions!(dialog, [Dismiss]); + +/// Key context of the dialog panel. +pub const DIALOG_CONTEXT: &str = "Dialog"; + /// Requests the dialog's close: `false` closes. type ChangeHandler = Rc; type ContentFn = Box AnyElement>; @@ -131,6 +137,14 @@ impl Dialog { } } + /// Binds the dialog's dismissal key. + pub fn bind_keys(cx: &mut App) { + cx.bind_keys([ + KeyBinding::new("escape", Dismiss, Some(DIALOG_CONTEXT)), + KeyBinding::new("escape", Dismiss, Some(POPOVER_CONTEXT)), + ]); + } + /// Sets the initial open state; a handle overrides it. pub fn open(mut self, open: bool) -> Self { self.open = open; @@ -248,19 +262,17 @@ impl gpui::Styled for Dialog { impl RenderOnce for Dialog { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { - let root = div().absolute().inset_0(); - let open = self .handle .as_ref() .map_or(self.open, DialogHandle::is_open); // Keyboard focus rides the panel across frames. - let focus = focus_handle(&self.id, window, cx); - track_overlay_focus(&self.id, &focus, open, window, cx); + let focus = self.id.focus_handle(window, cx); + self.id.track_overlay_focus(&focus, open, window, cx); if !open { - return root.into_any_element(); + return div().absolute().inset_0().into_any_element(); } // A handle routes dismissal through the shared state @@ -312,11 +324,11 @@ impl RenderOnce for Dialog { .read(cx) .clone(); - // The panel takes focus when it first paints, and again whenever nothing else holds it. - let painted = window.use_keyed_state((self.id.clone(), "dialog-painted"), cx, |_, _| false); - deferred( - root.flex() + div() + .absolute() + .inset_0() + .flex() .items_center() .justify_center() .p_4() @@ -327,7 +339,7 @@ impl RenderOnce for Dialog { .inset_0() .bg(scrim_color) .occlude() - .when(self.grain, |scrim| scrim.child(grain())) + .when(self.grain, |scrim| scrim.child(Grain)) .when(!alert && close_on_backdrop, |scrim| { scrim.on_mouse_down(MouseButton::Left, { let on_change = on_change.clone(); @@ -346,122 +358,108 @@ impl RenderOnce for Dialog { ), ) .child( - floating_panel( - cx, - radius, - v_flex() - .id((self.id.clone(), "dialog-panel")) - .track_focus(&focus) - .role(role) - .aria_label(label) - .when_some(self.width, |panel, width| panel.w(width)) - .when(self.width.is_none() && self.min_width.is_none(), |panel| { - panel.min_w(DIALOG_MIN_WIDTH) - }) - .when_some(self.min_width, |panel, width| panel.min_w(width)) - .max_w(relative(0.9)) - .when_some(height, |panel, height| panel.h(height)) - .text_color(foreground), - shadows, - ) - .bg(background) - .overflow_hidden() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_key_down({ - let on_change = on_change.clone(); - move |event: &KeyDownEvent, window, cx| { - if event.keystroke.key == "escape" - && !alert - && close_on_escape - && let Some(on_change) = &on_change - { - on_change(false, window, cx); - } - cx.stop_propagation(); - } - }) - .when(self.title.is_some() || show_close, |panel| { - panel.child( - h_flex() - .h_12() - .px_2() - .gap_2() - .justify_between() - .when(show_close, |row| row.child(div().w_7())) - .when_some(self.title.clone(), |row, title| { - row.child( - div() - .flex_1() - .text_center() - .text_sm() - .font_semibold() - .child(title), - ) - }) - .when(show_close, |row| { - row.child( - Button::new((self.id.clone(), "dialog-close")) - .icon(IconRole::Close) - .variant(ButtonVariant::Ghost) - .small() - .debug_selector(|| "dialog-close".to_string()) - .accessibility_label("Close") - .on_click({ - let on_change = on_change.clone(); - move |_, window, cx| { - if let Some(on_change) = &on_change { - on_change(false, window, cx); - } - } - }), - ) - }), - ) - }) - .when_some(content, |panel, content| { - panel.map(|this| { - if height.is_some() { - this.child( - ScrollArea::new((self.id.clone(), "dialog-content")) - .handle(scroll) - .flex_1() - .min_h_0() - .child(div().p_2().child(content)), - ) - } else { - this.child(div().p_2().child(content)) - } + v_flex() + .id((self.id.clone(), "dialog-panel")) + .track_focus(&focus) + .key_context(DIALOG_CONTEXT) + .role(role) + .aria_label(label) + .when_some(self.width, |panel, width| panel.w(width)) + .when(self.width.is_none() && self.min_width.is_none(), |panel| { + panel.min_w(DIALOG_MIN_WIDTH) }) - }) - .when_some(actions, |panel, actions| { - panel.child( - h_flex() - .px_2() - .h_12() - .justify_end() - .gap_2() - .children(actions), - ) - }) - .child( - canvas(|_, _, _| {}, { - let painted = painted.clone(); - move |_, _, window, cx| { - let first_paint = painted - .update(cx, |painted, _| !std::mem::replace(painted, true)); - if first_paint || window.focused(cx).is_none() { - window.focus(&focus, cx); + .when_some(self.min_width, |panel, width| panel.min_w(width)) + .max_w(relative(0.9)) + .when_some(height, |panel, height| panel.h(height)) + .text_color(foreground) + .floating_panel(cx, radius, shadows) + .bg(background) + .overflow_hidden() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_action({ + let on_change = on_change.clone(); + move |_: &Dismiss, window, cx| { + if !alert + && close_on_escape + && let Some(on_change) = &on_change + { + on_change(false, window, cx); } + cx.stop_propagation(); } }) - .absolute() - .inset_0(), - ) - .with_animation( - "dialog-enter", - Animation::new(enter_duration).with_easing(ease_out_quint()), - |panel, delta| panel.opacity(delta), - ), + .when(self.title.is_some() || show_close, |panel| { + panel.child( + h_flex() + .h_12() + .px_2() + .gap_2() + .justify_between() + .when(show_close, |row| row.child(div().w_7())) + .when_some(self.title.clone(), |row, title| { + row.child( + div() + .flex_1() + .text_center() + .text_sm() + .font_semibold() + .child(title), + ) + }) + .when(show_close, |row| { + row.child( + Button::new((self.id.clone(), "dialog-close")) + .icon(IconRole::Close) + .variant(ButtonVariant::Ghost) + .small() + .debug_selector(|| "dialog-close".to_string()) + .accessibility_label("Close") + .on_click({ + let on_change = on_change.clone(); + move |_, window, cx| { + if let Some(on_change) = &on_change { + on_change(false, window, cx); + } + } + }), + ) + }), + ) + }) + .when_some(content, |panel, content| { + panel.map(|this| { + if height.is_some() { + this.child( + ScrollArea::new((self.id.clone(), "dialog-content")) + .handle(scroll) + .flex_1() + .min_h_0() + .child(div().p_2().child(content)), + ) + } else { + this.child(div().p_2().child(content)) + } + }) + }) + .when_some(actions, |panel, actions| { + panel.child( + h_flex() + .px_2() + .h_12() + .justify_end() + .gap_2() + .children(actions), + ) + }) + // Keep focus inside the dialog: Tab past the last control stays here. + .child(focus_capture(focus.clone(), move |window, cx| { + !focus.contains_focused(window, cx) + })) + .with_animation( + "dialog-enter", + Animation::new(enter_duration).with_easing(ease_out_quint()), + |panel, delta| panel.opacity(delta), + ), ), ) .with_priority(DIALOG_LAYER) diff --git a/crates/ui/src/components/dropdown_menu.rs b/crates/ui/src/components/dropdown_menu.rs index 26f5aea..3cbf4be 100644 --- a/crates/ui/src/components/dropdown_menu.rs +++ b/crates/ui/src/components/dropdown_menu.rs @@ -19,19 +19,19 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ App, ClickEvent, DefiniteLength, DispatchPhase, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, ParentElement as _, RenderOnce, Role, - SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas, - div, relative, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, canvas, div, + relative, }; use crate::components::button::{ButtonChrome, ButtonVariant}; use crate::components::common::{ - ControlSizing, Sizable, StyledExt as _, focus_handle, focus_ring, h_flex, + ControlSizing, ElementIdExt as _, Sizable, StyledExt as _, h_flex, }; use crate::components::menu::{ - ChangeHandler, MenuChrome, MenuItem, MenuPanelSpec, TriggerBoundsCell, anchored_menu_panel, + ChangeHandler, MenuChrome, MenuItem, MenuPanelSpec, TriggerBoundsCell, }; use crate::components::spinner::Spinner; -use crate::icons::{Icon, IconRole, icon}; +use crate::icons::{Icon, IconRole}; use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; /// The main zone's activation handler, shared by pointer, Enter, and Space. @@ -184,7 +184,7 @@ impl Sizable for DropdownMenu { } } -impl gpui::Styled for DropdownMenu { +impl Styled for DropdownMenu { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } @@ -193,11 +193,8 @@ impl gpui::Styled for DropdownMenu { impl RenderOnce for DropdownMenu { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); - let colors = theme.colors; let radius = theme.radius.full; - - let ring = colors.ring; - + let ring = theme.focus_ring(); let (panel_chrome, enter_duration) = MenuChrome::read(cx); let ButtonChrome { @@ -219,7 +216,7 @@ impl RenderOnce for DropdownMenu { .unwrap_or_else(|| SharedString::from(self.id.to_string())); let a11y_label = self.a11y_label.or_else(|| self.label.clone()); - let focus = focus_handle(&self.id, window, cx).tab_stop(self.tab_stop); + let focus = self.id.focus_handle(window, cx).tab_stop(self.tab_stop); // How the menu was last opened, read by the frame that mounts the panel. let keyboard_open = window.use_keyed_state((self.id.clone(), "dropdown-open-origin"), cx, |_, _| false); @@ -242,147 +239,6 @@ impl RenderOnce for DropdownMenu { let trigger_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); let chevron_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); - let trigger = h_flex() - .debug_selector({ - let id = self.id.clone(); - move || format!("{id}-trigger") - }) - .control_height(self.size) - .when(icon_only, |trigger| trigger.control_width(self.size)) - .rounded(radius) - .border_1() - .border_color(border) - .when_some(background, |trigger, background| trigger.bg(background)) - .when(self.disabled, |trigger| trigger.opacity(DISABLED_OPACITY)) - .when(!inert, |trigger| { - trigger - .track_focus(&focus) - .focus_visible(move |style| style.shadow(focus_ring(ring))) - }) - .child( - h_flex() - .id(self.id.clone()) - .debug_selector({ - let id = self.id.clone(); - move || id.to_string() - }) - .justify_center() - .h_full() - .when(icon_only, |zone| zone.w_full()) - .gap_2() - .line_height(relative(1.0)) - .control_text(self.size) - .text_color(foreground) - .role(Role::Button) - .when_some(a11y_label, |zone, label| zone.aria_label(label)) - .aria_expanded(self.open) - .when(!icon_only, |zone| zone.control_padding_x(self.size)) - .when(split, |zone| zone.rounded_l(radius)) - .when(!split, |zone| { - zone.rounded(radius) - .when(self.open, |zone| zone.bg(pressed)) - }) - .when(!icon_only && !split, |zone| { - zone.child( - icon(IconRole::ChevronDown) - .size(self.size.dense_icon_rems()) - .color(foreground), - ) - }) - .child( - h_flex() - .gap_2() - .when(self.loading, |content| content.invisible()) - .when_some(self.icon, |content, icon| { - content.child(icon.size(self.size.icon_rems()).color(foreground)) - }) - .when_some(self.label, |content, label| content.child(label)), - ) - .when(self.loading, |zone| { - zone.child( - h_flex().absolute().inset_0().justify_center().child( - Spinner::new((self.id.clone(), "spinner")) - .with_size(self.size) - .color(foreground), - ), - ) - }) - .when(!inert, |main| { - main.track_focus(&focus) - .cursor_pointer() - .hover(move |style| style.bg(hover)) - .active(move |style| style.bg(pressed)) - .on_click({ - let on_click = self.on_click; - let on_open = on_open.clone(); - let keyboard_open = keyboard_open.clone(); - let open = self.open; - move |event, window, cx| match (on_click.as_ref(), event) { - (Some(on_click), _) => on_click(event, window, cx), - (None, ClickEvent::Keyboard(_)) => { - keyboard_open.update(cx, |keyboard_open, _| { - *keyboard_open = true; - }); - on_open(!open, window, cx); - } - (None, _) => {} - } - }) - .on_key_down({ - let on_open = on_open.clone(); - let keyboard_open = keyboard_open.clone(); - move |event: &KeyDownEvent, window, cx| { - if event.keystroke.key == "down" { - keyboard_open.update(cx, |keyboard_open, _| { - *keyboard_open = true; - }); - on_open(true, window, cx); - cx.stop_propagation(); - } - } - }) - }), - ) - .when(split, |trigger| { - trigger.child( - h_flex() - .id((self.id.clone(), "chevron")) - .debug_selector({ - let id = self.id.clone(); - move || format!("{id}-chevron") - }) - .relative() - .h_full() - .control_dense_padding_x(self.size) - .rounded_r(radius) - .rounded_l_none() - .border_l_1() - .border_color(border) - .when(self.open, |zone| zone.bg(pressed)) - .when(!inert, |zone| { - zone.cursor_pointer() - .hover(move |style| style.bg(hover)) - .active(move |style| style.bg(pressed)) - }) - .child( - icon(IconRole::ChevronDown) - .size(self.size.dense_icon_rems()) - .color(foreground), - ) - .child( - canvas( - { - let cell = chevron_bounds.clone(); - move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) - }, - |_, _, _, _| {}, - ) - .absolute() - .inset_0(), - ), - ) - }); - let items = if self.open { self.items .map(|build| Rc::from(build(window, cx))) @@ -462,9 +318,154 @@ impl RenderOnce for DropdownMenu { .absolute() .inset_0(), ) - .child(trigger) + .child( + h_flex() + .debug_selector({ + let id = self.id.clone(); + move || format!("{id}-trigger") + }) + .control_height(self.size) + .when(icon_only, |trigger| trigger.control_width(self.size)) + .rounded(radius) + .border_1() + .border_color(border) + .when_some(background, |trigger, background| trigger.bg(background)) + .when(self.disabled, |trigger| trigger.opacity(DISABLED_OPACITY)) + .when(!inert, |trigger| { + trigger + .track_focus(&focus) + .focus_visible(move |style| style.shadow(ring)) + }) + .child( + h_flex() + .id(self.id.clone()) + .debug_selector({ + let id = self.id.clone(); + move || id.to_string() + }) + .justify_center() + .h_full() + .when(icon_only, |zone| zone.w_full()) + .gap_2() + .line_height(relative(1.0)) + .control_text(self.size) + .text_color(foreground) + .role(Role::Button) + .when_some(a11y_label, |zone, label| zone.aria_label(label)) + .aria_expanded(self.open) + .when(!icon_only, |zone| zone.control_padding_x(self.size)) + .when(split, |zone| zone.rounded_l(radius)) + .when(!split, |zone| { + zone.rounded(radius) + .when(self.open, |zone| zone.bg(pressed)) + }) + .when(!icon_only && !split, |zone| { + zone.child( + Icon::from(IconRole::ChevronDown) + .size(self.size.dense_icon_rems()) + .color(foreground), + ) + }) + .child( + h_flex() + .gap_2() + .when(self.loading, |content| content.invisible()) + .when_some(self.icon, |content, icon| { + content.child( + icon.size(self.size.icon_rems()).color(foreground), + ) + }) + .when_some(self.label, |content, label| content.child(label)), + ) + .when(self.loading, |zone| { + zone.child( + h_flex().absolute().inset_0().justify_center().child( + Spinner::new((self.id.clone(), "spinner")) + .with_size(self.size) + .color(foreground), + ), + ) + }) + .when(!inert, |main| { + main.track_focus(&focus) + .cursor_pointer() + .hover(move |style| style.bg(hover)) + .active(move |style| style.bg(pressed)) + .on_click({ + let on_click = self.on_click; + let on_open = on_open.clone(); + let keyboard_open = keyboard_open.clone(); + let open = self.open; + move |event, window, cx| match (on_click.as_ref(), event) { + (Some(on_click), _) => on_click(event, window, cx), + (None, ClickEvent::Keyboard(_)) => { + keyboard_open.update(cx, |keyboard_open, _| { + *keyboard_open = true; + }); + on_open(!open, window, cx); + } + (None, _) => {} + } + }) + .on_key_down({ + let on_open = on_open.clone(); + let keyboard_open = keyboard_open.clone(); + move |event: &KeyDownEvent, window, cx| { + if event.keystroke.key == "down" { + keyboard_open.update(cx, |keyboard_open, _| { + *keyboard_open = true; + }); + on_open(true, window, cx); + cx.stop_propagation(); + } + } + }) + }), + ) + .when(split, |trigger| { + trigger.child( + h_flex() + .id((self.id.clone(), "chevron")) + .debug_selector({ + let id = self.id.clone(); + move || format!("{id}-chevron") + }) + .relative() + .h_full() + .control_dense_padding_x(self.size) + .rounded_r(radius) + .rounded_l_none() + .border_l_1() + .border_color(border) + .when(self.open, |zone| zone.bg(pressed)) + .when(!inert, |zone| { + zone.cursor_pointer() + .hover(move |style| style.bg(hover)) + .active(move |style| style.bg(pressed)) + }) + .child( + Icon::from(IconRole::ChevronDown) + .size(self.size.dense_icon_rems()) + .color(foreground), + ) + .child( + canvas( + { + let cell = chevron_bounds.clone(); + move |bounds, _window, _cx| { + *cell.borrow_mut() = Some(bounds) + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ), + ) + }), + ) .when_some( - anchored_menu_panel(window, cx, &self.id, spec, &panel_chrome, enter_duration), + spec.anchored(window, cx, &self.id, &panel_chrome, enter_duration), |wrapper, panel| wrapper.child(panel), ) } diff --git a/crates/ui/src/components/empty_state.rs b/crates/ui/src/components/empty_state.rs index e0c8e95..fbfc73f 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::{ - AnyElement, App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement, - Styled as _, Window, div, rems, + AnyElement, App, Div, IntoElement, ParentElement as _, RenderOnce, SharedString, + StyleRefinement, Styled as _, Window, div, rems, }; use crate::components::common::{StyledExt, v_flex}; @@ -26,7 +26,7 @@ pub struct EmptyState { icon: Option, headline: SharedString, hint: Option, - action: Option, + action: Option, style: StyleRefinement, } @@ -46,7 +46,7 @@ impl EmptyState { } /// The empty state centered in the full available space. - pub fn centered(message: L) -> AnyElement + pub fn centered(message: L) -> impl IntoElement where L: Into, { @@ -55,7 +55,6 @@ impl EmptyState { .items_center() .justify_center() .child(Self::new(message)) - .into_any_element() } /// Sets a large muted icon above the headline. @@ -87,7 +86,7 @@ impl EmptyState { /// A compact inline caption for popups with nothing to show. #[must_use] - pub fn compact(label: L, cx: &App) -> gpui::Div + pub fn compact(label: L, cx: &App) -> Div where L: Into, { diff --git a/crates/ui/src/components/field.rs b/crates/ui/src/components/field.rs index 77822ac..9ef3d23 100644 --- a/crates/ui/src/components/field.rs +++ b/crates/ui/src/components/field.rs @@ -103,84 +103,94 @@ impl RenderOnce for Field { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let error_color = theme.ramps.destructive.base; + let row = self.variant == FieldVariant::Row; let id = self.id.clone(); - let title = div() - .debug_selector({ - let id = id.clone(); - move || format!("{id}-label") - }) - .when(self.description.is_some(), |title| { - title.text_sm().font_semibold() - }) - .when(self.description.is_none(), |title| title.text_sm()) - .child(self.label.clone()); - - let control = h_flex() - .items_center() - .gap_2() - .debug_selector({ - let id = id.clone(); - move || format!("{id}-control") - }) - .children(self.control); - - let error = self.error.map(|error| { - div() - .debug_selector({ - let id = id.clone(); - move || format!("{id}-error") - }) - .text_xs() - .text_color(error_color) - .child(error) - }); - - let description_text = |cx: &App| { - div() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - }; - - let content = if self.variant == FieldVariant::Row { - v_flex() - .gap_1() - .child( - h_flex() - .items_center() - .justify_between() - .gap_4() - .child(title.flex_1().min_w_0()) - .child(control.flex_none()), - ) - .when_some(self.description.clone(), |field, description| { - field.child(description_text(cx).child(description)) - }) - .when_some(error, |field, error| field.child(error)) - } else { - v_flex() - .gap_2() - .child( - v_flex() - .gap_0p5() - .child(title) - .when_some(self.description.clone(), |slot, description| { - slot.child(description_text(cx).child(description)) - }), - ) - .child(control) - .when_some(error, |field, error| field.child(error)) - }; - div() .id(self.id) .w_full() .role(Role::Group) .aria_label(self.label.clone()) - .when_some(self.description, |field, description| { + .when_some(self.description.clone(), |field, description| { field.aria_description(description) }) .refine_style(&self.style) - .child(content) + .child( + v_flex() + .gap_1() + .when(!row, |field| field.gap_2()) + .child( + div() + .flex() + .when(row, |field| { + field.flex_row().items_center().justify_between().gap_4() + }) + .when(!row, |field| field.flex_col().gap_2()) + .child( + div() + .when(row, |label| label.flex_1().min_w_0()) + .when(!row, |label| label.flex().flex_col().gap_0p5()) + .child( + div() + .debug_selector({ + let id = id.clone(); + move || format!("{id}-label") + }) + .text_sm() + .when(self.description.is_some(), |title| { + title.font_semibold() + }) + .child(self.label.clone()), + ) + .when(!row, |label| { + label.when_some( + self.description.clone(), + |slot, description| { + slot.child( + div() + .text_xs() + .text_color(theme.colors.muted_foreground) + .child(description), + ) + }, + ) + }), + ) + .child( + div().when(row, |control| control.flex_none()).child( + h_flex() + .items_center() + .gap_2() + .debug_selector({ + let id = id.clone(); + move || format!("{id}-control") + }) + .children(self.control), + ), + ), + ) + .when(row, |field| { + field.when_some(self.description.clone(), |field, description| { + field.child( + div() + .text_xs() + .text_color(theme.colors.muted_foreground) + .child(description), + ) + }) + }) + .when_some(self.error, |field, error| { + field.child( + div() + .debug_selector({ + let id = id.clone(); + move || format!("{id}-error") + }) + .text_xs() + .text_color(error_color) + .child(error), + ) + }), + ) } } diff --git a/crates/ui/src/components/highlight.rs b/crates/ui/src/components/highlight.rs index 3d293f3..b61ffad 100644 --- a/crates/ui/src/components/highlight.rs +++ b/crates/ui/src/components/highlight.rs @@ -15,6 +15,7 @@ use std::cell::RefCell; use std::collections::HashMap; +use std::path::Path; use gpui::SharedString; #[cfg(not(target_arch = "wasm32"))] @@ -38,6 +39,24 @@ pub enum Language { Python, } +impl Language { + /// The grammar for a file path's extension; unknown extensions are plain text. + pub fn from_path(path: &str) -> Self { + let extension = Path::new(path) + .extension() + .and_then(|extension| extension.to_str()) + .map(|extension| extension.to_ascii_lowercase()); + + match extension.as_deref() { + Some("rs") => Self::Rust, + Some("ts" | "mts" | "cts" | "tsx") => Self::TypeScript, + Some("js" | "mjs" | "cjs" | "jsx") => Self::JavaScript, + Some("py") => Self::Python, + _ => Self::Plain, + } + } +} + /// The semantic role a span plays. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Role { diff --git a/crates/ui/src/components/input.rs b/crates/ui/src/components/input.rs index e7b5265..e93202f 100644 --- a/crates/ui/src/components/input.rs +++ b/crates/ui/src/components/input.rs @@ -3,16 +3,16 @@ //! The state is a [`gpui::Entity`] the application owns across frames: read it //! with [`InputState::value`], write it with [`InputState::set_value`], and //! subscribe to [`InputStateEvent`] for changes. [`Input`] is the view built -//! from that state each frame. Call [`bind_input_keys`] once at startup to +//! from that state each frame. Call [`InputState::bind_keys`] once at startup to //! register the editing keybindings. //! //! # Examples //! //! ```no_run -//! use ui::input::{Input, InputState, bind_input_keys}; +//! use ui::input::{Input, InputState}; //! //! # let mut cx: gpui::App = unimplemented!(); -//! bind_input_keys(&mut cx); +//! InputState::bind_keys(&mut cx); //! //! let state = InputState::builder() //! .text("Ada Lovelace") @@ -33,8 +33,8 @@ use gpui::{ EntityInputHandler, EventEmitter, Font, HitboxBehavior, InteractiveElement as _, IntoElement, KeyBinding, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, RenderOnce, Role, ScrollDelta, ScrollEvent, SharedString, - StatefulInteractiveElement as _, StyleRefinement, Styled as _, TextAlign, TextRun, - UTF16Selection, Window, WrappedLine, actions, canvas, div, fill, point, px, + StatefulInteractiveElement as _, StyleRefinement, Styled as _, Subscription, TextAlign, + TextRun, UTF16Selection, Window, WrappedLine, actions, canvas, div, fill, point, px, }; use unicode_segmentation::UnicodeSegmentation; @@ -128,7 +128,7 @@ actions!( ] ); -/// The keybindings [`bind_input_keys`] registers on the application. +/// The keybindings [`InputState::bind_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. @@ -473,7 +473,7 @@ impl HistoryEntry { /// Everything `shape_text` consumes, for cache reuse between frames. #[derive(Clone, PartialEq)] struct ShapeCacheKey { - text: String, + text: SharedString, wrap_width: Option, font_size: Pixels, font: Font, @@ -586,6 +586,10 @@ pub struct InputState { layout: Option, /// The last shaped buffer, reused while no shaping input changed. shaped_cache: std::cell::RefCell>, + /// Focus-in, while the field is painted; armed once per mount. + focus_in: Option, + /// Focus-out, while the field is painted; armed once per mount. + focus_out: Option, } impl EventEmitter for InputState {} @@ -623,6 +627,8 @@ impl InputState { caret_epoch_started: Instant::now(), layout: None, shaped_cache: std::cell::RefCell::new(None), + focus_in: None, + focus_out: None, } } @@ -680,6 +686,7 @@ impl InputState { cx.emit(InputStateEvent::TextChanged); } self.notify(window, cx); + window.notify_text_input_changed(&self.focus_handle); } /// Sets how long consecutive edits keep merging into one undo entry. @@ -747,11 +754,9 @@ impl InputState { let last_end = last.range.start + last.new_len; if self.marked_range.is_some() { - // A pre-edit step overlapping the previous entry's region. - if range.start >= last.range.start { - last.new_len += new_len; - let replaced = range.len(); - last.new_len -= replaced; + // A pre-edit step overlapping the previous entry's replaced region. + if range.start >= last.range.start && range.end <= last_end { + last.new_len += new_len - range.len(); last.timestamp = now; return; } @@ -807,13 +812,12 @@ impl InputState { self.cursor.min(self.anchor)..self.cursor.max(self.anchor) } - fn notify(&mut self, window: &mut Window, cx: &mut Context) { + fn notify(&mut self, _window: &mut Window, cx: &mut Context) { cx.notify(); self.scroll_to_caret_pending = true; self.goal_x = None; self.caret_epoch += 1; self.caret_epoch_started = Instant::now(); - window.notify_text_input_changed(&self.focus_handle); } /// Scrolls the field by a wheel delta, clamped at paint. @@ -918,6 +922,7 @@ impl InputState { cx.emit(InputStateEvent::TextChanged); self.notify(window, cx); + window.notify_text_input_changed(&self.focus_handle); } /// Deletes the selection, or one character/word before the caret. @@ -966,6 +971,7 @@ impl InputState { self.cursor = cursor; self.anchor = anchor; self.notify(window, cx); + window.notify_text_selection_changed(&self.focus_handle); } /// Selects `range`. @@ -976,6 +982,7 @@ impl InputState { self.anchor = range.start; self.cursor = range.end; self.notify(window, cx); + window.notify_text_selection_changed(&self.focus_handle); } /// Copies the selected text to the clipboard. @@ -1017,9 +1024,17 @@ impl InputState { let font_size = text_style.font_size.to_pixels(window.rem_size()); - if !self.masked() - && let Some((cached_key, shaped)) = self.shaped_cache.borrow().as_ref() - && cached_key.text == self.text + let masked = if self.masked() { + Some(masked_display(&self.text)) + } else { + None + }; + let display = masked + .as_ref() + .map_or_else(|| self.text.as_str(), |(display, _)| display.as_str()); + + if let Some((cached_key, shaped)) = self.shaped_cache.borrow().as_ref() + && cached_key.text.as_ref() == display && cached_key.wrap_width == wrap_width && cached_key.font_size == font_size && cached_key.font == font @@ -1028,10 +1043,9 @@ impl InputState { return shaped.clone(); } - let (text, mask_map) = if self.masked() { - masked_display(&self.text) - } else { - (self.text.clone(), None) + let (text, mask_map) = match masked { + Some((display, mask_map)) => (SharedString::from(display), mask_map), + None => (SharedString::from(self.text.as_str()), None), }; let key = ShapeCacheKey { @@ -1051,10 +1065,9 @@ impl InputState { strikethrough: None, }]; - let shaped = - window - .text_system() - .shape_text(text.into(), font_size, &runs, wrap_width, None); + let shaped = window + .text_system() + .shape_text(text, font_size, &runs, wrap_width, None); let mut lines = Vec::new(); match shaped { @@ -1294,9 +1307,6 @@ impl InputState { window: &mut Window, cx: &mut Context, ) -> bool { - let focused = self.focus_handle.is_focused(window); - self.sync_focus(focused, cx); - let text_style = window.text_style(); let font_size = text_style.font_size.to_pixels(window.rem_size()); let line_height = text_style @@ -1304,6 +1314,7 @@ impl InputState { .to_pixels(text_style.font_size, window.rem_size()); let origin = self.store_layout(text, bounds, padding, line_height); + let focused = self.focus_handle.is_focused(window); if focused && !self.selection().is_empty() { self.paint_selection(origin, colors.selection, window); @@ -1682,6 +1693,7 @@ impl InputState { cx.emit(InputStateEvent::TextChanged); self.notify(window, cx); + window.notify_text_input_changed(&self.focus_handle); } fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context) { @@ -1704,6 +1716,7 @@ impl InputState { cx.emit(InputStateEvent::TextChanged); self.notify(window, cx); + window.notify_text_input_changed(&self.focus_handle); } fn submit(&mut self, _: &Submit, _window: &mut Window, cx: &mut Context) { @@ -1734,6 +1747,12 @@ impl InputState { fn escape(&mut self, _: &Escape, window: &mut Window, cx: &mut Context) { window.blur(cx); + cx.propagate(); + } + + /// Registers the input keybindings on the application, once at startup. + pub fn bind_keys(cx: &mut App) { + cx.bind_keys(InputBindings::default().into_bindings()); } } @@ -1772,8 +1791,10 @@ impl EntityInputHandler for InputState { .map(|range| utf8_range_to_utf16(&self.text, range)) } - fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context) { - self.marked_range = None; + fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context) { + if self.marked_range.take().is_some() { + cx.notify(); + } } fn replace_text_in_range( @@ -2111,6 +2132,31 @@ impl RenderOnce for Input { window.set_cursor_style(CursorStyle::IBeam, &hitbox); } + // Focus transitions are events, not paint samples: a field that is + // never painted again still emits Blurred when focus leaves it. + if state.read(cx).focus_in.is_none() { + let listener = state.downgrade(); + let subscription = window.on_focus_in(&focus, cx, move |_, cx| { + let _ = listener.update(cx, |state, cx| { + state.focus_in = None; + state.sync_focus(true, cx); + cx.notify(); + }); + }); + state.update(cx, |state, _| state.focus_in = Some(subscription)); + } + if state.read(cx).focus_out.is_none() { + let listener = state.downgrade(); + let subscription = window.on_focus_out(&focus, cx, move |_, _, cx| { + let _ = listener.update(cx, |state, cx| { + state.focus_out = None; + state.sync_focus(false, cx); + cx.notify(); + }); + }); + state.update(cx, |state, _| state.focus_out = Some(subscription)); + } + let dragging = state.update(cx, |state, cx| { state.paint(text, bounds, field_padding, colors, window, cx) }); @@ -2129,7 +2175,7 @@ impl RenderOnce for Input { let state = state.clone(); move |event: &ScrollEvent, phase, window, cx| { if phase != DispatchPhase::Bubble - || !bounds.contains(&event.position) + || !hitbox.should_handle_scroll(window) { return; } @@ -2168,11 +2214,10 @@ impl RenderOnce for Input { canvas .with_animation( animation_id, - // The blink needs four repaints per period, - // not the display's refresh rate. + // The blink needs two repaints per period, not the display's rate. Animation::new(CARET_BLINK_INTERVAL * 2) .repeat() - .with_max_fps(4.0), + .with_steps(2), |canvas, _| canvas, ) .into_any_element() @@ -2491,11 +2536,6 @@ impl RenderOnce for Input { } } -/// Registers the input keybindings on the application, once at startup. -pub fn bind_input_keys(cx: &mut App) { - cx.bind_keys(InputBindings::default().into_bindings()); -} - /// The row holding `display`. fn row_ix_for_display(rows: &[VisualRow], display: usize) -> usize { rows.iter() diff --git a/crates/ui/src/components/markdown.rs b/crates/ui/src/components/markdown.rs index ea14da7..57d7a5d 100644 --- a/crates/ui/src/components/markdown.rs +++ b/crates/ui/src/components/markdown.rs @@ -5,24 +5,18 @@ //! report toggles and code blocks offer a copy action. Images render inline //! or as standalone blocks. Footnotes, math, and HTML render nothing; long //! code lines clip rather than scroll. -//! //! The view is the state: build a [`MarkdownViewState`] in a -//! [`gpui::Entity`] and embed it with [`TextView::new`], or let -//! [`TextView::markdown`] own its state under an element id. +//! [`gpui::Entity`] and embed that entity as a view. //! //! # Examples //! -//! ```no_run -//! use gpui::{App, AppContext as _}; -//! use ui::markdown::{MarkdownViewState, TextView}; +//! use ui::markdown::MarkdownViewState; //! -//! fn notes(cx: &mut App) -> TextView { -//! let state = cx.new(|_| MarkdownViewState::new("notes", "# Notes\n- [x] shipped")); -//! TextView::new(&state) +//! fn notes(cx: &mut App) -> Entity { +//! cx.new(|cx| MarkdownViewState::new("notes", "# Notes\n- [x] shipped", cx)) //! } //! ``` -use std::borrow::Borrow as _; use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; use std::ops::Range; @@ -30,13 +24,12 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, Bounds, ClipboardItem, Context, Div, Element, ElementId, Entity, FontStyle, - FontWeight, GlobalElementId, HighlightStyle, InspectorElementId, InteractiveElement as _, - InteractiveText, IntoElement, KeyBinding, KeyBindingContextPredicate, LayoutId, ListAlignment, - ListOffset, ListState, MouseButton, MouseDownEvent, MouseMoveEvent, ObjectFit, - ParentElement as _, Pixels, Refineable as _, Rems, Render, SharedString, - StatefulInteractiveElement as _, StrikethroughStyle, StyleRefinement, Styled, StyledImage as _, - StyledText, TextLayout, UnderlineStyle, Window, actions, div, img, list, px, relative, rems, + AnyElement, App, ClipboardItem, Context, Div, ElementId, Entity, FocusHandle, FontStyle, + FontWeight, HighlightStyle, InteractiveElement as _, InteractiveText, IntoElement, KeyBinding, + KeyBindingContextPredicate, ListAlignment, ListOffset, ListState, MouseButton, MouseDownEvent, + MouseMoveEvent, ObjectFit, ParentElement as _, Rems, Render, SharedString, + StatefulInteractiveElement as _, StrikethroughStyle, Styled, StyledImage as _, StyledText, + TextLayout, UnderlineStyle, Window, actions, div, img, list, px, relative, rems, }; use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd}; @@ -160,6 +153,8 @@ pub enum MarkdownBlock { Code { language: Option, lines: HighlightedCode, + /// The fenced source, kept for the copy button. + text: SharedString, /// How many lists the block sits under. indent: usize, /// Whether a blockquote wraps the block. @@ -189,24 +184,25 @@ impl MarkdownBlock { match self { MarkdownBlock::Heading { spans, .. } => vec![spans_text_of(spans)], MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => { + // One unit per image-separated text segment; images render no text. let mut units: Vec = Vec::new(); + let mut current = String::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()), + InlineItem::Text(span) => current.push_str(&span.text), + InlineItem::Image { .. } => { + if !current.is_empty() { + units.push(std::mem::take(&mut current)); + } + } } } + if !current.is_empty() { + units.push(current); + } units } - MarkdownBlock::Code { lines, .. } => { - lines.lines.iter().map(|line| line.text()).collect() - } + MarkdownBlock::Code { text, .. } => text.split('\n').map(str::to_owned).collect(), MarkdownBlock::Table { table, .. } => table .rows .iter() @@ -224,12 +220,12 @@ impl MarkdownBlock { match self { MarkdownBlock::Heading { level, - spans, + spans: _, indent, quote, } => heading_row( *level, - spans, + ctx.prepared.first().unwrap_or(&PreparedText::default()), *indent, *quote, if block_index == 0 { @@ -260,9 +256,10 @@ impl MarkdownBlock { MarkdownBlock::Code { language, lines, + text, indent, quote, - } => code_row(lines, language.as_ref(), *indent, *quote, ctx, cx), + } => code_row(lines, text, language.as_ref(), *indent, *quote, ctx, cx), MarkdownBlock::ThematicBreak { indent, quote } => rule_row(*indent, *quote, ctx, cx), MarkdownBlock::Table { table, @@ -303,13 +300,16 @@ pub struct MarkdownTable { /// Retained state for a markdown view. /// -/// Build one in a [`gpui::Entity`] and embed it with [`TextView::new`], or -/// let [`TextView::markdown`] own its state under an element id. +/// Build one in a [`gpui::Entity`] and embed that entity as a view. pub struct MarkdownViewState { id: ElementId, source: SharedString, blocks: Vec, block_ids: Vec, + /// The selectable pieces and their text, rebuilt with the blocks. + doc: std::rc::Rc, + /// Each block's inline text and style runs, rebuilt with the blocks. + prepared: std::rc::Rc>>, /// Whether fenced code blocks highlight with the code view's palette. highlight_code: bool, /// Drives the vertical scroll of the virtualized block list. @@ -319,12 +319,12 @@ pub struct MarkdownViewState { selection: Option<(usize, usize)>, /// Whether a drag is still extending the selection. selecting: bool, - focus_handle: Option, + focus_handle: FocusHandle, } impl MarkdownViewState { /// Builds the state, parsing `source`. - pub fn new(id: I, source: S) -> Self + pub fn new(id: I, source: S, cx: &mut App) -> Self where I: Into, S: Into, @@ -333,6 +333,8 @@ impl MarkdownViewState { let source = source.into(); let blocks = parse(&source, true); let block_ids = Self::stable_block_ids(&id, &blocks); + let doc = std::rc::Rc::new(text_document(&blocks)); + let prepared = std::rc::Rc::new(prepared_blocks(&blocks)); let count = blocks.len(); Self { @@ -340,12 +342,14 @@ impl MarkdownViewState { source, blocks, block_ids, + doc, + prepared, highlight_code: true, handle: ListState::new(count, ListAlignment::Top, CODE_OVERSCROLL_MAX), a11y_label: None, selection: None, selecting: false, - focus_handle: None, + focus_handle: cx.focus_handle().tab_stop(true), } } @@ -373,6 +377,9 @@ impl MarkdownViewState { fn reparse(&mut self) { let blocks = parse(&self.source, self.highlight_code); let block_ids = Self::stable_block_ids(&self.id, &blocks); + + self.doc = std::rc::Rc::new(text_document(&blocks)); + self.prepared = std::rc::Rc::new(prepared_blocks(&blocks)); self.blocks = blocks; self.block_ids = block_ids; self.selection = None; @@ -385,16 +392,17 @@ impl MarkdownViewState { fn stable_block_ids(id: &ElementId, blocks: &[MarkdownBlock]) -> Vec { let mut ids = Vec::with_capacity(blocks.len()); let mut occurrences = HashMap::with_capacity(blocks.len()); + for block in blocks { let hash = block.content_hash(); let occurrence = *occurrences .entry(hash) .and_modify(|count| *count += 1) .or_insert(0); - ids.push(ElementId::from(SharedString::from(format!( - "{id}-block-{hash:x}-{occurrence}" - )))); + + ids.push(ElementId::from(format!("{id}-block-{hash:x}-{occurrence}"))); } + ids } @@ -443,8 +451,7 @@ impl MarkdownViewState { cx.notify(); } - /// The selected range over the rendered text, endpoints in document - /// order, when there is one. + /// The selected range over the rendered text, endpoints in document order. pub fn selection(&self) -> Option<(usize, usize)> { let (anchor, head) = self.selection?; Some(if anchor <= head { @@ -456,18 +463,33 @@ impl MarkdownViewState { /// The selected text, or `None` when nothing is selected. pub fn selected_text(&self) -> Option { - let document = text_document(&self.blocks); let (start, end) = self.selection()?; - let end = end.min(document.len); + let end = end.min(self.doc.len); let start = start.min(end); - Some(document.text(&self.blocks)[start..end].to_string()).filter(|text| !text.is_empty()) + + Some(self.doc.text[start..end].to_string()).filter(|text| !text.is_empty()) } - /// The focus handle the view claims on click, created on first use. - fn focus_handle(&mut self, cx: &mut App) -> gpui::FocusHandle { - self.focus_handle - .get_or_insert_with(|| cx.focus_handle().tab_stop(true)) - .clone() + /// Binds the view's copy chord: cmd-c on macOS, ctrl-c elsewhere. + pub fn bind_keys(cx: &mut App) { + let context = match KeyBindingContextPredicate::parse(TEXT_VIEW_CONTEXT) { + Ok(context) => Some(Rc::new(context)), + Err(error) => { + log::error!("failed to parse text 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 text view copy keystroke: {error}"); + return; + } + }; + + cx.bind_keys([binding]); } } @@ -475,18 +497,22 @@ impl Render for MarkdownViewState { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let id = self.id.clone(); let state = cx.entity(); - let focus_handle = self.focus_handle(cx); + let focus_handle = self.focus_handle.clone(); + let frame = std::rc::Rc::new(ViewFrame { state: state.clone(), selection: self.selection(), focus_handle, pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)), }); - let doc = std::rc::Rc::new(text_document(&self.blocks)); + + let doc = self.doc.clone(); + let prepared = self.prepared.clone(); let blocks = list(self.handle.clone(), { let frame = frame.clone(); let doc = doc.clone(); + move |block_index, _window, cx| { let view = state.read(cx); match view @@ -498,6 +524,7 @@ impl Render for MarkdownViewState { let ctx = BlockContext { frame: &frame, doc: &doc, + prepared: prepared.get(block_index).map_or(&[], Vec::as_slice), block_index, block_id, }; @@ -538,6 +565,8 @@ struct ViewFrame { struct BlockContext<'a> { frame: &'a ViewFrame, doc: &'a TextDocument, + /// The block's prepared inline text, one entry per selectable unit. + prepared: &'a [PreparedText], block_index: usize, block_id: &'a ElementId, } @@ -586,6 +615,35 @@ struct PieceContext { pressed_on_piece: std::rc::Rc>, } +/// One block's inline text with its style runs, built once per parse. +#[derive(Clone, Debug, Default)] +struct PreparedText { + text: SharedString, + runs: Vec<(Range, InlineStyle)>, +} + +impl PreparedText { + fn from_spans<'a>(spans: impl IntoIterator) -> Self { + let mut text = String::new(); + let mut runs = Vec::new(); + + for span in spans { + let start = text.len(); + text.push_str(&span.text); + let range = start..text.len(); + if range.is_empty() || span.style == InlineStyle::Text { + continue; + } + runs.push((range, span.style.clone())); + } + + Self { + text: SharedString::from(text), + runs, + } + } +} + /// One selectable stretch of rendered text. #[derive(Clone, Debug)] pub struct TextPiece { @@ -602,169 +660,12 @@ pub struct TextPiece { pub struct TextDocument { /// The pieces, in document order. pub pieces: Vec, + /// The rendered text, joined by newlines. + pub text: String, /// The rendered text length in bytes. pub len: usize, } -impl TextDocument { - /// The rendered text, built on demand. - fn text(&self, blocks: &[MarkdownBlock]) -> String { - let mut out = String::with_capacity(self.len); - let mut piece_ix = 0; - - for (block_index, block) in blocks.iter().enumerate() { - if piece_ix >= self.pieces.len() || self.pieces[piece_ix].block_index != block_index { - continue; - } - - let block_end = self.pieces[piece_ix..] - .iter() - .position(|piece| piece.block_index != block_index) - .map_or(self.pieces.len(), |offset| piece_ix + offset); - 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 { - continue; - }; - if !out.is_empty() { - out.push('\n'); - } - out.push_str(unit); - } - piece_ix = block_end; - } - - out - } -} - -/// An embeddable markdown text view: fit-content height, no scrolling. -pub struct TextView { - id: ElementId, - source: Option, - state: Option>, - style: StyleRefinement, -} - -impl TextView { - /// Renders `source`, keeping its parsed state across frames under `id`. - pub fn markdown(id: I, source: S) -> Self - where - I: Into, - S: Into, - { - Self { - id: id.into(), - source: Some(source.into()), - state: None, - style: StyleRefinement::default(), - } - } - - /// Wraps an owned state; its source drives what the view renders. - pub fn new(state: &Entity) -> Self { - Self { - id: ElementId::from(SharedString::from(format!("{}", state.entity_id()))), - source: None, - state: Some(state.clone()), - style: StyleRefinement::default(), - } - } -} - -impl Styled for TextView { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl Element for TextView { - type PrepaintState = (); - type RequestLayoutState = AnyElement; - - fn id(&self) -> Option { - Some(self.id.clone()) - } - - fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { - None - } - - fn request_layout( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&InspectorElementId>, - window: &mut Window, - cx: &mut App, - ) -> (LayoutId, Self::RequestLayoutState) { - let state = match self.state.clone() { - Some(state) => state, - None => { - let view_id = self.id.clone(); - let source = self.source.clone().unwrap_or_default(); - let state_key = SharedString::from(format!("{}/state", self.id)); - window.use_keyed_state(state_key, cx, move |_, _| { - MarkdownViewState::new(view_id, source) - }) - } - }; - - let source = self.source.clone(); - - let (selection, focus_handle) = - state.update(cx, |view, cx| (view.selection(), view.focus_handle(cx))); - - state.update(cx, |view, cx| { - if let Some(source) = source { - view.set_source(source, cx); - } - }); - - let view = state.read(cx); - let frame = ViewFrame { - state: state.clone(), - selection, - focus_handle, - pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)), - }; - let doc = text_document(&view.blocks); - - let mut element = render_blocks(&view.blocks, &frame, &doc, &view.block_ids, cx); - element.style().refine(&self.style); - - let mut element = element.into_any_element(); - let layout_id = element.request_layout(window, cx); - - (layout_id, element) - } - - fn prepaint( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&InspectorElementId>, - _bounds: Bounds, - request_layout: &mut Self::RequestLayoutState, - window: &mut Window, - cx: &mut App, - ) { - request_layout.prepaint(window, cx); - } - - fn paint( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&InspectorElementId>, - _bounds: Bounds, - request_layout: &mut Self::RequestLayoutState, - _prepaint: &mut Self::PrepaintState, - window: &mut Window, - cx: &mut App, - ) { - request_layout.paint(window, cx); - } -} - /// One open list, tracking ordered numbering and an in-flight task marker. struct ListFrame { ordered: bool, @@ -836,28 +737,6 @@ impl InlineBuilder { } } -/// Binds the text 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_text_view_keys(cx: &mut App) { - let context = match KeyBindingContextPredicate::parse(TEXT_VIEW_CONTEXT) { - Ok(context) => Some(Rc::new(context)), - Err(error) => { - log::error!("failed to parse text 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 text view copy keystroke: {error}"); - return; - } - }; - cx.bind_keys([binding]); -} - -/// The view's base container: selection wiring, focus, and copy. fn view_container(frame: &ViewFrame) -> Div { let clear_flag = frame.pressed_on_piece.clone(); @@ -876,7 +755,7 @@ fn view_container(frame: &ViewFrame) -> Div { .on_mouse_down(MouseButton::Left, { let state = frame.state.clone(); move |_, window, cx| { - let focus_handle = state.update(cx, |view, cx| view.focus_handle(cx)); + let focus_handle = state.read(cx).focus_handle.clone(); window.focus(&focus_handle, cx); if !clear_flag.replace(false) { state.update(cx, |view, cx| { @@ -900,25 +779,52 @@ fn view_container(frame: &ViewFrame) -> Div { }) } -/// Renders every block stacked, without virtualization or scrolling. -fn render_blocks( - blocks: &[MarkdownBlock], - frame: &ViewFrame, - doc: &TextDocument, - block_ids: &[ElementId], - cx: &App, -) -> Div { - view_container(frame).children(blocks.iter().zip(block_ids).enumerate().map( - |(block_index, (block, block_id))| { - let ctx = BlockContext { - frame, - doc, - block_index, - block_id, - }; - block.render_block(block_index, &ctx, cx) - }, - )) +/// Builds each block's inline text and style runs, in the same unit order the selection uses. +fn prepared_blocks(blocks: &[MarkdownBlock]) -> Vec> { + fn text_units(items: &[InlineItem]) -> Vec { + let mut units = Vec::new(); + let mut run: Vec<&InlineSpan> = Vec::new(); + + for item in items { + match item { + InlineItem::Text(span) => run.push(span), + InlineItem::Image { .. } => { + if !run.is_empty() { + let unit = PreparedText::from_spans(run.drain(..)); + if !unit.text.is_empty() { + units.push(unit); + } + } + } + } + } + + if !run.is_empty() { + let unit = PreparedText::from_spans(run); + if !unit.text.is_empty() { + units.push(unit); + } + } + + units + } + + blocks + .iter() + .map(|block| match block { + MarkdownBlock::Heading { spans, .. } => vec![PreparedText::from_spans(spans.iter())], + MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => { + text_units(items) + } + MarkdownBlock::Table { table, .. } => table + .rows + .iter() + .flat_map(|row| row.cells.iter()) + .map(|cell| PreparedText::from_spans(cell.spans.iter())) + .collect(), + _ => Vec::new(), + }) + .collect() } fn spans_text_of(spans: &[InlineSpan]) -> String { @@ -928,6 +834,7 @@ fn spans_text_of(spans: &[InlineSpan]) -> String { /// Enumerates the selectable text pieces of `blocks`, in render order. fn text_document(blocks: &[MarkdownBlock]) -> TextDocument { let mut pieces = Vec::new(); + let mut text = String::new(); let mut len = 0usize; for (block_index, block) in blocks.iter().enumerate() { @@ -945,8 +852,10 @@ fn text_document(blocks: &[MarkdownBlock]) -> TextDocument { let mut range = len..len; if !unit.is_empty() { if len > 0 { + text.push('\n'); len += 1; // The newline that joins pieces. } + text.push_str(&unit); range = len..len + unit.len(); len = range.end; } @@ -959,7 +868,7 @@ fn text_document(blocks: &[MarkdownBlock]) -> TextDocument { } } - TextDocument { pieces, len } + TextDocument { pieces, text, len } } /// The markdown extensions the view parses, on top of CommonMark. @@ -1191,6 +1100,7 @@ fn parse(source: &str, highlight_code: bool) -> Vec { blocks.push(MarkdownBlock::Code { language, lines, + text: SharedString::from(text), indent: lists.len(), quote: quote_depth > 0, }); @@ -1419,7 +1329,7 @@ fn indented_frame(indent: usize, frame: Div) -> Div { #[allow(clippy::too_many_arguments)] fn heading_row( level: MarkdownHeading, - spans: &[InlineSpan], + prepared: &PreparedText, indent: usize, quote: bool, top: Rems, @@ -1437,7 +1347,7 @@ fn heading_row( frame.text_sm().font_semibold() } }) - .child(text_child(spans, ctx.block_id, ctx.piece_context(0), cx)), + .child(text_child(prepared, ctx.block_id, ctx.piece_context(0), cx)), ) .into_any_element() } @@ -1481,10 +1391,10 @@ fn text_row( ListMarker::Ordered(number) => div() .text_color(theme.colors.muted_foreground) .whitespace_nowrap() - .child(format!("{number}.")) + .child(SharedString::from(format!("{number}."))) .into_any_element(), ListMarker::Task(checked) => { - task_toggle(checked, item_text(items), ctx) + task_toggle(checked, InlineItem::text_of(items), ctx) } }), ) @@ -1505,9 +1415,8 @@ fn text_row( /// 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}")); Checkbox::new((ctx.block_id.clone(), "task")) - .debug_selector(move || selector.to_string()) + .debug_selector(move || format!("task-toggle-{block_index}")) .checked(checked) .with_size(Size::Small) .accessibility_label(label) @@ -1515,17 +1424,19 @@ fn task_toggle(checked: bool, label: SharedString, ctx: &BlockContext) -> AnyEle .into_any_element() } -/// The item's plain text, for the checkbox's accessibility label. -fn item_text(items: &[InlineItem]) -> SharedString { - let text = items - .iter() - .filter_map(|item| match item { - InlineItem::Text(span) => Some(span.text.as_ref()), - InlineItem::Image { .. } => None, - }) - .collect::>() - .join(""); - SharedString::from(text) +impl InlineItem { + /// The items' plain text, for the checkbox's accessibility label. + fn text_of(items: &[Self]) -> SharedString { + let text = items + .iter() + .filter_map(|item| match item { + InlineItem::Text(span) => Some(span.text.as_ref()), + InlineItem::Image { .. } => None, + }) + .collect::>() + .join(""); + SharedString::from(text) + } } /// Builds a paragraph's content. @@ -1534,31 +1445,38 @@ fn paragraph_child(items: &[InlineItem], ctx: &BlockContext, cx: &App) -> AnyEle .iter() .any(|item| matches!(item, InlineItem::Image { .. })); + let mut units = ctx.prepared.iter(); + if !has_image { - let spans = items.iter().filter_map(|item| match item { - InlineItem::Text(span) => Some(span), - InlineItem::Image { .. } => None, - }); - return text_child(spans, ctx.block_id, ctx.piece_context(0), cx); + return text_child( + units.next().unwrap_or(&PreparedText::default()), + ctx.block_id, + ctx.piece_context(0), + cx, + ); } let side = rems(0.8625); let mut flow = div().flex().flex_wrap().items_center(); - let mut segment: Vec<&InlineSpan> = Vec::new(); - let mut segment_index = 0; + // One prepared unit per image-separated text segment, in order. + let mut segment = false; + let mut segment_index = 0usize; + for item in items { match item { - InlineItem::Text(span) => segment.push(span), + InlineItem::Text(_) => segment = true, InlineItem::Image { source, .. } => { - if !segment.is_empty() { - flow = flow.child(text_child( - segment, - &text_segment_id(ctx.block_id, segment_index), - ctx.piece_context(segment_index), - cx, - )); - segment = Vec::new(); - segment_index += 1; + if segment { + if let Some(unit) = units.next() { + flow = flow.child(text_child( + unit, + &text_segment_id(ctx.block_id, segment_index), + ctx.piece_context(segment_index), + cx, + )); + segment_index += 1; + } + segment = false; } flow = flow.child( img(source.clone()) @@ -1569,14 +1487,16 @@ fn paragraph_child(items: &[InlineItem], ctx: &BlockContext, cx: &App) -> AnyEle } } } - if !segment.is_empty() { + + if segment && let Some(unit) = units.next() { flow = flow.child(text_child( - segment, + unit, &text_segment_id(ctx.block_id, segment_index), ctx.piece_context(segment_index), cx, )); } + flow.into_any_element() } @@ -1612,6 +1532,7 @@ fn text_segment_id(id: &ElementId, segment_index: usize) -> ElementId { fn code_row( lines: &HighlightedCode, + text: &SharedString, language: Option<&SharedString>, indent: usize, quote: bool, @@ -1621,12 +1542,7 @@ fn code_row( let theme = cx.theme(); let text_size = rems(0.75).to_pixels(theme.root_font_size); let line_height = text_size * CODE_LINE_HEIGHT; - let plain = lines - .lines - .iter() - .map(|line| line.text()) - .collect::>() - .join("\n"); + let plain = text.clone(); indented_frame( indent, @@ -1658,13 +1574,16 @@ fn code_row( .variant(ButtonVariant::Ghost) .debug_selector(|| "copy-code".to_string()) .on_click(move |_, _, cx| { - cx.write_to_clipboard(ClipboardItem::new_string(plain.clone())); + cx.write_to_clipboard(ClipboardItem::new_string( + plain.to_string(), + )); }), ), ) .children(lines.lines.iter().enumerate().map(|(line_ix, line)| { let styled = code_line(line, theme.colors, theme.ramps); let layout = styled.layout().clone(); + with_selection_handlers( div() .h(line_height) @@ -1699,19 +1618,24 @@ fn table_row( ) -> AnyElement { let theme = cx.theme(); let colors = theme.colors; + let width = table .rows .iter() .map(|row| row.cells.len()) .max() .unwrap_or(0); + let row_count = table.rows.len(); + let fallback = PreparedText::default(); + let mut cell_ix = 0usize; indented_frame( indent, block_frame(quote, Rems::ZERO, rems(0.75), ctx.block_id, cx).child( v_flex() + .id((ctx.block_id.clone(), "table")) .w_full() .border_1() .border_color(colors.border) @@ -1728,12 +1652,9 @@ fn table_row( .children( row.cells .iter() - .enumerate() - .map(|(column_index, cell)| { - let cell_id = ElementId::from(SharedString::from(format!( - "{}-cell-{row_index}-{column_index}", - ctx.block_id - ))); + .map(|_cell| { + let cell_id = ElementId::from(("cell", cell_ix)); + let prepared = ctx.prepared.get(cell_ix).unwrap_or(&fallback); let piece = ctx.piece_context(cell_ix); cell_ix += 1; div() @@ -1744,7 +1665,7 @@ fn table_row( .when(row.header, |cell_element| { cell_element.font_semibold() }) - .child(text_child(&cell.spans, &cell_id, piece, cx)) + .child(text_child(prepared, &cell_id, piece, cx)) }) // Ragged tables pad missing cells so rows align. .chain( @@ -1768,17 +1689,19 @@ fn with_selection_handlers(element: Div, piece: Option, layout: Te let doc_range = piece.doc_range.clone(); let pressed_on_piece = piece.pressed_on_piece.clone(); let layout_for_move = layout.clone(); + element .on_mouse_down( MouseButton::Left, move |event: &MouseDownEvent, window: &mut Window, cx: &mut App| { pressed_on_piece.set(true); - let focus_handle = state.update(cx, |view, cx| view.focus_handle(cx)); + let focus_handle = state.read(cx).focus_handle.clone(); window.focus(&focus_handle, cx); let local = match layout.index_for_position(event.position) { Ok(index) | Err(index) => index, }; + let index = doc_range.start + local; state.update(cx, |view, cx| { if event.modifiers.shift { @@ -1799,19 +1722,23 @@ fn with_selection_handlers(element: Div, piece: Option, layout: Te let state = piece.state.clone(); let doc_range = piece.doc_range.clone(); let layout = layout_for_move; + move |event: &MouseMoveEvent, _window: &mut Window, cx: &mut App| { if !state.read(cx).selecting { return; } + let local = match layout.index_for_position(event.position) { Ok(index) | Err(index) => index, }; + let index = doc_range.start + local; let changed = state .read(cx) .selection .map(|(_, head)| head != index) .unwrap_or(true); + if changed { state.update(cx, |view, cx| { if let Some((anchor, _)) = view.selection { @@ -1836,26 +1763,23 @@ fn with_selection_handlers(element: Div, piece: Option, layout: Te } /// Builds the block's text element, selectable when it renders a piece. -fn text_child(spans: I, id: &ElementId, piece: Option, cx: &App) -> AnyElement -where - I: IntoIterator, - I::Item: std::borrow::Borrow, -{ +fn text_child( + prepared: &PreparedText, + id: &ElementId, + piece: Option, + cx: &App, +) -> AnyElement { let theme = cx.theme(); - let mut text = String::new(); - let mut highlights: Vec<(Range, HighlightStyle)> = Vec::new(); + let mut highlights: Vec<(Range, HighlightStyle)> = + Vec::with_capacity(prepared.runs.len() + 1); + let mut family_overrides: Vec<(Range, SharedString)> = Vec::new(); let mut link_ranges: Vec> = Vec::new(); let mut destinations: Vec = Vec::new(); - for span in spans { - let span = span.borrow(); - let start = text.len(); - text.push_str(&span.text); - - let range = start..text.len(); - - match &span.style { + for (range, style) in &prepared.runs { + let range = range.clone(); + match style { InlineStyle::Text => {} InlineStyle::Emphasis => highlights.push(( range, @@ -1928,7 +1852,7 @@ where )); } - let styled = StyledText::new(text) + let styled = StyledText::new(prepared.text.clone()) .with_highlights(highlights) .with_font_family_overrides(family_overrides); let layout = styled.layout().clone(); @@ -1950,5 +1874,6 @@ where if let Some(piece) = piece { element = with_selection_handlers(element, Some(piece), layout); } + element.into_any_element() } diff --git a/crates/ui/src/components/menu.rs b/crates/ui/src/components/menu.rs index 25439d3..23ee4da 100644 --- a/crates/ui/src/components/menu.rs +++ b/crates/ui/src/components/menu.rs @@ -21,23 +21,24 @@ //! ``` use std::cell::RefCell; +use std::mem; use std::rc::Rc; +use std::time::Duration; use gpui::prelude::FluentBuilder; use gpui::{ - Animation, AnimationExt as _, AnyElement, App, Bounds, DefiniteLength, DispatchPhase, - ElementId, Entity, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, - MouseButton, MouseDownEvent, ParentElement as _, Pixels, Point, RenderOnce, Role, ScrollHandle, - SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, anchored, - canvas, deferred, div, ease_out_quint, point, px, relative, rems, + Animation, AnimationExt as _, AnyElement, App, Bounds, DefiniteLength, DispatchPhase, Div, + ElementId, Entity, FocusHandle, Hsla, InteractiveElement as _, IntoElement, KeyBinding, + ListAlignment, ListSizingBehavior, ListState, MouseButton, MouseDownEvent, ParentElement as _, + Pixels, Point, RenderOnce, Role, SharedString, Stateful, StatefulInteractiveElement as _, + StyleRefinement, Styled, Window, actions, anchored, canvas, deferred, div, ease_out_quint, + list, point, px, relative, rems, }; use crate::components::common::{ - OVERLAY_LAYER, StyledExt as _, floating_panel, focus_handle, track_overlay_focus, v_flex, - wrapping_adjacent_selectable, + ElementIdExt as _, OVERLAY_LAYER, SelectableRows as _, StyledExt as _, v_flex, }; -use crate::components::scroll_area::{ScrollArea, ScrollAxes}; -use crate::icons::{Icon, IconRole, icon as icon_glyph}; +use crate::icons::{Icon, IconRole}; use crate::theme::{ActiveTheme as _, MENU_MIN_WIDTH, POPUP_MAX_HEIGHT}; /// Runs the item's action. The menu closes itself before the handler runs. @@ -54,6 +55,24 @@ type TriggerFn = Box AnyElement>; /// The menu's rows, rebuilt on each render while open. type ItemsFn = Box Vec>; +actions!( + menu, + [ + SelectNext, + SelectPrevious, + SelectFirst, + SelectLast, + OpenSubmenu, + Activate, + Dismiss, + DismissLeft, + Leave + ] +); + +/// The key context the menu panel declares. +pub const MENU_CONTEXT: &str = "Menu"; + /// One row of a [`Menu`]: an action, a checkable action, a submenu, or a separator. #[derive(Clone)] enum MenuItemKind { @@ -184,6 +203,8 @@ impl MenuItem { selected: bool, env: &RowEnv, ) -> AnyElement { + let flyout = env.flyout.as_ref(); + match &self.kind { MenuItemKind::Separator => div() .h_px() @@ -193,7 +214,7 @@ impl MenuItem { .bg(env.chrome.border) .into_any_element(), MenuItemKind::Action => { - let label_color = self.row_color(selected, false, env.chrome); + let label_color = self.row_color(selected, false, &env.chrome); let disabled = self.disabled; let checked = self.checked; let icon = self.icon.clone(); @@ -202,6 +223,7 @@ impl MenuItem { .on_click({ let handler = self.handler.clone(); let on_activate = env.on_activate.clone(); + move |_, window, cx| { if disabled { return; @@ -222,12 +244,14 @@ impl MenuItem { .child( div() .flex_1() + .min_w_0() + .truncate() .text_color(label_color) .child(self.label.clone()), ) .when(checked, |row| { row.child( - icon_glyph(IconRole::Check) + Icon::from(IconRole::Check) .size(rems(0.75)) .color(label_color), ) @@ -235,37 +259,39 @@ impl MenuItem { .into_any_element() } MenuItemKind::Submenu(items) => { - let chrome = env.chrome; - let flyout = env.flyout; + let flyout_open = flyout.is_some_and(|flyout| *flyout.open.read(cx) == Some(index)); + let label_color = self.row_color(selected, flyout_open, &env.chrome); 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(); + let set_flyout = flyout.map(|flyout| flyout.set.clone()); move |_, _window, cx| { if disabled { return; } // Hover already opens the flyout; a click never closes it. - set_flyout(Some(index), false, cx); + if let Some(set_flyout) = &set_flyout { + set_flyout(Some(index), false, cx); + } } }) .child( div() .flex_1() + .min_w_0() + .truncate() .text_color(label_color) .child(self.label.clone()), ) .child( - icon_glyph(IconRole::ChevronRight) + Icon::from(IconRole::ChevronRight) .size(rems(0.75)) .color(label_color), ) - .aria_expanded(open) - .when(open, |row| { + .aria_expanded(flyout_open) + .when(flyout_open, |row| { row.child( canvas( { @@ -277,31 +303,34 @@ impl MenuItem { .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), - ) + .when_some(flyout, |row, flyout| { + row.child( + deferred(div().absolute().left_full().top_0().child( + flyout.state.panel( + window, + cx, + 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.clone(), + 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: &env.chrome, + enter_duration: flyout.enter_duration, + debug_prefix: "submenu", + }, + ), + )) + .with_priority(OVERLAY_LAYER), + ) + }) }) .into_any_element() } @@ -309,22 +338,31 @@ impl MenuItem { } /// 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; + fn row_shell(&self, cx: &App, index: usize, selected: bool, env: &RowEnv) -> Stateful
{ + let chrome = env.chrome.clone(); let selectable = self.selectable(); let opens_submenu = self.submenu_items().is_some(); - let flyout_open = *env.flyout.open.read(cx) == Some(index); + + let flyout_open = env + .flyout + .as_ref() + .is_some_and(|flyout| *flyout.open.read(cx) == Some(index)); + + // Positional: rows never reorder while the panel is open. let row_id = self .id .clone() .unwrap_or_else(|| ("menu-item", index).into()); + let selection = env.selection.clone(); + let hover = env.flyout.as_ref().map(|flyout| { + ( + flyout.open.clone(), + flyout.set.clone(), + flyout.dismiss.clone(), + ) + }); + div() .id(row_id) .role(Role::MenuItem) @@ -332,7 +370,7 @@ impl MenuItem { .flex() .items_center() .gap_2() - .min_h_8() + .h_8() .px_4() .text_sm() .line_height(relative(1.0)) @@ -353,23 +391,19 @@ impl MenuItem { 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; - } + .on_mouse_move(move |_, window, cx| { + if !selectable { + return; + } - if *selection.read(cx) != Some(index) { - selection.update(cx, |selection, _| *selection = Some(index)); - } + if *selection.read(cx) != Some(index) { + selection.update(cx, |selection, _| *selection = Some(index)); + } + if let Some((open, set_flyout, dismiss)) = &hover { if opens_submenu { set_flyout(Some(index), false, cx); - } else if flyout_open.read(cx).is_some() { + } else if open.read(cx).is_some() { dismiss(false, window, cx); } } @@ -377,10 +411,11 @@ impl MenuItem { } /// The row's label/icon color. - fn row_color(&self, selected: bool, flyout_open: bool, chrome: &MenuChrome) -> gpui::Hsla { + fn row_color(&self, selected: bool, flyout_open: bool, chrome: &MenuChrome) -> Hsla { if self.disabled { return chrome.muted_foreground; } + if self.destructive { return if selected && !flyout_open { chrome.destructive_foreground @@ -388,6 +423,7 @@ impl MenuItem { chrome.destructive }; } + if selected && !flyout_open { chrome.primary_foreground } else { @@ -402,17 +438,38 @@ impl FluentBuilder for MenuItem {} /// Menu chrome styles. #[derive(Clone)] pub(crate) struct MenuChrome { - border: gpui::Hsla, - foreground: gpui::Hsla, - muted_foreground: gpui::Hsla, - muted_hover: gpui::Hsla, - primary: gpui::Hsla, - primary_foreground: gpui::Hsla, - destructive: gpui::Hsla, - destructive_foreground: gpui::Hsla, + border: Hsla, + foreground: Hsla, + muted_foreground: Hsla, + muted_hover: Hsla, + primary: Hsla, + primary_foreground: Hsla, + destructive: Hsla, + destructive_foreground: Hsla, radius_full: Pixels, } +impl MenuChrome { + /// Reads the menu's chrome and enter duration from the active theme. + pub(crate) fn read(cx: &App) -> (Self, Duration) { + let theme = cx.theme(); + ( + Self { + border: theme.colors.border, + foreground: theme.colors.foreground, + muted_foreground: theme.colors.muted_foreground, + muted_hover: theme.colors.muted_hover, + primary: theme.ramps.primary.base, + primary_foreground: theme.colors.primary_foreground, + destructive: theme.ramps.destructive.base, + destructive_foreground: theme.colors.destructive_foreground, + radius_full: theme.radius.full, + }, + theme.motion.overlay, + ) + } +} + /// A floating menu of [`MenuItem`] rows anchored below its trigger. #[derive(IntoElement)] #[must_use] @@ -430,27 +487,6 @@ pub struct Menu { style: StyleRefinement, } -impl MenuChrome { - /// Reads the menu's chrome and enter duration from the active theme. - pub(crate) fn read(cx: &App) -> (Self, std::time::Duration) { - let theme = cx.theme(); - ( - Self { - border: theme.colors.border, - foreground: theme.colors.foreground, - muted_foreground: theme.colors.muted_foreground, - muted_hover: theme.colors.muted_hover, - primary: theme.ramps.primary.base, - primary_foreground: theme.colors.primary_foreground, - destructive: theme.ramps.destructive.base, - destructive_foreground: theme.colors.destructive_foreground, - radius_full: theme.radius.full, - }, - theme.motion.overlay, - ) - } -} - impl Menu { /// Creates a closed menu. pub fn new(id: I) -> Self @@ -472,6 +508,24 @@ impl Menu { } } + /// Binds the menu panel's navigation keys. + pub fn bind_keys(cx: &mut App) { + let context = Some(MENU_CONTEXT); + cx.bind_keys([ + KeyBinding::new("down", SelectNext, context), + KeyBinding::new("up", SelectPrevious, context), + KeyBinding::new("home", SelectFirst, context), + KeyBinding::new("end", SelectLast, context), + KeyBinding::new("right", OpenSubmenu, context), + KeyBinding::new("enter", Activate, context), + KeyBinding::new("space", Activate, context), + KeyBinding::new("escape", Dismiss, context), + KeyBinding::new("left", DismissLeft, context), + KeyBinding::new("tab", Leave, context), + KeyBinding::new("shift-tab", Leave, context), + ]); + } + /// Sets the row that starts keyboard-selected when the menu opens. pub fn initial_selection(mut self, index: usize) -> Self { self.initial_selection = Some(index); @@ -545,7 +599,7 @@ impl Menu { } } -impl gpui::Styled for Menu { +impl Styled for Menu { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } @@ -554,24 +608,26 @@ impl gpui::Styled for Menu { impl RenderOnce for Menu { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let (chrome, enter_duration) = MenuChrome::read(cx); - let trigger_bounds: Rc>>> = Rc::new(RefCell::new(None)); + let trigger_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); let on_change = self.on_change.clone(); - let panel_focus = focus_handle(&(self.id.clone(), "panel").into(), window, cx); - track_overlay_focus(&self.id, &panel_focus, self.open, window, cx); + let panel_focus = ElementId::from((self.id.clone(), "panel")).focus_handle(window, cx); + self.id + .track_overlay_focus(&panel_focus, self.open, window, cx); - let fallback_label = self - .a11y_label - .clone() - .unwrap_or_else(|| SharedString::from(self.id.to_string())); - - let items = if self.open { - match self.items { + let (items, label) = if self.open { + let items = match self.items { Some(build) => Rc::from(build(window, cx)), None => Rc::from([]), - } + }; + let label = self + .a11y_label + .clone() + .unwrap_or_else(|| SharedString::from(self.id.to_string())); + (items, label) } else { - Rc::from([]) + // A closed panel mounts no rows; it only resets its keyed state. + (Rc::from([]), SharedString::default()) }; let spec = MenuPanelSpec { @@ -580,7 +636,7 @@ impl RenderOnce for Menu { initial_selection: self.initial_selection, preselect: false, min_width: self.min_width, - label: fallback_label, + label, position: self.open_at, trigger_bounds: trigger_bounds.clone(), on_dismiss: on_change.clone(), @@ -593,14 +649,14 @@ impl RenderOnce for Menu { .child(trigger_toggle( &trigger_bounds, self.open, - on_change.clone(), + on_change, self.trigger_button, )) .when_some(self.trigger, |wrapper, trigger| { wrapper.child(trigger(window, cx)) }) .when_some( - anchored_menu_panel(window, cx, &self.id, spec, &chrome, enter_duration), + spec.anchored(window, cx, &self.id, &chrome, enter_duration), |wrapper, panel| wrapper.child(panel), ) } @@ -622,14 +678,62 @@ pub(crate) struct MenuPanelSpec { pub on_activate: Option, } -/// Per-panel state that survives across frames while the panel stays mounted. -struct MenuPanelState { - focus: FocusHandle, - was_open: Entity, - scroll: Entity, - selection: Entity>, +impl MenuPanelSpec { + pub(crate) fn anchored<'a>( + self, + window: &mut Window, + cx: &mut App, + id: &ElementId, + chrome: &'a MenuChrome, + enter_duration: Duration, + ) -> Option { + let was_open = window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false); + + if !self.open { + if *was_open.read(cx) { + was_open.update(cx, |was_open, _| *was_open = false); + // A closed menu drops any open flyout; fresh state on the next open. + window + .use_keyed_state::>((id.clone(), "submenu-open"), cx, |_, _| None) + .update(cx, |open, _| *open = None); + window + .use_keyed_state((id.clone(), "submenu-preselect"), cx, |_, _| false) + .update(cx, |preselect, _| *preselect = false); + window + .use_keyed_state((id.clone(), "menu-painted"), cx, |_, _| false) + .update(cx, |painted, _| *painted = false); + } + return None; + } + + let state = MenuPanelState::new(id, window, cx); + let panel = state.panel( + window, + cx, + MenuPanelParams { + id, + items: self.items, + initial_selection: self.initial_selection, + preselect: self.preselect, + min_width: self.min_width, + label: self.label, + dismiss_bounds: self.trigger_bounds.clone(), + bounds_sink: None, + outer_stack: None, + on_dismiss: self.on_dismiss, + on_activate: self.on_activate, + is_flyout: false, + chrome, + enter_duration, + debug_prefix: "menu", + }, + ); + + Some(anchored_overlay(self.position, panel, None)) + } } +/// One frame's inputs for a menu panel. struct MenuPanelParams<'a> { id: &'a ElementId, items: Rc<[MenuItem]>, @@ -638,7 +742,7 @@ struct MenuPanelParams<'a> { min_width: Option, label: SharedString, /// Clicks here do not dismiss the panel: the trigger or the owning row. - dismiss_bounds: &'a TriggerBoundsCell, + dismiss_bounds: TriggerBoundsCell, /// Receives the panel's painted bounds, for a parent's dismissal checks. bounds_sink: Option<&'a TriggerBoundsCell>, /// This panel's flyout bounds are pushed here. @@ -648,54 +752,467 @@ struct MenuPanelParams<'a> { /// Flyout panels dismiss themselves on `left`; top-level panels ignore it. is_flyout: bool, chrome: &'a MenuChrome, - enter_duration: std::time::Duration, + enter_duration: Duration, debug_prefix: &'static str, } -/// Wiring a panel's rows need to open their submenus. -struct FlyoutContext<'a> { - state: &'a MenuPanelState, - open: &'a Entity>, - preselect: &'a Entity, - /// Opens or closes this level's flyout, re-arming it on every switch. - set_flyout: FlyoutSetter, - /// The open flyout's painted bounds; a parent ignores clicks inside them. - bounds: &'a TriggerBoundsCell, +/// Per-panel state that survives across frames while the panel stays mounted. +#[derive(Clone)] +struct MenuPanelState { + focus: FocusHandle, + was_open: Entity, + list: Entity, + painted: Entity, + selection: Entity>, +} + +impl MenuPanelState { + /// Creates one panel's keyed state: focus, open tracking, list, and selection. + fn new(id: &ElementId, window: &mut Window, cx: &mut App) -> Self { + Self { + focus: ElementId::from((id.clone(), "panel")).focus_handle(window, cx), + was_open: window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false), + list: window.use_keyed_state((id.clone(), "menu-list"), cx, |_, _| { + ListState::new(0, ListAlignment::Top, px(32.)) + }), + painted: window.use_keyed_state((id.clone(), "menu-painted"), cx, |_, _| false), + selection: window.use_keyed_state((id.clone(), "menu-selection"), cx, |_, _| None), + } + } + + /// Builds one menu panel: chrome, rows, focus, navigation, and dismissals. + fn panel( + &self, + window: &mut Window, + cx: &mut App, + params: MenuPanelParams, + ) -> impl IntoElement { + let flyout = params + .items + .iter() + .any(|item| item.submenu_items().is_some()) + .then(|| Flyout::new(¶ms, &self.focus, window, cx)); + let flyout_stack = flyout.as_ref().map(|flyout| flyout.stack.clone()); + + let MenuPanelParams { + id: _, + items, + initial_selection, + preselect, + min_width, + label, + dismiss_bounds, + bounds_sink, + outer_stack: _, + on_dismiss, + on_activate, + is_flyout, + chrome, + enter_duration, + debug_prefix, + } = params; + + // Render-phase residue: panels open from owner state alone. + if !*self.was_open.read(cx) { + let requested = initial_selection + .map(|index| index.min(items.len().saturating_sub(1))) + .or_else(|| { + preselect + .then(|| items.iter().position(MenuItem::selectable)) + .flatten() + }); + self.selection + .update(cx, |selection, _| *selection = requested); + self.was_open.update(cx, |was_open, _| *was_open = true); + } + + if self.list.read(cx).item_count() != items.len() { + self.list.update(cx, |list, _| list.reset(items.len())); + } + + let keys = Rc::new(MenuKeys { + items: items.clone(), + selection: self.selection.clone(), + set_flyout: flyout.as_ref().map(|flyout| flyout.set.clone()), + on_dismiss: on_dismiss.clone(), + on_activate: on_activate.clone(), + left_dismisses: is_flyout, + }); + + let row_env = RowEnv { + items, + chrome: chrome.clone(), + selection: self.selection.clone(), + on_activate, + flyout, + debug_prefix, + }; + + let rows = list(self.list.read(cx).clone(), move |index, window, cx| { + let selected = *row_env.selection.read(cx) == Some(index); + row_env + .items + .get(index) + .map(|item| item.render_item(window, cx, index, selected, &row_env)) + .unwrap_or_else(|| div().into_any_element()) + }); + + v_flex() + .id("menu-panel") + .debug_selector(move || format!("{}-panel", debug_prefix)) + .occlude() + .track_focus(&self.focus) + .key_context(MENU_CONTEXT) + .role(Role::Menu) + .aria_label(label) + .when_some(min_width, |panel, width| panel.min_w(width)) + .when(min_width.is_none(), |panel| panel.min_w(MENU_MIN_WIDTH)) + .p_1() + .text_color(chrome.foreground) + .floating_panel( + cx, + cx.theme().radius.overlay, + cx.theme().elevations.popover.shadows(), + ) + .overflow_hidden() + .on_mouse_down_out({ + let on_dismiss = on_dismiss.clone(); + let dismiss_bounds = dismiss_bounds.clone(); + let flyout_stack = flyout_stack.clone(); + + move |event, window, cx| { + if dismiss_bounds + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)) + { + return; + } + + // Clicks inside any open flyout belong to that flyout. + if flyout_stack.as_ref().is_some_and(|stack| { + stack.borrow().iter().any(|cell| { + cell.borrow() + .is_some_and(|bounds| bounds.contains(&event.position)) + }) + }) { + return; + } + + if let Some(on_dismiss) = &on_dismiss { + on_dismiss(false, window, cx); + } + } + }) + .on_action({ + let keys = keys.clone(); + move |_: &SelectNext, _, cx| keys.step(true, cx) + }) + .on_action({ + let keys = keys.clone(); + move |_: &SelectPrevious, _, cx| keys.step(false, cx) + }) + .on_action({ + let keys = keys.clone(); + move |_: &SelectFirst, _, cx| keys.jump(true, cx) + }) + .on_action({ + let keys = keys.clone(); + move |_: &SelectLast, _, cx| keys.jump(false, cx) + }) + .on_action({ + let keys = keys.clone(); + move |_: &OpenSubmenu, _, cx| keys.open_submenu(cx) + }) + .on_action({ + let keys = keys.clone(); + move |_: &Activate, window, cx| keys.activate(window, cx) + }) + .on_action({ + let keys = keys.clone(); + move |_: &Dismiss, window, cx| keys.dismiss(window, cx) + }) + .on_action({ + let keys = keys.clone(); + move |_: &DismissLeft, window, cx| keys.dismiss_left(window, cx) + }) + // Tab leaves the panel and lets outer bindings move focus from there. + .on_action({ + let keys = keys.clone(); + move |_: &Leave, window, cx| { + keys.dismiss(window, cx); + cx.propagate(); + } + }) + .child( + v_flex() + .max_h(POPUP_MAX_HEIGHT) + .min_h_0() + .child(rows.with_sizing_behavior(ListSizingBehavior::Infer)), + ) + .child( + canvas( + { + let bounds_sink = bounds_sink.cloned(); + move |bounds, _window, _cx| { + if let Some(cell) = &bounds_sink { + *cell.borrow_mut() = Some(bounds); + } + } + }, + { + let painted = self.painted.clone(); + let focus = self.focus.clone(); + move |_, _, window, cx| { + let first = + painted.update(cx, |painted, _| mem::replace(painted, true)); + if first { + window.defer(cx, move |window, cx| window.focus(&focus, cx)); + } + } + }, + ) + .absolute() + .inset_0(), + ) + .with_animation( + "menu-enter", + Animation::new(enter_duration).with_easing(ease_out_quint()), + |panel, delta| panel.opacity(delta), + ) + } +} + +/// One panel's submenu wiring. +#[derive(Clone)] +struct Flyout { + state: MenuPanelState, + open: Entity>, + preselect: Entity, + set: FlyoutSetter, + bounds: TriggerBoundsCell, /// Bounds of every open flyout below this panel, this level's included. - stack: &'a Rc>>, + stack: Rc>>, /// Closes this level's flyout and returns focus to this panel. dismiss: ChangeHandler, on_activate: Option, id: ElementId, - enter_duration: std::time::Duration, + enter_duration: Duration, min_width: Option, } -struct RowEnv<'a> { - chrome: &'a MenuChrome, - selection: &'a Entity>, +impl Flyout { + /// Wires the flyout of the panel built from `params`, returning focus to `focus`. + fn new( + params: &MenuPanelParams, + focus: &FocusHandle, + window: &mut Window, + cx: &mut App, + ) -> Self { + let id: ElementId = (params.id.clone(), "submenu").into(); + let state = MenuPanelState::new(&id, window, cx); + let open = window.use_keyed_state((params.id.clone(), "submenu-open"), cx, |_, _| None); + let preselect = + window.use_keyed_state((params.id.clone(), "submenu-preselect"), cx, |_, _| false); + let bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); + let stack: Rc>> = Rc::new(RefCell::new(Vec::new())); + stack.borrow_mut().push(bounds.clone()); + + if let Some(outer_stack) = params.outer_stack { + outer_stack.borrow_mut().push(bounds.clone()); + } + + // Every open flip re-arms a clean flyout, so render never reconciles one. + let set: FlyoutSetter = { + let open = open.clone(); + let preselect = preselect.clone(); + let was_open = state.was_open.clone(); + let selection = state.selection.clone(); + + Rc::new(move |index, opens_preselected, cx| { + if index.is_some() && *open.read(cx) == index { + return; + } + + open.update(cx, |open, _| *open = index); + preselect.update(cx, |preselect, _| *preselect = opens_preselected); + was_open.update(cx, |was_open, _| *was_open = false); + selection.update(cx, |selection, _| *selection = None); + }) + }; + + let dismiss: ChangeHandler = { + let set = set.clone(); + let focus = focus.clone(); + Rc::new(move |_, window, cx| { + set(None, false, cx); + window.focus(&focus, cx); + }) + }; + + Self { + state, + open, + preselect, + set, + bounds, + stack, + dismiss, + on_activate: params.on_activate.clone(), + id, + enter_duration: params.enter_duration, + min_width: params.min_width, + } + } +} + +/// What one frame's rows read: their items, chrome, selection, and flyout. +#[derive(Clone)] +struct RowEnv { + items: Rc<[MenuItem]>, + chrome: MenuChrome, + selection: Entity>, on_activate: Option, - flyout: &'a FlyoutContext<'a>, + flyout: Option, 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, +struct MenuKeys { + items: Rc<[MenuItem]>, + selection: Entity>, + set_flyout: Option, + on_dismiss: Option, + on_activate: Option, left_dismisses: bool, } +impl MenuKeys { + /// The indices of the rows navigation may land on. + fn selectable(&self) -> Vec { + self.items + .iter() + .enumerate() + .filter(|(_, item)| item.selectable()) + .map(|(index, _)| index) + .collect() + } + + fn select(&self, next: Option, cx: &mut App) { + if let Some(next) = next { + self.selection.update(cx, |selection, _| { + *selection = Some(next); + }); + } + } + + /// Moves the selection one selectable row in the direction, wrapping at the ends. + fn step(&self, forward: bool, cx: &mut App) { + let selectable = self.selectable(); + + if selectable.is_empty() { + cx.propagate(); + return; + } + + self.select( + selectable.wrapping_adjacent(*self.selection.read(cx), forward), + cx, + ); + } + + /// Moves the selection to the first or last selectable row. + fn jump(&self, first: bool, cx: &mut App) { + let selectable = self.selectable(); + + if selectable.is_empty() { + cx.propagate(); + return; + } + + let target = if first { + selectable.first().copied() + } else { + selectable.last().copied() + }; + + self.select(target, cx); + } + + /// Whether the row at `index` is a selectable submenu. + fn opens_submenu(&self, index: usize) -> bool { + self.items + .get(index) + .is_some_and(|item| item.selectable() && item.submenu_items().is_some()) + } + + /// Opens the selected row's flyout with its first row armed. + fn open_submenu(&self, cx: &mut App) { + let current = *self.selection.read(cx); + let Some((current, set_flyout)) = current + .filter(|index| self.opens_submenu(*index)) + .zip(self.set_flyout.as_ref()) + else { + cx.propagate(); + return; + }; + + set_flyout(Some(current), true, cx); + } + + /// Runs the selected row's action, or opens its flyout. + fn activate(&self, window: &mut Window, cx: &mut App) { + let Some(current) = *self.selection.read(cx) else { + cx.propagate(); + return; + }; + + let Some(item) = self.items.get(current).filter(|item| item.selectable()) else { + cx.propagate(); + return; + }; + + if item.submenu_items().is_some() { + if let Some(set_flyout) = &self.set_flyout { + set_flyout(Some(current), true, cx); + } + return; + } + + if let Some(on_activate) = &self.on_activate { + on_activate(false, window, cx); + } + + if let Some(handler) = &item.handler { + handler(window, cx); + } + } + + /// Closes this panel. + fn dismiss(&self, window: &mut Window, cx: &mut App) { + if let Some(on_dismiss) = &self.on_dismiss { + on_dismiss(false, window, cx); + } else { + cx.propagate(); + } + } + + /// Closes a flyout on `left`; a top-level panel ignores the key. + fn dismiss_left(&self, window: &mut Window, cx: &mut App) { + if !self.left_dismisses { + cx.propagate(); + return; + } + self.dismiss(window, cx); + } +} + /// 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 { +) -> impl IntoElement { let painted = bounds.clone(); canvas( @@ -726,30 +1243,31 @@ pub(crate) fn trigger_toggle( ) .absolute() .inset_0() - .into_any_element() } /// Deferred anchored overlay on OVERLAY_LAYER, optionally fading in. -pub(crate) fn anchored_overlay( +pub(crate) fn anchored_overlay( position: Option>, - panel: AnyElement, - fade: Option<(&'static str, std::time::Duration)>, + panel: E, + fade: Option<(&'static str, Duration)>, ) -> AnyElement { + let wrapper = match fade { + Some((id, duration)) => div() + .with_animation( + id, + Animation::new(duration).with_easing(ease_out_quint()), + |wrapper, delta| wrapper.opacity(delta), + ) + .child(panel) + .into_any_element(), + None => div().child(panel).into_any_element(), + }; + deferred( anchored() .when_some(position, |anchored, position| anchored.position(position)) .offset(point(px(0.), px(4.))) - // AnyElement lacks `Styled`, so the opacity animation rides a wrapper. - .child(panel.when_some(fade, |panel, (id, duration)| { - div() - .child(panel) - .with_animation( - id, - Animation::new(duration).with_easing(ease_out_quint()), - |panel, delta| panel.opacity(delta), - ) - .into_any_element() - })), + .child(wrapper), ) .with_priority(OVERLAY_LAYER) .into_any_element() @@ -759,7 +1277,7 @@ pub(crate) fn anchored_overlay( pub(crate) fn focus_capture( focus: FocusHandle, should_grab: impl Fn(&mut Window, &mut App) -> bool + 'static, -) -> AnyElement { +) -> impl IntoElement { canvas( |_, _, _| {}, move |_, _, window, cx| { @@ -770,353 +1288,4 @@ pub(crate) fn focus_capture( ) .absolute() .inset_0() - .into_any_element() -} - -/// Assembles the floating menu panel anchored to its trigger. -pub(crate) fn anchored_menu_panel( - window: &mut Window, - cx: &mut App, - id: &ElementId, - spec: MenuPanelSpec, - chrome: &MenuChrome, - enter_duration: std::time::Duration, -) -> Option { - let was_open = window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false); - - 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. - window - .use_keyed_state::>((id.clone(), "submenu-open"), cx, |_, _| None) - .update(cx, |open, _| *open = None); - window - .use_keyed_state((id.clone(), "submenu-preselect"), cx, |_, _| false) - .update(cx, |preselect, _| *preselect = false); - return None; - } - - let state = create_menu_panel_state(id, window, cx); - let panel = menu_panel( - window, - cx, - &state, - MenuPanelParams { - id, - items: spec.items, - initial_selection: spec.initial_selection, - preselect: spec.preselect, - min_width: spec.min_width, - label: spec.label, - dismiss_bounds: &spec.trigger_bounds, - bounds_sink: None, - outer_stack: None, - on_dismiss: spec.on_dismiss, - on_activate: spec.on_activate, - is_flyout: false, - chrome, - enter_duration, - debug_prefix: "menu", - }, - ); - - Some(anchored_overlay(spec.position, panel, None)) -} - -/// Builds one menu panel: chrome, rows, focus, navigation, and dismissals. -fn menu_panel( - window: &mut Window, - cx: &mut App, - state: &MenuPanelState, - params: MenuPanelParams, -) -> AnyElement { - let MenuPanelState { - focus, - was_open, - scroll, - selection, - } = state; - - // Render-phase residue: panels open from owner state alone, so this mount - // frame is the only place fresh-selection init can read its params. - let selected = if *was_open.read(cx) { - *selection.read(cx) - } else { - let requested = params - .initial_selection - .map(|index| index.min(params.items.len().saturating_sub(1))) - .or_else(|| { - params - .preselect - .then(|| params.items.iter().position(MenuItem::selectable)) - .flatten() - }); - selection.update(cx, |selection, _| *selection = requested); - requested - }; - was_open.update(cx, |was_open, _| *was_open = true); - - // Submenu plumbing for this level; a flyout panel recurses with its own. - let flyout_id: ElementId = (params.id.clone(), "submenu").into(); - let flyout_state = create_menu_panel_state(&flyout_id, window, cx); - let flyout_open = window.use_keyed_state((params.id.clone(), "submenu-open"), cx, |_, _| None); - let flyout_preselect = - window.use_keyed_state((params.id.clone(), "submenu-preselect"), cx, |_, _| false); - let flyout_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); - let flyout_stack: Rc>> = Rc::new(RefCell::new(Vec::new())); - flyout_stack.borrow_mut().push(flyout_bounds.clone()); - - if let Some(outer_stack) = params.outer_stack { - outer_stack.borrow_mut().push(flyout_bounds.clone()); - } - - // Every open flip re-arms a clean flyout, so render never reconciles one. - let set_flyout: FlyoutSetter = { - let flyout_open = flyout_open.clone(); - let flyout_preselect = flyout_preselect.clone(); - let flyout_was_open = flyout_state.was_open.clone(); - let flyout_selection = flyout_state.selection.clone(); - Rc::new(move |index, opens_preselected, cx| { - if index.is_some() && *flyout_open.read(cx) == index { - return; - } - - flyout_open.update(cx, |open, _| *open = index); - flyout_preselect.update(cx, |preselect, _| *preselect = opens_preselected); - flyout_was_open.update(cx, |was_open, _| *was_open = false); - flyout_selection.update(cx, |selection, _| *selection = None); - }) - }; - - let dismiss_flyout: ChangeHandler = { - let set_flyout = set_flyout.clone(); - let focus = focus.clone(); - Rc::new(move |_, window, cx| { - set_flyout(None, false, cx); - window.focus(&focus, cx); - }) - }; - - let flyout = FlyoutContext { - state: &flyout_state, - open: &flyout_open, - preselect: &flyout_preselect, - set_flyout: set_flyout.clone(), - bounds: &flyout_bounds, - stack: &flyout_stack, - dismiss: dismiss_flyout, - on_activate: params.on_activate.clone(), - id: flyout_id, - enter_duration: params.enter_duration, - min_width: params.min_width, - }; - - let rows: Vec = params - .items - .iter() - .enumerate() - .map(|(index, item)| { - item.render_item( - window, - cx, - index, - selected == Some(index), - &RowEnv { - chrome: params.chrome, - selection, - on_activate: params.on_activate.clone(), - flyout: &flyout, - debug_prefix: params.debug_prefix, - }, - ) - }) - .collect(); - - floating_panel( - cx, - cx.theme().radius.overlay, - v_flex() - .id("menu-panel") - .debug_selector(move || format!("{}-panel", params.debug_prefix)) - .occlude() - .track_focus(focus) - .role(Role::Menu) - .aria_label(params.label) - .when_some(params.min_width, |panel, width| panel.min_w(width)) - .when(params.min_width.is_none(), |panel| { - panel.min_w(MENU_MIN_WIDTH) - }) - .p_1() - .text_color(params.chrome.foreground), - cx.theme().elevations.popover.shadows(), - ) - .overflow_hidden() - .on_mouse_down_out({ - let on_dismiss = params.on_dismiss.clone(); - let dismiss_bounds = params.dismiss_bounds.clone(); - let flyout_stack = flyout_stack.clone(); - - move |event, window, cx| { - if dismiss_bounds - .borrow() - .is_some_and(|bounds| bounds.contains(&event.position)) - { - return; - } - - // Clicks inside any open flyout belong to that flyout. - if flyout_stack.borrow().iter().any(|cell| { - cell.borrow() - .is_some_and(|bounds| bounds.contains(&event.position)) - }) { - return; - } - - if let Some(on_dismiss) = &on_dismiss { - on_dismiss(false, window, cx); - } - } - }) - .on_key_down({ - let items = params.items.clone(); - let selection = selection.clone(); - let set_flyout = set_flyout.clone(); - let on_dismiss = params.on_dismiss.clone(); - let on_activate = params.on_activate.clone(); - let left_dismisses = params.is_flyout; - move |event: &KeyDownEvent, window, cx| { - handle_menu_key( - event, - MenuKeyEnv { - items: &items, - selection: &selection, - set_flyout: &set_flyout, - on_dismiss: &on_dismiss, - on_activate: &on_activate, - left_dismisses, - }, - window, - cx, - ); - } - }) - .child( - ScrollArea::new("menu-items") - .handle(scroll.read(cx).clone()) - .axes(ScrollAxes::Vertical) - .max_h(POPUP_MAX_HEIGHT) - .child(v_flex().gap_0p5().children(rows)), - ) - .child( - canvas( - { - let bounds_sink = params.bounds_sink.cloned(); - move |bounds, _window, _cx| { - if let Some(cell) = &bounds_sink { - *cell.borrow_mut() = Some(bounds); - } - } - }, - { - let focus = focus.clone(); - let flyout_open = flyout_open.clone(); - move |_, _, window, cx| { - if flyout_open.read(cx).is_none() && !focus.contains_focused(window, cx) { - window.focus(&focus, cx); - } - } - }, - ) - .absolute() - .inset_0(), - ) - .with_animation( - "menu-enter", - Animation::new(params.enter_duration).with_easing(ease_out_quint()), - |panel, delta| panel.opacity(delta), - ) - .into_any_element() -} - -/// Handles the panel's navigation keys. -fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, cx: &mut App) { - let selectable: Vec = env - .items - .iter() - .enumerate() - .filter(|(_, item)| item.selectable()) - .map(|(index, _)| index) - .collect(); - - let current = *env.selection.read(cx); - - match event.keystroke.key.as_str() { - "down" | "up" | "home" | "end" => { - if selectable.is_empty() { - return; - } - let next = match event.keystroke.key.as_str() { - "down" => wrapping_adjacent_selectable(&selectable, current, true), - "up" => wrapping_adjacent_selectable(&selectable, current, false), - "home" => selectable.first().copied(), - _ => selectable.last().copied(), - }; - if let Some(next) = next { - env.selection - .update(cx, |selection, _| *selection = Some(next)); - } - } - "right" => { - let opens = current - .and_then(|current| env.items.get(current)) - .is_some_and(|item| item.selectable() && item.submenu_items().is_some()); - if !opens { - return; - } - (env.set_flyout)(current, true, cx); - } - "enter" | "space" => { - if let Some(current) = current - && let Some(item) = env.items.get(current) - && item.selectable() - { - if item.submenu_items().is_some() { - (env.set_flyout)(Some(current), true, cx); - } else { - if let Some(on_activate) = env.on_activate { - on_activate(false, window, cx); - } - if let Some(handler) = &item.handler { - handler(window, cx); - } - } - } - } - "escape" => { - if let Some(on_dismiss) = env.on_dismiss { - on_dismiss(false, window, cx); - } - } - "left" => { - if !env.left_dismisses { - return; - } - if let Some(on_dismiss) = env.on_dismiss { - on_dismiss(false, window, cx); - } - } - _ => return, - } - - 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/popover.rs b/crates/ui/src/components/popover.rs index 835fbff..a218818 100644 --- a/crates/ui/src/components/popover.rs +++ b/crates/ui/src/components/popover.rs @@ -24,19 +24,21 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, + AnyElement, App, ElementId, InteractiveElement as _, IntoElement, MouseButton, ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div, }; -use crate::components::common::{ - StyledExt as _, floating_panel, focus_handle, track_overlay_focus, v_flex, -}; +use crate::components::common::{ElementIdExt as _, StyledExt as _, v_flex}; +use crate::components::dialog::Dismiss; use crate::components::menu::{ ChangeHandler, TriggerBoundsCell, anchored_overlay, focus_capture, trigger_toggle, }; use crate::theme::{ActiveTheme as _, POPOVER_MIN_WIDTH}; +/// Key context of the popover panel. +pub const POPOVER_CONTEXT: &str = "Popover"; + /// The element the panel anchors below, built during render. type TriggerFn = Box AnyElement>; /// The panel's contents, built when it opens. @@ -136,8 +138,8 @@ impl RenderOnce for Popover { let trigger_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); // Keyboard focus rides the panel across frames. - let focus = focus_handle(&self.id, window, cx); - track_overlay_focus(&self.id, &focus, self.open, window, cx); + let focus = self.id.focus_handle(window, cx); + self.id.track_overlay_focus(&focus, self.open, window, cx); let fallback_label = self .a11y_label @@ -163,52 +165,46 @@ impl RenderOnce for Popover { wrapper.child(anchored_overlay( None, - floating_panel( - cx, - radius.overlay, - v_flex() - .id("popover-panel") - .debug_selector(|| "popover-panel".to_string()) - .occlude() - .track_focus(&focus) - .role(Role::Dialog) - .aria_label(label) - .min_w(POPOVER_MIN_WIDTH) - .text_color(colors.surface_foreground), - shadows, - ) - .overflow_hidden() - .on_mouse_down_out({ - let on_change = on_change.clone(); - let trigger_bounds = trigger_bounds.clone(); - move |event, window, cx| { - if trigger_bounds - .borrow() - .is_some_and(|bounds| bounds.contains(&event.position)) - { - return; + v_flex() + .id((self.id.clone(), "popover-panel")) + .debug_selector(|| "popover-panel".to_string()) + .occlude() + .track_focus(&focus) + .key_context(POPOVER_CONTEXT) + .role(Role::Dialog) + .aria_label(label) + .min_w(POPOVER_MIN_WIDTH) + .text_color(colors.surface_foreground) + .floating_panel(cx, radius.overlay, shadows) + .overflow_hidden() + .on_mouse_down_out({ + let on_change = on_change.clone(); + let trigger_bounds = trigger_bounds.clone(); + move |event, window, cx| { + if trigger_bounds + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)) + { + return; + } + if let Some(on_change) = &on_change { + on_change(false, window, cx); + } } - if let Some(on_change) = &on_change { - on_change(false, window, cx); - } - } - }) - .on_key_down({ - let on_change = on_change.clone(); - move |event: &KeyDownEvent, window, cx| { - if event.keystroke.key == "escape" { + }) + .on_action({ + let on_change = on_change.clone(); + move |_: &Dismiss, window, cx| { if let Some(on_change) = &on_change { on_change(false, window, cx); } cx.stop_propagation(); } - } - }) - .when_some(content, |panel, content| panel.child(content)) - .child(focus_capture(focus.clone(), move |window, cx| { - !focus.contains_focused(window, cx) - })) - .into_any_element(), + }) + .when_some(content, |panel, content| panel.child(content)) + .child(focus_capture(focus.clone(), move |window, cx| { + !focus.contains_focused(window, cx) + })), Some(("popover-enter", enter_duration)), )) }) diff --git a/crates/ui/src/components/scroll_area.rs b/crates/ui/src/components/scroll_area.rs index 80d53f1..1cf0759 100644 --- a/crates/ui/src/components/scroll_area.rs +++ b/crates/ui/src/components/scroll_area.rs @@ -14,11 +14,12 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, ScrollHandle, - SharedString, StatefulInteractiveElement as _, Styled, Window, div, + AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, + ScrollHandle, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, + div, }; -use crate::components::common::StyledExt; +use crate::components::common::StyledExt as _; use crate::components::scrollbar::{Scrollbar, ScrollbarVisibility}; /// Which directions the content scrolls in. @@ -42,18 +43,18 @@ pub struct ScrollArea { axes: ScrollAxes, visibility: ScrollbarVisibility, a11y_label: Option, - style: gpui::StyleRefinement, - children: Vec, + style: StyleRefinement, + children: Vec, } impl ParentElement for ScrollArea { - fn extend(&mut self, children: impl IntoIterator) { + fn extend(&mut self, children: impl IntoIterator) { self.children.extend(children); } } impl Styled for ScrollArea { - fn style(&mut self) -> &mut gpui::StyleRefinement { + fn style(&mut self) -> &mut StyleRefinement { &mut self.style } } @@ -70,7 +71,7 @@ impl ScrollArea { axes: ScrollAxes::Vertical, visibility: ScrollbarVisibility::default(), a11y_label: None, - style: gpui::StyleRefinement::default(), + style: StyleRefinement::default(), children: Vec::new(), } } @@ -110,6 +111,8 @@ impl RenderOnce for ScrollArea { div() .relative() + .min_h_0() + .min_w_0() .refine_style(&self.style) .child( div() @@ -140,15 +143,13 @@ impl RenderOnce for ScrollArea { .when(self.axes != ScrollAxes::Horizontal, |wrapper| { wrapper.child( Scrollbar::vertical((id.clone(), "v-scrollbar"), handle.clone()) - .visibility(self.visibility) - .into_any_element(), + .visibility(self.visibility), ) }) .when(self.axes != ScrollAxes::Vertical, |wrapper| { wrapper.child( Scrollbar::horizontal((id, "h-scrollbar"), handle) - .visibility(self.visibility) - .into_any_element(), + .visibility(self.visibility), ) }) }) diff --git a/crates/ui/src/components/scrollbar.rs b/crates/ui/src/components/scrollbar.rs index f186a16..41fb765 100644 --- a/crates/ui/src/components/scrollbar.rs +++ b/crates/ui/src/components/scrollbar.rs @@ -18,15 +18,21 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use gpui::{ - App, Bounds, DispatchPhase, ElementId, Entity, EntityId, Hitbox, HitboxBehavior, IntoElement, - ListState, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, - RenderOnce, ScrollEvent, ScrollHandle, SharedString, Styled as _, Task, + App, Bounds, DispatchPhase, ElementId, Entity, EntityId, Hitbox, HitboxBehavior, Hsla, + IntoElement, ListState, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, + Point, RenderOnce, ScrollEvent, ScrollHandle, SharedString, Styled as _, Task, UniformListScrollHandle, Window, canvas, fill, point, }; use crate::components::common::ResultLogErr as _; use crate::theme::{ActiveTheme as _, SCROLLBAR_AUTOHIDE_DELAY, SCROLLBAR_FADE_DURATION}; +/// 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)>; + /// When an overlay scrollbar shows. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum ScrollbarVisibility { @@ -39,121 +45,6 @@ pub enum ScrollbarVisibility { Autohide, } -/// 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 { - view: EntityId, - state: Entity, -} - -struct AutohideState { - last_activity: Option, - hide_task: Option>, -} - -impl Autohide { - fn new(key: ElementId, window: &mut Window, cx: &mut App) -> Self { - let view = window.current_view(); - let state = window.use_keyed_state(key, cx, |_, _| AutohideState { - last_activity: None, - hide_task: None, - }); - Self { view, state } - } - - /// Marks interaction. - fn touch(&self, window: &mut Window, cx: &mut App) { - let view = self.view; - let reduce_motion = cx.theme().accessibility.reduce_motion; - - let task = window.spawn(cx, async move |cx| { - if reduce_motion { - cx.background_executor() - .timer(SCROLLBAR_AUTOHIDE_DELAY + SCROLLBAR_FADE_DURATION) - .await; - cx.update(|_, cx| cx.notify(view)).log_err(); - return; - } - - let steps = (SCROLLBAR_FADE_DURATION.as_millis() / FADE_STEP.as_millis()).max(1); - cx.background_executor() - .timer(SCROLLBAR_AUTOHIDE_DELAY) - .await; - - for _ in 0..steps { - cx.update(|_, cx| cx.notify(view)).log_err(); - cx.background_executor().timer(FADE_STEP).await; - } - - cx.update(|_, cx| cx.notify(view)).log_err(); - }); - - self.state.update(cx, |state, _| { - state.last_activity = Some(Instant::now()); - state.hide_task = Some(task); - }); - } - - /// The thumb's opacity. - fn alpha(&self, cx: &App, dragging: bool) -> f32 { - if dragging { - return 1.0; - } - - let Some(activity) = self.state.read(cx).last_activity else { - return 0.0; - }; - - let idle = activity.elapsed(); - if idle <= SCROLLBAR_AUTOHIDE_DELAY { - return 1.0; - } - - let fade = idle.saturating_sub(SCROLLBAR_AUTOHIDE_DELAY); - if fade >= SCROLLBAR_FADE_DURATION { - return 0.0; - } - - 1.0 - fade.as_secs_f32() / SCROLLBAR_FADE_DURATION.as_secs_f32() - } -} - /// The scroll state a scrollbar drives, implemented for gpui's scroll handles. pub trait ScrollbarHandle: 'static { /// How far the content can scroll, positive along each axis. @@ -232,6 +123,126 @@ 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, + } + } +} + +/// The shared autohide timeline for an overlay scrollbar. +#[derive(Clone)] +struct Autohide { + view: EntityId, + state: Entity, +} + +struct AutohideState { + last_activity: Option, + hide_task: Option>, +} + +impl Autohide { + fn new(key: ElementId, window: &mut Window, cx: &mut App) -> Self { + let view = window.current_view(); + let state = window.use_keyed_state(key, cx, |_, _| AutohideState { + last_activity: None, + hide_task: None, + }); + Self { view, state } + } + + /// Marks interaction. + fn touch(&self, window: &mut Window, cx: &mut App) { + let view = self.view; + let reduce_motion = cx.reduce_motion(); + let was_hidden = self.alpha(cx, false) == 0.0; + + let task = window.spawn(cx, async move |cx| { + if reduce_motion { + cx.background_executor() + .timer(SCROLLBAR_AUTOHIDE_DELAY + SCROLLBAR_FADE_DURATION) + .await; + cx.update(|_, cx| cx.notify(view)).log_err(); + return; + } + + let steps = (SCROLLBAR_FADE_DURATION.as_millis() / FADE_STEP.as_millis()).max(1); + cx.background_executor() + .timer(SCROLLBAR_AUTOHIDE_DELAY) + .await; + + for _ in 0..steps { + cx.update(|_, cx| cx.notify(view)).log_err(); + cx.background_executor().timer(FADE_STEP).await; + } + + cx.update(|_, cx| cx.notify(view)).log_err(); + }); + + self.state.update(cx, |state, cx| { + state.last_activity = Some(Instant::now()); + state.hide_task = Some(task); + if was_hidden { + App::notify(cx, view); + } + }); + } + + /// The thumb's opacity. + fn alpha(&self, cx: &App, dragging: bool) -> f32 { + if dragging { + return 1.0; + } + + let Some(activity) = self.state.read(cx).last_activity else { + return 0.0; + }; + + let idle = activity.elapsed(); + if cx.reduce_motion() { + return if idle <= SCROLLBAR_AUTOHIDE_DELAY { + 1.0 + } else { + 0.0 + }; + } + if idle <= SCROLLBAR_AUTOHIDE_DELAY { + return 1.0; + } + + let fade = idle.saturating_sub(SCROLLBAR_AUTOHIDE_DELAY); + if fade >= SCROLLBAR_FADE_DURATION { + return 0.0; + } + + 1.0 - fade.as_secs_f32() / SCROLLBAR_FADE_DURATION.as_secs_f32() + } +} + /// One frame's painted scrollbar: track, thumb, and the track's hitbox. struct Metrics { viewport: Bounds, @@ -412,8 +423,8 @@ impl Scrollbar { } /// An overlay scrollbar thumb's style for one paint: `None` hides it. - fn thumb_style(color: gpui::Hsla, alpha: f32) -> Option { - (alpha > 0.0).then_some(gpui::Hsla { + fn thumb_style(color: Hsla, alpha: f32) -> Option { + (alpha > 0.0).then_some(Hsla { a: color.a * alpha, ..color }) diff --git a/crates/ui/src/components/segmented.rs b/crates/ui/src/components/segmented.rs index 2c3e544..ffd5bb7 100644 --- a/crates/ui/src/components/segmented.rs +++ b/crates/ui/src/components/segmented.rs @@ -19,13 +19,11 @@ use gpui::prelude::FluentBuilder; use gpui::{ AnimationExt as _, App, Bounds, ElementId, Entity, InteractiveElement as _, IntoElement, KeyDownEvent, ParentElement as _, Pixels, Point, RenderOnce, Role, SharedString, - SpringAnimation, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, - Window, canvas, div, + SpringAnimation, StatefulInteractiveElement as _, StyleRefinement, Styled, Toggled, Window, + canvas, div, }; -use crate::components::common::{ - ControlSizing, Sizable, StyledExt, focus_handle, focus_ring, h_flex, -}; +use crate::components::common::{ControlSizing, ElementIdExt as _, Sizable, StyledExt, h_flex}; use crate::icons::Icon; use crate::theme::{ActiveTheme as _, CONTROL_SPRING, Size}; @@ -158,6 +156,20 @@ where self.a11y_label = Some(label.into()); self } + + /// Stores what a frame measured and requests the frame that draws from it. + fn measure( + state: &Entity, + record: impl Fn(&mut S, Bounds) -> bool + 'static, + ) -> impl Fn(Bounds, &mut Window, &mut App) + 'static { + let state = state.clone(); + move |bounds, window, cx| { + let changed = state.update(cx, |state, _| record(state, bounds)); + if changed { + window.request_animation_frame(); + } + } + } } impl Sizable for Segmented @@ -169,7 +181,7 @@ where } } -impl gpui::Styled for Segmented +impl Styled for Segmented where T: Clone + PartialEq + 'static, { @@ -188,9 +200,8 @@ where let surface = theme.colors.surface; let foreground = theme.colors.foreground; let muted_foreground = theme.colors.muted_foreground; - let ring = theme.colors.ring; + let ring = theme.focus_ring(); let radius = theme.radius.full; - let plate_shadow = theme.elevations.control.shadows(); let selected_index = self .options @@ -215,7 +226,7 @@ where let track_origin: Entity>> = window.use_keyed_state("segmented-track-origin", cx, |_, _| None); - let focus = focus_handle(&self.id, window, cx); + let focus = self.id.focus_handle(window, cx); let track_point = *track_origin.read(cx); let plate_target = geometry @@ -263,7 +274,7 @@ where .when_some(segment.label.clone(), |segment, label| segment.child(label)) .child( canvas( - measure(&geometry, move |geometry, bounds| { + Self::measure(&geometry, move |geometry, bounds| { if geometry.get(index) == Some(&Some(bounds)) { return false; } @@ -296,7 +307,7 @@ where .track_focus(&focus) .focusable() .tab_stop(true) - .focus_visible(|style| style.shadow(focus_ring(ring))) + .focus_visible(|style| style.shadow(ring)) .role(Role::RadioGroup) .aria_label(label) .flex() @@ -311,7 +322,7 @@ where .control_text(self.size) .child( canvas( - measure(&track_origin, |origin, bounds| { + Self::measure(&track_origin, |origin, bounds| { if *origin == Some(bounds.origin) { return false; } @@ -324,6 +335,7 @@ where .inset_0(), ) .when_some(plate_target, |track, (x, width)| { + let plate_shadow = cx.theme().elevations.control.shadows(); track.child( div() .id("segmented-plate") @@ -333,7 +345,7 @@ where .bottom(self.size.plate_inset_rems()) .rounded(radius) .bg(surface) - .shadow(plate_shadow.clone()) + .shadow(plate_shadow.to_vec()) .with_spring( "segmented-plate-x", SpringAnimation::new(CONTROL_SPRING).to(x), @@ -380,17 +392,3 @@ where }) } } - -/// Stores what a frame measured and requests the frame that draws from it. -fn measure( - state: &Entity, - record: impl Fn(&mut S, Bounds) -> bool + 'static, -) -> impl Fn(Bounds, &mut Window, &mut App) + 'static { - let state = state.clone(); - move |bounds, window, cx| { - let changed = state.update(cx, |state, _| record(state, bounds)); - if changed { - window.request_animation_frame(); - } - } -} diff --git a/crates/ui/src/components/select.rs b/crates/ui/src/components/select.rs index 23d3b31..cb5c26e 100644 --- a/crates/ui/src/components/select.rs +++ b/crates/ui/src/components/select.rs @@ -19,13 +19,13 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder; use gpui::{ App, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, ParentElement as _, - RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, - Window, canvas, rems, + RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, + Window, rems, }; -use crate::components::common::{ControlSizing, Sizable, StyledExt, focus_handle, h_flex}; +use crate::components::common::{ControlSizing, ElementIdExt as _, Sizable, StyledExt, h_flex}; use crate::components::menu::{Menu, MenuItem}; -use crate::icons::{Icon, IconRole, icon}; +use crate::icons::{Icon, IconRole}; use crate::theme::{ActiveTheme as _, Size}; /// Reports the value the user chose. `None` means the select holds no value. @@ -173,7 +173,7 @@ where } } -impl gpui::Styled for Select +impl Styled for Select where T: Clone + PartialEq + 'static, { @@ -207,16 +207,7 @@ where .clone() }); - let focus = focus_handle(&self.id, window, cx); - - // Set when the popup closes without an activation; the trigger claims - // focus at paint, leaving keyboard activations to drop focus in place. - let refocus_pending = window.with_element_namespace(self.id.clone(), |window| { - window - .use_keyed_state("select-refocus", cx, |_, _| false) - .clone() - }); - + let focus = self.id.focus_handle(window, cx); let is_open = *open.read(cx); let open_for_items = open.clone(); @@ -242,7 +233,7 @@ where let trigger = { let open = open.clone(); let focus = focus.clone(); - let refocus_for_trigger = refocus_pending.clone(); + move |_window: &mut Window, _cx: &mut App| { h_flex() .id((trigger_id.clone(), "select-trigger")) @@ -284,31 +275,15 @@ where .hover(|style| style.bg(muted).border_color(rest_border)) .child(trigger_text.clone()) .child( - icon(IconRole::ChevronDown) + Icon::from(IconRole::ChevronDown) .size(self.size.dense_icon_rems()) .color(muted_foreground), ) - .child( - canvas(|_, _, _| {}, { - let focus = focus.clone(); - let refocus_pending = refocus_for_trigger.clone(); - move |_, _, window, cx| { - if *refocus_pending.read(cx) { - refocus_pending.update(cx, |pending, _| *pending = false); - window.focus(&focus, cx); - } - } - }) - .absolute() - .inset_0(), - ) .refine_style(&trigger_style) .into_any_element() } }; - let select_id = self.id.clone(); - let refocus_for_items = refocus_pending.clone(); let items = move |_window: &mut Window, _cx: &mut App| { self.options .iter() @@ -318,13 +293,10 @@ where let handler = { let open = open_for_items.clone(); - let refocus_pending = refocus_for_items.clone(); let value = option.value.clone(); let on_change = self.on_change.clone(); move |window: &mut Window, cx: &mut App| { open.update(cx, |open, _| *open = false); - // Activations own the close, so no focus returns to the trigger. - refocus_pending.update(cx, |pending, _| *pending = false); if let Some(on_change) = &on_change { on_change(Some(value.clone()), window, cx); } @@ -332,7 +304,7 @@ where }; MenuItem::new(option.label.clone()) - .id((select_id.clone(), format!("option-{index}"))) + .id(("option", index)) .when_some(option.icon.clone(), |row, icon| row.icon(icon)) .checked(is_selected) .handler(handler) @@ -344,11 +316,7 @@ where .open(is_open) .on_change({ let open = open.clone(); - let refocus_pending = refocus_pending.clone(); move |next, _window, cx| { - if !next { - refocus_pending.update(cx, |pending, _| *pending = true); - } open.update(cx, |open, _| *open = next); } }) diff --git a/crates/ui/src/components/separator.rs b/crates/ui/src/components/separator.rs index 910faf1..b6930f7 100644 --- a/crates/ui/src/components/separator.rs +++ b/crates/ui/src/components/separator.rs @@ -13,13 +13,15 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder as _; use gpui::{ - App, InteractiveElement as _, IntoElement, RenderOnce, StyleRefinement, Styled as _, Window, - div, + App, InteractiveElement as _, IntoElement, RenderOnce, StyleRefinement, Styled, Window, div, }; use crate::components::common::StyledExt as _; use crate::theme::{ActiveTheme as _, BORDER_WIDTH}; +/// The debug-bounds selector, for headless tests. +type DebugSelector = Rc String>; + /// The axis a [`Separator`] rule runs along. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum SeparatorOrientation { @@ -30,9 +32,6 @@ pub enum SeparatorOrientation { Vertical, } -/// The debug-bounds selector, for headless tests. -type DebugSelector = Rc String>; - /// A hairline rule that divides sibling content. #[derive(IntoElement)] #[must_use] @@ -77,7 +76,7 @@ impl Separator { } } -impl gpui::Styled for Separator { +impl Styled for Separator { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } diff --git a/crates/ui/src/components/sidebar.rs b/crates/ui/src/components/sidebar.rs index 4b067b2..1f498fb 100644 --- a/crates/ui/src/components/sidebar.rs +++ b/crates/ui/src/components/sidebar.rs @@ -24,10 +24,7 @@ use gpui::{ StyleRefinement, Styled as _, Window, div, }; -use crate::common::v_flex; -use crate::components::common::{ - StyledExt as _, nav_key, paint_selectable_row, selectable_label_color, -}; +use crate::components::common::{ElementIdExt as _, SelectableRows as _, StyledExt as _, v_flex}; use crate::components::grain::grain as grain_overlay; use crate::theme::{ActiveTheme as _, BORDER_WIDTH, SIDEBAR_DEFAULT_WIDTH}; @@ -198,7 +195,7 @@ impl SidebarEntry { suffix, disabled: row_disabled, } => { - let label_color = selectable_label_color(cx, selected, row_disabled); + let label_color = theme.selectable_label_color(selected, row_disabled); div() .id((key.clone(), "sidebar-row")) @@ -222,7 +219,7 @@ impl SidebarEntry { row.hover(|row| row.bg(theme.material.hover)) } } else { - paint_selectable_row(cx, row, selected, row_disabled) + row.selectable_row(cx, selected, row_disabled) } }) .when(!row_disabled, |row| { @@ -395,7 +392,7 @@ impl RenderOnce for Sidebar { .map(|(index, _)| index) .collect(); - let focus = crate::components::common::focus_handle(&id, window, cx); + let focus = id.focus_handle(window, cx); let row_count = entries .iter() @@ -464,7 +461,7 @@ impl RenderOnce for Sidebar { .on_key_down({ let on_change = on_change.clone(); move |event: &KeyDownEvent, window, cx| { - if nav_key(&selectable, selected, &event.keystroke.key, |next| { + if selectable.nav_key(selected, &event.keystroke.key, |next| { if let Some(on_change) = &on_change { on_change(next, window, cx); } diff --git a/crates/ui/src/components/spinner.rs b/crates/ui/src/components/spinner.rs index a85b0bb..247af5d 100644 --- a/crates/ui/src/components/spinner.rs +++ b/crates/ui/src/components/spinner.rs @@ -10,13 +10,12 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, - RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, - Window, div, + App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, + Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div, }; use crate::components::common::{Sizable, StyledExt as _, v_flex}; -use crate::icons::{IconRole, icon}; +use crate::icons::{Icon, IconRole}; use crate::theme::{ActiveTheme as _, SPINNER_PERIOD, Size}; /// A loader icon that spins for unknown work. @@ -46,7 +45,7 @@ impl Spinner { } /// The spinner centered in the full available space. - pub fn centered(id: I) -> AnyElement + pub fn centered(id: I) -> impl IntoElement where I: Into, { @@ -55,7 +54,6 @@ impl Spinner { .items_center() .justify_center() .child(Self::new(id)) - .into_any_element() } /// Overrides the icon color, for accent-filled surfaces. @@ -74,7 +72,7 @@ impl Spinner { } } -impl gpui::Styled for Spinner { +impl Styled for Spinner { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } @@ -100,7 +98,7 @@ impl RenderOnce for Spinner { .role(Role::ProgressIndicator) .when_some(self.a11y_label, |spinner, label| spinner.aria_label(label)) .child( - icon(IconRole::Loader) + Icon::from(IconRole::Loader) .size(side) .color(accent) .with_rotation_animation(SPINNER_PERIOD), diff --git a/crates/ui/src/components/status_dot.rs b/crates/ui/src/components/status_dot.rs index 8c9cdbe..d3cb5c2 100644 --- a/crates/ui/src/components/status_dot.rs +++ b/crates/ui/src/components/status_dot.rs @@ -5,7 +5,7 @@ //! ```no_run //! use ui::status_dot::{StatusDot, StatusDotVariant}; //! -//! let dot = StatusDot::new("deploy-status") +//! let dot = StatusDot::new() //! .variant(StatusDotVariant::Success) //! .label("Deployed"); //! ``` @@ -48,10 +48,9 @@ impl StatusDotVariant { } /// A small circular bead marking a row's state. -#[derive(IntoElement)] +#[derive(Default, IntoElement)] #[must_use] pub struct StatusDot { - id: ElementId, variant: StatusDotVariant, size: Size, label: Option, @@ -60,17 +59,8 @@ pub struct StatusDot { impl StatusDot { /// Creates an idle dot. - pub fn new(id: I) -> Self - where - I: Into, - { - Self { - id: id.into(), - variant: StatusDotVariant::default(), - size: Size::default(), - label: None, - style: StyleRefinement::default(), - } + pub fn new() -> Self { + Self::default() } /// Sets how loud the dot is. @@ -107,9 +97,7 @@ impl RenderOnce for StatusDot { let size = self.size; let color = self.variant.color(theme); - div() - .id(self.id.clone()) - .debug_selector(move || self.id.to_string()) + let dot = div() .flex_none() .rounded(theme.radius.full) .bg(color) @@ -118,9 +106,15 @@ impl RenderOnce for StatusDot { Size::Small | Size::Medium => dot.size_2(), Size::Large => dot.size_2p5(), }) - .refine_style(&self.style) - .when_some(self.label, |dot, label| { - dot.role(Role::Status).aria_label(label) - }) + .refine_style(&self.style); + + match self.label { + Some(label) => dot + .id((ElementId::from("status-dot"), label.clone())) + .role(Role::Status) + .aria_label(label) + .into_any_element(), + None => dot.into_any_element(), + } } } diff --git a/crates/ui/src/components/switch.rs b/crates/ui/src/components/switch.rs index fc181ee..bd18070 100644 --- a/crates/ui/src/components/switch.rs +++ b/crates/ui/src/components/switch.rs @@ -15,10 +15,10 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ AnimationExt as _, App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, SharedString, SpringAnimation, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, Toggled, Window, div, px, + StyleRefinement, Styled, Toggled, Window, div, px, }; -use crate::components::common::{ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex}; +use crate::components::common::{ControlSizing, Sizable, StyledExt as _, h_flex}; use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CONTROL_SPRING, DISABLED_OPACITY, Size}; /// The change reporter, fired with the next value by pointer, Enter, and Space. @@ -96,7 +96,7 @@ impl Switch { } } -impl gpui::Styled for Switch { +impl Styled for Switch { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } @@ -112,6 +112,7 @@ impl RenderOnce for Switch { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let colors = theme.colors; + let ring = theme.focus_ring(); let ramps = theme.ramps; let rem = window.rem_size(); @@ -145,7 +146,7 @@ impl RenderOnce for Switch { .cursor_pointer() .focusable() .tab_stop(true) - .focus_visible(|style| style.shadow(focus_ring(colors.ring))) + .focus_visible(|style| style.shadow(ring)) .when_some(on_change, |switch, on_change| { switch.on_click(move |_, window, cx| on_change(next, window, cx)) }) diff --git a/crates/ui/src/components/tabs.rs b/crates/ui/src/components/tabs.rs index bc00e5f..21164c4 100644 --- a/crates/ui/src/components/tabs.rs +++ b/crates/ui/src/components/tabs.rs @@ -16,20 +16,23 @@ //! ``` use std::cell::RefCell; +use std::cmp::Ordering; use std::collections::HashMap; use std::rc::Rc; use gpui::prelude::FluentBuilder; use gpui::{ - AnyElement, App, AppContext as _, Bounds, ClickEvent, Context, Div, ElementId, Global, Hsla, - InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _, Pixels, - Point, Render, RenderOnce, Role, SharedString, Stateful, StatefulInteractiveElement as _, - StyleRefinement, Styled, TextOverflow, Window, canvas, div, linear_color_stop, linear_gradient, - px, rems, + AnyElement, App, AppContext as _, Bounds, ClickEvent, Context, Div, ElementId, Entity, + FocusHandle, Global, Hsla, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, + ParentElement as _, Pixels, Point, Render, RenderOnce, Role, SharedString, Stateful, + StatefulInteractiveElement as _, StyleRefinement, Styled, TextOverflow, Window, canvas, div, + linear_color_stop, linear_gradient, px, rems, transparent_black, }; use crate::components::button::{Button, ButtonVariant}; -use crate::components::common::{Sizable as _, StyledExt as _, adjacent_selectable, v_flex}; +use crate::components::common::{ + ElementIdExt as _, SelectableRows as _, Sizable as _, StyledExt as _, v_flex, +}; use crate::components::popover::Popover; use crate::components::scroll_area::{ScrollArea, ScrollAxes}; use crate::components::spinner::Spinner; @@ -50,10 +53,111 @@ type TabsFn = Box Vec>; /// The open-state reporter of the overflow popover. type OpenHandler = Rc; /// Identifies one strip's measurements across windows. -type MeasureKey = (u64, String); +type MeasureKey = (u64, ElementId); /// Shared per-frame state that lets tab canvases read the strip's bounds. type RootBoundsCell = Rc>>>; +/// Displacement before a tab drag locks to an axis: horizontal reorders, +/// vertical cancels the reorder, like a browser tab strip. +const TAB_DRAG_AXIS_LOCK: Pixels = px(6.0); + +/// One slot of a strip: a lone tab, or same-kind tabs collapsed into a group chip. +enum StripItem { + /// A tab outside any two-member kind group, at its original index. + Single(usize, Tab), + /// Tabs of one kind collapsed into a chip, at the first member's index. + Group { + kind: SharedString, + /// The collapsed tabs with their original indices. + members: Vec<(usize, Tab)>, + }, +} + +impl StripItem { + /// The key the strip's geometry records the item under. + fn measure_key(&self, tabs_id: &ElementId) -> ElementId { + match self { + StripItem::Single(_, tab) => tab.key.clone(), + StripItem::Group { kind, .. } => Tabs::group_key(tabs_id, kind), + } + } +} + +/// The visual language of a [`Tabs`] strip. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum TabsVariant { + /// A bottom indicator line on the active tab. + #[default] + Underline, + /// Capsule tabs with an elevated active background. + Pill, + /// Floating capsule tabs sized for a window titlebar. + Titlebar, +} + +impl TabsVariant { + /// Whether the variant draws capsule-shaped tabs. + fn is_capsule(self) -> bool { + matches!(self, Self::Pill | Self::Titlebar) + } + + /// The label color shared by strip tabs and group chips. + fn label_color(self, active: bool, disabled: bool, cx: &App) -> Hsla { + let theme = cx.theme(); + if disabled { + return theme.colors.muted_foreground; + } + match self { + Self::Underline => { + if active { + theme.ramps.primary.base + } else { + theme.colors.foreground + } + } + Self::Pill => theme.colors.foreground, + Self::Titlebar => { + if active { + theme.colors.foreground + } else { + theme.colors.muted_foreground + } + } + } + } + + /// The variant treatment shared by strip tabs and group chips. + fn chrome(self, row: R, active: bool, cx: &App) -> R + where + R: Styled + IntoElement, + { + let theme = cx.theme(); + match self { + Self::Underline => row + .px_2() + .py_1() + .rounded_tl(theme.radius.sm) + .rounded_tr(theme.radius.sm) + .border_b_2() + .border_color(transparent_black()) + .when(active, |row| row.border_color(theme.ramps.primary.base)), + Self::Pill | Self::Titlebar => row + .h_8() + .px_2() + .pr_0p5() + .rounded(match self { + Self::Titlebar => theme.radius.full, + _ => theme.radius.control, + }) + .when(self == Self::Titlebar, |row| row.bg(theme.colors.muted)) + .when(active, |row| { + row.bg(theme.colors.background) + .shadow(theme.elevations.control.shadows().to_vec()) + }), + } + } +} + /// One inline tab's geometry relative to the strip's left edge. #[derive(Clone, Copy, Default)] struct TabMeasure { @@ -62,11 +166,11 @@ struct TabMeasure { } /// A strip's geometry captured the previous frame. -#[derive(Clone, Default)] +#[derive(Default)] struct StripMeasure { container_width: Pixels, trigger_width: Option, - tabs: HashMap, + tabs: HashMap, } /// The capture context handed to inline tabs, only in popover mode. @@ -93,7 +197,7 @@ impl TabsMeasurements { self.strips.entry(key.clone()).or_default().trigger_width = Some(width); } - fn record_tab(&mut self, key: &MeasureKey, tab: String, measure: TabMeasure) { + fn record_tab(&mut self, key: &MeasureKey, tab: ElementId, measure: TabMeasure) { self.strips .entry(key.clone()) .or_default() @@ -102,7 +206,7 @@ impl TabsMeasurements { } /// Drops measurements for tabs no longer rendered in the strip. - fn retain_tabs(&mut self, key: &MeasureKey, rendered: &[String]) { + fn retain_tabs(&mut self, key: &MeasureKey, rendered: &[ElementId]) { if let Some(strip) = self.strips.get_mut(key) { strip.tabs.retain(|tab, _| rendered.contains(tab)); } @@ -118,12 +222,12 @@ struct StripCtx { on_change: Option, on_close: Option, on_reorder: Option, - focus: gpui::FocusHandle, + focus: FocusHandle, measure: Option, /// Whether tabs drag onto each other to reorder; requires `on_reorder`. draggable: bool, /// The tab drag gesture's live state, for the drop indicator. - drop_at: gpui::Entity, + drop_at: Entity, } impl StripCtx { @@ -137,20 +241,6 @@ impl StripCtx { } } -/// The index the tab at `from` occupies once dropped before the tab at `onto`, -/// or `None` when the drop is a no-op. -fn reorder_target(from: usize, onto: usize) -> Option { - match from.cmp(&onto) { - std::cmp::Ordering::Equal => None, - std::cmp::Ordering::Less => Some(onto - 1), - std::cmp::Ordering::Greater => Some(onto), - } -} - -/// Displacement before a tab drag locks to an axis: horizontal reorders, -/// vertical cancels the reorder, like a browser tab strip. -const TAB_DRAG_AXIS_LOCK: Pixels = px(6.0); - /// One tab drag gesture's live state. #[derive(Clone, Copy, Default, PartialEq)] struct TabDrop { @@ -168,93 +258,17 @@ impl TabDrop { fn canceled(&self) -> bool { self.horizontal == Some(false) } -} -/// One slot of a strip: a lone tab, or same-kind tabs collapsed into a group chip. -enum StripItem { - /// A tab outside any two-member kind group, at its original index. - Single(usize, Tab), - /// Tabs of one kind collapsed into a chip, at the first member's index. - Group { - kind: SharedString, - /// The collapsed tabs with their original indices. - members: Vec<(usize, Tab)>, - }, -} - -impl StripItem { - /// The key the strip's geometry records the item under. - fn measure_key(&self, tabs_id: &ElementId) -> String { - match self { - StripItem::Single(_, tab) => tab.key.to_string(), - StripItem::Group { kind, .. } => group_key(tabs_id, kind).to_string(), + /// The index the tab at `from` occupies once dropped before the tab at `onto`. + fn reorder_target(from: usize, onto: usize) -> Option { + match from.cmp(&onto) { + Ordering::Equal => None, + Ordering::Less => Some(onto - 1), + Ordering::Greater => Some(onto), } } } -/// The group chip's identity for one strip and kind. -fn group_key(tabs_id: &ElementId, kind: &SharedString) -> ElementId { - SharedString::from(format!("{tabs_id}-tabs-group-{kind}")).into() -} - -/// The label color shared by strip tabs and group chips. -fn tab_label_color(variant: TabsVariant, active: bool, disabled: bool, cx: &App) -> Hsla { - let theme = cx.theme(); - if disabled { - return theme.colors.muted_foreground; - } - match variant { - TabsVariant::Underline => { - if active { - theme.ramps.primary.base - } else { - theme.colors.foreground - } - } - TabsVariant::Pill => theme.colors.foreground, - TabsVariant::Titlebar => { - if active { - theme.colors.foreground - } else { - theme.colors.muted_foreground - } - } - } -} - -/// The variant treatment shared by strip tabs and group chips. -fn apply_tab_chrome(row: R, variant: TabsVariant, active: bool, cx: &App) -> R -where - R: Styled + IntoElement, -{ - let theme = cx.theme(); - match variant { - TabsVariant::Underline => row - .px_2() - .py_1() - .rounded_tl(theme.radius.sm) - .rounded_tr(theme.radius.sm) - .border_b_2() - .border_color(gpui::transparent_black()) - .when(active, |row| row.border_color(theme.ramps.primary.base)), - TabsVariant::Pill | TabsVariant::Titlebar => row - .h_8() - .px_2() - .pr_0p5() - .rounded(match variant { - TabsVariant::Titlebar => theme.radius.full, - _ => theme.radius.control, - }) - .when(variant == TabsVariant::Titlebar, |row| { - row.bg(theme.colors.muted) - }) - .when(active, |row| { - row.bg(theme.colors.background) - .shadow(theme.elevations.control.shadows()) - }), - } -} - /// The payload dragged when reordering a tab. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TabDrag { @@ -279,30 +293,11 @@ impl Render for TabDragPreview { .bg(theme.colors.background) .text_sm() .text_color(theme.colors.foreground) - .shadow(theme.elevations.control.shadows()) + .shadow(theme.elevations.control.shadows().to_vec()) .child(self.label.clone()) } } -/// The visual language of a [`Tabs`] strip. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum TabsVariant { - /// A bottom indicator line on the active tab. - #[default] - Underline, - /// Capsule tabs with an elevated active background. - Pill, - /// Floating capsule tabs sized for a window titlebar. - Titlebar, -} - -impl TabsVariant { - /// Whether the variant draws capsule-shaped tabs. - fn is_capsule(self) -> bool { - matches!(self, Self::Pill | Self::Titlebar) - } -} - /// One tab of a [`Tabs`] strip. #[must_use] pub struct Tab { @@ -390,86 +385,99 @@ impl Tab { } fn render_tab(mut self, ctx: &StripCtx, cx: &App, index: usize) -> AnyElement { + let wrap = self.wrap.take(); + let element = self.tab_element(ctx, cx, index); + match wrap { + Some(wrap) => wrap(element), + None => element.into_any_element(), + } + } + + fn tab_element(mut self, ctx: &StripCtx, cx: &App, index: usize) -> Stateful
{ 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 label_color = ctx.variant.label_color(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 close = ctx + .on_close + .as_ref() + .filter(|_| self.closeable && !self.disabled) + .map(|on_close| self.render_tab_close(&ctx.id, index, on_close)); - let label = div() - .flex_grow(1.0) - .when(titlebar, |label| { - let fade = if active { - theme.colors.background - } else { - theme.colors.muted - }; + div() + .child( + 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 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); + let fade_width = rems(0.75); + let hover_fade_width = rems(1.5); - label - .min_w_0() - .relative() - .overflow_hidden() - .child( - div() - .w_full() + 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 + .min_w_0() .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 - .min_w_0() - .whitespace_nowrap() - .overflow_hidden() - .text_ellipsis() - .child(self.label.clone()) - }); - - let strip_tab = div() + .overflow_hidden() + .text_ellipsis() + .child(self.label.clone()) + }), + ) .id((self.key.clone(), "tab")) .debug_selector({ let tabs_id = ctx.id.clone(); @@ -492,12 +500,12 @@ impl Tab { }) }) .map(|strip_tab| { - apply_tab_chrome(strip_tab, ctx.variant, active, cx) + ctx.variant + .chrome(strip_tab, active, cx) .max_w(TAB_MAX_WIDTH) .when(titlebar, |strip_tab| strip_tab.min_w(TAB_MIN_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()) }) @@ -542,7 +550,7 @@ impl Tab { .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(); + let tab_key = self.key.clone(); strip_tab.child( canvas( move |bounds, _, cx| { @@ -636,27 +644,22 @@ impl Tab { } }); let target = (!canceled) - .then(|| reorder_target(drag.index, index)) + .then(|| TabDrop::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 { + on_close: &CloseHandler, + ) -> Button { Button::new((self.key.clone(), "tab-close")) .icon(IconRole::Close) .variant(ButtonVariant::Ghost) @@ -674,12 +677,9 @@ impl Tab { let on_close = on_close.clone(); move |_, window, cx| { cx.stop_propagation(); - if let Some(on_close) = &on_close { - on_close(index, window, cx); - } + on_close(index, window, cx); } }) - .into_any_element() } } @@ -866,52 +866,51 @@ impl Tabs { Popover::new((id.clone(), "tabs-overflow")) .open(open) - .on_change({ + .trigger({ let on_overflow_open = on_overflow_open.clone(); - move |next, window, cx| { - if let Some(on_overflow_open) = &on_overflow_open { - on_overflow_open(next, window, cx); - } - } - }) - .trigger(move |_, _| { - Button::new((trigger_id.clone(), "tabs-overflow-trigger")) - .icon(IconRole::More) - .variant(ButtonVariant::Ghost) - .small() - .accessibility_label("More tabs") - .on_click({ - let on_overflow_open = on_overflow_open.clone(); - move |event, window, cx| { + move |_, _| { + Button::new((trigger_id.clone(), "tabs-overflow-trigger")) + .icon(IconRole::More) + .variant(ButtonVariant::Ghost) + .small() + .accessibility_label("More tabs") + .on_click(move |event, window, cx| { // Pointer clicks toggle inside Popover; only the keyboard path lands here. if let ClickEvent::Keyboard(_) = event - && let Some(on_overflow_open) = &on_overflow_open + && let Some(on_overflow_open) = on_overflow_open.as_ref() { on_overflow_open(!open, window, cx); } - } - }) - .into_any_element() + }) + .into_any_element() + } + }) + .on_change(move |next, window, cx| { + if let Some(on_overflow_open) = on_overflow_open.as_ref() { + on_overflow_open(next, window, cx); + } }) .content(move |_, cx| { - let rows: Vec = overflow_items - .into_iter() - .flat_map(|item| match item { - StripItem::Single(index, tab) => { - vec![tab.render_tab(&row_ctx, cx, index)] - } - // A group that ran out of room lists its members inline. - StripItem::Group { members, .. } => members - .into_iter() - .map(|(index, tab)| tab.render_tab(&row_ctx, cx, index)) - .collect::>(), - }) - .collect(); - ScrollArea::new((id.clone(), "tabs-overflow-list")) .axes(ScrollAxes::Vertical) .max_h(POPUP_MAX_HEIGHT) - .child(v_flex().gap_0p5().p_1().children(rows)) + .child( + v_flex() + .gap_0p5() + .p_1() + .children(overflow_items.into_iter().flat_map(|item| { + match item { + StripItem::Single(index, tab) => { + vec![tab.render_tab(&row_ctx, cx, index)] + } + // A group that ran out of room lists its members inline. + StripItem::Group { members, .. } => members + .into_iter() + .map(|(index, tab)| tab.render_tab(&row_ctx, cx, index)) + .collect::>(), + } + })), + ) .into_any_element() }) } @@ -931,8 +930,9 @@ impl Tabs { for (index, tab) in tabs.into_iter().enumerate() { let grouped_kind = tab .kind - .clone() - .filter(|kind| counts.get(kind).copied().unwrap_or(0) >= 2); + .as_ref() + .filter(|kind| counts.get(*kind).copied().unwrap_or(0) >= 2) + .cloned(); match grouped_kind { Some(kind) => match group_slots.get(&kind).copied() { @@ -956,6 +956,14 @@ impl Tabs { items } + /// The group chip's identity for one strip and kind. + fn group_key(tabs_id: &ElementId, kind: &SharedString) -> ElementId { + ElementId::from(( + ElementId::from((tabs_id.clone(), "tabs-group")), + kind.clone(), + )) + } + /// Renders a group chip labeled with the kind and its member count. fn render_group_tab( ctx: &StripCtx, @@ -964,131 +972,135 @@ impl Tabs { window: &mut Window, cx: &mut App, ) -> AnyElement { - let tabs_id = ctx.id.clone(); let count = members.len(); let selected = members.iter().any(|(index, _)| *index == ctx.selected); // A pinned member keeps the chip in the active treatment, selected or not. let active = selected || members.iter().any(|(_, tab)| tab.pinned); + let group_key = Self::group_key(&ctx.id, &kind); let open = window - .use_keyed_state((group_key(&tabs_id, &kind), "open"), cx, |_, _| false) + .use_keyed_state((group_key.clone(), "open"), cx, |_, _| false) .clone(); - let theme = cx.theme(); - let group_key = group_key(&tabs_id, &kind); - - let label_color = tab_label_color(ctx.variant, active, false, cx); - - let chip = div() - .id((group_key.clone(), "group-tab")) - .debug_selector({ - let tabs_id = tabs_id.clone(); - let label = kind.clone(); - move || format!("{tabs_id}-group-{label}") - }) - .flex() - .items_center() - .gap_2() - .cursor_pointer() - .role(Role::Tab) - .aria_selected(selected) - .aria_label(SharedString::from(format!("{kind}, {count} tabs"))) - .text_color(label_color) - .when(!active, |chip| { - chip.hover(|chip| { - chip.bg(match ctx.variant { - TabsVariant::Titlebar => theme.colors.muted_hover, - _ => theme.colors.muted, - }) - }) - }) - .map(|chip| apply_tab_chrome(chip, ctx.variant, active, cx)) - .child(SharedString::from(format!("{kind} ({count})"))) - .when(ctx.variant.is_capsule(), |chip| { - chip.child(div().flex_none().w_4()) - }) - .when_some(ctx.measure.clone(), |chip, measure| { - let key = measure.key.clone(); - let root_bounds = measure.root_bounds.clone(); - let item_key = group_key.to_string(); - chip.child( - canvas( - move |bounds, _, cx| { - let root = root_bounds.borrow(); - if let Some(root) = root.as_ref() { - cx.default_global::().record_tab( - &key, - item_key, - TabMeasure { - left: bounds.origin.x - root.origin.x, - width: bounds.size.width, - }, - ); - } - }, - |_, _, _, _| {}, - ) - .absolute() - .inset_0(), - ) - }); - // Selecting a row also dismisses the popover, mirroring the overflow popover. - let row_change: Option = { + let row_change: ChangeHandler = { let open = open.clone(); let on_change = ctx.on_change.clone(); - Some(Rc::new(move |index, window, cx| { + Rc::new(move |index, window, cx| { open.update(cx, |open, cx| { - *open = false; - cx.notify(); + if *open { + *open = false; + cx.notify(); + } }); if let Some(on_change) = &on_change { on_change(index, window, cx); } - })) + }) }; let row_ctx = StripCtx { - on_change: row_change, + on_change: Some(row_change), ..ctx.for_popover() }; Popover::new((group_key.clone(), "group-popover")) .open(*open.read(cx)) - .on_change({ - let open = open.clone(); - move |next, _, cx| { - open.update(cx, |open, cx| { - *open = next; - cx.notify(); - }); + .trigger({ + let ctx = ctx.clone(); + let chip_key = group_key.clone(); + move |_, cx| { + let theme = cx.theme(); + let label_color = ctx.variant.label_color(active, false, cx); + div() + .id((chip_key.clone(), "group-tab")) + .debug_selector({ + let tabs_id = ctx.id.clone(); + let label = kind.clone(); + move || format!("{tabs_id}-group-{label}") + }) + .flex() + .items_center() + .gap_2() + .cursor_pointer() + .role(Role::Tab) + .aria_selected(selected) + .aria_label(SharedString::from(format!("{kind}, {count} tabs"))) + .text_color(label_color) + .when(!active, |chip| { + chip.hover(|chip| { + chip.bg(match ctx.variant { + TabsVariant::Titlebar => theme.colors.muted_hover, + _ => theme.colors.muted, + }) + }) + }) + .map(|chip| ctx.variant.chrome(chip, active, cx)) + .child(SharedString::from(format!("{kind} ({count})"))) + .when(ctx.variant.is_capsule(), |chip| { + chip.child(div().flex_none().w_4()) + }) + .when_some(ctx.measure.clone(), |chip, measure| { + let key = measure.key.clone(); + let root_bounds = measure.root_bounds.clone(); + let item_key = chip_key.clone(); + chip.child( + canvas( + move |bounds, _, cx| { + let root = root_bounds.borrow(); + if let Some(root) = root.as_ref() { + cx.default_global::().record_tab( + &key, + item_key, + TabMeasure { + left: bounds.origin.x - root.origin.x, + width: bounds.size.width, + }, + ); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + }) + .into_any_element() } }) - .trigger(move |_, _| chip.into_any_element()) + .on_change(move |next, _, cx| { + open.update(cx, |open, cx| { + if *open != next { + *open = next; + cx.notify(); + } + }); + }) .content(move |_, cx| { - let rows: Vec = members - .into_iter() - .map(|(index, tab)| tab.render_tab(&row_ctx, cx, index)) - .collect(); - ScrollArea::new((group_key.clone(), "tabs-group-list")) .axes(ScrollAxes::Vertical) .max_h(POPUP_MAX_HEIGHT) - .child(v_flex().gap_0p5().p_1().children(rows)) + .child( + v_flex().gap_0p5().p_1().children( + members + .into_iter() + .map(|(index, tab)| tab.render_tab(&row_ctx, cx, index)), + ), + ) .into_any_element() }) .into_any_element() } } -impl gpui::Styled for Tabs { +impl Styled for Tabs { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } } impl RenderOnce for Tabs { - fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement { let tabs = match self.tabs { Some(build) => build(window, cx), None => Vec::new(), @@ -1110,7 +1122,7 @@ impl RenderOnce for Tabs { }) .collect(); - let focus = crate::components::common::focus_handle(&self.id, window, cx); + let focus = self.id.focus_handle(window, cx); // Theme reads end here, so the strip's group chips can take `cx` mutably. let (border_color, shadow_bleed) = { let theme = cx.theme(); @@ -1123,31 +1135,32 @@ impl RenderOnce for Tabs { let label = self .a11y_label - .clone() + .take() .unwrap_or_else(|| SharedString::from(self.id.to_string())); - let measure_key: MeasureKey = ( - window.window_handle().window_id().as_u64(), - self.id.to_string(), - ); + let measure_key: MeasureKey = + (window.window_handle().window_id().as_u64(), self.id.clone()); - let measure = if self.overflow_popover { - cx.try_global::() - .and_then(|cache| cache.strips.get(&measure_key).cloned()) - } else { - None - }; - - let inline_count = measure - .as_ref() - .map(|measure| Self::inline_count(&self.id, &items, measure)) - .unwrap_or(items.len()); + // Read last frame's geometry under the borrow instead of cloning the strip. + let (measured, inline_count, trigger_width) = cx + .try_global::() + .filter(|_| self.overflow_popover) + .and_then(|cache| { + cache.strips.get(&measure_key).map(|measure| { + ( + Self::inline_count(&self.id, &items, measure), + measure.trigger_width, + ) + }) + }) + .map(|(count, trigger_width)| (true, count, trigger_width)) + .unwrap_or((false, items.len(), None)); let overflow_items = items.split_off(inline_count); // The strip records geometry per inline tab each frame; drop entries // for tabs no longer rendered inline. if cx.try_global::().is_some() { - let rendered: Vec = items + let rendered: Vec = items .iter() .map(|item| item.measure_key(&self.id)) .collect(); @@ -1169,7 +1182,7 @@ impl RenderOnce for Tabs { selected: self.selected, variant: self.variant, on_change: self.on_change.clone(), - on_close: self.on_close.clone(), + on_close: self.on_close, on_reorder: self.on_reorder.clone(), focus: focus.clone(), measure: measure_frame.clone(), @@ -1187,8 +1200,8 @@ impl RenderOnce for Tabs { }) .collect(); - let popover = (self.overflow_popover && measure.is_some() && !overflow_items.is_empty()) - .then(|| { + let popover = + (self.overflow_popover && measured && !overflow_items.is_empty()).then(|| { Self::render_overflow_popover( &ctx, overflow_items, @@ -1212,8 +1225,8 @@ impl RenderOnce for Tabs { let on_change = self.on_change.clone(); move |event: &KeyDownEvent, window, cx| { let target = match event.keystroke.key.as_str() { - "right" => adjacent_selectable(&selectable, Some(selected), true), - "left" => adjacent_selectable(&selectable, Some(selected), false), + "right" => selectable.adjacent(Some(selected), true), + "left" => selectable.adjacent(Some(selected), false), "home" => selectable.first().copied(), "end" => selectable.last().copied(), _ => return, @@ -1264,7 +1277,7 @@ impl RenderOnce for Tabs { }); if let (Some(onto), Some(on_reorder)) = (onto, on_reorder.as_ref()) && !canceled - && let Some(to) = reorder_target(drag.index, onto) + && let Some(to) = TabDrop::reorder_target(drag.index, onto) { on_reorder(drag.index, to, window, cx); } @@ -1283,12 +1296,10 @@ impl RenderOnce for Tabs { let control = match popover { Some(popover) => div().flex_none().relative().child(popover), - None => div().flex_none().relative().child( - div().w(measure - .as_ref() - .and_then(|measure| measure.trigger_width) - .unwrap_or(Pixels::ZERO)), - ), + None => div() + .flex_none() + .relative() + .child(div().w(trigger_width.unwrap_or(Pixels::ZERO))), }; root.min_w_0() diff --git a/crates/ui/src/components/toast.rs b/crates/ui/src/components/toast.rs index ca45215..bd4171b 100644 --- a/crates/ui/src/components/toast.rs +++ b/crates/ui/src/components/toast.rs @@ -15,7 +15,7 @@ use gpui::{ use crate::components::button::{Button, ButtonVariant}; use crate::components::common::{ - ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, floating_panel, v_flex, + ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, v_flex, }; use crate::icons::{Icon, IconRole}; use crate::theme::{ActiveTheme as _, TOAST_MAX_WIDTH}; @@ -77,55 +77,51 @@ impl ToastEntry { 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() + .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() + .floating_panel(cx, radius, 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_none() - .flex() - .items_center() - .child(icon.size(rems(1.0)).color(foreground)), + .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); + }); + }), + ), ) - }) - .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); - }); - }), - ), - ) } } @@ -156,14 +152,17 @@ impl Toasts { self.current = Some(ToastEntry { id, toast }); cx.notify(); - if let Some(duration) = duration.filter(|duration| !duration.is_zero()) { - let task = cx.spawn(async move |this, cx| { - cx.background_executor().timer(duration).await; - this.update(cx, |toasts, cx| toasts.dismiss(id, cx)) + self.dismiss_task = duration + .filter(|duration| !duration.is_zero()) + .map(|duration| { + cx.spawn(async move |this, cx| { + cx.background_executor().timer(duration).await; + this.update(cx, |toasts, cx| { + toasts.dismiss(id, cx); + }) .log_err(); + }) }); - self.dismiss_task.replace(task); - } id } diff --git a/crates/ui/src/components/toggle.rs b/crates/ui/src/components/toggle.rs index 9e52592..4d0a030 100644 --- a/crates/ui/src/components/toggle.rs +++ b/crates/ui/src/components/toggle.rs @@ -14,10 +14,10 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, - SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Toggled, Window, }; -use crate::components::common::{ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex}; +use crate::components::common::{ControlSizing, Sizable, StyledExt as _, h_flex}; use crate::icons::Icon; use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; @@ -107,7 +107,7 @@ impl Toggle { } } -impl gpui::Styled for Toggle { +impl Styled for Toggle { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } @@ -123,6 +123,7 @@ impl RenderOnce for Toggle { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let colors = theme.colors; + let ring = theme.focus_ring(); let ramps = theme.ramps; let size = self.size; let on_change = self.on_change; @@ -159,7 +160,7 @@ impl RenderOnce for Toggle { .cursor_pointer() .focusable() .tab_stop(true) - .focus_visible(|style| style.shadow(focus_ring(colors.ring))) + .focus_visible(|style| style.shadow(ring)) .when_some(on_change, |toggle, on_change| { toggle.on_click(move |_, window, cx| on_change(next, window, cx)) }) diff --git a/crates/ui/src/components/tooltip.rs b/crates/ui/src/components/tooltip.rs index 6d71d14..793d991 100644 --- a/crates/ui/src/components/tooltip.rs +++ b/crates/ui/src/components/tooltip.rs @@ -19,7 +19,7 @@ use gpui::{ Window, div, }; -use crate::components::common::floating_panel; +use crate::components::common::StyledExt as _; use crate::theme::{ActiveTheme as _, TOOLTIP_MAX_WIDTH}; /// A small text panel gpui shows next to a hovered element. @@ -57,9 +57,7 @@ impl Render for Tooltip { .debug_selector(|| "tooltip-anchor".to_string()) .pl_2() .pt_2() - .child(floating_panel( - cx, - radius_sm, + .child( div() .id("tooltip-panel") .role(Role::Tooltip) @@ -69,8 +67,8 @@ impl Render for Tooltip { .max_w(TOOLTIP_MAX_WIDTH) .text_sm() .text_color(surface_foreground) - .child(self.text.clone()), - shadows, - )) + .child(self.text.clone()) + .floating_panel(cx, radius_sm, shadows), + ) } } diff --git a/crates/ui/src/components/tree.rs b/crates/ui/src/components/tree.rs index 94e3370..c8a5ff5 100644 --- a/crates/ui/src/components/tree.rs +++ b/crates/ui/src/components/tree.rs @@ -24,17 +24,15 @@ use std::sync::Arc; use gpui::prelude::FluentBuilder; use gpui::{ - AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, + App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, UniformListScrollHandle, Window, div, rems, uniform_list, + StyleRefinement, Styled, UniformListScrollHandle, Window, div, rems, uniform_list, }; -use crate::common::{focus_handle, h_flex}; -use crate::components::common::{ - StyledExt as _, nav_key, paint_selectable_row, selectable_label_color, v_flex, -}; +use crate::common::h_flex; +use crate::components::common::{ElementIdExt as _, SelectableRows as _, StyledExt as _, v_flex}; use crate::components::scrollbar::Scrollbar; -use crate::icons::{Icon, IconRole, icon}; +use crate::icons::{Icon, IconRole}; use crate::theme::ActiveTheme as _; /// The change reporter, fired with the next selection by pointer and keys. @@ -58,6 +56,10 @@ pub struct TreeItem { expandable: bool, expanded: bool, disabled: bool, + /// One-based position among the row's siblings. + position_in_set: usize, + /// Number of siblings sharing the row's parent. + size_of_set: usize, } impl TreeItem { @@ -75,6 +77,8 @@ impl TreeItem { expandable: false, expanded: false, disabled: false, + position_in_set: 0, + size_of_set: 0, } } @@ -88,6 +92,16 @@ impl TreeItem { self.expandable } + /// The row's nesting level, zero at the root. + pub fn level(&self) -> usize { + self.depth + } + + /// Whether the row is currently expanded. + pub fn is_expanded(&self) -> bool { + self.expanded + } + /// Shows a custom icon leading the label. pub fn icon(mut self, icon: I) -> Self where @@ -132,9 +146,9 @@ impl TreeItem { on_change: &Option, on_disclosure: &Option, focus: &FocusHandle, - ) -> AnyElement { + ) -> impl IntoElement { let theme = cx.theme(); - let label_color = selectable_label_color(cx, selected, self.disabled); + let label_color = theme.selectable_label_color(selected, self.disabled); let disabled = self.disabled; let depth = self.depth.min(TREE_MAX_DEPTH) as f32; @@ -156,7 +170,7 @@ impl TreeItem { .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)) + .map(|row| row.selectable_row(cx, selected, disabled)) .when(!disabled, |row| { row.cursor_pointer().on_click({ let on_change = on_change.clone(); @@ -190,7 +204,7 @@ impl TreeItem { .when_some( self.icon .clone() - .or_else(|| (!self.expandable).then(|| icon(IconRole::File))), + .or_else(|| (!self.expandable).then(|| Icon::from(IconRole::File))), |row, icon| row.child(icon.size(rems(1.0)).color(label_color)), ) .child( @@ -203,10 +217,9 @@ impl TreeItem { .text_color(label_color) .child(self.label.clone()), ) - .into_any_element() } - fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement { + fn render_disclosure(&self, cx: &App, selected: bool) -> impl IntoElement { let theme = cx.theme(); let glyph_color = if self.disabled || !selected { theme.colors.muted_foreground @@ -223,7 +236,7 @@ impl TreeItem { .justify_center() .when(self.expandable, |cell| { cell.child( - icon(if self.expanded { + Icon::from(if self.expanded { IconRole::ChevronDown } else { IconRole::ChevronRight @@ -250,13 +263,12 @@ pub struct TreeItemSeed { 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, + position: usize, + siblings: usize, expanded: &HashSet, rows: &mut Vec, ) { @@ -265,22 +277,34 @@ impl TreeItemSeed { .depth(depth) .expandable(!seed.children.is_empty()) .expanded(is_expanded); + if !seed.children.is_empty() { item = item.icon(Icon::named(IconRole::Folder)); } + + item.position_in_set = position; + item.size_of_set = siblings; rows.push(item); if is_expanded { - for child in &seed.children { - push(child, depth + 1, expanded, rows); + for (index, child) in seed.children.iter().enumerate() { + push( + child, + depth + 1, + index + 1, + seed.children.len(), + expanded, + rows, + ); } } } let mut rows = Vec::new(); - for seed in seeds { - push(seed, 0, expanded, &mut rows); + for (index, seed) in seeds.iter().enumerate() { + push(seed, 0, index + 1, seeds.len(), expanded, &mut rows); } + rows } @@ -299,6 +323,7 @@ impl TreeItemSeed { for seed in seeds { push(seed, &mut expanded); } + expanded } @@ -312,6 +337,7 @@ impl TreeItemSeed { 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() { @@ -319,21 +345,26 @@ impl TreeItemSeed { } 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(), @@ -348,74 +379,6 @@ impl TreeItemSeed { } } -#[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] @@ -488,45 +451,6 @@ impl Tree { self } - /// Maps each visible row to its 1-based position-in-set and set size among its siblings. - fn sibling_sets(items: &[TreeItem]) -> Vec<(usize, usize)> { - let mut sets = vec![(0usize, 0usize); items.len()]; - // Open sibling runs along the ancestry path, deeper runs above shallower ones. - let mut runs: Vec<(usize, Vec)> = Vec::new(); - - for (index, item) in items.iter().enumerate() { - while runs - .last() - .is_some_and(|(run_depth, _)| *run_depth > item.depth) - { - if let Some((_, pending)) = runs.pop() { - Self::stamp_sibling_run(&mut sets, pending); - } - } - - match runs.last_mut() { - // A row at the running depth extends the open sibling run. - Some((run_depth, pending)) if *run_depth == item.depth => pending.push(index), - _ => runs.push((item.depth, vec![index])), - } - } - - for (_, pending) in runs { - Self::stamp_sibling_run(&mut sets, pending); - } - - sets - } - - fn stamp_sibling_run(sets: &mut [(usize, usize)], pending: Vec) { - let size_of_set = pending.len(); - for (position, index) in pending.into_iter().enumerate() { - if let Some(set) = sets.get_mut(index) { - *set = (position + 1, size_of_set); - } - } - } - /// The nearest row above `index` with a smaller depth. fn parent_of(items: &[TreeItem], index: usize) -> Option { let depth = items.get(index)?.depth; @@ -544,7 +468,7 @@ impl Tree { } } -impl gpui::Styled for Tree { +impl Styled for Tree { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } @@ -575,9 +499,8 @@ impl RenderOnce for Tree { .map(|(index, _)| index) .collect(); - let focus = focus_handle(&id, window, cx); + let focus = id.focus_handle(window, cx); let label = a11y_label.unwrap_or_else(|| SharedString::from(id.to_string())); - let sibling_sets = Self::sibling_sets(&items); let scroll = window.with_element_namespace(id.clone(), |window| { window.use_keyed_state("scroll", cx, |_, _| UniformListScrollHandle::new()) @@ -610,7 +533,7 @@ impl RenderOnce for Tree { .role(Role::Tree) .aria_label(label) .on_key_down(move |event: &KeyDownEvent, window, cx| { - if nav_key(&selectable, selected, &event.keystroke.key, |next| { + if selectable.nav_key(selected, &event.keystroke.key, |next| { if let Some(on_change) = &on_change { on_change(next, window, cx); } @@ -659,7 +582,8 @@ impl RenderOnce for Tree { let Some(item) = items_for_rows.get(index) else { return div().into_any_element(); }; - let (position_in_set, size_of_set) = sibling_sets[index]; + let position_in_set = item.position_in_set; + let size_of_set = item.size_of_set; item.render_row( cx, @@ -671,6 +595,7 @@ impl RenderOnce for Tree { &on_disclosure_for_rows, &focus_for_rows, ) + .into_any_element() }) .collect() }) diff --git a/crates/ui/src/icons/mod.rs b/crates/ui/src/icons/mod.rs index ce29de6..d284eab 100644 --- a/crates/ui/src/icons/mod.rs +++ b/crates/ui/src/icons/mod.rs @@ -1,12 +1,13 @@ //! Signed's icon set: application-defined SVG glyphs. +use std::borrow::Cow; use std::time::Duration; use gpui::prelude::FluentBuilder as _; use gpui::{ - AbsoluteLength, AnyElement, AssetSource, Hsla, IntoElement, ParentElement as _, Pixels, Rems, - RenderOnce, SharedString, Styled as _, TimedTransformation, Transformation, Window, div, rems, - svg, + AbsoluteLength, App, AssetSource, Div, Hsla, IntoElement, ParentElement as _, Pixels, Rems, + RenderOnce, Result, SharedString, Styled as _, TimedTransformation, Transformation, Window, + div, rems, svg, }; const SMALL_ICON_SIZE: Rems = rems(0.875); @@ -122,8 +123,56 @@ impl IconRole { } /// The bundled SVG asset path for the role. - fn asset_path(self) -> SharedString { - SharedString::from(format!("icons/{}.svg", self.slug())) + pub fn asset_path(self) -> &'static str { + match self { + Self::Check => "icons/check.svg", + Self::Close => "icons/close.svg", + Self::ChevronDown => "icons/chevron-down.svg", + Self::ChevronRight => "icons/chevron-right.svg", + Self::Plus => "icons/plus.svg", + Self::Search => "icons/search.svg", + Self::Folder => "icons/folder.svg", + Self::Warning => "icons/warning.svg", + Self::Copy => "icons/copy.svg", + Self::Eye => "icons/eye.svg", + Self::EyeOff => "icons/eye-off.svg", + Self::WindowMinimize => "icons/window-minimize.svg", + Self::WindowMaximize => "icons/window-maximize.svg", + Self::WindowRestore => "icons/window-restore.svg", + Self::Loader => "icons/loader.svg", + Self::Microphone => "icons/microphone.svg", + Self::Stop => "icons/stop.svg", + Self::Settings => "icons/settings.svg", + Self::Refresh => "icons/refresh.svg", + Self::More => "icons/more.svg", + Self::Grid => "icons/grid.svg", + Self::File => "icons/file.svg", + Self::Clock => "icons/clock.svg", + Self::Unlock => "icons/unlock.svg", + Self::CirclePlus => "icons/circle-plus.svg", + Self::GitCommit => "icons/git-commit.svg", + Self::GitIssueDone => "icons/git-issue-done.svg", + Self::GitIssueClosed => "icons/git-issue-closed.svg", + Self::GitIssueOngoing => "icons/git-issue-ongoing.svg", + Self::GitPullRequest => "icons/git-pull-request.svg", + Self::GitPullRequestClosed => "icons/git-pull-request-closed.svg", + Self::GitPullRequestDraft => "icons/git-pull-request-draft.svg", + Self::GitPullRequestMerged => "icons/git-pull-request-merged.svg", + Self::GitClone => "icons/git-clone.svg", + Self::GitBranch => "icons/git-branch.svg", + Self::Markdown => "icons/markdown.svg", + Self::Trending => "icons/trending.svg", + Self::EllipsisVertical => "icons/ellipsis-vertical.svg", + Self::ArrowUp => "icons/arrow-up.svg", + Self::Inbox => "icons/inbox.svg", + Self::Stack => "icons/stack.svg", + Self::Message => "icons/message.svg", + Self::PanelLeft => "icons/panel-left.svg", + Self::UnfoldVertical => "icons/unfold-vertical.svg", + Self::Download => "icons/download.svg", + Self::Maximize => "icons/maximize.svg", + Self::Minimize => "icons/minimize.svg", + } } } @@ -135,14 +184,13 @@ pub trait IconNamed { impl IconNamed for IconRole { fn path(self) -> SharedString { - self.asset_path() + SharedString::from(self.asset_path()) } } /// The glyph an icon draws. #[derive(Clone)] enum Glyph { - Role(IconRole), Named(SharedString), } @@ -217,29 +265,22 @@ impl Icon { transformation: Option, rotation_period: Option, path: SharedString, - ) -> AnyElement { - div() - .flex_none() - .size(size) - .child( - svg() - .size_full() - .path(path) - .when_some(color, |el, color| el.text_color(color)) - .when_some(transformation, |el, transformation| { - el.with_transformation(transformation) - }) - .when_some(rotation_period, |el, period| { - el.with_timed_transformation( - TimedTransformation::rotation( - period, - transformation.unwrap_or_default(), - ) + ) -> Div { + div().flex_none().size(size).child( + svg() + .size_full() + .path(path) + .when_some(color, |el, color| el.text_color(color)) + .when_some(transformation, |el, transformation| { + el.with_transformation(transformation) + }) + .when_some(rotation_period, |el, period| { + el.with_timed_transformation( + TimedTransformation::rotation(period, transformation.unwrap_or_default()) .with_max_fps(SPIN_MAX_FPS), - ) - }), - ) - .into_any_element() + ) + }), + ) } } @@ -253,7 +294,7 @@ where } impl RenderOnce for Icon { - fn render(self, window: &mut Window, _cx: &mut gpui::App) -> impl IntoElement { + fn render(self, window: &mut Window, _cx: &mut App) -> impl IntoElement { let Icon { glyph, size, @@ -264,19 +305,9 @@ impl RenderOnce for Icon { let size = size.to_pixels(window.rem_size()); let color = color.unwrap_or_else(|| window.text_style().color); + let Glyph::Named(path) = glyph; - match glyph { - Glyph::Named(path) => { - Self::render_svg_path(size, Some(color), transformation, rotation_period, path) - } - Glyph::Role(role) => Self::render_svg_path( - size, - Some(color), - transformation, - rotation_period, - role.asset_path(), - ), - } + Self::render_svg_path(size, Some(color), transformation, rotation_period, path) } } @@ -286,7 +317,7 @@ impl RenderOnce for Icon { pub struct Assets; impl AssetSource for Assets { - fn load(&self, path: &str) -> gpui::Result>> { + fn load(&self, path: &str) -> Result>> { let name = match path.strip_prefix("icons/") { Some(name) => name, None => return Ok(None), @@ -301,14 +332,3 @@ 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/mod.rs b/crates/ui/src/layout/mod.rs index e471ced..58fbe80 100644 --- a/crates/ui/src/layout/mod.rs +++ b/crates/ui/src/layout/mod.rs @@ -3,7 +3,7 @@ //! The shared flex and focus helpers live in [`crate::components::common`]; //! they are re-exported here for the `ui::layout::…` paths. -pub use crate::components::common::{StyledExt, focus_handle, focus_ring, h_flex, v_flex}; +pub use crate::components::common::{StyledExt, h_flex, v_flex}; pub mod panel; pub mod resizable; @@ -11,5 +11,3 @@ pub mod resize_handle; pub mod root; pub mod titlebar; pub mod window_controls; - -mod window_frame; diff --git a/crates/ui/src/layout/panel.rs b/crates/ui/src/layout/panel.rs index c9a16b0..d952e30 100644 --- a/crates/ui/src/layout/panel.rs +++ b/crates/ui/src/layout/panel.rs @@ -253,33 +253,12 @@ pub struct PanelStack { split_width: Option, /// The side of the main panel the on-screen split pane opened on. split_side: SplitSide, - /// The main pane width the divider was last seeded at, to tell a drag from a window resize. - opened_at: Option, /// The panel shown alone while it is zoomed. zoomed: Option, /// The divider position, kept only while a split is on screen. sizes: Entity, } -/// The layout the cached panel content lays out with. -fn content_style() -> StyleRefinement { - StyleRefinement::default().size_full() -} - -/// The island chrome every panel paints. -fn island(panel: Div, cx: &App) -> Div { - let theme = cx.theme(); - let colors = theme.colors; - - panel - .size_full() - .bg(colors.background) - .border_1() - .border_color(colors.border) - .rounded(theme.radius.overlay) - .overflow_hidden() -} - impl PanelStack { /// Creates the panel stack with the main and split stacks empty. pub fn new(id: I, cx: &mut Context) -> Self @@ -294,7 +273,6 @@ impl PanelStack { resizable: true, split_width: None, split_side: SplitSide::Trailing, - opened_at: None, zoomed: None, sizes: ResizableState::new(cx), } @@ -307,18 +285,29 @@ impl PanelStack { split: Option<(AnyView, Pixels)>, cx: &mut Context, ) { + let width = split.as_ref().map(|(_, width)| *width); + self.empty = Some(EmptyContent { main: main.into(), split, }); + + if let Some(width) = width { + self.sizes.update(cx, |state, cx| { + state.open_pane(width, false, cx); + }); + } + self.forget_divider(cx); cx.notify(); } /// Sets whether the divider can be dragged; a fixed split keeps its opening width. pub fn set_resizable(&mut self, resizable: bool, cx: &mut Context) { - self.resizable = resizable; - cx.notify(); + if self.resizable != resizable { + self.resizable = resizable; + cx.notify(); + } } /// Shows `view` in `slot` under `id`, opening it at the end of the stack when new. @@ -381,6 +370,9 @@ impl PanelStack { if !self.is_split_shown() { self.split_width = Some(width); self.split_side = side; + self.sizes.update(cx, |state, cx| { + state.open_pane(width, side == SplitSide::Trailing, cx) + }); } self.insert(PanelSlot::Split, id, view, cx); } @@ -488,6 +480,7 @@ impl PanelStack { } if slot == PanelSlot::Main && was_shown { self.split.clear(); + self.open_empty_split(cx); } self.forget_divider(cx); cx.notify(); @@ -532,16 +525,21 @@ impl PanelStack { self.split_width = None; self.split_side = SplitSide::Trailing; - self.opened_at = None; self.zoomed = None; - if !self.sizes.read(cx).sizes().is_empty() { - self.sizes.update(cx, |state, cx| state.set_sizes([], cx)); + self.sizes.update(cx, |state, cx| state.clear(cx)); + } + + /// Opens the empty state's split beside the main pane at the width it was given. + fn open_empty_split(&self, cx: &mut Context) { + if let Some((_, width)) = self.empty.as_ref().and_then(|empty| empty.split.as_ref()) { + self.sizes + .update(cx, |state, cx| state.open_pane(*width, false, cx)); } } /// The split pane's content: the split stack's tabs over its shown panel. - fn split_pane(&self, cx: &mut Context) -> AnyElement { + fn split_pane(&self, cx: &Context) -> impl IntoElement { let selected = self.split.selected().unwrap_or(usize::MAX); let change = cx.weak_entity(); let close = change.clone(); @@ -587,14 +585,13 @@ impl PanelStack { div().flex_1().min_h_0().w_full().children( self.split .active() - .map(|panel| panel.view().cached(content_style()).into_any_element()), + .map(|panel| panel.view().cached(Self::content_style())), ), ) - .into_any_element() } /// The zoom and close buttons over a pane's top right corner, when its shown panel asks for them. - fn toolbar(&self, slot: PanelSlot, cx: &Context) -> Option { + fn toolbar(&self, slot: PanelSlot, cx: &Context) -> Option { if !self.stack(slot).active()?.toolbar(cx) { return None; } @@ -657,21 +654,30 @@ impl PanelStack { .update(cx, |stack, cx| stack.close_active(slot, cx)) .log_err(); }), - ) - .into_any_element(), + ), ) } /// The island around a pane's content, with its toolbar over the top right corner. - fn pane(&self, content: AnyElement, toolbar: Option, cx: &App) -> Div { - island( - div() - .size_full() - .relative() - .child(content) - .children(toolbar), - cx, - ) + fn pane(&self, content: impl IntoElement, toolbar: Option, cx: &App) -> Div { + let theme = cx.theme(); + let colors = theme.colors; + + div() + .size_full() + .bg(colors.background) + .border_1() + .border_color(colors.border) + .rounded(theme.radius.overlay) + .overflow_hidden() + .relative() + .child(content) + .children(toolbar) + } + + /// The layout the cached panel content lays out with. + fn content_style() -> StyleRefinement { + StyleRefinement::default().size_full() } } @@ -679,7 +685,6 @@ impl Render for PanelStack { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let gutter = RESIZE_HANDLE_WIDTH; let extent = window.viewport_size().width - gutter * 2.0; - let cached = |view: AnyView| view.cached(content_style()).into_any_element(); // The main pane's content, the split pane's when one is on screen, and how the first pane opens. let (main, split, width, leading) = match self.main.active() { @@ -693,8 +698,11 @@ impl Render for PanelStack { .map(|split_width| extent - gutter - split_width) }; ( - cached(panel.view()), - (!self.split.is_empty()).then(|| self.split_pane(cx)), + panel + .view() + .cached(Self::content_style()) + .into_any_element(), + (!self.split.is_empty()).then(|| self.split_pane(cx).into_any_element()), width, leading, ) @@ -702,92 +710,108 @@ impl Render for PanelStack { None => match &self.empty { Some(empty) => { let (split, width) = match &empty.split { - Some((view, width)) => (Some(cached(view.clone())), Some(*width)), + Some((view, width)) => ( + Some( + view.clone() + .cached(Self::content_style()) + .into_any_element(), + ), + Some(*width), + ), None => (None, None), }; - (cached(empty.main.clone()), split, width, false) + ( + empty + .main + .clone() + .cached(Self::content_style()) + .into_any_element(), + split, + width, + false, + ) } None => (div().into_any_element(), None, None, false), }, }; + let has_split = split.is_some(); // The pane shown alone while its panel is zoomed. let zoomed = self.zoomed.as_ref().and_then(|zoomed| { [PanelSlot::Main, PanelSlot::Split] .into_iter() - .find(|slot| split.is_some() && self.stack(*slot).active.as_ref() == Some(zoomed)) + .find(|slot| has_split && self.stack(*slot).active.as_ref() == Some(zoomed)) }); - div().flex_1().min_w_0().h_full().p_2().pt_1().map(|this| { - match split { - Some(split) => match zoomed { - // A zoomed panel fills the row; its toolbar is the way back. - Some(slot) => { - let content = match slot { - PanelSlot::Main => main, - PanelSlot::Split => split, - }; - this.child(div().w_full().h_full().child(self.pane( - content, - self.toolbar(slot, cx), - cx, - ))) - } - None => { - let main = self.pane(main, self.toolbar(PanelSlot::Main, cx), cx); - let split = self.pane(split, self.toolbar(PanelSlot::Split, cx), cx); - let (first, last) = if leading { - (split, main) - } else { - (main, split) - }; - let first_width = - width.unwrap_or((extent - gutter) / 2.0).max(PANE_MIN_SIZE); + div() + .flex_1() + .min_w_0() + .min_h_0() + .h_full() + .p_2() + .pt_1() + .map(|this| { + match split { + Some(split) => match zoomed { + // A zoomed panel fills the row; its toolbar is the way back. + Some(slot) => { + let content = match slot { + PanelSlot::Main => main, + PanelSlot::Split => split, + }; + this.child(div().w_full().h_full().child(self.pane( + content, + self.toolbar(slot, cx), + cx, + ))) + } + None => { + let main = self.pane(main, self.toolbar(PanelSlot::Main, cx), cx); + let split = self.pane(split, self.toolbar(PanelSlot::Split, cx), cx); + let (first, last) = if leading { + (split, main) + } else { + (main, split) + }; + let first_width = + width.unwrap_or((extent - gutter) / 2.0).max(PANE_MIN_SIZE); - if !self.resizable { - this.child( - div() - .w_full() - .h_full() - .flex() - .flex_row() - .child(div().flex_none().w(first_width).h_full().child(first)) - .child(div().flex_none().w(gutter)) - .child(div().flex_1().min_w_0().h_full().child(last)), - ) - } else { - // A split opened at a width keeps it across window resizes until the divider is dragged. - let current = self.sizes.read(cx).sizes().first().copied(); - let keeps_width = - self.split_width.is_some() && current == self.opened_at; - - if current.is_none() - || (keeps_width && self.opened_at != Some(first_width)) - { - self.sizes.update(cx, |state, cx| { - state.set_pane_width(0, first_width, cx); - }); - self.opened_at = Some(first_width); - } - - this.child( - div().w_full().h_full().child( - Resizable::new((self.id.clone(), "split"), self.sizes.clone()) + if !self.resizable { + this.child( + div() + .w_full() + .h_full() + .flex() + .flex_row() + .child( + div().flex_none().w(first_width).h_full().child(first), + ) + .child(div().flex_none().w(gutter)) + .child(div().flex_1().min_w_0().h_full().child(last)), + ) + } else { + this.child( + div().w_full().h_full().child( + Resizable::new( + (self.id.clone(), "split"), + self.sizes.clone(), + ) .axis(Axis::Horizontal) .pane(first) .pane(last) + .extent(extent) .h_full(), - ), - ) + ), + ) + } } - } - }, - None => this.child(div().w_full().h_full().child(self.pane( - main, - self.toolbar(PanelSlot::Main, cx), - cx, - ))), - } - }) + }, + None => this.child(div().w_full().h_full().child(self.pane( + main, + self.toolbar(PanelSlot::Main, cx), + cx, + ))), + } + }) } } diff --git a/crates/ui/src/layout/resizable.rs b/crates/ui/src/layout/resizable.rs index 4120c20..cbfc3a4 100644 --- a/crates/ui/src/layout/resizable.rs +++ b/crates/ui/src/layout/resizable.rs @@ -1,17 +1,28 @@ //! The resizable group: stacked panes with drag dividers, outside the dock. +use std::rc::Rc; + use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Axis, Bounds, Context, ElementId, Entity, - InteractiveElement as _, IntoElement, ParentElement as _, Pixels, RenderOnce, SharedString, - StyleRefinement, Styled, Window, canvas, div, px, + InteractiveElement as _, IntoElement, ParentElement as _, Pixels, RenderOnce, StyleRefinement, + Styled, Window, canvas, div, px, }; use crate::layout::StyledExt as _; use crate::layout::resize_handle::ResizeHandle; -use crate::theme::{PANE_DEFAULT_SIZE, PANE_MIN_SIZE}; +use crate::theme::{PANE_DEFAULT_SIZE, PANE_MIN_SIZE, RESIZE_HANDLE_WIDTH}; -type DebugSelector = std::rc::Rc String>; +type DebugSelector = Rc String>; + +/// How the first pane opens beside a split of the given width. +#[derive(Clone, Copy)] +enum Opening { + /// The first pane is the split. + Fixed(Pixels), + /// The first pane is the main pane, which keeps what the split leaves of the extent. + Remainder(Pixels), +} /// The retained pane sizes of one resizable group. #[derive(Default)] @@ -20,6 +31,8 @@ pub struct ResizableState { sizes: Vec, /// The group's main-axis extent, captured at paint for drag clamping. measured: Option, + /// The split the first pane opened beside, followed across resizes until a drag. + opening: Option, } impl ResizableState { @@ -42,6 +55,27 @@ impl ResizableState { cx.notify(); } + /// Forgets every pane size and opening. + pub fn clear(&mut self, cx: &mut Context) { + if self.sizes.is_empty() && self.opening.is_none() { + return; + } + self.sizes.clear(); + self.opening = None; + cx.notify(); + } + + /// Opens the first pane beside a split of `width`, keeping it across resizes until a drag; `remainder` when the first pane is the main pane. + pub fn open_pane(&mut self, width: Pixels, remainder: bool, cx: &mut Context) { + self.opening = Some(if remainder { + Opening::Remainder(width) + } else { + Opening::Fixed(width) + }); + self.sizes.clear(); + cx.notify(); + } + /// Records the group's measured extent, notifying only when it changes. fn set_measured(&mut self, extent: Pixels, cx: &mut Context) { if self.measured != Some(extent) { @@ -50,21 +84,33 @@ impl ResizableState { } } - /// The equal split of the measured extent, or the default pane size unmeasured. - fn equal_split(&self, pane_count: usize) -> Pixels { - match self.measured { + /// The equal split of an extent, or the default pane size unmeasured. + fn equal_split(extent: Option, pane_count: usize) -> Pixels { + match extent { // usize can exceed f32's exact integer range; bound it via u32 before casting. Some(extent) => extent / u32::try_from(pane_count).unwrap_or(u32::MAX) as f32, None => PANE_DEFAULT_SIZE, } } - /// The size pane `ix` renders at: its stored size, or the equal split. - fn pane_size(&self, ix: usize, pane_count: usize) -> Pixels { + /// The size pane `ix` renders at within `extent` (the measured extent when unmeasured): its opening, its stored size, or the equal split. + fn pane_size(&self, ix: usize, pane_count: usize, extent: Option) -> Pixels { + if ix == 0 + && let Some(opening) = self.opening + { + return match opening { + Opening::Fixed(width) => width, + Opening::Remainder(width) => { + extent.unwrap_or(PANE_DEFAULT_SIZE) - RESIZE_HANDLE_WIDTH - width + } + } + .max(PANE_MIN_SIZE); + } + self.sizes .get(ix) .copied() - .unwrap_or_else(|| self.equal_split(pane_count)) + .unwrap_or_else(|| Self::equal_split(extent.or(self.measured), pane_count)) } /// Applies a drag at divider `ix` (between pane ix and ix+1). @@ -75,7 +121,7 @@ impl ResizableState { let pane_count = mins.len(); - let previous = self.pane_size(ix, pane_count); + let previous = self.pane_size(ix, pane_count, None); let mut size = previous + delta; size = size.max(floor); @@ -93,12 +139,13 @@ impl ResizableState { // Earlier panes hold the equal split they already render at, // so the first drag does not snap them to a backfilled default. - let backfill = self.equal_split(pane_count); + let backfill = Self::equal_split(self.measured, pane_count); while self.sizes.len() <= ix { self.sizes.push(backfill); } self.sizes[ix] = size; + self.opening = None; // A drag clamped at its floor or ceiling lands here on every mouse move, // only a change to the rendered size is worth a frame. @@ -107,29 +154,20 @@ impl ResizableState { } } - /// Sets pane `ix`'s width, backfilling earlier panes. - pub fn set_pane_width(&mut self, ix: usize, width: Pixels, cx: &mut Context) { - // Persisted layouts can carry negative sizes. - let width = width.max(PANE_MIN_SIZE); - - while self.sizes.len() <= ix { - self.sizes.push(width); - } - - if self.sizes[ix] != width { - self.sizes[ix] = width; - cx.notify(); - } - } - /// Restores pane `ix` to the equal split, as a double-click does. fn reset_pane(&mut self, ix: usize, pane_count: usize, cx: &mut Context) { - let split = self.equal_split(pane_count); + let split = Self::equal_split(self.measured, pane_count); + while self.sizes.len() <= ix { self.sizes.push(split); } - self.sizes[ix] = split; - cx.notify(); + + self.opening = None; + + if self.sizes[ix] != split { + self.sizes[ix] = split; + cx.notify(); + } } } @@ -171,6 +209,7 @@ pub struct Resizable { axis: Axis, panes: Vec, debug_selector: Option, + extent: Option, style: StyleRefinement, } @@ -186,6 +225,7 @@ impl Resizable { axis: Axis::Vertical, panes: Vec::new(), debug_selector: None, + extent: None, style: StyleRefinement::default(), } } @@ -214,12 +254,18 @@ impl Resizable { self } + /// Sets the group's main-axis extent its owner knows before layout, so panes size right on the frame the extent changes. + pub fn extent(mut self, extent: Pixels) -> Self { + self.extent = Some(extent); + self + } + /// Sets the debug-bounds selector of each pane, suffixed with its index. pub fn debug_selector(mut self, selector: F) -> Self where F: Fn() -> String + 'static, { - self.debug_selector = Some(std::rc::Rc::new(selector)); + self.debug_selector = Some(Rc::new(selector)); self } } @@ -236,14 +282,12 @@ impl RenderOnce for Resizable { let state = self.state.clone(); let pane_count = self.panes.len(); - let mins: Vec = self.panes.iter().map(|pane| pane.min).collect(); + let extent = self.extent; + let mins: Rc<[Pixels]> = self.panes.iter().map(|pane| pane.min).collect(); let debug_selector = self.debug_selector; - let sizes: Vec = (0..pane_count) - .map(|ix| state.read(cx).pane_size(ix, pane_count)) - .collect(); - div() + .id(self.id) .flex() .overflow_hidden() .when(axis == Axis::Vertical, |group| group.flex_col()) @@ -251,10 +295,12 @@ impl RenderOnce for Resizable { .refine_style(&self.style) .children(self.panes.into_iter().enumerate().flat_map(|(ix, pane)| { let remainder = ix + 1 == pane_count; + let size = state.read(cx).pane_size(ix, pane_count, extent); + let min = pane.min; let divider = (!remainder).then(|| { - // The positional index is a stable id: panes are append-only, never reordered. - ResizeHandle::new(SharedString::from(format!("{}-divider-{ix}", self.id))) + // Positional: panes are append-only, never reordered. + ResizeHandle::new(ElementId::from(("divider", ix))) .axis(axis) .on_resize({ let state = state.clone(); @@ -279,14 +325,15 @@ impl RenderOnce for Resizable { .when(remainder, |pane_element| { pane_element .flex_1() - .when(axis == Axis::Vertical, |p| p.min_h(pane.min)) - .when(axis == Axis::Horizontal, |p| p.min_w(pane.min)) + .min_h_0() + .when(axis == Axis::Vertical, |pane| pane.min_h(min)) + .when(axis == Axis::Horizontal, |pane| pane.min_w(min).min_w_0()) }) .when(!remainder, |pane_element| { pane_element .flex_none() - .when(axis == Axis::Vertical, |p| p.h(sizes[ix]).w_full()) - .when(axis == Axis::Horizontal, |p| p.w(sizes[ix]).h_full()) + .when(axis == Axis::Vertical, |pane| pane.h(size).w_full()) + .when(axis == Axis::Horizontal, |pane| pane.w(size).h_full()) }) .when_some(debug_selector.clone(), |pane_element, selector| { let prefix = selector(); diff --git a/crates/ui/src/layout/resize_handle.rs b/crates/ui/src/layout/resize_handle.rs index 0b874a5..895cee0 100644 --- a/crates/ui/src/layout/resize_handle.rs +++ b/crates/ui/src/layout/resize_handle.rs @@ -8,11 +8,12 @@ use gpui::{ App, Axis, Bounds, CursorStyle, DispatchPhase, ElementId, HitboxBehavior, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point, RenderOnce, Role, - SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, canvas, deferred, div, fill, point, px, }; -use crate::layout::{StyledExt as _, focus_handle, focus_ring}; +use crate::components::common::ElementIdExt as _; +use crate::layout::StyledExt as _; use crate::theme::{ ActiveTheme as _, BORDER_WIDTH, DISABLED_OPACITY, HAIRLINE_WIDTH, RESIZE_HANDLE_WIDTH, RESIZE_KEYBOARD_STEP, @@ -102,7 +103,7 @@ impl ResizeHandle { } } -impl gpui::Styled for ResizeHandle { +impl Styled for ResizeHandle { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } @@ -112,6 +113,7 @@ impl RenderOnce for ResizeHandle { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let ring = theme.colors.ring; + let focus_ring = theme.focus_ring(); let thickness = RESIZE_HANDLE_WIDTH; let label = self @@ -128,7 +130,7 @@ impl RenderOnce for ResizeHandle { .clone() }); - let focus = focus_handle(&self.id, window, cx); + let focus = self.id.focus_handle(window, cx); let dragging = drag.read(cx).dragging; let axis = self.axis; let disabled = self.disabled; @@ -160,7 +162,7 @@ impl RenderOnce for ResizeHandle { .track_focus(&focus) .focusable() .tab_stop(true) - .focus_visible(|style| style.shadow(focus_ring(ring))) + .focus_visible(|style| style.shadow(focus_ring)) .on_mouse_down_out({ let focus = focus.clone(); move |_, window, cx| { diff --git a/crates/ui/src/layout/root.rs b/crates/ui/src/layout/root.rs index e53385e..4c2ab08 100644 --- a/crates/ui/src/layout/root.rs +++ b/crates/ui/src/layout/root.rs @@ -8,25 +8,20 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyView, App, AppContext as _, Context, Entity, Global, IntoElement, ParentElement as _, - Render, StyleRefinement, Styled, WeakEntity, Window, div, + AnyView, App, AppContext as _, Bounds, BoxShadow, Context, CursorStyle, Decorations, Div, + Entity, Global, Hitbox, HitboxBehavior, InteractiveElement as _, IntoElement, MouseButton, + ParentElement as _, Pixels, Point, Render, ResizeEdge, Size, StyleRefinement, Styled, Tiling, + WeakEntity, Window, canvas, div, point, px, size, }; use crate::components::alert::{Alerts, AlertsView}; -use crate::components::grain::grain as grain_overlay; +use crate::components::grain::Grain; use crate::components::toast::{Toasts, ToastsView}; -use crate::layout::window_frame::frame; use crate::layout::{StyledExt as _, v_flex}; use crate::theme::ActiveTheme as _; +use crate::theme::{BORDER_WIDTH, INACTIVE_SHADOW_OPACITY, WINDOW_RESIZE_INSET}; use crate::toast::Toast; -/// The mounted root's handle, for access from anywhere. -struct RootGlobal { - root: WeakEntity, -} - -impl Global for RootGlobal {} - /// Root presentation helpers on gpui contexts. pub trait RootContext { /// Pushes a toast on the mounted root's store. @@ -66,6 +61,13 @@ impl RootContext for App { } } +/// The mounted root's handle, for access from anywhere. +struct RootGlobal { + root: WeakEntity, +} + +impl Global for RootGlobal {} + /// The window's content and floating-surface host. pub struct Root { content: Option, @@ -152,6 +154,179 @@ impl Root { self.grain = grain; self } + + /// Wraps a window's content in the frame it owes. + fn frame(&self, child: impl IntoElement, window: &mut Window, cx: &App) -> Div { + let Decorations::Client { tiling } = window.window_decorations() else { + return div().size_full().child(child); + }; + + let tiling = if window.is_maximized() { + Tiling::tiled() + } else { + tiling + }; + + let inset = WINDOW_RESIZE_INSET; + let border = cx.theme().colors.border; + let radius = cx.theme().radius.overlay; + + let shadow = Self::frame_shadow(cx, window.is_window_active()); + window.set_client_inset(inset); + + div() + .size_full() + .child( + canvas( + move |_, window, _| Self::resize_bands(window, inset, tiling), + |_, bands, window, _| { + for (edge, hitbox) in bands.iter().filter_map(|(edge, hitbox)| { + hitbox.as_ref().map(|hitbox| (*edge, hitbox)) + }) { + window.set_cursor_style(Self::cursor(edge), hitbox); + } + }, + ) + .absolute() + .size_full(), + ) + .when(!tiling.top, |this| this.pt(inset)) + .when(!tiling.bottom, |this| this.pb(inset)) + .when(!tiling.left, |this| this.pl(inset)) + .when(!tiling.right, |this| this.pr(inset)) + .on_mouse_down(MouseButton::Left, move |event, window, _| { + let size = window.window_bounds().get_bounds().size; + if let Some(edge) = Self::resize_edge(event.position, inset, size) + .filter(|edge| Self::live(*edge, tiling)) + { + window.start_window_resize(edge); + } + }) + .child( + div() + .size_full() + .overflow_hidden() + .border_color(border) + .when(!tiling.top, |surface| surface.border_t(BORDER_WIDTH)) + .when(!tiling.bottom, |surface| surface.border_b(BORDER_WIDTH)) + .when(!tiling.left, |surface| surface.border_l(BORDER_WIDTH)) + .when(!tiling.right, |surface| surface.border_r(BORDER_WIDTH)) + .when(!(tiling.top || tiling.left), |surface| { + surface.rounded_tl(radius) + }) + .when(!(tiling.top || tiling.right), |surface| { + surface.rounded_tr(radius) + }) + .when(!(tiling.bottom || tiling.left), |surface| { + surface.rounded_bl(radius) + }) + .when(!(tiling.bottom || tiling.right), |surface| { + surface.rounded_br(radius) + }) + .when(!tiling.is_tiled(), |surface| surface.shadow(shadow)) + .child(child), + ) + } + + /// The dialog elevation's shadow, dimmed while the window is inactive. + fn frame_shadow(cx: &App, active: bool) -> Vec { + let opacity = if active { 1.0 } else { INACTIVE_SHADOW_OPACITY }; + cx.theme() + .elevations + .dialog + .shadows() + .iter() + .map(|shadow| { + let mut dimmed = shadow.clone(); + dimmed.color.a *= opacity; + dimmed + }) + .collect() + } + + /// Which edge a press at `pos` resizes, or `None` for a press on the content. + fn resize_edge(pos: Point, inset: Pixels, size: Size) -> Option { + let (top, bottom) = (pos.y < inset, pos.y > size.height - inset); + let (left, right) = (pos.x < inset, pos.x > size.width - inset); + + Some(match (top, bottom, left, right) { + (true, _, true, _) => ResizeEdge::TopLeft, + (true, _, _, true) => ResizeEdge::TopRight, + (_, true, true, _) => ResizeEdge::BottomLeft, + (_, true, _, true) => ResizeEdge::BottomRight, + (true, ..) => ResizeEdge::Top, + (_, true, ..) => ResizeEdge::Bottom, + (_, _, true, _) => ResizeEdge::Left, + (_, _, _, true) => ResizeEdge::Right, + _ => return None, + }) + } + + /// The eight resize bands, as the rects [`Self::resize_edge`] classifies to, each with the hitbox its live edges insert. + fn resize_bands( + window: &mut Window, + inset: Pixels, + tiling: Tiling, + ) -> [(ResizeEdge, Option); 8] { + let window_size = window.window_bounds().get_bounds().size; + let band = |x: Pixels, y: Pixels, width: Pixels, height: Pixels| Bounds { + origin: point(x, y), + size: size(width, height), + }; + + let (far_x, far_y) = (window_size.width - inset, window_size.height - inset); + let (span_x, span_y) = ( + window_size.width - inset - inset, + window_size.height - inset - inset, + ); + let zero = px(0.0); + + [ + (ResizeEdge::TopLeft, band(zero, zero, inset, inset)), + (ResizeEdge::TopRight, band(far_x, zero, inset, inset)), + (ResizeEdge::BottomLeft, band(zero, far_y, inset, inset)), + (ResizeEdge::BottomRight, band(far_x, far_y, inset, inset)), + (ResizeEdge::Top, band(inset, zero, span_x, inset)), + (ResizeEdge::Bottom, band(inset, far_y, span_x, inset)), + (ResizeEdge::Left, band(zero, inset, inset, span_y)), + (ResizeEdge::Right, band(far_x, inset, inset, span_y)), + ] + .map(|(edge, band)| { + ( + edge, + Self::live(edge, tiling) + .then(|| window.insert_hitbox(band, HitboxBehavior::Normal)), + ) + }) + } + + /// Whether `edge` resizes: none of the sides it touches is flush. + fn live(edge: ResizeEdge, tiling: Tiling) -> bool { + let (top, bottom, left, right) = match edge { + ResizeEdge::Top => (true, false, false, false), + ResizeEdge::Bottom => (false, true, false, false), + ResizeEdge::Left => (false, false, true, false), + ResizeEdge::Right => (false, false, false, true), + ResizeEdge::TopLeft => (true, false, true, false), + ResizeEdge::TopRight => (true, false, false, true), + ResizeEdge::BottomLeft => (false, true, true, false), + ResizeEdge::BottomRight => (false, true, false, true), + }; + !(top && tiling.top + || bottom && tiling.bottom + || left && tiling.left + || right && tiling.right) + } + + /// The pointer an edge shows. + fn cursor(edge: ResizeEdge) -> CursorStyle { + match edge { + ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown, + ResizeEdge::Left | ResizeEdge::Right => CursorStyle::ResizeLeftRight, + ResizeEdge::TopLeft | ResizeEdge::BottomRight => CursorStyle::ResizeUpLeftDownRight, + ResizeEdge::TopRight | ResizeEdge::BottomLeft => CursorStyle::ResizeUpRightDownLeft, + } + } } impl Styled for Root { @@ -174,29 +349,26 @@ impl Render for Root { .size_full() .font_family(theme.ui_font()) .text_color(theme.colors.foreground) - .child(frame( - v_flex() - .w_full() - .h_full() - .overflow_hidden() - .bg(background) - .refine_style(&self.style) - .when(self.transparent && self.grain, |layout| { - layout.child(grain_overlay()) - }) - .child( - self.content - .clone() - .map(AnyView::into_any_element) - .unwrap_or_else(|| div().into_any_element()), - ), - window, - cx, - )) + .child( + self.frame( + v_flex() + .w_full() + .h_full() + .overflow_hidden() + .bg(background) + .refine_style(&self.style) + .when(self.transparent && self.grain, |layout| layout.child(Grain)) + .when_some(self.content.clone(), |layout, content| { + layout.child(content) + }), + window, + cx, + ), + ) .when_some(self.palette.clone(), |layout, palette| { layout.child(palette) }) - .children(self.dialogs.clone()) + .children(self.dialogs.iter().cloned()) .child(ToastsView::new("root-toasts", self.toasts.clone())) .child(AlertsView::new("root-alerts", self.alerts.clone())) } diff --git a/crates/ui/src/layout/titlebar.rs b/crates/ui/src/layout/titlebar.rs index 1087ac2..7b6f560 100644 --- a/crates/ui/src/layout/titlebar.rs +++ b/crates/ui/src/layout/titlebar.rs @@ -6,11 +6,12 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, - RenderOnce, SharedString, StyleRefinement, Styled as _, Window, + AnyElement, App, ClickEvent, Div, ElementId, InteractiveElement as _, IntoElement, MouseButton, + ParentElement as _, RenderOnce, Stateful, StatefulInteractiveElement as _, StyleRefinement, + Styled, Window, WindowControlArea, }; -use crate::layout::window_controls::{WindowControls, titlebar_strip}; +use crate::layout::window_controls::WindowControls; use crate::layout::{StyledExt as _, h_flex}; use crate::theme::{ActiveTheme as _, TRAFFIC_LIGHT_PAD}; @@ -66,9 +67,61 @@ impl Titlebar { self.suffix = vec![suffix.into_any_element()]; self } + + /// Makes `this` a titlebar strip that moves the window; `id` keys its drag state, which `use_state` would otherwise share among every strip in the window. + pub fn strip(id: I, this: Stateful
, window: &mut Window, cx: &mut App) -> Stateful
+ where + I: Into, + { + let should_move = window.use_keyed_state(id.into(), cx, |_, _| false); + this.window_control_area(WindowControlArea::Drag) + .on_mouse_down_out(window.listener_for(&should_move, |should_move, _, _, _| { + *should_move = false; + })) + .on_mouse_down( + MouseButton::Left, + window.listener_for(&should_move, |should_move, _, _, _| { + *should_move = true; + }), + ) + .on_mouse_up( + MouseButton::Left, + window.listener_for(&should_move, |should_move, _, _, _| { + *should_move = false; + }), + ) + .on_mouse_move( + window.listener_for(&should_move, |should_move, _, window, cx| { + if *should_move { + *should_move = false; + if !cx.has_active_drag() { + window.start_window_move(); + } + } + }), + ) + .on_click(Self::on_titlebar_click) + } + + /// Maximizes on a double-click where the platform does not do it. + pub fn on_titlebar_click(event: &ClickEvent, window: &mut Window, _cx: &mut App) { + if event.click_count() != 2 { + return; + } + #[cfg(target_os = "macos")] + window.titlebar_double_click(); + #[cfg(target_os = "linux")] + window.zoom_window(); + // Windows handles titlebar double-click natively via WindowControlArea::Drag. + #[cfg(any( + target_os = "windows", + not(any(target_os = "macos", target_os = "linux")) + ))] + let _ = (event, window, _cx); + } } -impl gpui::Styled for Titlebar { +impl Styled for Titlebar { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } @@ -81,12 +134,15 @@ impl RenderOnce for Titlebar { let shadow_bleed = theme.elevations.control.bleed(); let id = self.id; - let bar_id = SharedString::from(format!("{id}-bar")); - titlebar_strip( + Self::strip( + (id.clone(), "drag"), h_flex() .id(id.clone()) - .debug_selector(move || bar_id.to_string()) + .debug_selector({ + let id = id.clone(); + move || format!("{id}-bar") + }) .flex_none() .w_full() .h(height) @@ -131,7 +187,6 @@ impl RenderOnce for Titlebar { .children(self.suffix), ) }), - (id.clone(), "drag"), window, cx, ) diff --git a/crates/ui/src/layout/window_controls.rs b/crates/ui/src/layout/window_controls.rs index 2ed1f4f..841c70f 100644 --- a/crates/ui/src/layout/window_controls.rs +++ b/crates/ui/src/layout/window_controls.rs @@ -1,9 +1,11 @@ //! The window controls: minimize, maximize/restore, close — in the platform's -//! own dress and behavior. Titlebar strips are app-owned: they move the -//! window themselves via [`titlebar_strip`], so a dragged tab or button press -//! never moves it; macOS draws its traffic lights in the shell's reserved pad -//! and needs no controls of ours. +//! own dress and behavior. Titlebar strips are app-owned and move the window +//! themselves (see [`crate::layout::titlebar::Titlebar::strip`]), so a dragged +//! tab or button press never moves it; macOS draws its traffic lights in the +//! shell's reserved pad and needs no controls of ours. +/// macOS traffic-lights zone: the pad a leading titlebar strip reserves. +pub use crate::theme::TRAFFIC_LIGHT_PAD; #[cfg(target_os = "linux")] use gpui::Decorations; #[cfg(any(target_os = "windows", target_os = "linux"))] @@ -12,21 +14,21 @@ use gpui::SharedString; use gpui::Styled as _; #[cfg(any(target_os = "windows", target_os = "linux"))] use gpui::prelude::FluentBuilder as _; +use gpui::{App, ElementId, IntoElement, RenderOnce, Window, div}; #[cfg(any(target_os = "windows", target_os = "linux"))] -use gpui::{AnyElement, ParentElement as _, rems}; use gpui::{ - App, ClickEvent, Div, ElementId, InteractiveElement as _, IntoElement, MouseButton, RenderOnce, - Stateful, StatefulInteractiveElement as _, Window, WindowControlArea, div, + Div, InteractiveElement as _, ParentElement as _, Stateful, StatefulInteractiveElement as _, + WindowControlArea, rems, }; #[cfg(any(target_os = "windows", target_os = "linux"))] use crate::components::common::h_flex; #[cfg(any(target_os = "windows", target_os = "linux"))] -use crate::icons::{IconRole, icon}; +use crate::icons::{Icon, IconRole}; #[cfg(any(target_os = "windows", target_os = "linux"))] use crate::theme::ActiveTheme as _; -/// macOS traffic-lights zone: the pad a leading titlebar strip reserves. -pub use crate::theme::TRAFFIC_LIGHT_PAD; +#[cfg(any(target_os = "windows", target_os = "linux"))] +use crate::theme::OVERLAY_ICON_SIZE; #[cfg(target_os = "windows")] use crate::theme::{ WINDOWS_CAPTION_WIDTH as CAPTION_WIDTH, WINDOWS_CLOSE_FOREGROUND, WINDOWS_CLOSE_HOVER, @@ -47,6 +49,101 @@ impl WindowControls { { Self { id: id.into() } } + + /// One Windows caption button. + #[cfg(target_os = "windows")] + fn caption_button( + cx: &App, + id: ElementId, + role: IconRole, + area: WindowControlArea, + enabled: bool, + close: bool, + ) -> Stateful
{ + let theme = cx.theme(); + + let hover = if close { + WINDOWS_CLOSE_HOVER + } else { + theme.colors.muted_hover + }; + + div() + .id(id) + .debug_selector({ + let id = SharedString::from(format!("window-control-{}", role.slug())); + move || id.to_string() + }) + .occlude() + .flex() + .items_center() + .justify_center() + .w(CAPTION_WIDTH) + .h_full() + .window_control_area(area) + .text_color(if enabled { + theme.colors.foreground + } else { + theme.colors.muted_foreground + }) + .when(enabled, |button| { + button + .cursor_pointer() + .hover(|hovered| { + hovered.bg(hover).text_color(if close { + WINDOWS_CLOSE_FOREGROUND + } else { + theme.colors.foreground + }) + }) + .active(|pressed| { + pressed + .bg(if close { + WINDOWS_CLOSE_PRESSED + } else { + theme.ramps.secondary.pressed + }) + .text_color(theme.colors.foreground) + }) + }) + .child(Icon::from(role).size(OVERLAY_ICON_SIZE)) + } + + /// Adwaita's headerbar control: a small circle around a symbolic glyph. + #[cfg(target_os = "linux")] + fn circle_button( + cx: &App, + id: ElementId, + role: IconRole, + enabled: bool, + action: impl Fn(&mut Window, &mut App) + 'static, + ) -> Stateful
{ + let theme = cx.theme(); + + div() + .id(id) + .debug_selector(move || format!("window-control-{}", role.slug())) + .flex() + .items_center() + .justify_center() + .size_7() + .rounded(theme.radius.full) + .text_color(if enabled { + theme.colors.foreground + } else { + theme.colors.muted_foreground + }) + .when(enabled, |button| { + button + .cursor_pointer() + .hover(|hovered| hovered.bg(theme.colors.muted_hover)) + .on_click(move |_, window, cx| { + cx.stop_propagation(); + action(window, cx); + }) + }) + .child(Icon::from(role).size(OVERLAY_ICON_SIZE)) + } } impl RenderOnce for WindowControls { @@ -69,9 +166,9 @@ impl RenderOnce for WindowControls { .flex_row() .h_full() .when(controls.minimize, |row| { - row.child(caption_button( + row.child(Self::caption_button( cx, - SharedString::from(format!("{id}-minimize")), + ElementId::from((id.clone(), "minimize")), IconRole::WindowMinimize, WindowControlArea::Min, window.is_minimizable(), @@ -79,9 +176,9 @@ impl RenderOnce for WindowControls { )) }) .when(controls.maximize, |row| { - row.child(caption_button( + row.child(Self::caption_button( cx, - SharedString::from(format!("{id}-maximize")), + ElementId::from((id.clone(), "maximize")), if window.is_maximized() { IconRole::WindowRestore } else { @@ -92,9 +189,9 @@ impl RenderOnce for WindowControls { false, )) }) - .child(caption_button( + .child(Self::caption_button( cx, - SharedString::from(format!("{id}-close")), + ElementId::from((id, "close")), IconRole::Close, WindowControlArea::Close, true, @@ -113,18 +210,18 @@ impl RenderOnce for WindowControls { .h_full() .gap_1() .when(client_decorated && controls.minimize, |row| { - row.child(circle_button( + row.child(Self::circle_button( cx, - SharedString::from(format!("{id}-minimize")), + ElementId::from((id.clone(), "minimize")), IconRole::WindowMinimize, window.is_minimizable(), |window, _cx| window.minimize_window(), )) }) .when(client_decorated && controls.maximize, |row| { - row.child(circle_button( + row.child(Self::circle_button( cx, - SharedString::from(format!("{id}-maximize")), + ElementId::from((id.clone(), "maximize")), if window.is_maximized() { IconRole::WindowRestore } else { @@ -135,9 +232,9 @@ impl RenderOnce for WindowControls { )) }) .when(client_decorated, |row| { - row.child(circle_button( + row.child(Self::circle_button( cx, - SharedString::from(format!("{id}-close")), + ElementId::from((id, "close")), IconRole::Close, true, |window, _cx| window.remove_window(), @@ -154,161 +251,3 @@ impl RenderOnce for WindowControls { controls } } - -/// Double-click on a titlebar strip maximizes where the platform does not do it. -fn maximize_on_double_click() -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static { - move |event, window, _cx| { - if event.click_count() != 2 { - return; - } - #[cfg(target_os = "macos")] - window.titlebar_double_click(); - #[cfg(target_os = "linux")] - window.zoom_window(); - // Windows handles titlebar double-click natively via WindowControlArea::Drag. - #[cfg(target_os = "windows")] - { - let _ = (event, window); - } - #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] - { - let _ = (event, window); - } - } -} - -/// Makes an element a titlebar strip; `id` keys its drag state, which -/// `use_state` would otherwise share among every strip in the window. -pub fn titlebar_strip( - this: Stateful
, - id: I, - window: &mut Window, - cx: &mut App, -) -> Stateful
-where - I: Into, -{ - let should_move = window.use_keyed_state(id.into(), cx, |_, _| false); - this.window_control_area(WindowControlArea::Drag) - .on_mouse_down_out(window.listener_for(&should_move, |should_move, _, _, _| { - *should_move = false; - })) - .on_mouse_down( - MouseButton::Left, - window.listener_for(&should_move, |should_move, _, _, _| { - *should_move = true; - }), - ) - .on_mouse_up( - MouseButton::Left, - window.listener_for(&should_move, |should_move, _, _, _| { - *should_move = false; - }), - ) - .on_mouse_move( - window.listener_for(&should_move, |should_move, _, window, cx| { - if *should_move { - *should_move = false; - if !cx.has_active_drag() { - window.start_window_move(); - } - } - }), - ) - .on_click(maximize_on_double_click()) -} - -/// One Windows caption button. -#[cfg(target_os = "windows")] -fn caption_button( - cx: &App, - id: ElementId, - role: IconRole, - area: WindowControlArea, - enabled: bool, - close: bool, -) -> AnyElement { - let theme = cx.theme(); - - let hover = if close { - WINDOWS_CLOSE_HOVER - } else { - theme.colors.muted_hover - }; - - div() - .id(id) - .debug_selector({ - let id = SharedString::from(format!("window-control-{}", role.slug())); - move || id.to_string() - }) - .occlude() - .flex() - .items_center() - .justify_center() - .w(CAPTION_WIDTH) - .h_full() - .window_control_area(area) - .text_color(if enabled { - theme.colors.foreground - } else { - theme.colors.muted_foreground - }) - .when(enabled, |button| { - button - .cursor_pointer() - .hover(|hovered| { - hovered.bg(hover).text_color(if close { - WINDOWS_CLOSE_FOREGROUND - } else { - theme.colors.foreground - }) - }) - .active(|pressed| { - pressed - .bg(if close { - WINDOWS_CLOSE_PRESSED - } else { - theme.ramps.secondary.pressed - }) - .text_color(theme.colors.foreground) - }) - }) - .child(icon(role).size(crate::theme::OVERLAY_ICON_SIZE)) - .into_any_element() -} - -/// Adwaita's headerbar control: a small circle around a symbolic glyph. -#[cfg(target_os = "linux")] -fn circle_button(cx: &App, id: I, role: IconRole, enabled: bool, action: F) -> AnyElement -where - I: Into, - F: Fn(&mut Window, &mut App) + 'static, -{ - let theme = cx.theme(); - - div() - .id(id) - .debug_selector(move || format!("window-control-{}", role.slug())) - .flex() - .items_center() - .justify_center() - .size_7() - .rounded(theme.radius.full) - .text_color(if enabled { - theme.colors.foreground - } else { - theme.colors.muted_foreground - }) - .when(enabled, |button| { - button - .cursor_pointer() - .hover(|hovered| hovered.bg(theme.colors.muted_hover)) - .on_click(move |_, window, cx| { - cx.stop_propagation(); - action(window, cx); - }) - }) - .child(icon(role).size(crate::theme::OVERLAY_ICON_SIZE)) - .into_any_element() -} diff --git a/crates/ui/src/layout/window_frame.rs b/crates/ui/src/layout/window_frame.rs deleted file mode 100644 index 97d988f..0000000 --- a/crates/ui/src/layout/window_frame.rs +++ /dev/null @@ -1,176 +0,0 @@ -//! The client-side window frame: the border, corners, shadow, and resize -//! edges of a window the system does not decorate. - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - App, Bounds, BoxShadow, CursorStyle, Decorations, Div, HitboxBehavior, InteractiveElement as _, - IntoElement, MouseButton, ParentElement as _, Pixels, Point, ResizeEdge, Size, Styled as _, - Tiling, Window, canvas, div, point, px, size, -}; - -use crate::theme::{ActiveTheme as _, BORDER_WIDTH, INACTIVE_SHADOW_OPACITY, WINDOW_RESIZE_INSET}; - -/// Wraps a window's root in the frame it owes. -pub fn frame(child: E, window: &mut Window, cx: &App) -> Div -where - E: IntoElement, -{ - let Decorations::Client { tiling } = window.window_decorations() else { - return div().size_full().child(child); - }; - - let tiling = if window.is_maximized() { - Tiling::tiled() - } else { - tiling - }; - - let inset = WINDOW_RESIZE_INSET; - let border = cx.theme().colors.border; - let radius = cx.theme().radius.overlay; - - let shadow = frame_shadow(cx, window.is_window_active()); - window.set_client_inset(inset); - - div() - .size_full() - .child( - canvas( - move |_, window, _| { - let size = window.window_bounds().get_bounds().size; - bands(size, inset) - .into_iter() - .filter(|(edge, _)| live(*edge, tiling)) - .map(|(edge, band)| { - (edge, window.insert_hitbox(band, HitboxBehavior::Normal)) - }) - .collect::>() - }, - |_, bands, window, _| { - for (edge, band) in bands { - window.set_cursor_style(cursor(edge), &band); - } - }, - ) - .absolute() - .size_full(), - ) - .when(!tiling.top, |frame| frame.pt(inset)) - .when(!tiling.bottom, |frame| frame.pb(inset)) - .when(!tiling.left, |frame| frame.pl(inset)) - .when(!tiling.right, |frame| frame.pr(inset)) - .on_mouse_down(MouseButton::Left, move |event, window, _| { - let size = window.window_bounds().get_bounds().size; - if let Some(edge) = - resize_edge(event.position, inset, size).filter(|edge| live(*edge, tiling)) - { - window.start_window_resize(edge); - } - }) - .child( - div() - .size_full() - .overflow_hidden() - .border_color(border) - .when(!tiling.top, |surface| surface.border_t(BORDER_WIDTH)) - .when(!tiling.bottom, |surface| surface.border_b(BORDER_WIDTH)) - .when(!tiling.left, |surface| surface.border_l(BORDER_WIDTH)) - .when(!tiling.right, |surface| surface.border_r(BORDER_WIDTH)) - .when(!(tiling.top || tiling.left), |surface| { - surface.rounded_tl(radius) - }) - .when(!(tiling.top || tiling.right), |surface| { - surface.rounded_tr(radius) - }) - .when(!(tiling.bottom || tiling.left), |surface| { - surface.rounded_bl(radius) - }) - .when(!(tiling.bottom || tiling.right), |surface| { - surface.rounded_br(radius) - }) - .when(!tiling.is_tiled(), |surface| surface.shadow(shadow)) - .child(child), - ) -} - -/// The dialog elevation's shadow, dimmed while the window is inactive. -fn frame_shadow(cx: &App, active: bool) -> Vec { - let opacity = if active { 1.0 } else { INACTIVE_SHADOW_OPACITY }; - cx.theme() - .elevations - .dialog - .shadows() - .iter() - .map(|shadow| { - let mut dimmed = shadow.clone(); - dimmed.color.a *= opacity; - dimmed - }) - .collect() -} - -/// Which edge a press at `pos` resizes, or `None` for a press on the content. -fn resize_edge(pos: Point, inset: Pixels, size: Size) -> Option { - let (top, bottom) = (pos.y < inset, pos.y > size.height - inset); - let (left, right) = (pos.x < inset, pos.x > size.width - inset); - - Some(match (top, bottom, left, right) { - (true, _, true, _) => ResizeEdge::TopLeft, - (true, _, _, true) => ResizeEdge::TopRight, - (_, true, true, _) => ResizeEdge::BottomLeft, - (_, true, _, true) => ResizeEdge::BottomRight, - (true, ..) => ResizeEdge::Top, - (_, true, ..) => ResizeEdge::Bottom, - (_, _, true, _) => ResizeEdge::Left, - (_, _, _, true) => ResizeEdge::Right, - _ => return None, - }) -} - -/// The eight bands, as the rects [`resize_edge`] classifies to. -fn bands(window: Size, inset: Pixels) -> [(ResizeEdge, Bounds); 8] { - let band = |x: Pixels, y: Pixels, width: Pixels, height: Pixels| Bounds { - origin: point(x, y), - size: size(width, height), - }; - - let (far_x, far_y) = (window.width - inset, window.height - inset); - let (span_x, span_y) = (window.width - inset - inset, window.height - inset - inset); - let zero = px(0.0); - - [ - (ResizeEdge::TopLeft, band(zero, zero, inset, inset)), - (ResizeEdge::TopRight, band(far_x, zero, inset, inset)), - (ResizeEdge::BottomLeft, band(zero, far_y, inset, inset)), - (ResizeEdge::BottomRight, band(far_x, far_y, inset, inset)), - (ResizeEdge::Top, band(inset, zero, span_x, inset)), - (ResizeEdge::Bottom, band(inset, far_y, span_x, inset)), - (ResizeEdge::Left, band(zero, inset, inset, span_y)), - (ResizeEdge::Right, band(far_x, inset, inset, span_y)), - ] -} - -/// Whether `edge` resizes: none of the sides it touches is flush. -fn live(edge: ResizeEdge, tiling: Tiling) -> bool { - let (top, bottom, left, right) = match edge { - ResizeEdge::Top => (true, false, false, false), - ResizeEdge::Bottom => (false, true, false, false), - ResizeEdge::Left => (false, false, true, false), - ResizeEdge::Right => (false, false, false, true), - ResizeEdge::TopLeft => (true, false, true, false), - ResizeEdge::TopRight => (true, false, false, true), - ResizeEdge::BottomLeft => (false, true, true, false), - ResizeEdge::BottomRight => (false, true, false, true), - }; - !(top && tiling.top || bottom && tiling.bottom || left && tiling.left || right && tiling.right) -} - -/// The pointer an edge shows. -fn cursor(edge: ResizeEdge) -> CursorStyle { - match edge { - ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown, - ResizeEdge::Left | ResizeEdge::Right => CursorStyle::ResizeLeftRight, - ResizeEdge::TopLeft | ResizeEdge::BottomRight => CursorStyle::ResizeUpLeftDownRight, - ResizeEdge::TopRight | ResizeEdge::BottomLeft => CursorStyle::ResizeUpRightDownLeft, - } -} diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index 5d12738..5344ecf 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -12,9 +12,11 @@ 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); - components::combobox::bind_combobox_keys(cx); - components::command_palette::bind_command_palette_keys(cx); - components::code::bind_code_view_keys(cx); - components::markdown::bind_text_view_keys(cx); + components::input::InputState::bind_keys(cx); + components::combobox::Combobox::<()>::bind_keys(cx); + components::command_palette::CommandPaletteState::bind_keys(cx); + components::code::CodeViewState::bind_keys(cx); + components::markdown::MarkdownViewState::bind_keys(cx); + components::menu::Menu::bind_keys(cx); + components::dialog::Dialog::bind_keys(cx); } diff --git a/crates/ui/src/theme/colors.rs b/crates/ui/src/theme/colors.rs index 03664a5..65707a6 100644 --- a/crates/ui/src/theme/colors.rs +++ b/crates/ui/src/theme/colors.rs @@ -1,7 +1,7 @@ //! Semantic color roles. This module is the only place in the workspace //! allowed to hold color literals. -use gpui::{Hsla, hsla, rgb}; +use gpui::{Hsla, hsla, rgb, white}; use crate::theme::{ DEFAULT_TRANSPARENCY, MIN_MATERIAL_FILL_DARK, MIN_MATERIAL_FILL_LIGHT, ThemeVariant, @@ -12,7 +12,7 @@ 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(); +pub const WINDOWS_CLOSE_FOREGROUND: Hsla = white(); /// The semantic color roles components paint from. #[derive(Clone, Copy, Debug, PartialEq)] @@ -52,32 +52,32 @@ impl ColorTokens { /// Neutral light palette; the fallback when no system theme applies. pub fn light() -> Self { Self { - background: hex(0xffffff), - foreground: hex(0x18181b), - surface: hex(0xfafafa), - surface_foreground: hex(0x18181b), - primary: hex(0x2563eb), - primary_foreground: hex(0xffffff), - secondary: hex(0xf4f4f5), - secondary_foreground: hex(0x18181b), - muted: hex(0xf4f4f5), - muted_hover: hex(0xe4e4e7), - muted_foreground: hex(0x71717a), - accent: hex(0x2563eb), - accent_foreground: hex(0xffffff), - destructive: hex(0xdc2626), - destructive_foreground: hex(0xffffff), - success: hex(0x16a34a), - success_foreground: hex(0xffffff), - warning: hex(0xd97706), - warning_foreground: hex(0xffffff), - info: hex(0x0284c7), - info_foreground: hex(0xffffff), - border: hex(0xe4e4e7), - input: hex(0xffffff), - ring: hex(0x2563eb), - selection: hex(0xdbeafe), - overlay: scrim(0.25), + background: Self::hex(0xffffff), + foreground: Self::hex(0x18181b), + surface: Self::hex(0xfafafa), + surface_foreground: Self::hex(0x18181b), + primary: Self::hex(0x2563eb), + primary_foreground: Self::hex(0xffffff), + secondary: Self::hex(0xf4f4f5), + secondary_foreground: Self::hex(0x18181b), + muted: Self::hex(0xf4f4f5), + muted_hover: Self::hex(0xe4e4e7), + muted_foreground: Self::hex(0x71717a), + accent: Self::hex(0x2563eb), + accent_foreground: Self::hex(0xffffff), + destructive: Self::hex(0xdc2626), + destructive_foreground: Self::hex(0xffffff), + success: Self::hex(0x16a34a), + success_foreground: Self::hex(0xffffff), + warning: Self::hex(0xd97706), + warning_foreground: Self::hex(0xffffff), + info: Self::hex(0x0284c7), + info_foreground: Self::hex(0xffffff), + border: Self::hex(0xe4e4e7), + input: Self::hex(0xffffff), + ring: Self::hex(0x2563eb), + selection: Self::hex(0xdbeafe), + overlay: Self::scrim(0.25), // macOS light overlay thumbs are translucent black. scrollbar_thumb: hsla(0., 0., 0., 0.25), } @@ -86,36 +86,46 @@ impl ColorTokens { /// Neutral dark palette; the fallback when no system theme applies. pub fn dark() -> Self { Self { - background: hex(0x09090b), - foreground: hex(0xfafafa), - surface: hex(0x18181b), - surface_foreground: hex(0xfafafa), - primary: hex(0x3b82f6), - primary_foreground: hex(0xffffff), - secondary: hex(0x27272a), - secondary_foreground: hex(0xfafafa), - muted: hex(0x27272a), - muted_hover: hex(0x3f3f46), - muted_foreground: hex(0xa1a1aa), - accent: hex(0x3b82f6), - accent_foreground: hex(0xffffff), - destructive: hex(0xef4444), - destructive_foreground: hex(0xffffff), - success: hex(0x22c55e), - success_foreground: hex(0x052e16), - warning: hex(0xf59e0b), - warning_foreground: hex(0x451a03), - info: hex(0x38bdf8), - info_foreground: hex(0x082f49), - border: hex(0x27272a), - input: hex(0x09090b), - ring: hex(0x3b82f6), - selection: hex(0x1e3a8a), - overlay: scrim(0.45), + background: Self::hex(0x09090b), + foreground: Self::hex(0xfafafa), + surface: Self::hex(0x18181b), + surface_foreground: Self::hex(0xfafafa), + primary: Self::hex(0x3b82f6), + primary_foreground: Self::hex(0xffffff), + secondary: Self::hex(0x27272a), + secondary_foreground: Self::hex(0xfafafa), + muted: Self::hex(0x27272a), + muted_hover: Self::hex(0x3f3f46), + muted_foreground: Self::hex(0xa1a1aa), + accent: Self::hex(0x3b82f6), + accent_foreground: Self::hex(0xffffff), + destructive: Self::hex(0xef4444), + destructive_foreground: Self::hex(0xffffff), + success: Self::hex(0x22c55e), + success_foreground: Self::hex(0x052e16), + warning: Self::hex(0xf59e0b), + warning_foreground: Self::hex(0x451a03), + info: Self::hex(0x38bdf8), + info_foreground: Self::hex(0x082f49), + border: Self::hex(0x27272a), + input: Self::hex(0x09090b), + ring: Self::hex(0x3b82f6), + selection: Self::hex(0x1e3a8a), + overlay: Self::scrim(0.45), // macOS dark overlay thumbs are translucent light gray. scrollbar_thumb: hsla(0., 0., 1., 0.3), } } + + /// An opaque `0xrrggbb` color. + 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) + } } /// The translucent paints surfaces lay over a native window material. @@ -162,12 +172,3 @@ impl MaterialTokens { } } } - -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/definition.rs b/crates/ui/src/theme/definition.rs index 1fbf7a7..a965d3c 100644 --- a/crates/ui/src/theme/definition.rs +++ b/crates/ui/src/theme/definition.rs @@ -7,6 +7,10 @@ use serde::Deserialize; use crate::theme::ThemeVariant; +/// The bundled presets: `(name, TOML source)`. Enumeration and lookup both +/// read this one table. +const PRESETS: &[(&str, &str)] = &[("tokyo-night", include_str!("presets/tokyo-night.toml"))]; + #[derive(Clone, Debug, Default, PartialEq, Deserialize)] pub struct ThemeDefinition { mode: Option, @@ -51,6 +55,44 @@ impl ThemeDefinition { self.mode } + /// Parses `#rgb` or `#rrggbb` into an opaque color. + pub fn parse_hex(value: &str) -> Option { + let digits = value.strip_prefix('#')?; + // Lengths are byte lengths; non-ASCII input would panic the slicing below. + if !digits.is_ascii() { + return None; + } + + let expand_rgb = |[r, g, b]: [f32; 3]| Hsla::from(Rgba { r, g, b, a: 1.0 }); + let expand = |channels: [f32; 3]| Some(expand_rgb(channels)); + + match digits.len() { + 3 => { + let mut channels = [0u8; 3]; + for (i, byte) in channels.iter_mut().enumerate() { + *byte = u8::from_str_radix(&digits[i..i + 1], 16).ok()?; + } + expand([ + channels[0] as f32 / 15.0, + channels[1] as f32 / 15.0, + channels[2] as f32 / 15.0, + ]) + } + 6 => { + let mut channels = [0u8; 3]; + for (i, byte) in channels.iter_mut().enumerate() { + *byte = u8::from_str_radix(&digits[i * 2..i * 2 + 2], 16).ok()?; + } + expand([ + channels[0] as f32 / 255.0, + channels[1] as f32 / 255.0, + channels[2] as f32 / 255.0, + ]) + } + _ => None, + } + } + pub fn control_radius(&self) -> Option { self.control_radius } @@ -174,7 +216,7 @@ impl ThemeDefinition { /// Parses a color field, warning when a stated value is malformed. fn color(&self, field: &Option, role: &str) -> Option { let value = field.as_deref()?; - match parse_hex(value) { + match Self::parse_hex(value) { Some(color) => Some(color), None => { log::warn!("theme definition {role} is not #rgb/#rrggbb: {value:?}"); @@ -182,63 +224,25 @@ impl ThemeDefinition { } } } -} -/// Parses `#rgb` or `#rrggbb` into an opaque color. -pub(crate) fn parse_hex(value: &str) -> Option { - let digits = value.strip_prefix('#')?; - // Lengths are byte lengths; non-ASCII input would panic the slicing below. - if !digits.is_ascii() { - return None; + /// Every bundled preset's name. + pub fn preset_names() -> impl Iterator { + PRESETS.iter().map(|(name, _)| *name) } - let expand = |channels: [f32; 3]| Some(expand_rgb([channels[0], channels[1], channels[2]])); - match digits.len() { - 3 => { - let mut channels = [0u8; 3]; - for (i, byte) in channels.iter_mut().enumerate() { - *byte = u8::from_str_radix(&digits[i..i + 1], 16).ok()?; + /// Parses the named preset, returning its static name and definition. + pub fn builtin(name: &str) -> Option<(&'static str, Self)> { + let (name, source) = PRESETS + .iter() + .find(|(candidate, _)| *candidate == name) + .copied()?; + + match Self::parse_toml(source) { + Ok(definition) => Some((name, definition)), + Err(error) => { + log::error!("bundled preset {name} failed to parse: {error}"); + None } - expand([ - channels[0] as f32 / 15.0, - channels[1] as f32 / 15.0, - channels[2] as f32 / 15.0, - ]) } - 6 => { - let mut channels = [0u8; 3]; - for (i, byte) in channels.iter_mut().enumerate() { - *byte = u8::from_str_radix(&digits[i * 2..i * 2 + 2], 16).ok()?; - } - expand([ - channels[0] as f32 / 255.0, - channels[1] as f32 / 255.0, - channels[2] as f32 / 255.0, - ]) - } - _ => None, - } -} - -fn expand_rgb([r, g, b]: [f32; 3]) -> Hsla { - Hsla::from(Rgba { r, g, b, a: 1.0 }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_hex_rejects_non_ascii_digits() { - assert_eq!(parse_hex("#éa"), None); - assert_eq!(parse_hex("#éaabbcc"), None); - } - - #[test] - fn parse_hex_resolves_three_and_six_digits() { - assert!(parse_hex("#abc").is_some()); - assert!(parse_hex("#aabbcc").is_some()); - assert_eq!(parse_hex("abc"), None); - assert_eq!(parse_hex("#ab"), None); } } diff --git a/crates/ui/src/theme/mod.rs b/crates/ui/src/theme/mod.rs index 9195124..ee7dda8 100644 --- a/crates/ui/src/theme/mod.rs +++ b/crates/ui/src/theme/mod.rs @@ -8,12 +8,12 @@ mod colors; mod definition; -mod presets; mod ramps; mod resolve; mod source; mod system; +use std::sync::Arc; use std::time::Duration; pub use colors::{ @@ -22,11 +22,13 @@ pub use colors::{ }; pub use definition::ThemeDefinition; use gpui::{ - App, Global, Hsla, Pixels, Rems, SpringConfig, WindowAppearance, WindowBackgroundAppearance, - px, rems, + App, BoxShadow, Global, Hsla, Pixels, Rems, SpringConfig, Window, WindowAppearance, + WindowBackgroundAppearance, point, px, rems, }; pub use ramps::{AccentShades, Oklch}; pub use resolve::{Ramps, ResolvedTheme}; +use source::fallback::FallbackSource; +use source::{ThemeSource, platform_source}; pub use system::{AccessibilityPreferences, SourceKind, SystemTheme}; /// The hairline width of the control border every button and field paints. @@ -130,6 +132,25 @@ pub const DEFAULT_TRANSPARENCY: u8 = 80; pub const MIN_MATERIAL_FILL_LIGHT: f32 = 0.45; /// The dark-mode floor of the material fill. pub const MIN_MATERIAL_FILL_DARK: f32 = 0.15; + +/// Reads the resolved theme global from any app context. +pub trait ActiveTheme { + fn theme(&self) -> &Theme; + + /// The engine that produced [`Self::theme`]. + fn theme_engine(&self) -> &ThemeEngine; +} + +impl ActiveTheme for App { + fn theme(&self) -> &Theme { + Theme::global(self) + } + + fn theme_engine(&self) -> &ThemeEngine { + self.global::() + } +} + /// The opacity of the grain overlay's noise. pub const GRAIN_ALPHA: f32 = 0.08; @@ -172,7 +193,7 @@ pub enum Size { } /// The resolved theme, installed as the app-wide global. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq)] pub struct Theme { pub variant: ThemeVariant, pub colors: ColorTokens, @@ -227,31 +248,67 @@ impl Theme { } } - /// Installs the engine global, its platform watchers, and the initial resolved theme. + /// Installs the engine with the platform source, its watchers, and the initial theme. pub fn init(cx: &mut App) { + Self::init_with(cx, platform_source()); + } + + /// Installs the engine with the given source, its watchers, and the initial theme. + pub fn init_with(cx: &mut App, source: Box) { let mut engine = ThemeEngine { - source: source::platform_source(), + source, mode_override: None, preset: None, custom: None, }; engine.source.install_watchers(cx.to_async()); cx.set_global(engine); - reapply(cx); + ThemeEngine::reapply(cx); + } + + /// The source that reads no platform state, for tests. + pub fn fallback_source() -> Box { + Box::new(FallbackSource) + } + + /// The focus ring's shadow, at half ink. + pub fn focus_ring(&self) -> Vec { + vec![ + BoxShadow::new(px(0.), px(0.), self.colors.ring.alpha(FOCUS_RING_ALPHA)) + .spread_radius(FOCUS_RING_SPREAD), + ] + } + + /// A selectable row's label and icon color. + pub fn selectable_label_color(&self, selected: bool, disabled: bool) -> Hsla { + if disabled { + self.colors.muted_foreground + } else if selected { + self.colors.primary_foreground + } else { + self.colors.foreground + } } /// Synchronizes the theme from the window's appearance. - pub fn sync_from_window(window: &mut gpui::Window, cx: &mut App) { + pub fn sync_from_window(window: &mut Window, cx: &mut App) { let window_variant = ThemeVariant::from_appearance(window.appearance()); let theme = cx.global::(); let engine = cx.global::(); - if engine.mode_override.is_none() && theme.variant != window_variant { - reapply(cx); + if engine.mode_override.is_none() + && engine + .preset + .as_ref() + .and_then(|(_, def)| def.mode()) + .is_none() + && theme.variant != window_variant + { + ThemeEngine::reapply(cx); } } /// Sizes the window's rem to the theme's root font size. - pub fn sync_window_rem_size(window: &mut gpui::Window, cx: &App) { + pub fn sync_window_rem_size(window: &mut Window, cx: &App) { let theme = cx.global::(); window.set_rem_size(theme.root_font_size); } @@ -298,7 +355,7 @@ impl Shadow { offset_y: px(0.), blur_radius: px(0.), spread_radius: px(0.), - color: colors::scrim(0.), + color: ColorTokens::scrim(0.), } } @@ -308,40 +365,51 @@ impl Shadow { offset_y: px(offset_y), blur_radius: px(blur_radius), spread_radius: px(0.), - color: colors::scrim(alpha), + color: ColorTokens::scrim(alpha), } } } /// The drop shadow stack of a floating layer. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq)] pub struct Elevation { /// Key shadow first, ambient grounding second. pub layers: [Shadow; 2], + /// The gpui shadow stack an overlay panel paints with. + shadows: Arc<[BoxShadow]>, } impl Elevation { + fn new(layers: [Shadow; 2]) -> Self { + let shadows = layers + .iter() + .filter(|layer| layer.color.a > 0.) + .map(|layer| BoxShadow { + color: layer.color, + offset: point(layer.offset_x, layer.offset_y), + blur_radius: layer.blur_radius, + spread_radius: layer.spread_radius, + inset: false, + }) + .collect(); + Self { layers, shadows } + } + /// No shadow: dark floating layers separate by border. fn none() -> Self { - Self { - layers: [Shadow::none(), Shadow::none()], - } + Self::new([Shadow::none(), Shadow::none()]) } fn single(key: Shadow) -> Self { - Self { - layers: [key, Shadow::none()], - } + Self::new([key, Shadow::none()]) } fn layered(key: Shadow, ambient: Shadow) -> Self { - Self { - layers: [key, ambient], - } + Self::new([key, ambient]) } /// How far the shadow layers paint past the element's bounds. - pub fn bleed(self) -> Pixels { + pub fn bleed(&self) -> Pixels { self.layers.iter().fold(px(0.), |bleed, layer| { if layer.color.a > 0. { bleed.max( @@ -356,23 +424,13 @@ impl Elevation { } /// The gpui shadow list an overlay panel paints with. - pub fn shadows(self) -> Vec { - self.layers - .iter() - .filter(|layer| layer.color.a > 0.) - .map(|layer| gpui::BoxShadow { - color: layer.color, - offset: gpui::point(layer.offset_x, layer.offset_y), - blur_radius: layer.blur_radius, - spread_radius: layer.spread_radius, - inset: false, - }) - .collect() + pub fn shadows(&self) -> Arc<[BoxShadow]> { + Arc::clone(&self.shadows) } } /// The drop shadows of each floating layer class. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq)] pub struct Elevations { /// Popovers, menus, and pushed alerts ride above content. pub popover: Elevation, @@ -446,7 +504,7 @@ impl Default for Scrollbar { } /// User customizations layered over the resolved theme. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct CustomTheme { pub root_font_size: Option, pub sm_radius: Option, @@ -462,8 +520,8 @@ pub struct CustomTheme { } /// The engine's knobs and its platform source. -struct ThemeEngine { - source: Box, +pub struct ThemeEngine { + source: Box, mode_override: Option, preset: Option<(&'static str, ThemeDefinition)>, custom: Option, @@ -471,107 +529,93 @@ struct ThemeEngine { impl Global for ThemeEngine {} -/// Reads the resolved theme global from any app context. -pub trait ActiveTheme { - fn theme(&self) -> &Theme; -} +impl ThemeEngine { + /// Reapplies the theme to the application. + pub(crate) fn reapply(cx: &mut App) { + let (preset, mode_override, custom, system) = { + let engine = cx.global::(); + let system_appearance = ThemeVariant::from_appearance(cx.window_appearance()); + let preset = engine.preset.as_ref().map(|(_, def)| def.clone()); + let mode_override = engine.mode_override; + let custom = engine.custom.clone(); + let variant = mode_override + .or(preset.as_ref().and_then(|def| def.mode())) + .unwrap_or(system_appearance); + ( + preset, + mode_override, + custom, + engine.source.snapshot(variant), + ) + }; -impl ActiveTheme for App { - fn theme(&self) -> &Theme { - Theme::global(self) + let resolved = ResolvedTheme::resolve(&system, preset.as_ref(), mode_override, custom); + + cx.set_reduce_motion(resolved.accessibility.reduce_motion); + let theme = Theme::from_resolved(resolved); + let theme_changed = cx.try_global::() != Some(&theme); + if theme_changed { + cx.set_global(theme); + cx.refresh_windows(); + } } -} -/// Reapplies the theme to the application. -pub(crate) fn reapply(cx: &mut App) { - let (preset, mode_override, custom, system) = { - let engine = cx.global::(); - let system_appearance = ThemeVariant::from_appearance(cx.window_appearance()); - let preset = engine.preset.as_ref().map(|(_, def)| def.clone()); - let mode_override = engine.mode_override; - let custom = engine.custom; - let variant = mode_override - .or(preset.as_ref().and_then(|def| def.mode())) - .unwrap_or(system_appearance); - ( - preset, - mode_override, - custom, - engine.source.snapshot(variant), - ) - }; - - let resolved = resolve::resolve(&system, preset.as_ref(), mode_override, custom); - - cx.set_reduce_motion(resolved.accessibility.reduce_motion); - let theme = Theme::from_resolved(resolved); - let theme_changed = cx.try_global::() != Some(&theme); - cx.set_global(theme); - if theme_changed { - cx.refresh_windows(); + /// Forces a variant, independent of the OS. `None` follows the system. + pub fn set_mode_override(variant: Option, cx: &mut App) { + cx.global_mut::().mode_override = variant; + Self::reapply(cx); } -} -/// Forces a variant, independent of the OS. `None` follows the system. -pub fn set_mode_override(variant: Option, cx: &mut App) { - let engine = cx.global_mut::(); - engine.mode_override = variant; - reapply(cx); -} - -/// Installs a built-in preset, or `None` to follow the system again. -pub fn set_preset(name: Option<&str>, cx: &mut App) -> anyhow::Result<()> { - let preset = name - .map(|name| { - presets::builtin(name).ok_or_else(|| { - anyhow::anyhow!( - "unknown preset: {name}; available: {}", - presets::preset_names().collect::>().join(", ") - ) + /// Installs a built-in preset, or `None` to follow the system again. + pub fn set_preset(name: Option<&str>, cx: &mut App) -> anyhow::Result<()> { + let preset = name + .map(|name| { + ThemeDefinition::builtin(name).ok_or_else(|| { + anyhow::anyhow!( + "unknown preset: {name}; available: {}", + ThemeDefinition::preset_names() + .collect::>() + .join(", ") + ) + }) }) - }) - .transpose()?; - let engine = cx.global_mut::(); - engine.preset = preset; - reapply(cx); - Ok(()) -} + .transpose()?; + cx.global_mut::().preset = preset; + Self::reapply(cx); + Ok(()) + } -/// Installs the user's custom theme, or `None` to follow the current scheme. -pub fn set_custom_theme(custom: Option, cx: &mut App) { - let engine = cx.global_mut::(); - engine.custom = custom; - reapply(cx); -} + /// Installs the user's custom theme, or `None` to follow the current scheme. + pub fn set_custom_theme(custom: Option, cx: &mut App) { + cx.global_mut::().custom = custom; + Self::reapply(cx); + } -/// The variant the mode override forces, if any. -pub fn mode_override(cx: &App) -> Option { - let engine = cx.global::(); - engine.mode_override -} + /// Clears the mode override and preset; the theme follows the system again. + pub fn follow_system(cx: &mut App) { + let engine = cx.global_mut::(); + engine.mode_override = None; + engine.preset = None; + Self::reapply(cx); + } -/// The installed custom theme, if any. -pub fn custom_theme(cx: &App) -> Option { - let engine = cx.global::(); - engine.custom -} + /// The variant the mode override forces, if any. + pub fn mode_override(&self) -> Option { + self.mode_override + } -/// The active preset name, if one is installed. -pub fn active_preset(cx: &App) -> Option<&'static str> { - let engine = cx.global::(); - engine.preset.as_ref().map(|(name, _)| *name) -} + /// The installed custom theme, if any. + pub fn custom_theme(&self) -> Option { + self.custom.clone() + } -/// Clears the mode override and preset; the theme follows the system again. -pub fn follow_system(cx: &mut App) { - let engine = cx.global_mut::(); - engine.mode_override = None; - engine.preset = None; - reapply(cx); -} + /// The active preset name, if one is installed. + pub fn active_preset(&self) -> Option<&'static str> { + self.preset.as_ref().map(|(name, _)| *name) + } -/// Which adapter produced the current system snapshot. -pub fn detected_source(cx: &App) -> &'static str { - let engine = cx.global::(); - engine.source.label() + /// Which adapter produced the current system snapshot. + pub fn detected_source(&self) -> &'static str { + self.source.label() + } } diff --git a/crates/ui/src/theme/presets.rs b/crates/ui/src/theme/presets.rs deleted file mode 100644 index 1a011cc..0000000 --- a/crates/ui/src/theme/presets.rs +++ /dev/null @@ -1,27 +0,0 @@ -//! Built-in `ThemeDefinition` presets (D11). - -use crate::theme::definition::ThemeDefinition; - -/// The bundled presets: `(name, TOML source)`. Enumeration and lookup both -/// read this one table. -const PRESETS: &[(&str, &str)] = &[("tokyo-night", include_str!("presets/tokyo-night.toml"))]; - -/// Every bundled preset's name. -pub fn preset_names() -> impl Iterator { - PRESETS.iter().map(|(name, _)| *name) -} - -/// Parses the named preset, returning its static name and definition. -pub fn builtin(name: &str) -> Option<(&'static str, ThemeDefinition)> { - let (name, source) = PRESETS - .iter() - .find(|(candidate, _)| *candidate == name) - .copied()?; - match ThemeDefinition::parse_toml(source) { - Ok(definition) => Some((name, definition)), - Err(error) => { - log::error!("bundled preset {name} failed to parse: {error}"); - None - } - } -} diff --git a/crates/ui/src/theme/ramps.rs b/crates/ui/src/theme/ramps.rs index a795120..07cbaf8 100644 --- a/crates/ui/src/theme/ramps.rs +++ b/crates/ui/src/theme/ramps.rs @@ -19,12 +19,12 @@ pub struct Oklch { impl Oklch { pub fn from_hsla(color: Hsla) -> Self { let Rgba { r, g, b, a } = Rgba::from(color); - let (l, c, h) = rgb_to_oklch(r, g, b); + let (l, c, h) = Self::from_rgb(r, g, b); Self { l, c, h, a } } pub fn to_hsla(self) -> Hsla { - let (r, g, b) = oklch_to_rgb(self.l, self.c, self.h); + let (r, g, b) = self.to_rgb(); Hsla::from(Rgba { r, g, b, a: self.a }) } @@ -38,6 +38,125 @@ impl Oklch { a: self.a, } } + + /// Mixes `self` toward `b` by `t` in OKLCH, taking the shortest arc between hues. + /// + /// `t = 0` returns `self`, `t = 1` returns `b`. + pub fn mix(self, b: Oklch, t: f32) -> Oklch { + let a = self; + let mut dh = b.h - a.h; + + if dh > 180.0 { + dh -= 360.0; + } else if dh < -180.0 { + dh += 360.0; + } + + Oklch { + l: a.l + (b.l - a.l) * t, + c: a.c + (b.c - a.c) * t, + h: (a.h + dh * t + 360.0) % 360.0, + a: a.a + (b.a - a.a) * t, + } + } + + /// Calculate the foreground color that provides sufficient contrast against the background. + pub fn contrast_foreground(background: Hsla) -> Hsla { + const MIN_CONTRAST: f32 = 3.0; + + let Rgba { r, g, b, .. } = Rgba::from(background); + + let luminance = + 0.2126 * Self::linearize(r) + 0.7152 * Self::linearize(g) + 0.0722 * Self::linearize(b); + let white_contrast = 1.05 / (luminance + 0.05); + let black_contrast = (luminance + 0.05) / 0.05; + + let white = Hsla::from(Rgba { + r: 1.0, + g: 1.0, + b: 1.0, + a: 1.0, + }); + + let black = Hsla::from(Rgba { + r: 0.0, + g: 0.0, + b: 0.0, + a: 1.0, + }); + + if white_contrast >= MIN_CONTRAST || white_contrast >= black_contrast { + white + } else { + black + } + } + + /// Linear sRGB to OKLCH. + fn from_rgb(r: f32, g: f32, b: f32) -> (f32, f32, f32) { + let (r, g, b) = (Self::linearize(r), Self::linearize(g), Self::linearize(b)); + let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b; + let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b; + let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b; + + let (l_, m_, s_) = (Self::cbrt(l), Self::cbrt(m), Self::cbrt(s)); + let lab_l = 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_; + let lab_a = 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_; + let lab_b = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_; + + let c = (lab_a * lab_a + lab_b * lab_b).sqrt(); + let mut h = lab_b.atan2(lab_a).to_degrees(); + + if h < 0.0 { + h += 360.0; + } + + (lab_l, c, h) + } + + fn to_rgb(self) -> (f32, f32, f32) { + let hr = self.h.to_radians(); + let lab_a = self.c * hr.cos(); + let lab_b = self.c * hr.sin(); + + let l_ = self.l + 0.3963377774 * lab_a + 0.2158037573 * lab_b; + let m_ = self.l - 0.1055613458 * lab_a - 0.0638541728 * lab_b; + let s_ = self.l - 0.0894841775 * lab_a - 1.2914855480 * lab_b; + + let l = l_ * l_ * l_; + let m = m_ * m_ * m_; + let s = s_ * s_ * s_; + + let r = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s; + let g = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s; + let b = -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s; + + ( + Self::delinearize(r), + Self::delinearize(g), + Self::delinearize(b), + ) + } + + fn linearize(c: f32) -> f32 { + if c <= 0.04045 { + c / 12.92 + } else { + ((c + 0.055) / 1.055).powf(2.4) + } + } + + fn delinearize(c: f32) -> f32 { + if c <= 0.0031308 { + c * 12.92 + } else { + 1.055 * c.powf(1.0 / 2.4) - 0.055 + } + } + + fn cbrt(v: f32) -> f32 { + if v >= 0.0 { v.cbrt() } else { -(-v).cbrt() } + } } /// The state shades components paint from for one accent color. @@ -50,131 +169,21 @@ pub struct AccentShades { 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`. -pub fn mix(a: Oklch, b: Oklch, t: f32) -> Oklch { - let mut dh = b.h - a.h; - - if dh > 180.0 { - dh -= 360.0; - } else if dh < -180.0 { - dh += 360.0; - } - - Oklch { - l: a.l + (b.l - a.l) * t, - c: a.c + (b.c - a.c) * t, - h: (a.h + dh * t + 360.0) % 360.0, - a: a.a + (b.a - a.a) * t, - } -} - -fn rgb_to_oklch(r: f32, g: f32, b: f32) -> (f32, f32, f32) { - let (r, g, b) = (linearize(r), linearize(g), linearize(b)); - let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b; - let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b; - let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b; - - let (l_, m_, s_) = (cbrt(l), cbrt(m), cbrt(s)); - let lab_l = 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_; - let lab_a = 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_; - let lab_b = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_; - - let c = (lab_a * lab_a + lab_b * lab_b).sqrt(); - let mut h = lab_b.atan2(lab_a).to_degrees(); - - if h < 0.0 { - h += 360.0; - } - - (lab_l, c, h) -} - -fn oklch_to_rgb(l: f32, c: f32, h: f32) -> (f32, f32, f32) { - let hr = h.to_radians(); - let lab_a = c * hr.cos(); - let lab_b = c * hr.sin(); - - let l_ = l + 0.3963377774 * lab_a + 0.2158037573 * lab_b; - let m_ = l - 0.1055613458 * lab_a - 0.0638541728 * lab_b; - let s_ = l - 0.0894841775 * lab_a - 1.2914855480 * lab_b; - - let l = l_ * l_ * l_; - let m = m_ * m_ * m_; - let s = s_ * s_ * s_; - - let r = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s; - let g = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s; - let b = -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s; - - (delinearize(r), delinearize(g), delinearize(b)) -} - -fn linearize(c: f32) -> f32 { - if c <= 0.04045 { - c / 12.92 - } else { - ((c + 0.055) / 1.055).powf(2.4) - } -} - -fn delinearize(c: f32) -> f32 { - if c <= 0.0031308 { - c * 12.92 - } else { - 1.055 * c.powf(1.0 / 2.4) - 0.055 - } -} - -fn cbrt(v: f32) -> f32 { - if v >= 0.0 { v.cbrt() } else { -(-v).cbrt() } -} - -/// Calculate the foreground color that provides sufficient contrast against the background. -pub fn contrast_foreground(background: Hsla) -> Hsla { - const MIN_CONTRAST: f32 = 3.0; - - let Rgba { r, g, b, .. } = Rgba::from(background); - - let luminance = 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b); - let white_contrast = 1.05 / (luminance + 0.05); - let black_contrast = (luminance + 0.05) / 0.05; - - let white = Hsla::from(Rgba { - r: 1.0, - g: 1.0, - b: 1.0, - a: 1.0, - }); - - let black = Hsla::from(Rgba { - r: 0.0, - g: 0.0, - b: 0.0, - a: 1.0, - }); - - if white_contrast >= MIN_CONTRAST || white_contrast >= black_contrast { - white - } else { - black - } -} - -/// Derives hover/pressed/subtle shades for an accent against its background. -/// -/// Where a platform states ramps (WinUI, KDE) those are used instead, -/// every other platform derives its shades here. -pub fn derive_shades(accent: Hsla, background: Hsla, is_dark: bool) -> AccentShades { - let accent_ok = Oklch::from_hsla(accent); - let step = if is_dark { 0.05 } else { -0.05 }; - let bg = Oklch::from_hsla(background); - AccentShades { - base: accent, - hover: accent_ok.shifted(step, 1.05).to_hsla(), - pressed: accent_ok.shifted(step * 2.0, 1.1).to_hsla(), - subtle: mix(accent_ok, bg, 0.88).to_hsla(), - foreground: contrast_foreground(accent), +impl AccentShades { + /// Derives hover/pressed/subtle shades for an accent against its background. + /// + /// Where a platform states ramps (WinUI, KDE) those are used instead, + /// every other platform derives its shades here. + pub fn derive(accent: Hsla, background: Hsla, is_dark: bool) -> Self { + let accent_ok = Oklch::from_hsla(accent); + let step = if is_dark { 0.05 } else { -0.05 }; + let bg = Oklch::from_hsla(background); + Self { + base: accent, + hover: accent_ok.shifted(step, 1.05).to_hsla(), + pressed: accent_ok.shifted(step * 2.0, 1.1).to_hsla(), + subtle: accent_ok.mix(bg, 0.88).to_hsla(), + foreground: Oklch::contrast_foreground(accent), + } } } diff --git a/crates/ui/src/theme/resolve.rs b/crates/ui/src/theme/resolve.rs index ce3baf4..230ed0f 100644 --- a/crates/ui/src/theme/resolve.rs +++ b/crates/ui/src/theme/resolve.rs @@ -1,7 +1,7 @@ -use gpui::{WindowBackgroundAppearance, px}; +use gpui::{Hsla, Pixels, WindowBackgroundAppearance, px}; use crate::theme::definition::ThemeDefinition; -use crate::theme::ramps::{AccentShades, Oklch, contrast_foreground, derive_shades, mix}; +use crate::theme::ramps::{AccentShades, Oklch}; use crate::theme::system::{SourceKind, SystemTheme}; use crate::theme::{ AccessibilityPreferences, ColorTokens, CustomTheme, Elevations, MaterialTokens, Motion, Radius, @@ -20,7 +20,7 @@ pub struct Ramps { } /// Everything a component paints from, after the overlay chain. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq)] pub struct ResolvedTheme { pub variant: ThemeVariant, pub colors: ColorTokens, @@ -32,9 +32,9 @@ pub struct ResolvedTheme { pub motion: Motion, pub scrollbar: Scrollbar, /// The height the window's titlebar strips draw at. - pub titlebar_height: gpui::Pixels, + pub titlebar_height: Pixels, /// The theme's root font size. - pub root_font_size: gpui::Pixels, + pub root_font_size: Pixels, /// The monospace family, for code surfaces. pub mono_font: &'static str, pub accessibility: AccessibilityPreferences, @@ -42,199 +42,189 @@ pub struct ResolvedTheme { pub window_background: WindowBackgroundAppearance, } -/// Overlay order (later wins): -/// neutral base → system → preset definition → custom theme. -pub(crate) fn resolve( - system: &SystemTheme, - preset: Option<&ThemeDefinition>, - mode_override: Option, - custom: Option, -) -> ResolvedTheme { - let custom = custom.unwrap_or_default(); +impl ResolvedTheme { + /// Overlays the chain neutral base → system → preset definition → custom theme + /// (later wins). + pub(crate) fn resolve( + system: &SystemTheme, + preset: Option<&ThemeDefinition>, + mode_override: Option, + custom: Option, + ) -> Self { + let custom = custom.unwrap_or_default(); - let variant = mode_override - .or(preset.and_then(|def| def.mode())) - .unwrap_or(system.variant); + let variant = mode_override + .or(preset.and_then(|def| def.mode())) + .unwrap_or(system.variant); - let base = match variant { - ThemeVariant::Light => ColorTokens::light(), - ThemeVariant::Dark => ColorTokens::dark(), - }; + let base = match variant { + ThemeVariant::Light => ColorTokens::light(), + ThemeVariant::Dark => ColorTokens::dark(), + }; - let def_color = |field: fn(&ThemeDefinition) -> Option| preset.and_then(field); + let def_color = |field: fn(&ThemeDefinition) -> Option| preset.and_then(field); - let accent = def_color(|d| d.accent()) - .or(system.accent) - .unwrap_or(base.accent); - let primary = def_color(|d| d.primary()).unwrap_or(accent); - let destructive = def_color(|d| d.destructive()).unwrap_or(base.destructive); - let success = def_color(|d| d.success()).unwrap_or(base.success); - let warning = def_color(|d| d.warning()).unwrap_or(base.warning); - let info = def_color(|d| d.info()).unwrap_or(base.info); + let accent = def_color(|d| d.accent()) + .or(system.accent) + .unwrap_or(base.accent); + let primary = def_color(|d| d.primary()).unwrap_or(accent); + let destructive = def_color(|d| d.destructive()).unwrap_or(base.destructive); + let success = def_color(|d| d.success()).unwrap_or(base.success); + let warning = def_color(|d| d.warning()).unwrap_or(base.warning); + let info = def_color(|d| d.info()).unwrap_or(base.info); - let mut colors = ColorTokens { - background: def_color(|d| d.background()).unwrap_or(base.background), - foreground: def_color(|d| d.foreground()).unwrap_or(base.foreground), - surface: def_color(|d| d.surface()).unwrap_or(base.surface), - surface_foreground: def_color(|d| d.surface_foreground()) - .unwrap_or(base.surface_foreground), - primary, - primary_foreground: def_color(|d| d.primary_foreground()) - .unwrap_or_else(|| contrast_foreground(primary)), - secondary: def_color(|d| d.secondary()).unwrap_or(base.secondary), - secondary_foreground: def_color(|d| d.secondary_foreground()) - .unwrap_or(base.secondary_foreground), - muted: def_color(|d| d.muted()).unwrap_or(base.muted), - muted_hover: def_color(|d| d.muted_hover()).unwrap_or(base.muted_hover), - muted_foreground: def_color(|d| d.muted_foreground()).unwrap_or(base.muted_foreground), - accent, - accent_foreground: def_color(|d| d.accent_foreground()) - .unwrap_or_else(|| contrast_foreground(accent)), - destructive, - destructive_foreground: def_color(|d| d.destructive_foreground()) - .unwrap_or_else(|| contrast_foreground(destructive)), - success, - success_foreground: def_color(|d| d.success_foreground()) - .unwrap_or_else(|| contrast_foreground(success)), - warning, - warning_foreground: def_color(|d| d.warning_foreground()) - .unwrap_or_else(|| contrast_foreground(warning)), - info, - info_foreground: def_color(|d| d.info_foreground()) - .unwrap_or_else(|| contrast_foreground(info)), - border: def_color(|d| d.border()).unwrap_or(base.border), - input: def_color(|d| d.input()).unwrap_or(base.input), - ring: def_color(|d| d.ring()).unwrap_or(accent), - selection: def_color(|d| d.selection()).unwrap_or(base.selection), - overlay: def_color(|d| d.overlay()).unwrap_or(base.overlay), - scrollbar_thumb: def_color(|d| d.scrollbar_thumb()).unwrap_or(base.scrollbar_thumb), - }; - - // The knob scales the fill over a platform-stated blur. - let transparency = custom - .transparency - .map(|level| level.min(100)) - .filter(|_| system.source != SourceKind::Windows && system.window_background.is_some()); - - // Reduced transparency forces the window opaque. - let window_background = if system.accessibility.reduce_transparency || transparency == Some(0) { - WindowBackgroundAppearance::Opaque - } else { - system - .window_background - .unwrap_or(WindowBackgroundAppearance::Opaque) - }; - - let accessibility = system.accessibility; - if accessibility.high_contrast { - colors.border = mix( - Oklch::from_hsla(colors.border), - Oklch::from_hsla(colors.foreground), - 0.35, - ) - .to_hsla(); - } - - // A custom theme's stated font size wins over the 16px design root. - let root_font_size = custom.root_font_size.unwrap_or(px(16.)); - let titlebar_height = root_font_size * 2.5; - - let mut radius = Radius::default(); - - if let Some(control) = custom - .control_radius - .or(preset.and_then(|def| def.control_radius()).map(px)) - { - radius.control = control; - } - - if let Some(overlay) = custom - .overlay_radius - .or(preset.and_then(|def| def.overlay_radius()).map(px)) - { - radius.overlay = overlay; - } - - if let Some(sm) = custom - .sm_radius - .or(preset.and_then(|def| def.sm_radius()).map(px)) - { - radius.sm = sm; - } - - let ramps = Ramps { - primary: derive_shades(primary, colors.background, variant == ThemeVariant::Dark), - secondary: derive_shades( - colors.secondary, - colors.background, - variant == ThemeVariant::Dark, - ), - destructive: derive_shades( + let mut colors = ColorTokens { + background: def_color(|d| d.background()).unwrap_or(base.background), + foreground: def_color(|d| d.foreground()).unwrap_or(base.foreground), + surface: def_color(|d| d.surface()).unwrap_or(base.surface), + surface_foreground: def_color(|d| d.surface_foreground()) + .unwrap_or(base.surface_foreground), + primary, + primary_foreground: def_color(|d| d.primary_foreground()) + .unwrap_or_else(|| Oklch::contrast_foreground(primary)), + secondary: def_color(|d| d.secondary()).unwrap_or(base.secondary), + secondary_foreground: def_color(|d| d.secondary_foreground()) + .unwrap_or(base.secondary_foreground), + muted: def_color(|d| d.muted()).unwrap_or(base.muted), + muted_hover: def_color(|d| d.muted_hover()).unwrap_or(base.muted_hover), + muted_foreground: def_color(|d| d.muted_foreground()).unwrap_or(base.muted_foreground), + accent, + accent_foreground: def_color(|d| d.accent_foreground()) + .unwrap_or_else(|| Oklch::contrast_foreground(accent)), destructive, - colors.background, - variant == ThemeVariant::Dark, - ), - success: derive_shades(success, colors.background, variant == ThemeVariant::Dark), - warning: derive_shades(warning, colors.background, variant == ThemeVariant::Dark), - info: derive_shades(info, colors.background, variant == ThemeVariant::Dark), - }; + destructive_foreground: def_color(|d| d.destructive_foreground()) + .unwrap_or_else(|| Oklch::contrast_foreground(destructive)), + success, + success_foreground: def_color(|d| d.success_foreground()) + .unwrap_or_else(|| Oklch::contrast_foreground(success)), + warning, + warning_foreground: def_color(|d| d.warning_foreground()) + .unwrap_or_else(|| Oklch::contrast_foreground(warning)), + info, + info_foreground: def_color(|d| d.info_foreground()) + .unwrap_or_else(|| Oklch::contrast_foreground(info)), + border: def_color(|d| d.border()).unwrap_or(base.border), + input: def_color(|d| d.input()).unwrap_or(base.input), + ring: def_color(|d| d.ring()).unwrap_or(accent), + selection: def_color(|d| d.selection()).unwrap_or(base.selection), + overlay: def_color(|d| d.overlay()).unwrap_or(base.overlay), + scrollbar_thumb: def_color(|d| d.scrollbar_thumb()).unwrap_or(base.scrollbar_thumb), + }; - // Subtle is too faint over field fills; weight the accent so selection reads. - if def_color(|d| d.selection()).is_none() { - colors.selection = mix( - Oklch::from_hsla(ramps.primary.base), - Oklch::from_hsla(colors.background), - 0.65, - ) - .to_hsla(); + // The knob scales the fill over a platform-stated blur. + let transparency = custom + .transparency + .map(|level| level.min(100)) + .filter(|_| system.source != SourceKind::Windows && system.window_background.is_some()); + + // Reduced transparency forces the window opaque. + let window_background = + if system.accessibility.reduce_transparency || transparency == Some(0) { + WindowBackgroundAppearance::Opaque + } else { + system + .window_background + .unwrap_or(WindowBackgroundAppearance::Opaque) + }; + + let accessibility = system.accessibility; + if accessibility.high_contrast { + colors.border = Oklch::from_hsla(colors.border) + .mix(Oklch::from_hsla(colors.foreground), 0.35) + .to_hsla(); + } + + // A custom theme's stated font size wins over the 16px design root. + let root_font_size = custom.root_font_size.unwrap_or(px(16.)); + let titlebar_height = root_font_size * 2.5; + + let mut radius = Radius::default(); + + if let Some(control) = custom + .control_radius + .or(preset.and_then(|def| def.control_radius()).map(px)) + { + radius.control = control; + } + + if let Some(overlay) = custom + .overlay_radius + .or(preset.and_then(|def| def.overlay_radius()).map(px)) + { + radius.overlay = overlay; + } + + if let Some(sm) = custom + .sm_radius + .or(preset.and_then(|def| def.sm_radius()).map(px)) + { + radius.sm = sm; + } + + let is_dark = variant == ThemeVariant::Dark; + let ramps = Ramps { + primary: AccentShades::derive(primary, colors.background, is_dark), + secondary: AccentShades::derive(colors.secondary, colors.background, is_dark), + destructive: AccentShades::derive(destructive, colors.background, is_dark), + success: AccentShades::derive(success, colors.background, is_dark), + warning: AccentShades::derive(warning, colors.background, is_dark), + info: AccentShades::derive(info, colors.background, is_dark), + }; + + // Subtle is too faint over field fills; weight the accent so selection reads. + if def_color(|d| d.selection()).is_none() { + colors.selection = Oklch::from_hsla(ramps.primary.base) + .mix(Oklch::from_hsla(colors.background), 0.65) + .to_hsla(); + } + + let material = MaterialTokens::derive( + &colors, + ramps.primary.base, + variant, + window_background != WindowBackgroundAppearance::Opaque, + transparency, + ); + + let default_elevations = Elevations::for_variant(variant); + let elevations = Elevations { + popover: custom + .popover_elevation + .unwrap_or(default_elevations.popover), + dialog: custom.dialog_elevation.unwrap_or(default_elevations.dialog), + control: custom + .control_elevation + .unwrap_or(default_elevations.control), + }; + + Self { + variant, + ramps, + colors, + material, + radius, + elevations, + motion: Motion::default(), + scrollbar: Scrollbar { + autohide: system.source.scrollbar_autohide(), + ..Scrollbar::default() + }, + titlebar_height, + root_font_size, + mono_font: Self::mono_font(), + accessibility, + window_background, + } } - let material = MaterialTokens::derive( - &colors, - ramps.primary.base, - variant, - window_background != WindowBackgroundAppearance::Opaque, - transparency, - ); - - let default_elevations = Elevations::for_variant(variant); - let elevations = Elevations { - popover: custom - .popover_elevation - .unwrap_or(default_elevations.popover), - dialog: custom.dialog_elevation.unwrap_or(default_elevations.dialog), - control: custom - .control_elevation - .unwrap_or(default_elevations.control), - }; - - ResolvedTheme { - variant, - ramps, - colors, - material, - radius, - elevations, - motion: Motion::default(), - scrollbar: Scrollbar { - autohide: system.source.scrollbar_autohide(), - ..Scrollbar::default() - }, - titlebar_height, - root_font_size, - mono_font: mono_font(), - accessibility, - window_background, - } -} - -/// The platform's monospace family, for code surfaces. -fn mono_font() -> &'static str { - if cfg!(target_os = "macos") { - "Menlo" - } else if cfg!(target_os = "windows") { - "Consolas" - } else { - "monospace" + /// The platform's monospace family, for code surfaces. + fn mono_font() -> &'static str { + if cfg!(target_os = "macos") { + "Menlo" + } else if cfg!(target_os = "windows") { + "Consolas" + } else { + "monospace" + } } } diff --git a/crates/ui/src/theme/source.rs b/crates/ui/src/theme/source.rs index b037427..55fb8b4 100644 --- a/crates/ui/src/theme/source.rs +++ b/crates/ui/src/theme/source.rs @@ -2,46 +2,14 @@ //! system, `install_watchers()` forwards real change events. use gpui::AsyncApp; +#[cfg(target_os = "windows")] +use windows::Win32::Foundation::RPC_E_CHANGED_MODE; +#[cfg(target_os = "windows")] +use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx}; use crate::theme::ThemeVariant; use crate::theme::system::SystemTheme; -pub(crate) trait ThemeSource: 'static { - fn snapshot(&self, variant: ThemeVariant) -> SystemTheme; - fn install_watchers(&mut self, _async_cx: AsyncApp) {} - fn label(&self) -> &'static str; -} - -/// Narrows an f64 color component to f32, clamping to the 0..=1 range and -/// mapping non-finite values to 0.0 rather than truncating garbage silently. -pub(crate) fn narrow_component(value: f64) -> f32 { - if value.is_finite() { - value.clamp(0.0, 1.0) as f32 - } else { - 0.0 - } -} - -#[cfg(target_os = "macos")] -pub(crate) fn platform_source() -> Box { - Box::new(macos::MacosSource::default()) -} - -#[cfg(target_os = "linux")] -pub(crate) fn platform_source() -> Box { - linux::platform_source() -} - -#[cfg(target_os = "windows")] -pub(crate) fn platform_source() -> Box { - windows::platform_source() -} - -#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] -pub(crate) fn platform_source() -> Box { - Box::new(fallback::FallbackSource) -} - #[cfg(target_os = "macos")] pub(crate) mod macos; @@ -62,3 +30,58 @@ pub(crate) mod omarchy; pub(crate) mod portal; pub(crate) mod fallback; + +pub trait ThemeSource: 'static { + fn snapshot(&self, variant: ThemeVariant) -> SystemTheme; + fn install_watchers(&mut self, _async_cx: AsyncApp) {} + fn label(&self) -> &'static str; +} + +/// The adapter for the running platform. +#[cfg(target_os = "macos")] +pub fn platform_source() -> Box { + Box::new(macos::MacosSource::default()) +} + +/// The adapter for the running platform. +#[cfg(target_os = "linux")] +pub fn platform_source() -> Box { + linux::platform_source() +} + +/// The adapter for the running platform. +#[cfg(target_os = "windows")] +pub 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 windows::WindowsSource::new() { + Some(source) => Box::new(source), + None => { + log::warn!("theme: Windows system theme unavailable; using fallback"); + Box::new(fallback::FallbackSource) + } + } +} + +/// The adapter for the running platform. +#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] +pub fn platform_source() -> Box { + Box::new(fallback::FallbackSource) +} + +/// Narrows an f64 color component to f32, clamping to the 0..=1 range and +/// mapping non-finite values to 0.0 rather than truncating garbage silently. +pub(super) fn narrow_component(value: f64) -> f32 { + if value.is_finite() { + value.clamp(0.0, 1.0) as f32 + } else { + 0.0 + } +} diff --git a/crates/ui/src/theme/source/fallback.rs b/crates/ui/src/theme/source/fallback.rs index f857ffa..76f3029 100644 --- a/crates/ui/src/theme/source/fallback.rs +++ b/crates/ui/src/theme/source/fallback.rs @@ -3,10 +3,9 @@ use super::ThemeSource; use crate::theme::ThemeVariant; -use crate::theme::system::SystemTheme; +use crate::theme::system::{SourceKind, SystemTheme}; -// Constructed only by `platform_source` on platforms without their own adapter. -#[cfg_attr(any(target_os = "macos", target_os = "linux"), allow(dead_code))] +/// The source for platforms without their own adapter, and for tests. pub(crate) struct FallbackSource; impl ThemeSource for FallbackSource { @@ -15,6 +14,6 @@ impl ThemeSource for FallbackSource { } fn label(&self) -> &'static str { - crate::theme::system::SourceKind::Fallback.label() + SourceKind::Fallback.label() } } diff --git a/crates/ui/src/theme/source/macos.rs b/crates/ui/src/theme/source/macos.rs index 2925dc2..e891700 100644 --- a/crates/ui/src/theme/source/macos.rs +++ b/crates/ui/src/theme/source/macos.rs @@ -2,6 +2,7 @@ //! //! Reads the system accent and watches the system's color preferences. +use gpui::{AsyncApp, Hsla, Rgba, WindowBackgroundAppearance}; use objc2::rc::Retained; use objc2::runtime::{AnyObject, NSObject}; use objc2::{AnyThread, DefinedClass, define_class, msg_send, sel}; @@ -19,6 +20,25 @@ use super::{ThemeSource, narrow_component}; use crate::theme::ThemeVariant; use crate::theme::system::{AccessibilityPreferences, SourceKind, SystemTheme}; +/// One watcher registration, kept so [`Drop`] can undo it. +enum Watcher { + /// A distributed notification, registered by name. + Distributed { + center: Retained, + name: Retained, + }, + /// A defaults key path observed via KVO, which does not retain observers. + Defaults { + defaults: Retained, + key: Retained, + }, + /// A workspace notification, registered by name. + Workspace { + center: Retained, + name: &'static NSNotificationName, + }, +} + // An observer that forwards distributed notifications and preference. define_class!( #[unsafe(super(NSObject))] @@ -44,25 +64,6 @@ define_class!( } ); -/// One watcher registration, kept so [`Drop`] can undo it. -enum Watcher { - /// A distributed notification, registered by name. - Distributed { - center: Retained, - name: Retained, - }, - /// A defaults key path observed via KVO, which does not retain observers. - Defaults { - defaults: Retained, - key: Retained, - }, - /// A workspace notification, registered by name. - Workspace { - center: Retained, - name: &'static NSNotificationName, - }, -} - #[derive(Default)] pub(crate) struct MacosSource { /// The observer, retained until `Drop` has removed every registration. @@ -83,11 +84,11 @@ impl ThemeObserver { } impl MacosSource { - fn color_to_hsla(color: &NSColor) -> Option { + fn color_to_hsla(color: &NSColor) -> Option { let srgb = NSColorSpace::sRGBColorSpace(); let converted = color.colorUsingColorSpace(&srgb)?; - Some(gpui::Hsla::from(gpui::Rgba { + Some(Hsla::from(Rgba { r: narrow_component(converted.redComponent()), g: narrow_component(converted.greenComponent()), b: narrow_component(converted.blueComponent()), @@ -111,13 +112,13 @@ impl ThemeSource for MacosSource { accent: Self::color_to_hsla(&NSColor::controlAccentColor()), accessibility, // macOS blurs what is behind the window natively. - window_background: Some(gpui::WindowBackgroundAppearance::Blurred), + window_background: Some(WindowBackgroundAppearance::Blurred), source: SourceKind::Macos, } } /// Re-runs the resolve pipeline when the system's theme changes. - fn install_watchers(&mut self, async_cx: gpui::AsyncApp) { + fn install_watchers(&mut self, async_cx: AsyncApp) { let signal = ReapplySignal::install(&async_cx); let observer = ThemeObserver::new(signal.sender()); let mut watchers = Vec::new(); @@ -128,9 +129,8 @@ impl ThemeSource for MacosSource { "AppleInterfaceThemeChangedNotification", ] { let name = NSNotificationName::from_str(name); - // SAFETY: the center tracks this exact registration until `Drop` - // removes it, and the observer is retained by `MacosSource` until - // after that removal. + // SAFETY: the center tracks this exact registration until `Drop` removes it, + // and the observer is retained by `MacosSource` until after that removal. unsafe { center.addObserver_selector_name_object( &observer, @@ -152,9 +152,7 @@ impl ThemeSource for MacosSource { "AppleInterfaceStyle", ] { let key = NSString::from_str(key); - // SAFETY: KVO does not retain the observer, so the registration is - // only valid while `MacosSource` keeps the observer alive and - // `Drop` unregisters the key path before releasing it. + // SAFETY: KVO does not retain the observer. unsafe { defaults.addObserver_forKeyPath_options_context( &observer, @@ -173,8 +171,8 @@ impl ThemeSource for MacosSource { let accessibility_name = unsafe { NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification }; - // SAFETY: the workspace center retains the observer for the - // registration's lifetime, and `Drop` removes the registration. + // SAFETY: the workspace center retains the observer for the registration's lifetime, + // and `Drop` removes the registration. unsafe { workspace_center.addObserver_selector_name_object( &observer, @@ -206,22 +204,19 @@ impl Drop for MacosSource { for watcher in self.watchers.drain(..) { match watcher { Watcher::Distributed { center, name } => { - // SAFETY: the observer is registered with this center - // under this name and object. + // SAFETY: the observer is registered with this center under this name and object. unsafe { center.removeObserver_name_object(&observer, Some(&name), None); } } Watcher::Defaults { defaults, key } => { - // SAFETY: the observer is registered for this key path - // with no context. + // SAFETY: the observer is registered for this key path with no context. unsafe { defaults.removeObserver_forKeyPath(&observer, &key); } } Watcher::Workspace { center, name } => { - // SAFETY: the observer is registered with this center - // under this name and object. + // SAFETY: the observer is registered with this center under this name and object. unsafe { center.removeObserver_name_object(&observer, Some(name), None); } diff --git a/crates/ui/src/theme/source/signal.rs b/crates/ui/src/theme/source/signal.rs index 16dd700..7b5ea04 100644 --- a/crates/ui/src/theme/source/signal.rs +++ b/crates/ui/src/theme/source/signal.rs @@ -3,6 +3,8 @@ use gpui::{AsyncApp, Task}; +use crate::theme::ThemeEngine; + pub(crate) struct ReapplySignal { sender: async_channel::Sender<()>, _task: Task<()>, @@ -17,7 +19,8 @@ impl ReapplySignal { let task = executor.spawn(async move { while events.recv().await.is_ok() { - async_cx.update(crate::theme::reapply); + while events.try_recv().is_ok() {} + async_cx.update(ThemeEngine::reapply); } }); diff --git a/crates/ui/src/theme/source/windows.rs b/crates/ui/src/theme/source/windows.rs index af47619..562c6f2 100644 --- a/crates/ui/src/theme/source/windows.rs +++ b/crates/ui/src/theme/source/windows.rs @@ -4,8 +4,6 @@ use windows::Foundation::TypedEventHandler; use windows::UI::ViewManagement::{AccessibilitySettings, UIColorType, UISettings}; -use windows::Win32::Foundation::RPC_E_CHANGED_MODE; -use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx}; use windows::core::IInspectable; use super::ThemeSource; @@ -56,7 +54,7 @@ pub(crate) struct WindowsSource { } impl WindowsSource { - fn new() -> Option { + pub(crate) fn new() -> Option { let ui_settings = match UISettings::new() { Ok(ui_settings) => ui_settings, Err(error) => { @@ -187,22 +185,3 @@ 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/crates/ui/src/theme/system.rs b/crates/ui/src/theme/system.rs index 7334575..4496161 100644 --- a/crates/ui/src/theme/system.rs +++ b/crates/ui/src/theme/system.rs @@ -4,14 +4,6 @@ use gpui::{Hsla, WindowBackgroundAppearance}; use crate::theme::ThemeVariant; -/// Accessibility preferences read from the OS, forwarded into resolution. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct AccessibilityPreferences { - pub high_contrast: bool, - pub reduce_motion: bool, - pub reduce_transparency: bool, -} - /// Which adapter produced a [`SystemTheme`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr(not(any(target_os = "linux", target_os = "windows")), allow(dead_code))] @@ -45,6 +37,14 @@ impl SourceKind { } } +/// Accessibility preferences read from the OS, forwarded into resolution. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct AccessibilityPreferences { + pub high_contrast: bool, + pub reduce_motion: bool, + pub reduce_transparency: bool, +} + /// A normalized snapshot of the running system's theme. #[derive(Clone, Copy, Debug, PartialEq)] pub struct SystemTheme { diff --git a/crates/ui/tests/dialog.rs b/crates/ui/tests/dialog.rs new file mode 100644 index 0000000..df5ea71 --- /dev/null +++ b/crates/ui/tests/dialog.rs @@ -0,0 +1,112 @@ +//! One Escape closes a dialog even when a text field inside it has focus. + +use gpui::{ + Context, IntoElement, Modifiers, ParentElement as _, Render, Styled as _, TestAppContext, + VisualTestContext, Window, div, px, size, +}; +use ui::common::{ResultLogErr as _, v_flex}; +use ui::dialog::{Dialog, DialogHandle}; +use ui::input::{Input, InputState}; +use ui::theme::Theme; + +const WINDOW_WIDTH: f32 = 800.0; +const WINDOW_HEIGHT: f32 = 600.0; + +/// A dialog with a text field and an action, with its open state held by the view. +struct DialogHarness { + handle: DialogHandle, + input: gpui::Entity, + closes: Vec, +} + +impl Render for DialogHarness { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let input = self.input.clone(); + let this = cx.weak_entity(); + + v_flex().size_full().p_4().child( + Dialog::new("escape-dialog") + .handle(self.handle.clone()) + .title("Escape closes") + .on_change(move |open, _window, cx| { + this.update(cx, |harness, _| harness.closes.push(open)) + .log_err(); + }) + .content(move |_, _| { + div() + .p_2() + .child(Input::new("dialog-field", input.clone())) + .into_any_element() + }), + ) + } +} + +#[gpui::test] +fn one_escape_closes_a_dialog_with_a_focused_field(cx: &mut TestAppContext) { + cx.update(|cx| { + Theme::init_with(cx, Theme::fallback_source()); + Dialog::bind_keys(cx); + }); + let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, cx| { + DialogHarness { + handle: DialogHandle::new(true), + input: InputState::new(cx), + closes: Vec::new(), + } + }); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + + let harness = window.root(&mut cx).expect("harness view"); + cx.update(|window, cx| window.focus(&harness.read(cx).input.read(cx).focus_handle(), cx)); + cx.update(|_, _| {}); + cx.run_until_parked(); + + cx.simulate_keystrokes("escape"); + cx.run_until_parked(); + + assert_eq!( + harness.read_with(&cx, |harness, _| harness.closes.clone()), + vec![false], + "one escape press reports a single close to the dialog's owner" + ); +} + +#[gpui::test] +fn tab_keeps_focus_inside_the_dialog(cx: &mut TestAppContext) { + cx.update(|cx| { + Theme::init_with(cx, Theme::fallback_source()); + Dialog::bind_keys(cx); + }); + let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, cx| { + DialogHarness { + handle: DialogHandle::new(true), + input: InputState::new(cx), + closes: Vec::new(), + } + }); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + + let harness = window.root(&mut cx).expect("harness view"); + let field = cx.update(|_, cx| harness.read(cx).input.read(cx).focus_handle()); + cx.update(|window, cx| window.focus(&field, cx)); + cx.update(|_, _| {}); + cx.run_until_parked(); + + cx.simulate_keystrokes("tab"); + cx.run_until_parked(); + + let contained = cx.update(|window, cx| { + let dialog = window.focused(cx).expect("focus stays in the window"); + dialog.contains_focused(window, cx) || dialog == field + }); + assert!(contained, "tab does not move focus behind the dialog"); + assert!( + cx.debug_bounds("escape-dialog").is_some() + || harness.read_with(&cx, |h, _| h.closes.is_empty()), + "the dialog stays open" + ); + let _ = Modifiers::default(); +} diff --git a/crates/ui/tests/input.rs b/crates/ui/tests/input.rs new file mode 100644 index 0000000..fbc4cc0 --- /dev/null +++ b/crates/ui/tests/input.rs @@ -0,0 +1,64 @@ +//! Ending a composition repaints the field, so its underline disappears. + +use std::cell::Cell; +use std::rc::Rc; + +use gpui::{ + EntityInputHandler, Modifiers, Styled as _, TestAppContext, VisualTestContext, px, size, +}; +use ui::input::InputState; +use ui::theme::Theme; + +struct EmptyView; + +impl gpui::Render for EmptyView { + fn render( + &mut self, + _window: &mut gpui::Window, + _cx: &mut gpui::Context, + ) -> impl gpui::IntoElement { + gpui::div().size_full() + } +} + +#[gpui::test] +fn unmarking_a_composition_notifies_the_field(cx: &mut TestAppContext) { + cx.update(|cx| Theme::init_with(cx, Theme::fallback_source())); + let window = cx.open_window(size(px(400.), px(100.)), |_, _| EmptyView); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + + let state = cx.update(|_, cx| InputState::new(cx)); + let notifies = Rc::new(Cell::new(0)); + let counted = notifies.clone(); + let _subscription = + cx.update(|_, cx| cx.observe(&state, move |_, _| counted.set(counted.get() + 1))); + + cx.update(|window, cx| { + state.update(cx, |state, cx| { + EntityInputHandler::replace_and_mark_text_in_range( + state, + None, + "ab", + Some(0..2), + window, + cx, + ); + }); + }); + cx.run_until_parked(); + let marked = notifies.get(); + + cx.update(|window, cx| { + state.update(cx, |state, cx| { + EntityInputHandler::unmark_text(state, window, cx); + }); + }); + cx.run_until_parked(); + + assert!( + notifies.get() > marked, + "ending the composition repaints the field" + ); + let _ = Modifiers::default(); +} diff --git a/crates/ui/tests/menu.rs b/crates/ui/tests/menu.rs new file mode 100644 index 0000000..6c46f8a --- /dev/null +++ b/crates/ui/tests/menu.rs @@ -0,0 +1,106 @@ +//! Menu panels render only their visible rows and dispatch navigation keys as actions. + +use gpui::{ + Context, InteractiveElement as _, IntoElement, ParentElement as _, Render, Styled as _, + TestAppContext, VisualTestContext, Window, div, px, size, +}; +use ui::common::{ResultLogErr as _, v_flex}; +use ui::menu::{Menu, MenuItem}; +use ui::theme::Theme; + +const WINDOW_WIDTH: f32 = 800.0; +const WINDOW_HEIGHT: f32 = 1000.0; +const ROWS: usize = 300; + +/// A menu of `ROWS` action rows, with its open state held by the view. +struct MenuHarness { + open: bool, + activated: Vec, + changes: Vec, +} + +impl Render for MenuHarness { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let weak = cx.weak_entity(); + + v_flex().size_full().p_4().child( + Menu::new("m") + .open(self.open) + .on_change(cx.processor(|this, open: bool, _, cx| { + this.open = open; + this.changes.push(open); + cx.notify(); + })) + .trigger(|_, _| { + div() + .h(px(24.)) + .w(px(120.)) + .debug_selector(|| "m-trigger".to_string()) + .into_any_element() + }) + .items(move |_, _| { + (0..ROWS) + .map(|index| { + let activated = weak.clone(); + MenuItem::new(format!("Item {index}")).handler(move |_, cx| { + activated + .update(cx, |harness, cx| { + harness.activated.push(index); + cx.notify(); + }) + .log_err(); + }) + }) + .collect() + }), + ) + } +} + +/// Opens the harness's menu with its recordings cleared, and parks the frame. +fn open(cx: &mut VisualTestContext, harness: &gpui::Entity) { + harness.update(cx, |harness, cx| { + harness.open = true; + harness.activated.clear(); + harness.changes.clear(); + cx.notify(); + }); + // Draw once so the panel's paint-time focus grab runs before the keys arrive. + cx.update(|_, _| {}); + cx.run_until_parked(); + // Draw twice: the first paint defers the focus grab, the second registers the + // panel's focus path so dispatched keys reach it. + cx.update(|_, _| {}); + cx.run_until_parked(); + cx.update(|_, _| {}); + cx.run_until_parked(); +} + +#[gpui::test] +fn menu_rows_are_virtualized(cx: &mut TestAppContext) { + cx.update(|cx| { + Theme::init_with(cx, Theme::fallback_source()); + Menu::bind_keys(cx); + }); + let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, _| { + MenuHarness { + open: false, + activated: Vec::new(), + changes: Vec::new(), + } + }); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + let harness = window.root(&mut cx).expect("harness view"); + + open(&mut cx, &harness); + + assert!( + cx.debug_bounds("menu-item-0").is_some(), + "the first row is on screen" + ); + assert!( + cx.debug_bounds("menu-item-299").is_none(), + "rows beyond the panel's height are never laid out" + ); +} diff --git a/crates/ui/tests/panel.rs b/crates/ui/tests/panel.rs index 3c633fb..97da686 100644 --- a/crates/ui/tests/panel.rs +++ b/crates/ui/tests/panel.rs @@ -94,6 +94,78 @@ impl Panel for FieldView { } } +struct MetaView { + loading: bool, + prefix: bool, +} + +impl Render for MetaView { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + div().size_full() + } +} + +impl Panel for MetaView { + fn title(&self, _cx: &App) -> SharedString { + SharedString::from("Meta") + } + + fn prefix(&self, _cx: &App) -> Option { + self.prefix.then(|| { + div() + .debug_selector(|| "meta-prefix".to_string()) + .into_any_element() + }) + } + + fn loading(&self, _cx: &App) -> bool { + self.loading + } +} + +struct MetaStripHarness { + busy: Entity, + idle: Entity, + prefixed: Entity, +} + +impl Render for MetaStripHarness { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + let busy = self.busy.clone(); + let idle = self.idle.clone(); + let prefixed = self.prefixed.clone(); + v_flex() + .size_full() + .gap_1() + .child( + Tabs::new("busy-strip") + .tabs(move |_, cx| vec![busy.tab("busy".into(), cx).closeable(false)]), + ) + .child( + Tabs::new("idle-strip") + .tabs(move |_, cx| vec![idle.tab("idle".into(), cx).closeable(false)]), + ) + .child( + Tabs::new("prefix-strip") + .tabs(move |_, cx| vec![prefixed.tab("prefix".into(), cx).closeable(false)]), + ) + } +} + +/// The titlebar strip above the stack. +struct TabsHarness { + stack: Entity, +} + +impl Render for TabsHarness { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + v_flex() + .size_full() + .children(PanelStack::main_tabs(self.stack.clone(), cx)) + .child(self.stack.clone()) + } +} + /// A marker view. fn tag(cx: &mut App, selector: &'static str) -> Entity { cx.new(|_| TagView::new(selector)) @@ -110,7 +182,7 @@ fn stack_window( seed: impl FnOnce(&mut PanelStack, &mut Context), ) -> (VisualTestContext, Entity) { let stack = cx.update(|cx| { - Theme::init(cx); + Theme::init_with(cx, Theme::fallback_source()); let stack = cx.new(|cx| PanelStack::new("panel-harness", cx)); stack.update(cx, seed); stack @@ -294,67 +366,9 @@ fn dragging_the_divider_resizes_the_panels(cx: &mut TestAppContext) { assert_eq!(after.size.width, before.size.width + px(100.0)); } -struct MetaView { - loading: bool, - prefix: bool, -} - -impl Render for MetaView { - fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { - div().size_full() - } -} - -impl Panel for MetaView { - fn title(&self, _cx: &App) -> SharedString { - SharedString::from("Meta") - } - - fn prefix(&self, _cx: &App) -> Option { - self.prefix.then(|| { - div() - .debug_selector(|| "meta-prefix".to_string()) - .into_any_element() - }) - } - - fn loading(&self, _cx: &App) -> bool { - self.loading - } -} - -struct MetaStripHarness { - busy: Entity, - idle: Entity, - prefixed: Entity, -} - -impl Render for MetaStripHarness { - fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { - let busy = self.busy.clone(); - let idle = self.idle.clone(); - let prefixed = self.prefixed.clone(); - v_flex() - .size_full() - .gap_1() - .child( - Tabs::new("busy-strip") - .tabs(move |_, cx| vec![busy.tab("busy".into(), cx).closeable(false)]), - ) - .child( - Tabs::new("idle-strip") - .tabs(move |_, cx| vec![idle.tab("idle".into(), cx).closeable(false)]), - ) - .child( - Tabs::new("prefix-strip") - .tabs(move |_, cx| vec![prefixed.tab("prefix".into(), cx).closeable(false)]), - ) - } -} - #[gpui::test] fn panel_tab_uses_title_prefix_and_loading(cx: &mut TestAppContext) { - cx.update(Theme::init); + cx.update(|cx| Theme::init_with(cx, Theme::fallback_source())); let busy = cx.new(|_| MetaView { loading: true, prefix: false, @@ -513,7 +527,7 @@ fn a_reopened_split_starts_at_half_again(cx: &mut TestAppContext) { stack.update(cx, |stack, cx| { stack.insert( PanelSlot::Split, - split.clone(), + split, Arc::new(tag(cx, "panel-test-split")), cx, ) @@ -532,25 +546,11 @@ fn a_reopened_split_starts_at_half_again(cx: &mut TestAppContext) { ); } -/// The titlebar strip above the stack. -struct TabsHarness { - stack: Entity, -} - -impl Render for TabsHarness { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - v_flex() - .size_full() - .children(PanelStack::main_tabs(self.stack.clone(), cx)) - .child(self.stack.clone()) - } -} - /// The titlebar strip lists the main stack; its tabs switch and close panels. #[gpui::test] fn main_tabs_switch_and_close_the_main_stack(cx: &mut TestAppContext) { let stack = cx.update(|cx| { - Theme::init(cx); + Theme::init_with(cx, Theme::fallback_source()); cx.new(|cx| PanelStack::new("panel-harness", cx)) }); let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, _| { diff --git a/crates/ui/tests/popover.rs b/crates/ui/tests/popover.rs index 2ef8352..f54890c 100644 --- a/crates/ui/tests/popover.rs +++ b/crates/ui/tests/popover.rs @@ -5,6 +5,7 @@ use gpui::{ Render, Styled as _, TestAppContext, VisualTestContext, Window, div, px, size, }; use ui::common::v_flex; +use ui::dialog::Dialog; use ui::popover::Popover; use ui::theme::Theme; @@ -60,7 +61,10 @@ fn focus_state(cx: &mut VisualTestContext) -> Option<(FocusHandle, bool)> { #[gpui::test] fn closing_a_popover_restores_the_previous_focus(cx: &mut TestAppContext) { - cx.update(Theme::init); + cx.update(|cx| { + Theme::init_with(cx, Theme::fallback_source()); + Dialog::bind_keys(cx); + }); let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, cx| { PopoverHarness { open: false, diff --git a/crates/ui/tests/scroll_area.rs b/crates/ui/tests/scroll_area.rs index cbdfc5f..7cad8bf 100644 --- a/crates/ui/tests/scroll_area.rs +++ b/crates/ui/tests/scroll_area.rs @@ -58,7 +58,7 @@ fn press_track(cx: &mut VisualTestContext) { #[gpui::test] fn a_covering_overlay_blocks_scrollbar_drags(cx: &mut TestAppContext) { - cx.update(Theme::init); + cx.update(|cx| Theme::init_with(cx, Theme::fallback_source())); let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, _| { ScrollHarness { handle: ScrollHandle::new(), diff --git a/crates/ui/tests/scrollbar.rs b/crates/ui/tests/scrollbar.rs new file mode 100644 index 0000000..b89a3ec --- /dev/null +++ b/crates/ui/tests/scrollbar.rs @@ -0,0 +1,81 @@ +//! A hidden auto-hide scrollbar repaints its owner as soon as the pointer +//! reaches its track. + +use std::cell::Cell; +use std::rc::Rc; + +use gpui::{ + Context, InteractiveElement as _, IntoElement, Modifiers, ParentElement as _, Render, + ScrollHandle, StatefulInteractiveElement as _, Styled as _, TestAppContext, VisualTestContext, + Window, div, point, px, size, +}; +use ui::scrollbar::{Scrollbar, ScrollbarVisibility}; +use ui::theme::Theme; + +const WINDOW_WIDTH: f32 = 800.0; +const WINDOW_HEIGHT: f32 = 600.0; +const ROW_HEIGHT: f32 = 40.0; +const ROWS: usize = 50; + +/// A scrolled surface with an auto-hide scrollbar overlaid on its right edge. +struct ScrollbarHarness { + handle: ScrollHandle, + renders: Rc>, +} + +impl Render for ScrollbarHarness { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + self.renders.set(self.renders.get() + 1); + div() + .relative() + .size_full() + .child( + div() + .id("log") + .size_full() + .overflow_y_scroll() + .track_scroll(&self.handle) + .children( + (0..ROWS).map(|row| { + div().w_full().h(px(ROW_HEIGHT)).child(format!("row {row}")) + }), + ), + ) + .child( + Scrollbar::vertical("log-bar", self.handle.clone()) + .visibility(ScrollbarVisibility::Autohide), + ) + } +} + +#[gpui::test] +fn hovering_a_hidden_scrollbar_repaints_its_owner(cx: &mut TestAppContext) { + cx.update(|cx| Theme::init_with(cx, Theme::fallback_source())); + let renders = Rc::new(Cell::new(0)); + let harness = { + let renders = renders.clone(); + move |_: &mut Window, _: &mut Context| ScrollbarHarness { + handle: ScrollHandle::new(), + renders, + } + }; + let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), harness); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + renders.set(0); + + // A scrollbar that has never been touched is hidden; reaching its track must + // repaint the owner so the thumb can appear. + cx.simulate_mouse_move( + point(px(WINDOW_WIDTH - 2.), px(WINDOW_HEIGHT / 2.0)), + None, + Modifiers::default(), + ); + cx.update(|_, _| {}); + cx.run_until_parked(); + + assert!( + renders.get() > 0, + "reaching the track of a hidden scrollbar repaints its owner" + ); +} diff --git a/crates/ui/tests/select.rs b/crates/ui/tests/select.rs new file mode 100644 index 0000000..b3728e4 --- /dev/null +++ b/crates/ui/tests/select.rs @@ -0,0 +1,91 @@ +//! An outside click closes an open Select and leaves focus on the click target. + +use gpui::{ + Context, FocusHandle, InteractiveElement as _, IntoElement, Modifiers, ParentElement as _, + Render, Styled as _, TestAppContext, VisualTestContext, Window, div, px, size, +}; +use ui::common::v_flex; +use ui::select::{Select, SelectOption}; +use ui::theme::Theme; + +const WINDOW_WIDTH: f32 = 800.0; +const WINDOW_HEIGHT: f32 = 1000.0; + +/// A select above a focusable element, so the open panel never covers the target. +struct SelectHarness { + value: Option, + outside_focus: FocusHandle, +} + +impl Render for SelectHarness { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let outside_focus = self.outside_focus.clone(); + + v_flex() + .size_full() + .p_4() + .child( + Select::new("s") + .options( + ["alpha", "beta"].map(|value| SelectOption::new(value.to_string(), value)), + ) + .placeholder("Pick") + .on_change(cx.processor(|this, value: Option, _, cx| { + this.value = value.clone(); + cx.notify(); + })), + ) + .child(div().h(px(500.))) + .child( + div() + .id("outside") + .track_focus(&outside_focus) + .debug_selector(|| "outside".to_string()) + .h(px(40.)) + .w(px(200.)), + ) + } +} + +#[gpui::test] +fn outside_click_leaves_focus_on_the_target(cx: &mut TestAppContext) { + cx.update(|cx| Theme::init_with(cx, Theme::fallback_source())); + let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, cx| { + SelectHarness { + value: None, + outside_focus: cx.focus_handle(), + } + }); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + let harness = window.root(&mut cx).expect("harness view"); + let outside_focus = cx.update(|_, cx| harness.read(cx).outside_focus.clone()); + let trigger = cx.debug_bounds("select-trigger").expect("trigger laid out"); + + cx.simulate_click(trigger.center(), Modifiers::default()); + cx.run_until_parked(); + + assert!( + cx.debug_bounds("menu-panel").is_some(), + "clicking the trigger opens the options" + ); + + let outside = cx.debug_bounds("outside").expect("target laid out"); + cx.simulate_click(outside.center(), Modifiers::default()); + cx.run_until_parked(); + + assert!( + cx.debug_bounds("menu-panel").is_none(), + "the outside click closes the options" + ); + assert_eq!( + cx.update(|window, cx| window.focused(cx)), + Some(outside_focus), + "focus stays on the clicked element, not the trigger" + ); + assert_eq!( + harness.read_with(&cx, |harness, _| harness.value.clone()), + None, + "an outside click chooses nothing" + ); +} diff --git a/crates/ui/tests/sizing.rs b/crates/ui/tests/sizing.rs index 0af4046..f667c2a 100644 --- a/crates/ui/tests/sizing.rs +++ b/crates/ui/tests/sizing.rs @@ -59,7 +59,7 @@ impl Render for Harness { #[gpui::test] fn buttons_render_at_their_token_heights(cx: &mut TestAppContext) { - cx.update(Theme::init); + cx.update(|cx| Theme::init_with(cx, Theme::fallback_source())); let window = cx.open_window(size(px(400.), px(400.)), |_, _| Harness); let mut cx = VisualTestContext::from_window(window.into(), cx); cx.run_until_parked(); diff --git a/crates/ui/tests/tabs.rs b/crates/ui/tests/tabs.rs index 059b6de..d785753 100644 --- a/crates/ui/tests/tabs.rs +++ b/crates/ui/tests/tabs.rs @@ -45,23 +45,6 @@ impl Render for StripHarness { } } -fn strip_window( - cx: &mut TestAppContext, - changed: Rc>>, - reordered: Rc>>, - pinned: bool, -) -> VisualTestContext { - cx.update(Theme::init); - let window = cx.open_window(size(px(800.), px(600.)), |_, _| StripHarness { - changed, - reordered, - pinned, - }); - let cx = VisualTestContext::from_window(window.into(), cx); - cx.run_until_parked(); - cx -} - struct CloseHarness { closed: Rc>>, } @@ -82,6 +65,22 @@ impl Render for CloseHarness { ) } } +fn strip_window( + cx: &mut TestAppContext, + changed: Rc>>, + reordered: Rc>>, + pinned: bool, +) -> VisualTestContext { + cx.update(|cx| Theme::init_with(cx, Theme::fallback_source())); + let window = cx.open_window(size(px(800.), px(600.)), |_, _| StripHarness { + changed, + reordered, + pinned, + }); + let cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + cx +} #[gpui::test] fn a_pinned_tab_draws_inline_and_selects_itself(cx: &mut TestAppContext) { @@ -103,7 +102,7 @@ fn a_pinned_tab_draws_inline_and_selects_itself(cx: &mut TestAppContext) { #[gpui::test] fn a_closeable_tab_reports_its_close(cx: &mut TestAppContext) { - cx.update(Theme::init); + cx.update(|cx| Theme::init_with(cx, Theme::fallback_source())); let closed = Rc::new(RefCell::new(Vec::new())); let window = cx.open_window(size(px(800.), px(600.)), |_, _| CloseHarness { closed: closed.clone(), diff --git a/crates/ui/tests/theme_definition.rs b/crates/ui/tests/theme_definition.rs new file mode 100644 index 0000000..36967ad --- /dev/null +++ b/crates/ui/tests/theme_definition.rs @@ -0,0 +1,15 @@ +use ui::theme::ThemeDefinition; + +#[test] +fn parse_hex_rejects_non_ascii_digits() { + assert_eq!(ThemeDefinition::parse_hex("#éa"), None); + assert_eq!(ThemeDefinition::parse_hex("#éaabbcc"), None); +} + +#[test] +fn parse_hex_resolves_three_and_six_digits() { + assert!(ThemeDefinition::parse_hex("#abc").is_some()); + assert!(ThemeDefinition::parse_hex("#aabbcc").is_some()); + assert_eq!(ThemeDefinition::parse_hex("abc"), None); + assert_eq!(ThemeDefinition::parse_hex("#ab"), None); +} diff --git a/crates/ui/tests/tree.rs b/crates/ui/tests/tree.rs new file mode 100644 index 0000000..ce9e6fd --- /dev/null +++ b/crates/ui/tests/tree.rs @@ -0,0 +1,69 @@ +//! Flattening a path tree honors expansion and nests children in order. + +use std::collections::HashSet; +use std::path::PathBuf; + +use ui::tree::{TreeItem, TreeItemSeed}; + +fn ids(rows: &[TreeItem]) -> Vec<(String, usize)> { + rows.iter() + .map(|row| (row.key().to_string(), row.level())) + .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].is_expandable()); + assert!(!rows[0].is_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"); +} diff --git a/desktop/src/main.rs b/desktop/src/main.rs index b295f26..da3b50f 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -54,7 +54,7 @@ fn main() { SettingsStore::set_global(store.clone(), cx); let settings = store.read(cx).settings().clone(); - signed_app::apply_appearance_mode(settings.appearance, cx); + signed_app::AppRoot::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}"); @@ -107,7 +107,7 @@ fn main() { cx.refresh_windows(); }) .detach(); - signed_app::root(window, cx) + signed_app::AppRoot::mount(window, cx) }) { tracing::error!("failed to open window: {error}"); cx.quit();