refactor: consolidate shared ui helpers and prune unused code

This commit is contained in:
2026-11-22 18:23:21 +07:00
parent 4a72f2b4a0
commit 9daee9d54d
82 changed files with 3607 additions and 7184 deletions
+1 -6
View File
@@ -1,12 +1,7 @@
use gpui::App; use gpui::App;
use settings::{AppearanceMode, Settings}; use settings::AppearanceMode;
use ui::theme::{ThemeVariant, follow_system, set_mode_override}; use ui::theme::{ThemeVariant, follow_system, set_mode_override};
/// Applies the persisted light/dark/system preference to the kit theme.
pub fn apply_appearance(settings: &Settings, cx: &mut App) {
apply_appearance_mode(settings.appearance, cx);
}
/// Applies one appearance mode to the kit theme. /// Applies one appearance mode to the kit theme.
pub fn apply_appearance_mode(mode: AppearanceMode, cx: &mut App) { pub fn apply_appearance_mode(mode: AppearanceMode, cx: &mut App) {
match mode { match mode {
+2 -2
View File
@@ -7,7 +7,7 @@ use gpui::{
AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
Render, Styled as _, Subscription, Window, div, px, Render, Styled as _, Subscription, Window, div, px,
}; };
use helpers::apply_appearance; use helpers::apply_appearance_mode;
use settings::SettingsStore; use settings::SettingsStore;
use signed_state::{Backend, BackendEvent}; use signed_state::{Backend, BackendEvent};
use ui::common::h_flex; use ui::common::h_flex;
@@ -82,7 +82,7 @@ impl AppRoot {
subscriptions.push(cx.observe(&settings, |_this, store, cx| { subscriptions.push(cx.observe(&settings, |_this, store, cx| {
let settings = store.read(cx).settings().clone(); let settings = store.read(cx).settings().clone();
apply_appearance(&settings, cx); apply_appearance_mode(settings.appearance, cx);
})); }));
let app = cx.entity().downgrade(); let app = cx.entity().downgrade();
+9 -9
View File
@@ -45,15 +45,6 @@ impl Panel for SignedOutView {
} }
} }
/// One of the three banner photos, picked per process launch.
fn pick_banner() -> SharedString {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|now| now.subsec_nanos())
.unwrap_or(0);
format!("backgrounds/banner{}.jpg", nanos % 3 + 1).into()
}
impl Render for SignedOutView { impl Render for SignedOutView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme(); let theme = cx.theme();
@@ -110,3 +101,12 @@ impl Render for SignedOutView {
.when_some(self.import.clone(), |el, view| el.child(view)) .when_some(self.import.clone(), |el, view| el.child(view))
} }
} }
/// One of the three banner photos, picked per process launch.
fn pick_banner() -> SharedString {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|now| now.subsec_nanos())
.unwrap_or(0);
format!("backgrounds/banner{}.jpg", nanos % 3 + 1).into()
}
+2 -11
View File
@@ -13,7 +13,7 @@ use ui::theme::ActiveTheme as _;
use utils::relative_time; use utils::relative_time;
use crate::repo::actions::open_repo_panel; use crate::repo::actions::open_repo_panel;
use crate::repo::helpers::announcement_display_name; use crate::repo::helpers::{announcement_display_name, upstream_display_name};
use crate::workspace::Workspace; use crate::workspace::Workspace;
const RECENT_COUNT: usize = 10; const RECENT_COUNT: usize = 10;
@@ -78,16 +78,7 @@ pub(super) fn render_card(
let fork_label: Option<SharedString> = announcement.upstream.as_ref().and_then(|upstream| { let fork_label: Option<SharedString> = announcement.upstream.as_ref().and_then(|upstream| {
let addr = upstream.addr.as_ref()?; let addr = upstream.addr.as_ref()?;
let name = announcements let name = upstream_display_name(addr, announcements);
.iter()
.find(|a| a.addr() == *addr)
.map(|a| {
a.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(a.id.clone()))
})
.unwrap_or_else(|| SharedString::from(addr.identifier().to_owned()));
Some(SharedString::from(format!("forked from {name}"))) Some(SharedString::from(format!("forked from {name}")))
}); });
+2 -4
View File
@@ -14,6 +14,7 @@ use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent}; use ui::input::{Input, InputState, InputStateEvent};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption}; use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
@@ -256,9 +257,6 @@ impl Render for ExploreView {
}) })
.size_full(), .size_full(),
) )
.child(crate::shared::widgets::scroll_overlay( .child(Scrollbar::vertical("explore-scroll", scroll_handle))
"explore-scroll",
scroll_handle,
))
} }
} }
+12 -11
View File
@@ -4,14 +4,13 @@ use gpui::{
Styled as _, Window, div, px, Styled as _, Window, div, px,
}; };
use signed_state::Backend; use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle}; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use crate::shared::progress::{DialogProgress, error_row, run_dialog_task}; use crate::shared::progress::{DialogProgress, dialog_submit_button, error_row, run_dialog_task};
pub struct OnboardingDialog { pub struct OnboardingDialog {
handle: DialogHandle, handle: DialogHandle,
@@ -108,15 +107,17 @@ impl Render for OnboardingDialog {
let busy = action_state.read(cx).busy; let busy = action_state.read(cx).busy;
let this = this.clone(); let this = this.clone();
let create: AnyElement = Button::new("create-identity") let create: AnyElement = dialog_submit_button(
.label("Create new identity") "create-identity",
.loading(busy) "Create new identity",
.disabled(busy) None,
.on_click(move |_, _, cx| { busy,
crate::shared::log_dropped( &this,
this.update(cx, |this, cx| this.create_identity(cx)), |this, _window, cx| {
); this.create_identity(cx);
}) Ok(())
},
)
.into_any_element(); .into_any_element();
vec![create] vec![create]
+13 -11
View File
@@ -4,14 +4,13 @@ use gpui::{
Styled as _, Subscription, Window, px, Styled as _, Subscription, Window, px,
}; };
use signed_state::Backend; use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle}; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::icons::{Icon, IconRole}; use ui::icons::IconRole;
use ui::input::{Input, InputState, InputStateEvent}; use ui::input::{Input, InputState, InputStateEvent};
use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task}; use crate::shared::progress::{DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task};
pub struct PassphraseDialog { pub struct PassphraseDialog {
handle: DialogHandle, handle: DialogHandle,
@@ -102,14 +101,17 @@ impl Render for PassphraseDialog {
let busy = action_state.read(cx).busy; let busy = action_state.read(cx).busy;
let this = this.clone(); let this = this.clone();
let unlock: AnyElement = Button::new("unlock") let unlock: AnyElement = dialog_submit_button(
.label("Unlock") "unlock",
.icon(Icon::named(IconRole::Unlock)) "Unlock",
.loading(busy) Some(IconRole::Unlock),
.disabled(busy) busy,
.on_click(move |_, _, cx| { &this,
crate::shared::log_dropped(this.update(cx, |this, cx| this.unlock(cx))); |this, _window, cx| {
}) this.unlock(cx);
Ok(())
},
)
.into_any_element(); .into_any_element();
vec![unlock] vec![unlock]
+2 -2
View File
@@ -9,6 +9,7 @@ use ui::avatar::Avatar;
use ui::badge::Badge; use ui::badge::Badge;
use ui::common::{Sizable as _, h_flex, v_flex}; use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::status_dot::{StatusDot, StatusDotVariant};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use utils::relative_time; use utils::relative_time;
@@ -101,8 +102,7 @@ pub fn thread(
.child(div().flex_1()) .child(div().flex_1())
.when(unread, |this| { .when(unread, |this| {
this.child( this.child(
ui::status_dot::StatusDot::new(("inbox-unread", ix)) StatusDot::new(("inbox-unread", ix)).variant(StatusDotVariant::Accent),
.variant(ui::status_dot::StatusDotVariant::Accent),
) )
}), }),
) )
+2 -2
View File
@@ -15,6 +15,7 @@ use signed_state::{Backend, BackendEvent, Inbox, RefreshGate, RefreshRequest, Re
use ui::alert::{Alert, AlertSeverity, AlertStyle}; use ui::alert::{Alert, AlertSeverity, AlertStyle};
use ui::button::Button; use ui::button::Button;
use ui::common::{StyledExt as _, h_flex, v_flex}; use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea; use ui::scroll_area::ScrollArea;
@@ -25,7 +26,6 @@ use helpers::{empty_section_row, repo_header, thread};
use crate::repo::actions::{RepoItem, open_repo_item}; use crate::repo::actions::{RepoItem, open_repo_item};
use crate::repo::helpers::announcement_display_name; use crate::repo::helpers::announcement_display_name;
use crate::shared::widgets::empty_state;
use crate::workspace::Workspace; use crate::workspace::Workspace;
const MAX_SUB_ACTIVITIES: usize = 5; const MAX_SUB_ACTIVITIES: usize = 5;
@@ -470,7 +470,7 @@ impl Render for InboxView {
.min_h_0() .min_h_0()
.px_4() .px_4()
.child(if rows.is_empty() { .child(if rows.is_empty() {
empty_state("You're all caught up.") EmptyState::centered("You're all caught up.")
} else { } else {
ScrollArea::new("inbox-scroll") ScrollArea::new("inbox-scroll")
.flex_1() .flex_1()
+9 -6
View File
@@ -8,13 +8,16 @@ use signed_core::GitEvent;
use signed_state::RepoStore; use signed_state::RepoStore;
use ui::avatar::Avatar; use ui::avatar::Avatar;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::input::InputState; use ui::input::InputState;
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea; use ui::scroll_area::ScrollArea;
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use utils::relative_time; use utils::relative_time;
use crate::issues::helpers::{comment_form, comments_section, issue_roots, sidebar_section}; use crate::issues::helpers::{comment_form, comments_section, sidebar_section};
use crate::shared::log_dropped;
use crate::shared::widgets::status_badge; use crate::shared::widgets::status_badge;
pub struct IssueDetailView { pub struct IssueDetailView {
@@ -39,7 +42,7 @@ impl IssueDetailView {
let directory = ProfileDirectory::new(cx); let directory = ProfileDirectory::new(cx);
let weak = cx.entity().downgrade(); let weak = cx.entity().downgrade();
cx.defer(move |cx| { cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.track_participants(cx))); log_dropped(weak.update(cx, |this, cx| this.track_participants(cx)));
}); });
Self { Self {
@@ -94,9 +97,9 @@ impl Render for IssueDetailView {
let Some(issue) = store.issues.iter().find(|issue| issue.id == self.issue_id) else { let Some(issue) = store.issues.iter().find(|issue| issue.id == self.issue_id) else {
// A not-yet-loaded store is not the same as a missing issue. // A not-yet-loaded store is not the same as a missing issue.
return if store.loaded { return if store.loaded {
crate::shared::widgets::empty_state("Issue not found") EmptyState::centered("Issue not found")
} else { } else {
crate::shared::widgets::centered_spinner("issue-loading") Spinner::centered("issue-loading")
}; };
}; };
@@ -189,7 +192,7 @@ impl Render for IssueDetailView {
.child(comment_form( .child(comment_form(
&self.store, &self.store,
issue_id, issue_id,
issue_roots, &store.issues,
&self.comment_input, &self.comment_input,
"comment", "comment",
cx, cx,
@@ -200,7 +203,7 @@ impl Render for IssueDetailView {
.child(sidebar_section( .child(sidebar_section(
&self.store, &self.store,
issue_id, issue_id,
issue_roots, &store.issues,
true, true,
&self.directory, &self.directory,
cx, cx,
+20 -20
View File
@@ -76,24 +76,16 @@ pub(crate) fn filter_by_status<'a>(
(visible, counts) (visible, counts)
} }
pub(crate) fn issue_roots(store: &RepoStore) -> &[Event] {
&store.issues
}
pub(crate) fn pr_roots(store: &RepoStore) -> &[Event] {
&store.pull_requests
}
pub(crate) fn sidebar_section( pub(crate) fn sidebar_section(
store: &Entity<RepoStore>, store: &Entity<RepoStore>,
id: EventId, id: EventId,
roots: fn(&RepoStore) -> &[Event], roots: &[Event],
top_gap: bool, top_gap: bool,
directory: &Entity<ProfileDirectory>, directory: &Entity<ProfileDirectory>,
cx: &App, cx: &App,
) -> AnyElement { ) -> AnyElement {
let store = store.read(cx); let store = store.read(cx);
let Some(root) = roots(store).iter().find(|event| event.id == id) else { let Some(root) = roots.iter().find(|event| event.id == id) else {
return div().into_any_element(); return div().into_any_element();
}; };
@@ -116,7 +108,13 @@ pub(crate) fn sidebar_section(
v_flex() v_flex()
.when(top_gap, |this| this.mt_4()) .when(top_gap, |this| this.mt_4())
.gap_2() .gap_2()
.child(crate::shared::widgets::section_label("Participants", cx)) .child(
div()
.text_xs()
.font_medium()
.text_color(cx.theme().colors.muted_foreground)
.child("Participants"),
)
.children(participants.iter().map(|pubkey| { .children(participants.iter().map(|pubkey| {
let profile = directory.read(cx).profile(pubkey, cx); let profile = directory.read(cx).profile(pubkey, cx);
let name = profile.name(); let name = profile.name();
@@ -136,7 +134,13 @@ pub(crate) fn sidebar_section(
.child( .child(
v_flex() v_flex()
.gap_2() .gap_2()
.child(crate::shared::widgets::section_label("Labels", cx)) .child(
div()
.text_xs()
.font_medium()
.text_color(cx.theme().colors.muted_foreground)
.child("Labels"),
)
.map(|this| { .map(|this| {
if labels.is_empty() { if labels.is_empty() {
this.child( this.child(
@@ -215,11 +219,14 @@ pub(crate) fn comments_section(
pub(crate) fn comment_form( pub(crate) fn comment_form(
store: &Entity<RepoStore>, store: &Entity<RepoStore>,
root: EventId, root: EventId,
roots: fn(&RepoStore) -> &[Event], roots: &[Event],
comment_input: &Entity<InputState>, comment_input: &Entity<InputState>,
button_id: &'static str, button_id: &'static str,
cx: &App, cx: &App,
) -> AnyElement { ) -> 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 comment_input = comment_input.clone();
let store = store.clone(); let store = store.clone();
@@ -254,13 +261,6 @@ pub(crate) fn comment_form(
if content.is_empty() { if content.is_empty() {
return; return;
} }
let Some(root) = roots(store.read(cx))
.iter()
.find(|event| event.id == root)
.cloned()
else {
return;
};
store.update(cx, |store, cx| { store.update(cx, |store, cx| {
store.comment(&root, content, cx); store.comment(&root, content, cx);
}); });
+5 -4
View File
@@ -20,7 +20,8 @@ use std::rc::Rc;
use self::detail::IssueDetailView; use self::detail::IssueDetailView;
use crate::repo::helpers::short_id; use crate::repo::helpers::short_id;
use crate::shared::event_list::{EventList, EventRow}; use crate::shared::event_list::{EventHandler, EventList, EventRow, filter_toolbar};
use crate::shared::log_dropped;
use crate::shared::panels; use crate::shared::panels;
use crate::workspace::Workspace; use crate::workspace::Workspace;
@@ -54,7 +55,7 @@ impl IssuesView {
}); });
let weak = cx.entity().downgrade(); let weak = cx.entity().downgrade();
cx.defer(move |cx| { cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.rebuild(cx))); log_dropped(weak.update(cx, |this, cx| this.rebuild(cx)));
}); });
Self { Self {
@@ -128,7 +129,7 @@ impl IssuesView {
let muted = cx.theme().colors.muted_foreground; let muted = cx.theme().colors.muted_foreground;
let weak = cx.entity().downgrade(); let weak = cx.entity().downgrade();
crate::shared::event_list::filter_toolbar( filter_toolbar(
cx, cx,
[ [
Segmented::new("issue-filter", self.filter) Segmented::new("issue-filter", self.filter)
@@ -190,7 +191,7 @@ impl Render for IssuesView {
let id_hex = issue.id.to_hex(); let id_hex = issue.id.to_hex();
let status = store.read(cx).status_of(issue); let status = store.read(cx).status_of(issue);
let on_click: crate::shared::event_list::EventHandler = { let on_click: EventHandler = {
let workspace = workspace.clone(); let workspace = workspace.clone();
let store = store.clone(); let store = store.clone();
Rc::new(move |_, window, cx| { Rc::new(move |_, window, cx| {
+12 -9
View File
@@ -3,14 +3,13 @@ use gpui::{
Styled as _, Window, div, Styled as _, Window, div,
}; };
use signed_state::RepoStore; use signed_state::RepoStore;
use ui::button::Button;
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle}; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use crate::shared::progress::DialogProgress; use crate::shared::progress::{DialogProgress, dialog_submit_button};
pub struct NewIssueDialog { pub struct NewIssueDialog {
handle: DialogHandle, handle: DialogHandle,
@@ -87,13 +86,17 @@ impl Render for NewIssueDialog {
let this = this.clone(); let this = this.clone();
let busy = action_state.read(cx).busy; let busy = action_state.read(cx).busy;
vec![ vec![
Button::new("create-issue") dialog_submit_button(
.label("Create issue") "create-issue",
.loading(busy) "Create issue",
.disabled(busy) None,
.on_click(move |_, _, cx| { busy,
crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx))); &this,
}) |this, _window, cx| {
this.submit(cx);
Ok(())
},
)
.into_any_element() as AnyElement, .into_any_element() as AnyElement,
] ]
}) })
+1 -1
View File
@@ -12,7 +12,7 @@ mod titlebar;
mod workspace; mod workspace;
pub use app::AppRoot; pub use app::AppRoot;
pub use app::helpers::{apply_appearance, apply_appearance_mode}; pub use app::helpers::apply_appearance_mode;
use gpui::{App, AppContext as _, Entity, Window}; use gpui::{App, AppContext as _, Entity, Window};
pub fn root(window: &mut Window, cx: &mut App) -> Entity<AppRoot> { pub fn root(window: &mut Window, cx: &mut App) -> Entity<AppRoot> {
+25 -23
View File
@@ -16,18 +16,23 @@ use ui::avatar::Avatar;
use ui::button::Button; use ui::button::Button;
use ui::clipboard::ClipboardButton; use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::input::InputState; use ui::input::InputState;
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea; use ui::scroll_area::ScrollArea;
use ui::spinner::Spinner;
use ui::tabs::{Tab, Tabs}; use ui::tabs::{Tab, Tabs};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use utils::relative_time; use utils::relative_time;
use super::dialogs; use super::dialogs;
use crate::issues::helpers::{comment_form, comments_section, pr_roots, sidebar_section}; use crate::issues::helpers::{comment_form, comments_section, sidebar_section};
use crate::repo::commit_diff::{CommitDiffView, DiffPane}; use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::shared::widgets::{empty_state, status_badge}; use crate::shared::event_list::commit_list;
use crate::shared::log_dropped;
use crate::shared::panels::open_detail;
use crate::shared::widgets::status_badge;
use crate::workspace::Workspace; use crate::workspace::Workspace;
const NOT_FOUND: &str = "Pull request not found"; const NOT_FOUND: &str = "Pull request not found";
@@ -82,7 +87,7 @@ impl PullRequestDetailView {
}); });
cx.defer(move |cx| { cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.sync(cx))); log_dropped(weak.update(cx, |this, cx| this.sync(cx)));
}); });
Self { Self {
@@ -300,7 +305,7 @@ impl PullRequestDetailView {
}; };
let workspace = self.workspace.clone(); let workspace = self.workspace.clone();
let commit_id = commit_id.to_owned(); let commit_id = commit_id.to_owned();
crate::shared::panels::open_detail( open_detail(
&workspace, &workspace,
id, id,
move |window, cx| { move |window, cx| {
@@ -336,7 +341,7 @@ impl PullRequestDetailView {
] ]
}) })
.on_change(move |index, _, cx| { .on_change(move |index, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| { log_dropped(weak.update(cx, |this, cx| {
this.active_tab = index; this.active_tab = index;
cx.notify(); cx.notify();
})); }));
@@ -346,10 +351,10 @@ impl PullRequestDetailView {
fn render_discussion(&mut self, cx: &mut Context<Self>) -> AnyElement { fn render_discussion(&mut self, cx: &mut Context<Self>) -> AnyElement {
if self.loading { if self.loading {
return centered_spinner(); return Spinner::centered("pr-loading");
} }
if let Some(error) = self.error.clone() { if let Some(error) = self.error.clone() {
return empty_state(error); return EmptyState::centered(error);
} }
let (author, picture, age, root_id, pubkey) = { let (author, picture, age, root_id, pubkey) = {
let store = self.store.read(cx); let store = self.store.read(cx);
@@ -358,7 +363,7 @@ impl PullRequestDetailView {
.iter() .iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest) .find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
else { else {
return empty_state(NOT_FOUND); return EmptyState::centered(NOT_FOUND);
}; };
let profile = self.directory.read(cx).profile(&root.pubkey, cx); let profile = self.directory.read(cx).profile(&root.pubkey, cx);
( (
@@ -370,6 +375,8 @@ impl PullRequestDetailView {
) )
}; };
let store = self.store.read(cx);
h_flex() h_flex()
.size_full() .size_full()
.min_h_0() .min_h_0()
@@ -416,7 +423,7 @@ impl PullRequestDetailView {
.child(comment_form( .child(comment_form(
&self.store, &self.store,
root_id, root_id,
pr_roots, &store.pull_requests,
&self.comment_input, &self.comment_input,
"pr-comment", "pr-comment",
cx, cx,
@@ -426,7 +433,7 @@ impl PullRequestDetailView {
.child(sidebar_section( .child(sidebar_section(
&self.store, &self.store,
root_id, root_id,
pr_roots, &store.pull_requests,
true, true,
&self.directory, &self.directory,
cx, cx,
@@ -436,29 +443,29 @@ impl PullRequestDetailView {
fn render_files(&self, _cx: &mut Context<Self>) -> AnyElement { fn render_files(&self, _cx: &mut Context<Self>) -> AnyElement {
if self.loading { if self.loading {
return centered_spinner(); return Spinner::centered("pr-loading");
} }
if let Some(error) = self.error.clone() { if let Some(error) = self.error.clone() {
return empty_state(error); return EmptyState::centered(error);
} }
self.pane.clone().into_any_element() self.pane.clone().into_any_element()
} }
fn render_commits(&self, cx: &mut Context<Self>) -> AnyElement { fn render_commits(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading { if self.loading {
return centered_spinner(); return Spinner::centered("pr-loading");
} }
if let Some(error) = self.error.clone() { if let Some(error) = self.error.clone() {
return empty_state(error); return EmptyState::centered(error);
} }
if self.commits.is_empty() { if self.commits.is_empty() {
return empty_state("No commits found"); return EmptyState::centered("No commits found");
} }
let commits = Arc::clone(&self.commits); let commits = Arc::clone(&self.commits);
let worktree = self.worktree.clone(); let worktree = self.worktree.clone();
let view = cx.entity().downgrade(); let view = cx.entity().downgrade();
crate::shared::event_list::commit_list( commit_list(
"pr-commits", "pr-commits",
"pr-commits-scroll", "pr-commits-scroll",
commits, commits,
@@ -467,12 +474,11 @@ impl PullRequestDetailView {
move |commit, window, cx| { move |commit, window, cx| {
if let Some(worktree) = worktree.clone() { if let Some(worktree) = worktree.clone() {
let id = commit.id.clone(); let id = commit.id.clone();
crate::shared::log_dropped(view.update(cx, |this, cx| { log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(worktree, &id, window, cx); this.open_commit_diff(worktree, &id, window, cx);
})); }));
} }
}, },
cx,
) )
} }
@@ -528,7 +534,7 @@ impl PullRequestDetailView {
.when(can_update, |this| { .when(can_update, |this| {
this.child(Button::new("update-pr").label("Update").small().on_click( this.child(Button::new("update-pr").label("Update").small().on_click(
move |_, _, cx| { move |_, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| { log_dropped(weak.update(cx, |this, cx| {
let root = this let root = this
.store .store
.read(cx) .read(cx)
@@ -595,7 +601,3 @@ impl Render for PullRequestDetailView {
}) })
} }
} }
fn centered_spinner() -> AnyElement {
crate::shared::widgets::centered_spinner("pr-loading")
}
@@ -4,14 +4,13 @@ use gpui::{
}; };
use nostr::prelude::Event; use nostr::prelude::Event;
use signed_state::RepoStore; use signed_state::RepoStore;
use ui::button::Button;
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle}; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use crate::shared::progress::DialogProgress; use crate::shared::progress::{DialogProgress, dialog_submit_button};
pub struct UpdatePrDialog { pub struct UpdatePrDialog {
handle: DialogHandle, handle: DialogHandle,
@@ -80,13 +79,17 @@ impl Render for UpdatePrDialog {
let this = this.clone(); let this = this.clone();
let busy = action_state.read(cx).busy; let busy = action_state.read(cx).busy;
vec![ vec![
Button::new("submit-update") dialog_submit_button(
.label("Update pull request") "submit-update",
.loading(busy) "Update pull request",
.disabled(busy) None,
.on_click(move |_, _, cx| { busy,
crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx))); &this,
}) |this, _window, cx| {
this.submit(cx);
Ok(())
},
)
.into_any_element() as AnyElement, .into_any_element() as AnyElement,
] ]
}) })
@@ -7,6 +7,7 @@ use ui::menu::MenuItem;
use utils::middle_truncate; use utils::middle_truncate;
use super::NewPullRequestView; use super::NewPullRequestView;
use crate::repo::helpers::announcement_display_name;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PullRequestFilter { pub enum PullRequestFilter {
@@ -115,7 +116,7 @@ pub fn source_menu_items(
}; };
let title = format!( let title = format!(
"{} — {}", "{} — {}",
crate::repo::helpers::announcement_display_name(&candidate), announcement_display_name(&candidate),
subtitle subtitle
); );
let target = view.clone(); let target = view.clone();
+11 -9
View File
@@ -31,7 +31,9 @@ pub use send_patch::SendPatchView;
use crate::issues::helpers::{StatusCounts, filter_by_status}; use crate::issues::helpers::{StatusCounts, filter_by_status};
use crate::repo::helpers::short_id; use crate::repo::helpers::short_id;
use crate::shared::event_list::{EventList, EventRow}; use crate::shared::event_list::{EventHandler, EventList, EventRow, filter_toolbar};
use crate::shared::log_dropped;
use crate::shared::panels::open_detail;
use crate::workspace::Workspace; use crate::workspace::Workspace;
pub struct PullRequestsView { pub struct PullRequestsView {
@@ -59,7 +61,7 @@ impl PullRequestsView {
}); });
cx.defer(move |cx| { cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| { log_dropped(weak.update(cx, |this, cx| {
this.rebuild(cx); this.rebuild(cx);
})); }));
}); });
@@ -139,7 +141,7 @@ impl PullRequestsView {
let workspace_for_build = workspace.clone(); let workspace_for_build = workspace.clone();
let store = self.store.clone(); let store = self.store.clone();
crate::shared::panels::open_detail( open_detail(
&workspace, &workspace,
id.clone(), id.clone(),
move |window, cx| { move |window, cx| {
@@ -168,7 +170,7 @@ impl PullRequestsView {
let workspace_for_build = workspace.clone(); let workspace_for_build = workspace.clone();
let store = self.store.clone(); let store = self.store.clone();
crate::shared::panels::open_detail( open_detail(
&workspace, &workspace,
id.clone(), id.clone(),
move |window, cx| { move |window, cx| {
@@ -195,7 +197,7 @@ impl PullRequestsView {
let menu_open_weak = cx.entity().downgrade(); let menu_open_weak = cx.entity().downgrade();
let patch_weak = cx.entity().downgrade(); let patch_weak = cx.entity().downgrade();
crate::shared::event_list::filter_toolbar( filter_toolbar(
cx, cx,
[ [
Segmented::new("pr-filter", self.filter) Segmented::new("pr-filter", self.filter)
@@ -248,7 +250,7 @@ impl PullRequestsView {
} }
}) })
.on_open_change(move |open, _, cx| { .on_open_change(move |open, _, cx| {
crate::shared::log_dropped(menu_open_weak.update(cx, |this, cx| { log_dropped(menu_open_weak.update(cx, |this, cx| {
this.new_pr_menu_open = open; this.new_pr_menu_open = open;
cx.notify(); cx.notify();
})); }));
@@ -257,7 +259,7 @@ impl PullRequestsView {
vec![MenuItem::new("Send Patch").handler({ vec![MenuItem::new("Send Patch").handler({
let weak = patch_weak.clone(); let weak = patch_weak.clone();
move |window, cx| { move |window, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| { log_dropped(weak.update(cx, |this, cx| {
this.open_send_patch(window, cx); this.open_send_patch(window, cx);
})); }));
} }
@@ -302,14 +304,14 @@ impl Render for PullRequestsView {
let id_hex = pr.id.to_hex(); let id_hex = pr.id.to_hex();
let status = store.read(cx).status_of(pr); let status = store.read(cx).status_of(pr);
let on_click: crate::shared::event_list::EventHandler = { let on_click: EventHandler = {
let workspace = workspace.clone(); let workspace = workspace.clone();
let store = store.clone(); let store = store.clone();
Rc::new(move |_, window, cx| { Rc::new(move |_, window, cx| {
let id = SharedString::from(format!("pr:{pr_id}")); let id = SharedString::from(format!("pr:{pr_id}"));
let workspace_for_build = workspace.clone(); let workspace_for_build = workspace.clone();
let store = store.clone(); let store = store.clone();
crate::shared::panels::open_detail( open_detail(
&workspace, &workspace,
id, id,
move |window, cx| { move |window, cx| {
+418 -31
View File
@@ -1,30 +1,36 @@
use std::path::PathBuf; use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle, ParentElement as _, PathPromptOptions, Render, SharedString, Styled as _, Subscription,
WeakEntity, Window, div, px, UniformListScrollHandle, WeakEntity, Window, div, px,
}; };
use signed_state::{CheckoutsStore, RepoStore}; use nostr::prelude::Url;
use ui::button::Button; use signed_core::Announcement;
use signed_git::{GitCache, Repo};
use signed_state::{Backend, CheckoutsStore, Mirrors, RepoListStore, RepoStore};
use ui::button::{Button, ButtonVariant};
use ui::combobox::{Combobox, ComboboxState}; use ui::combobox::{Combobox, ComboboxState};
use ui::common::{StyledExt as _, h_flex, v_flex}; use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::menu::Menu; use ui::menu::Menu;
use ui::spinner::Spinner;
use ui::tabs::{Tab, Tabs}; use ui::tabs::{Tab, Tabs};
use super::helpers::{ForkCompare, truncate_label}; use super::helpers::{ForkCompare, truncate_label};
use crate::repo::commit_diff::{CommitDiffView, DiffPane}; use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::repo::helpers::announcement_display_name;
use crate::shared::event_list::commit_list;
use crate::shared::log_dropped;
use crate::shared::panels::open_detail;
use crate::shared::progress::error_row; use crate::shared::progress::error_row;
use crate::shared::widgets::empty_state;
use crate::workspace::Workspace; use crate::workspace::Workspace;
mod source;
pub struct NewPullRequestView { pub struct NewPullRequestView {
workspace: WeakEntity<Workspace>, workspace: WeakEntity<Workspace>,
panel_id: SharedString, panel_id: SharedString,
@@ -73,7 +79,7 @@ impl NewPullRequestView {
let weak = weak.clone(); let weak = weak.clone();
move |value, _window, cx| { move |value, _window, cx| {
if let Some(base) = value { if let Some(base) = value {
crate::shared::log_dropped(weak.update(cx, |this, cx| { log_dropped(weak.update(cx, |this, cx| {
if this.base == base { if this.base == base {
return; return;
} }
@@ -94,7 +100,7 @@ impl NewPullRequestView {
let weak = weak.clone(); let weak = weak.clone();
move |value, _window, cx| { move |value, _window, cx| {
if let Some(compare) = value { if let Some(compare) = value {
crate::shared::log_dropped(weak.update(cx, |this, cx| { log_dropped(weak.update(cx, |this, cx| {
if this.compare == compare { if this.compare == compare {
return; return;
} }
@@ -110,7 +116,7 @@ impl NewPullRequestView {
}); });
window.defer(cx, move |window, cx| { window.defer(cx, move |window, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| { log_dropped(weak.update(cx, |this, cx| {
let Some(addr) = this.store.read(cx).addr().cloned() else { let Some(addr) = this.store.read(cx).addr().cloned() else {
return; return;
}; };
@@ -209,7 +215,7 @@ impl NewPullRequestView {
this.update(cx, |this, _cx| { this.update(cx, |this, _cx| {
this.submitting = false; this.submitting = false;
})?; })?;
crate::shared::log_dropped( log_dropped(
workspace.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)), workspace.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)),
); );
Ok(()) Ok(())
@@ -227,7 +233,7 @@ impl NewPullRequestView {
}; };
let workspace = self.workspace.clone(); let workspace = self.workspace.clone();
let commit_id = commit_id.to_owned(); let commit_id = commit_id.to_owned();
crate::shared::panels::open_detail( open_detail(
&workspace, &workspace,
id, id,
move |window, cx| { move |window, cx| {
@@ -270,7 +276,7 @@ impl NewPullRequestView {
let active_fork = self.fork.as_ref().map(|fork| fork.announcement.addr()); let active_fork = self.fork.as_ref().map(|fork| fork.announcement.addr());
let can_submit = self.submit_enabled(cx); let can_submit = self.submit_enabled(cx);
let source_label = match &self.fork { let source_label = match &self.fork {
Some(fork) => truncate_label(&crate::repo::helpers::announcement_display_name( Some(fork) => truncate_label(&announcement_display_name(
&fork.announcement, &fork.announcement,
)), )),
None => self.repo_path.as_ref().map_or_else( None => self.repo_path.as_ref().map_or_else(
@@ -289,21 +295,21 @@ impl NewPullRequestView {
.child( .child(
v_flex() v_flex()
.gap_1() .gap_1()
.child(label("Merge Into")) .child(div().text_xs().font_medium().child("Merge Into"))
.child(div().w(px(160.)).child(self.base_select.clone())), .child(div().w(px(160.)).child(self.base_select.clone())),
) )
.child( .child(
v_flex() v_flex()
.gap_1() .gap_1()
.child(label("Pull From")) .child(div().text_xs().font_medium().child("Pull From"))
.child(div().w(px(160.)).child(self.compare_select.clone())), .child(div().w(px(160.)).child(self.compare_select.clone())),
) )
.child( .child(
v_flex().gap_1().child(label("Source")).child( v_flex().gap_1().child(div().text_xs().font_medium().child("Source")).child(
Menu::new("pr-source") Menu::new("pr-source")
.open(self.source_open) .open(self.source_open)
.on_change(move |open, _, cx| { .on_change(move |open, _, cx| {
crate::shared::log_dropped(weak_menu.update(cx, |this, cx| { log_dropped(weak_menu.update(cx, |this, cx| {
this.source_open = open; this.source_open = open;
cx.notify(); cx.notify();
})); }));
@@ -311,7 +317,7 @@ impl NewPullRequestView {
.trigger(move |_, _| { .trigger(move |_, _| {
Button::new("compare-source") Button::new("compare-source")
.label(source_label.clone()) .label(source_label.clone())
.variant(ui::button::ButtonVariant::Secondary) .variant(ButtonVariant::Secondary)
.into_any_element() .into_any_element()
}) })
.items(move |_, _| { .items(move |_, _| {
@@ -343,7 +349,7 @@ impl NewPullRequestView {
.loading(self.submitting) .loading(self.submitting)
.disabled(!can_submit) .disabled(!can_submit)
.on_click(move |_, window, cx| { .on_click(move |_, window, cx| {
crate::shared::log_dropped( log_dropped(
weak.update(cx, |this, cx| this.submit(window, cx)), weak.update(cx, |this, cx| this.submit(window, cx)),
); );
}), }),
@@ -366,7 +372,7 @@ impl NewPullRequestView {
] ]
}) })
.on_change(move |index, _, cx| { .on_change(move |index, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| { log_dropped(weak.update(cx, |this, cx| {
this.active_tab = index; this.active_tab = index;
cx.notify(); cx.notify();
})); }));
@@ -376,13 +382,15 @@ impl NewPullRequestView {
fn render_content(&self, cx: &mut Context<Self>) -> AnyElement { fn render_content(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading { if self.loading {
return crate::shared::widgets::centered_spinner("new-pr-loading"); return Spinner::centered("new-pr-loading");
} }
if !self.has_source() { if !self.has_source() {
return empty_state("Choose a local checkout or an announced fork to compare"); return EmptyState::centered(
"Choose a local checkout or an announced fork to compare",
);
} }
if self.commits.is_none() && self.error.is_some() { if self.commits.is_none() && self.error.is_some() {
return empty_state("Nothing to compare"); return EmptyState::centered("Nothing to compare");
} }
match self.active_tab { match self.active_tab {
0 => self.pane.clone().into_any_element(), 0 => self.pane.clone().into_any_element(),
@@ -392,15 +400,15 @@ impl NewPullRequestView {
fn render_commits(&self, cx: &mut Context<Self>) -> AnyElement { fn render_commits(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(commits) = self.commits.as_ref() else { let Some(commits) = self.commits.as_ref() else {
return empty_state("No commits"); return EmptyState::centered("No commits");
}; };
if commits.is_empty() { if commits.is_empty() {
return empty_state("No commits between the branches"); return EmptyState::centered("No commits between the branches");
} }
let commits = Arc::clone(commits); let commits = Arc::clone(commits);
let view = cx.entity().downgrade(); let view = cx.entity().downgrade();
crate::shared::event_list::commit_list( commit_list(
"new-pr-commits", "new-pr-commits",
"new-pr-commits-scroll", "new-pr-commits-scroll",
commits, commits,
@@ -408,13 +416,383 @@ impl NewPullRequestView {
|_, _, _| None, |_, _, _| None,
move |commit, window, cx| { move |commit, window, cx| {
let id = commit.id.clone(); let id = commit.id.clone();
crate::shared::log_dropped(view.update(cx, |this, cx| { log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(&id, window, cx); this.open_commit_diff(&id, window, cx);
})); }));
}, },
cx,
) )
} }
pub(super) fn has_source(&self) -> bool {
self.repo_path.is_some() || self.fork.is_some()
}
pub(super) fn work_path(&self) -> Option<PathBuf> {
match &self.fork {
Some(fork) => Some(fork.mirror_path.clone()),
None => self.repo_path.clone(),
}
}
pub(super) fn base_ref(&self) -> String {
match &self.fork {
Some(_) => ForkCompare::base_ref(&self.base),
None => self.base.to_string(),
}
}
pub(super) fn compare_ref(&self) -> String {
match &self.fork {
Some(fork) => fork.compare_ref(&self.compare),
None => self.compare.to_string(),
}
}
pub(crate) fn choose_checkout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Choose local checkout".into()),
});
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let picked = match prompt.await {
Ok(Ok(Some(mut paths))) => paths.pop(),
_ => None,
};
let Some(path) = picked else {
return Ok(());
};
this.update_in(cx, |this, window, cx| {
this.apply_folder_path(path, window, cx)
})?;
Ok(())
});
self.push_task(task);
}
pub(crate) fn apply_folder_path(
&mut self,
path: PathBuf,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.fork_generation = self.fork_generation.wrapping_add(1);
let generation = self.fork_generation;
let path_string = path.to_string_lossy().to_string();
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let info = cx
.background_spawn({
let path = path.clone();
async move {
let repo = Repo::try_open(&path)?;
match repo.branches() {
Ok(branches) => Some((branches, repo.current_branch())),
Err(error) => {
log::warn!("failed to list branches: {error}");
None
}
}
}
})
.await;
this.update_in(cx, |this, window, cx| {
if generation != this.fork_generation {
return;
}
this.apply_checkout(path_string, info, window, cx);
})?;
Ok(())
});
self.push_task(task);
}
fn apply_checkout(
&mut self,
path: String,
info: Option<(Vec<String>, Option<String>)>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.fork = None;
let Some((branches, current)) = info else {
self.error = Some("The chosen folder is not a git repository".into());
self.repo_path = None;
self.branches.clear();
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
cx.notify();
return;
};
if branches.is_empty() {
self.error = Some("The repository has no branches yet".into());
self.repo_path = None;
self.branches.clear();
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
cx.notify();
return;
}
let announced = self.store.read(cx).head.clone();
let base = preferred_branch(&branches, announced);
let compare = current
.filter(|branch| branches.contains(branch))
.unwrap_or_else(|| base.clone());
self.repo_path = Some(PathBuf::from(&path));
self.error = None;
self.branches = branches.into_iter().map(SharedString::from).collect();
if let Some(addr) = self.store.read(cx).addr().cloned() {
CheckoutsStore::global(cx).update(cx, |store, cx| {
store.record(PathBuf::from(&path), addr, cx);
});
}
self.base = SharedString::from(base);
self.compare = SharedString::from(compare);
self.sync_selectors(window, cx);
self.reload_compare(cx);
}
fn sync_selectors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let options: Vec<(SharedString, SharedString)> = self
.branches
.iter()
.map(|branch| (branch.clone(), branch.clone()))
.collect();
let base = self.base.clone();
let compare = self.compare.clone();
self.base_select.update(cx, |state, cx| {
state.set_options(options.clone(), cx);
state.set_selected(Some(base), window, cx);
});
self.compare_select.update(cx, |state, cx| {
state.set_options(options, cx);
state.set_selected(Some(compare), window, cx);
});
}
pub(super) fn fork_candidates(&self, cx: &App) -> Vec<Announcement> {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return Vec::new();
};
let euc = self
.store
.read(cx)
.announcement
.as_ref()
.and_then(|a| a.euc.clone());
let user = Backend::global(cx).read(cx).current_user();
let announcements = RepoListStore::global(cx).read(cx).announcements.clone();
Announcement::forks_in(&announcements, &addr, euc.as_deref(), user)
.into_iter()
.cloned()
.collect()
}
pub(crate) fn choose_fork(
&mut self,
announcement: Announcement,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(base) = self.store.read(cx).addr().cloned() else {
return;
};
let mirror_path = Mirrors::path(&base);
let namespace = GitCache::fork_namespace(&announcement);
let clone_urls: Vec<Url> = announcement.clone.clone();
let base_clone_urls: Vec<Url> = self
.store
.read(cx)
.announcement
.as_ref()
.map(|a| a.clone.clone())
.unwrap_or_default();
self.fork_generation = self.fork_generation.wrapping_add(1);
let generation = self.fork_generation;
let handle = window.window_handle();
self.loading = true;
self.error = None;
cx.notify();
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
let namespace = namespace.clone();
let mirror_path = mirror_path.clone();
async move {
Mirrors::ensure(&base, &base_clone_urls)?;
let repo = Repo::open(&mirror_path)?;
repo.delete_refs_with_prefix("refs/fork")?;
repo.fetch_refs(
&clone_urls,
&format!("+refs/heads/*:refs/fork/{namespace}/*"),
)?;
let strip = |refs: Vec<String>, prefix: &str| {
let mut names: Vec<String> = refs
.into_iter()
.filter_map(|name| {
name.strip_prefix(prefix)
.map(|rest| rest.trim_start_matches('/').to_owned())
})
.filter(|name| !name.is_empty())
.collect();
names.sort();
names
};
let base_branches = strip(
repo.refs_with_prefix("refs/remotes/origin")?,
"refs/remotes/origin",
);
let compare_branches = strip(
repo.refs_with_prefix(&format!("refs/fork/{namespace}"))?,
&format!("refs/fork/{namespace}"),
);
Ok::<_, anyhow::Error>((base_branches, compare_branches))
}
})
.await;
if let Err(error) = cx.update_window(handle, |_, window, cx| {
this.update(cx, |this, cx| {
if generation != this.fork_generation {
return;
}
this.apply_fork(announcement, mirror_path, namespace, result, window, cx);
})
}) {
log::warn!("failed to apply fork: {error}");
}
Ok(())
});
self.push_task(task);
}
fn apply_fork(
&mut self,
announcement: Announcement,
mirror_path: PathBuf,
namespace: String,
result: Result<(Vec<String>, Vec<String>), anyhow::Error>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.loading = false;
let (base_branches, compare_branches) = match result {
Ok(branches) => branches,
Err(error) => {
self.error = Some(format!("Could not compare against the fork: {error}").into());
cx.notify();
return;
}
};
if compare_branches.is_empty() {
self.error = Some("The fork has no branches to compare".into());
cx.notify();
return;
}
if base_branches.is_empty() {
self.error = Some("Could not list the target repository's branches.".into());
cx.notify();
return;
}
let announced = self.store.read(cx).head.clone();
let base = preferred_branch(&base_branches, announced);
let compare = compare_branches
.iter()
.find(|branch| branch.as_str() == "main")
.map(|branch| SharedString::from(branch.clone()))
.unwrap_or_else(|| SharedString::from(compare_branches[0].clone()));
self.fork = Some(ForkCompare {
announcement,
namespace,
mirror_path,
});
self.error = None;
self.base = SharedString::from(base);
self.compare = compare;
self.branches = base_branches.into_iter().map(SharedString::from).collect();
self.sync_selectors(window, cx);
self.reload_compare(cx);
}
pub(super) fn reload_compare(&mut self, cx: &mut Context<Self>) {
let Some(repo_path) = self.work_path() else {
return;
};
let base = self.base_ref();
let compare = self.compare_ref();
let base_name = self.base.to_string();
let compare_name = self.compare.to_string();
self.loading = true;
self.error = None;
self.compare_generation += 1;
let generation = self.compare_generation;
cx.notify();
if base == compare {
self.loading = false;
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
self.error = Some("Choose different base and compare branches".into());
cx.notify();
return;
}
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
async move {
let repo = Repo::open(Path::new(&repo_path))?;
let merge_base = repo.merge_base(&base, &compare)?.ok_or_else(|| {
anyhow::anyhow!(
"{base_name} and {compare_name} share no common ancestor"
)
})?;
let commits = repo.commit_range(&merge_base, &compare)?;
let diff = repo.range_diff(&merge_base, &compare)?;
Ok::<_, anyhow::Error>((merge_base, commits, diff))
}
})
.await;
this.update(cx, |this, cx| {
if generation != this.compare_generation {
return;
}
this.loading = false;
match result {
Ok((merge_base, commits, diff)) => {
this.merge_base = Some(merge_base);
this.commits = Some(Arc::new(commits));
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
}
Err(error) => {
this.merge_base = None;
this.commits = None;
this.pane.update(cx, |pane, cx| pane.clear(cx));
this.error = Some(error.to_string().into());
}
}
cx.notify();
})?;
Ok(())
});
self.push_task(task);
}
} }
impl Panel for NewPullRequestView { impl Panel for NewPullRequestView {
@@ -462,6 +840,15 @@ impl Render for NewPullRequestView {
} }
} }
fn label(text: &'static str) -> AnyElement { /// The announced head when listed, else `main`, else the first branch.
div().text_xs().font_medium().child(text).into_any_element() fn preferred_branch(branches: &[String], announced: Option<String>) -> String {
announced
.filter(|branch| branches.contains(branch))
.or_else(|| {
branches
.iter()
.find(|branch| branch.as_str() == "main")
.cloned()
})
.unwrap_or_else(|| branches[0].clone())
} }
@@ -1,397 +0,0 @@
use std::path::{Path, PathBuf};
use std::sync::Arc;
use gpui::{App, AppContext as _, Context, PathPromptOptions, SharedString, Window};
use nostr::prelude::Url;
use signed_core::Announcement;
use signed_git::{GitCache, Repo};
use signed_state::{Backend, CheckoutsStore, Mirrors, RepoListStore};
use super::NewPullRequestView;
use crate::pull_requests::helpers::ForkCompare;
/// The announced head when listed, else `main`, else the first branch.
fn preferred_branch(branches: &[String], announced: Option<String>) -> String {
announced
.filter(|branch| branches.contains(branch))
.or_else(|| {
branches
.iter()
.find(|branch| branch.as_str() == "main")
.cloned()
})
.unwrap_or_else(|| branches[0].clone())
}
impl NewPullRequestView {
pub(super) fn has_source(&self) -> bool {
self.repo_path.is_some() || self.fork.is_some()
}
pub(super) fn work_path(&self) -> Option<PathBuf> {
match &self.fork {
Some(fork) => Some(fork.mirror_path.clone()),
None => self.repo_path.clone(),
}
}
pub(super) fn base_ref(&self) -> String {
match &self.fork {
Some(_) => ForkCompare::base_ref(&self.base),
None => self.base.to_string(),
}
}
pub(super) fn compare_ref(&self) -> String {
match &self.fork {
Some(fork) => fork.compare_ref(&self.compare),
None => self.compare.to_string(),
}
}
pub(crate) fn choose_checkout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Choose local checkout".into()),
});
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let picked = match prompt.await {
Ok(Ok(Some(mut paths))) => paths.pop(),
_ => None,
};
let Some(path) = picked else {
return Ok(());
};
this.update_in(cx, |this, window, cx| {
this.apply_folder_path(path, window, cx)
})?;
Ok(())
});
self.push_task(task);
}
pub(crate) fn apply_folder_path(
&mut self,
path: PathBuf,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.fork_generation = self.fork_generation.wrapping_add(1);
let generation = self.fork_generation;
let path_string = path.to_string_lossy().to_string();
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let info = cx
.background_spawn({
let path = path.clone();
async move {
let repo = Repo::try_open(&path)?;
match repo.branches() {
Ok(branches) => Some((branches, repo.current_branch())),
Err(error) => {
log::warn!("failed to list branches: {error}");
None
}
}
}
})
.await;
this.update_in(cx, |this, window, cx| {
if generation != this.fork_generation {
return;
}
this.apply_checkout(path_string, info, window, cx);
})?;
Ok(())
});
self.push_task(task);
}
fn apply_checkout(
&mut self,
path: String,
info: Option<(Vec<String>, Option<String>)>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.fork = None;
let Some((branches, current)) = info else {
self.error = Some("The chosen folder is not a git repository".into());
self.repo_path = None;
self.branches.clear();
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
cx.notify();
return;
};
if branches.is_empty() {
self.error = Some("The repository has no branches yet".into());
self.repo_path = None;
self.branches.clear();
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
cx.notify();
return;
}
let announced = self.store.read(cx).head.clone();
let base = preferred_branch(&branches, announced);
let compare = current
.filter(|branch| branches.contains(branch))
.unwrap_or_else(|| base.clone());
self.repo_path = Some(PathBuf::from(&path));
self.error = None;
self.branches = branches.into_iter().map(SharedString::from).collect();
if let Some(addr) = self.store.read(cx).addr().cloned() {
CheckoutsStore::global(cx).update(cx, |store, cx| {
store.record(PathBuf::from(&path), addr, cx);
});
}
self.base = SharedString::from(base);
self.compare = SharedString::from(compare);
self.sync_selectors(window, cx);
self.reload_compare(cx);
}
fn sync_selectors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let options: Vec<(SharedString, SharedString)> = self
.branches
.iter()
.map(|branch| (branch.clone(), branch.clone()))
.collect();
let base = self.base.clone();
let compare = self.compare.clone();
self.base_select.update(cx, |state, cx| {
state.set_options(options.clone(), cx);
state.set_selected(Some(base), window, cx);
});
self.compare_select.update(cx, |state, cx| {
state.set_options(options, cx);
state.set_selected(Some(compare), window, cx);
});
}
pub(super) fn fork_candidates(&self, cx: &App) -> Vec<Announcement> {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return Vec::new();
};
let euc = self
.store
.read(cx)
.announcement
.as_ref()
.and_then(|a| a.euc.clone());
let user = Backend::global(cx).read(cx).current_user();
let announcements = RepoListStore::global(cx).read(cx).announcements.clone();
Announcement::forks_in(&announcements, &addr, euc.as_deref(), user)
.into_iter()
.cloned()
.collect()
}
pub(crate) fn choose_fork(
&mut self,
announcement: Announcement,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(base) = self.store.read(cx).addr().cloned() else {
return;
};
let mirror_path = Mirrors::path(&base);
let namespace = GitCache::fork_namespace(&announcement);
let clone_urls: Vec<Url> = announcement.clone.clone();
let base_clone_urls: Vec<Url> = self
.store
.read(cx)
.announcement
.as_ref()
.map(|a| a.clone.clone())
.unwrap_or_default();
self.fork_generation = self.fork_generation.wrapping_add(1);
let generation = self.fork_generation;
let handle = window.window_handle();
self.loading = true;
self.error = None;
cx.notify();
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
let namespace = namespace.clone();
let mirror_path = mirror_path.clone();
async move {
Mirrors::ensure(&base, &base_clone_urls)?;
let repo = Repo::open(&mirror_path)?;
repo.delete_refs_with_prefix("refs/fork")?;
repo.fetch_refs(
&clone_urls,
&format!("+refs/heads/*:refs/fork/{namespace}/*"),
)?;
let strip = |refs: Vec<String>, prefix: &str| {
let mut names: Vec<String> = refs
.into_iter()
.filter_map(|name| {
name.strip_prefix(prefix)
.map(|rest| rest.trim_start_matches('/').to_owned())
})
.filter(|name| !name.is_empty())
.collect();
names.sort();
names
};
let base_branches = strip(
repo.refs_with_prefix("refs/remotes/origin")?,
"refs/remotes/origin",
);
let compare_branches = strip(
repo.refs_with_prefix(&format!("refs/fork/{namespace}"))?,
&format!("refs/fork/{namespace}"),
);
Ok::<_, anyhow::Error>((base_branches, compare_branches))
}
})
.await;
if let Err(error) = cx.update_window(handle, |_, window, cx| {
this.update(cx, |this, cx| {
if generation != this.fork_generation {
return;
}
this.apply_fork(announcement, mirror_path, namespace, result, window, cx);
})
}) {
log::warn!("failed to apply fork: {error}");
}
Ok(())
});
self.push_task(task);
}
fn apply_fork(
&mut self,
announcement: Announcement,
mirror_path: PathBuf,
namespace: String,
result: Result<(Vec<String>, Vec<String>), anyhow::Error>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.loading = false;
let (base_branches, compare_branches) = match result {
Ok(branches) => branches,
Err(error) => {
self.error = Some(format!("Could not compare against the fork: {error}").into());
cx.notify();
return;
}
};
if compare_branches.is_empty() {
self.error = Some("The fork has no branches to compare".into());
cx.notify();
return;
}
if base_branches.is_empty() {
self.error = Some("Could not list the target repository's branches.".into());
cx.notify();
return;
}
let announced = self.store.read(cx).head.clone();
let base = preferred_branch(&base_branches, announced);
let compare = compare_branches
.iter()
.find(|branch| branch.as_str() == "main")
.map(|branch| SharedString::from(branch.clone()))
.unwrap_or_else(|| SharedString::from(compare_branches[0].clone()));
self.fork = Some(ForkCompare {
announcement,
namespace,
mirror_path,
});
self.error = None;
self.base = SharedString::from(base);
self.compare = compare;
self.branches = base_branches.into_iter().map(SharedString::from).collect();
self.sync_selectors(window, cx);
self.reload_compare(cx);
}
pub(super) fn reload_compare(&mut self, cx: &mut Context<Self>) {
let Some(repo_path) = self.work_path() else {
return;
};
let base = self.base_ref();
let compare = self.compare_ref();
let base_name = self.base.to_string();
let compare_name = self.compare.to_string();
self.loading = true;
self.error = None;
self.compare_generation += 1;
let generation = self.compare_generation;
cx.notify();
if base == compare {
self.loading = false;
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
self.error = Some("Choose different base and compare branches".into());
cx.notify();
return;
}
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
async move {
let repo = Repo::open(Path::new(&repo_path))?;
let merge_base = repo.merge_base(&base, &compare)?.ok_or_else(|| {
anyhow::anyhow!(
"{base_name} and {compare_name} share no common ancestor"
)
})?;
let commits = repo.commit_range(&merge_base, &compare)?;
let diff = repo.range_diff(&merge_base, &compare)?;
Ok::<_, anyhow::Error>((merge_base, commits, diff))
}
})
.await;
this.update(cx, |this, cx| {
if generation != this.compare_generation {
return;
}
this.loading = false;
match result {
Ok((merge_base, commits, diff)) => {
this.merge_base = Some(merge_base);
this.commits = Some(Arc::new(commits));
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
}
Err(error) => {
this.merge_base = None;
this.commits = None;
this.pane.update(cx, |pane, cx| pane.clear(cx));
this.error = Some(error.to_string().into());
}
}
cx.notify();
})?;
Ok(())
});
self.push_task(task);
}
}
@@ -11,6 +11,7 @@ use ui::input::{Input, InputState};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use crate::shared::log_dropped;
use crate::shared::progress::error_row; use crate::shared::progress::error_row;
use crate::workspace::Workspace; use crate::workspace::Workspace;
@@ -83,7 +84,7 @@ impl SendPatchView {
Ok(()) => { Ok(()) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
let panel_id = this.panel_id.clone(); let panel_id = this.panel_id.clone();
crate::shared::log_dropped( log_dropped(
this.workspace this.workspace
.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)), .update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)),
); );
@@ -122,7 +123,7 @@ impl SendPatchView {
.loading(self.submitting) .loading(self.submitting)
.disabled(!can_submit) .disabled(!can_submit)
.on_click(move |_, _, cx| { .on_click(move |_, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.submit(cx))); log_dropped(weak.update(cx, |this, cx| this.submit(cx)));
}), }),
) )
.into_any_element() .into_any_element()
+28 -36
View File
@@ -14,20 +14,21 @@ use ui::badge::GroupedBadge;
use ui::button::{Button, ButtonVariant}; use ui::button::{Button, ButtonVariant};
use ui::clipboard::ClipboardButton; use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::layout::resizable::{Resizable, ResizableState}; use ui::layout::resizable::{Resizable, ResizableState};
use ui::scrollbar::Scrollbar;
use ui::separator::Separator; use ui::separator::Separator;
use ui::spinner::Spinner;
use ui::switch::Switch; use ui::switch::Switch;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use ui::toggle::Toggle; use ui::toggle::Toggle;
use ui::tooltip::Tooltip; use ui::tooltip::Tooltip;
use ui::tree::{Tree, TreeItem}; use ui::tree::{Tree, TreeItem, TreeItemSeed};
use utils::relative_time_secs; use utils::relative_time_secs;
use super::helpers::{DiffRow, co_authors, diff_rows, render_diff_row, short_id}; use super::helpers::{DiffRow, co_authors, diff_rows, short_id};
use crate::shared::tree::{TreeItemSeed, TreeRow, build_tree_items, collect_expanded, flatten};
use crate::shared::widgets::{centered_spinner, empty_state, scroll_overlay};
/// Emitted when the user activates the Download commit button. /// Emitted when the user activates the Download commit button.
pub enum DiffPaneEvent { pub enum DiffPaneEvent {
@@ -59,7 +60,7 @@ pub struct DiffPane {
diff: Option<CommitDiff>, diff: Option<CommitDiff>,
seeds: Vec<TreeItemSeed>, seeds: Vec<TreeItemSeed>,
expanded: HashSet<String>, expanded: HashSet<String>,
rows: Vec<TreeRow>, rows: Vec<TreeItem>,
selected_index: Option<usize>, selected_index: Option<usize>,
tree_visible: bool, tree_visible: bool,
split: Entity<ResizableState>, split: Entity<ResizableState>,
@@ -103,9 +104,9 @@ impl DiffPane {
.collect(); .collect();
paths.sort(); paths.sort();
self.seeds = build_tree_items(&paths); self.seeds = TreeItemSeed::from_paths(&paths);
self.expanded = collect_expanded(&self.seeds); self.expanded = TreeItemSeed::collect_expanded(&self.seeds);
self.rows = flatten(&self.seeds, &self.expanded); self.rows = TreeItemSeed::flatten_all(&self.seeds, &self.expanded);
self.selected_index = None; self.selected_index = None;
self.diff = Some(diff); self.diff = Some(diff);
@@ -172,7 +173,10 @@ impl DiffPane {
} }
fn select_tree_file(&mut self, path: &str, cx: &mut Context<Self>) { fn select_tree_file(&mut self, path: &str, cx: &mut Context<Self>) {
self.selected_index = self.rows.iter().position(|row| row.id == path); self.selected_index = self
.rows
.iter()
.position(|row| row.key().to_string() == path);
if self.expanded_files.insert(path.to_owned()) { if self.expanded_files.insert(path.to_owned()) {
self.rebuild_rows(); self.rebuild_rows();
} }
@@ -249,7 +253,7 @@ impl DiffPane {
if !self.expanded.remove(id) { if !self.expanded.remove(id) {
self.expanded.insert(id.to_owned()); self.expanded.insert(id.to_owned());
} }
self.rows = flatten(&self.seeds, &self.expanded); self.rows = TreeItemSeed::flatten_all(&self.seeds, &self.expanded);
self.selected_index = self self.selected_index = self
.selected_index .selected_index
.and_then(|index| self.rows.get(index).map(|_| index)); .and_then(|index| self.rows.get(index).map(|_| index));
@@ -269,22 +273,7 @@ impl DiffPane {
.child( .child(
Tree::new("commit-diff-tree") Tree::new("commit-diff-tree")
.selected(selected) .selected(selected)
.items(move |_, _| { .items(move |_, _| rows.clone())
rows.iter()
.map(|row| {
let item = TreeItem::new(row.id.clone(), row.label.clone())
.depth(row.depth)
.expandable(row.expandable)
.expanded(row.expanded);
if row.expandable {
item.icon(Icon::named(IconRole::Folder))
} else {
item.icon(Icon::named(IconRole::File))
}
})
.collect()
})
.on_change(move |index, window, cx| { .on_change(move |index, window, cx| {
if let Some(index) = index if let Some(index) = index
&& let Err(error) = change_view.update(cx, |this, cx| { && let Err(error) = change_view.update(cx, |this, cx| {
@@ -298,7 +287,10 @@ impl DiffPane {
let view = view; let view = view;
move |index, _, cx| { move |index, _, cx| {
if let Err(error) = view.update(cx, |this, cx| { if let Err(error) = view.update(cx, |this, cx| {
let id = this.rows.get(index).map(|row| row.id.clone()); let id = this
.rows
.get(index)
.map(|row| row.key().to_string());
if let Some(id) = id { if let Some(id) = id {
this.toggle_folder(&id, cx); this.toggle_folder(&id, cx);
} }
@@ -315,8 +307,8 @@ impl DiffPane {
let Some(row) = self.rows.get(index) else { let Some(row) = self.rows.get(index) else {
return; return;
}; };
let id = row.id.clone(); let id = row.key().to_string();
let expandable = row.expandable; let expandable = row.is_expandable();
self.selected_index = Some(index); self.selected_index = Some(index);
if expandable { if expandable {
@@ -427,7 +419,7 @@ impl DiffPane {
fn render_file_list(&self, cx: &mut Context<Self>) -> AnyElement { fn render_file_list(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(diff) = self.diff.as_ref() else { let Some(diff) = self.diff.as_ref() else {
return empty_state("No changes"); return EmptyState::centered("No changes");
}; };
let files = diff.files.clone(); let files = diff.files.clone();
@@ -451,7 +443,7 @@ impl DiffPane {
.size_full() .size_full()
.p_2(), .p_2(),
) )
.child(scroll_overlay("commit-diff-files", self.list.clone())) .child(Scrollbar::vertical("commit-diff-files", self.list.clone()))
.into_any_element() .into_any_element()
} }
} }
@@ -562,7 +554,7 @@ fn render_pane_row(
.border_color(border) .border_color(border)
.bg(surface) .bg(surface)
.when(*last, |this| this.border_b_1().rounded_b_lg()) .when(*last, |this| this.border_b_1().rounded_b_lg())
.child(render_diff_row(&file.hunks, *row, wrap, cx)) .child(row.render(&file.hunks, wrap, cx))
.into_any_element() .into_any_element()
} }
} }
@@ -571,13 +563,13 @@ fn render_pane_row(
impl Render for DiffPane { impl Render for DiffPane {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
if self.diff.is_none() { if self.diff.is_none() {
return empty_state("No changes"); return EmptyState::centered("No changes");
} }
let diff = self.diff.as_ref().expect("diff checked above"); let diff = self.diff.as_ref().expect("diff checked above");
if diff.files.is_empty() { if diff.files.is_empty() {
return empty_state("No files changed"); return EmptyState::centered("No files changed");
} }
let toolbar = self.render_toolbar(cx); let toolbar = self.render_toolbar(cx);
@@ -898,9 +890,9 @@ impl Panel for CommitDiffView {
impl Render for CommitDiffView { impl Render for CommitDiffView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let body = if self.loading { let body = if self.loading {
centered_spinner("commit-diff-loading") Spinner::centered("commit-diff-loading")
} else if let Some(error) = self.error.clone() { } else if let Some(error) = self.error.clone() {
empty_state(error) EmptyState::centered(error)
} else { } else {
self.pane.clone().into_any_element() self.pane.clone().into_any_element()
}; };
+12 -11
View File
@@ -17,7 +17,7 @@ use ui::tooltip::Tooltip;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::repo::actions::open_repo_panel; use crate::repo::actions::open_repo_panel;
use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with}; use crate::shared::progress::{DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task_with};
use crate::workspace::Workspace; use crate::workspace::Workspace;
/// Progress of the create-repository flow, so async results can be rendered. /// Progress of the create-repository flow, so async results can be rendered.
@@ -229,16 +229,17 @@ impl Render for CreateRepoDialog {
let busy = action_state.read(cx).busy; let busy = action_state.read(cx).busy;
let this = this.clone(); let this = this.clone();
let create: AnyElement = Button::new("create-repository") let create: AnyElement = dialog_submit_button(
.label("Create repository") "create-repository",
.icon(Icon::named(IconRole::Plus)) "Create repository",
.loading(busy) Some(IconRole::Plus),
.disabled(busy) busy,
.on_click(move |_, window, cx| { &this,
crate::shared::log_dropped( |this, window, cx| {
this.update(cx, |this, cx| this.create(window, cx)), this.create(window, cx);
); Ok(())
}) },
)
.into_any_element(); .into_any_element();
vec![create] vec![create]
+13 -13
View File
@@ -9,11 +9,10 @@ use settings::SettingsStore;
use signed_core::RepoAddr; use signed_core::RepoAddr;
use signed_git::Repo; use signed_git::Repo;
use signed_state::Backend; use signed_state::Backend;
use ui::button::Button;
use ui::common::{ResultLogErr as _, v_flex}; use ui::common::{ResultLogErr as _, v_flex};
use ui::dialog::{Dialog, DialogHandle}; use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field; use ui::field::Field;
use ui::icons::{Icon, IconRole}; use ui::icons::IconRole;
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
use ui::layout::h_flex; use ui::layout::h_flex;
use ui::select::{Select, SelectOption}; use ui::select::{Select, SelectOption};
@@ -21,7 +20,7 @@ use ui::theme::ActiveTheme as _;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::repo::RepoDetailView; use crate::repo::RepoDetailView;
use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with}; use crate::shared::progress::{DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task_with};
pub struct InitRepoDialog { pub struct InitRepoDialog {
handle: DialogHandle, handle: DialogHandle,
@@ -246,16 +245,17 @@ impl Render for InitRepoDialog {
let busy = action_state.read(cx).busy; let busy = action_state.read(cx).busy;
let this = this.clone(); let this = this.clone();
let init: AnyElement = Button::new("initialize-repository") let init: AnyElement = dialog_submit_button(
.label("Initialize") "initialize-repository",
.icon(Icon::named(IconRole::Plus)) "Initialize",
.loading(busy) Some(IconRole::Plus),
.disabled(busy) busy,
.on_click(move |_, window, cx| { &this,
crate::shared::log_dropped( |this, window, cx| {
this.update(cx, |this, cx| this.init_repository(window, cx)), this.init_repository(window, cx);
); Ok(())
}) },
)
.into_any_element(); .into_any_element();
vec![init] vec![init]
+30 -37
View File
@@ -10,15 +10,14 @@ use gpui::{
use signed_git::{FileCommit, Repo, WorktreeSnapshot}; use signed_git::{FileCommit, Repo, WorktreeSnapshot};
use ui::code::CodeViewState; use ui::code::CodeViewState;
use ui::common::{StyledExt as _, h_flex, v_flex}; use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole}; use ui::empty_state::EmptyState;
use ui::markdown::MarkdownViewState; use ui::markdown::MarkdownViewState;
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use ui::tree::{Tree, TreeItem}; use ui::tree::{Tree, TreeItem, TreeItemSeed};
use super::helpers::{code_language, is_markdown_path, preview_spinner, source_hash}; use super::helpers::{code_language, is_markdown_path, source_hash};
use crate::repo::helpers::short_id; use crate::repo::helpers::short_id;
use crate::shared::tree::{TreeItemSeed, TreeRow, collect_expanded, flatten};
use crate::shared::widgets::empty_state;
const MAX_PREVIEW_BYTES: usize = 1024 * 1024; const MAX_PREVIEW_BYTES: usize = 1024 * 1024;
const MAX_PREVIEWED_FILES: usize = 32; const MAX_PREVIEWED_FILES: usize = 32;
@@ -56,7 +55,7 @@ struct CodeView {
pub struct RepoFilesView { pub struct RepoFilesView {
seeds: Vec<TreeItemSeed>, seeds: Vec<TreeItemSeed>,
expanded: HashSet<String>, expanded: HashSet<String>,
rows: Vec<TreeRow>, rows: Vec<TreeItem>,
selected_index: Option<usize>, selected_index: Option<usize>,
worktree: Option<PathBuf>, worktree: Option<PathBuf>,
worktree_paths: Vec<String>, worktree_paths: Vec<String>,
@@ -112,18 +111,22 @@ impl RepoFilesView {
) { ) {
self.worktree_paths = paths; self.worktree_paths = paths;
self.seeds = tree; self.seeds = tree;
let folder_ids = collect_expanded(&self.seeds); let folder_ids = TreeItemSeed::collect_expanded(&self.seeds);
self.expanded.retain(|id| folder_ids.contains(id)); self.expanded.retain(|id| folder_ids.contains(id));
self.rebuild_rows(); self.rebuild_rows();
cx.notify(); cx.notify();
} }
fn rebuild_rows(&mut self) { fn rebuild_rows(&mut self) {
self.rows = flatten(&self.seeds, &self.expanded); self.rows = TreeItemSeed::flatten_all(&self.seeds, &self.expanded);
self.selected_index = self self.selected_index = self
.selected_file .selected_file
.as_ref() .as_ref()
.and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref())); .and_then(|path| {
self.rows
.iter()
.position(|row| row.key().to_string() == path.as_ref())
});
} }
fn toggle_folder(&mut self, id: &str) { fn toggle_folder(&mut self, id: &str) {
@@ -235,8 +238,8 @@ impl RepoFilesView {
let Some(row) = self.rows.get(index) else { let Some(row) = self.rows.get(index) else {
return; return;
}; };
let id = row.id.clone(); let id = row.key().to_string();
let expandable = row.expandable; let expandable = row.is_expandable();
self.selected_index = Some(index); self.selected_index = Some(index);
@@ -261,22 +264,7 @@ impl RepoFilesView {
.child( .child(
Tree::new("repo-tree") Tree::new("repo-tree")
.selected(selected) .selected(selected)
.items(move |_, _| { .items(move |_, _| rows.clone())
rows.iter()
.map(|row| {
let item = TreeItem::new(row.id.clone(), row.label.clone())
.depth(row.depth)
.expandable(row.expandable)
.expanded(row.expanded);
if row.expandable {
item.icon(Icon::named(IconRole::Folder))
} else {
item.icon(Icon::named(IconRole::File))
}
})
.collect()
})
.on_change({ .on_change({
let view = change_view; let view = change_view;
move |index, window, cx| { move |index, window, cx| {
@@ -293,7 +281,10 @@ impl RepoFilesView {
let view = disclosure_view; let view = disclosure_view;
move |index, _, cx| { move |index, _, cx| {
if let Err(error) = view.update(cx, |this, cx| { if let Err(error) = view.update(cx, |this, cx| {
let id = this.rows.get(index).map(|row| row.id.clone()); let id = this
.rows
.get(index)
.map(|row| row.key().to_string());
if let Some(id) = id { if let Some(id) = id {
this.toggle_folder(&id); this.toggle_folder(&id);
cx.emit(RepoFilesEvent::Activated); cx.emit(RepoFilesEvent::Activated);
@@ -319,15 +310,17 @@ impl RepoFilesView {
self.code_element(path.as_ref()) self.code_element(path.as_ref())
} }
} }
Some(FileContent::Binary) => empty_state("Binary file - preview not supported"), Some(FileContent::Binary) => EmptyState::centered(
Some(FileContent::TooLarge) => empty_state("File is too large to preview"), "Binary file - preview not supported",
Some(FileContent::Failed(message)) => empty_state(message), ),
None => preview_spinner(), 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() { } else if self.readme_name.is_some() {
self.markdown_element(None) self.markdown_element(None)
} else { } else {
empty_state("No README found") EmptyState::centered("No README found")
}; };
let commit = match &self.selected_file { let commit = match &self.selected_file {
@@ -426,7 +419,7 @@ impl RepoFilesView {
fn markdown_element(&self, path: Option<&str>) -> AnyElement { fn markdown_element(&self, path: Option<&str>) -> AnyElement {
let Some(md) = &self.md else { let Some(md) = &self.md else {
return preview_spinner(); return Spinner::centered("repo-preview-spinner");
}; };
let ready = match path { let ready = match path {
@@ -435,7 +428,7 @@ impl RepoFilesView {
}; };
if !ready { if !ready {
return preview_spinner(); return Spinner::centered("repo-preview-spinner");
} }
div() div()
@@ -481,10 +474,10 @@ impl RepoFilesView {
fn code_element(&self, path: &str) -> AnyElement { fn code_element(&self, path: &str) -> AnyElement {
let Some(code) = &self.code else { let Some(code) = &self.code else {
return preview_spinner(); return Spinner::centered("repo-preview-spinner");
}; };
if code.path.as_ref() != path { if code.path.as_ref() != path {
return preview_spinner(); return Spinner::centered("repo-preview-spinner");
} }
div() div()
-455
View File
@@ -1,455 +0,0 @@
use std::collections::HashSet;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, Context, InteractiveElement as _, IntoElement, ParentElement as _, SharedString,
StatefulInteractiveElement as _, Styled as _, Window, div, px,
};
use signed_state::{Backend, Nip34Kind};
use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariant};
use ui::common::{Sizable, StyledExt as _, h_flex, v_flex};
use ui::dropdown_menu::DropdownMenu;
use ui::icons::{Icon, IconRole};
use ui::menu::MenuItem;
use ui::popover::Popover;
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use utils::relative_time_secs;
use super::helpers::{bound_repo_label, clone_group, fork_row, nostr_clone_url, repo_display_name};
use super::{RepoDetailView, actions, dialogs};
use crate::shared::widgets::clone_row;
impl RepoDetailView {
pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(addr) = self
.announcement(cx)
.and_then(|announcement| announcement.upstream.as_ref())
.and_then(|upstream| upstream.addr.clone())
else {
return;
};
actions::open_repo_panel(&self.workspace, &addr, None, window, cx);
}
/// Open the dialog that publishes the local repository to NIP-34.
fn open_init_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(local_path) = self.store.read(cx).path.clone() else {
return;
};
self.init = Some(dialogs::init::InitRepoDialog::new(
local_path,
cx.entity().downgrade(),
window,
cx,
));
cx.notify();
}
pub(super) fn render_about(&mut self, cx: &mut Context<Self>) -> AnyElement {
if self.store.read(cx).addr().is_none() {
return self.render_init_banner(cx);
}
let backend = Backend::global(cx);
let store = self.store.read(cx);
let pushing = store.pushing;
let cloning = store.cloning;
let Some(announcement) = store.announcement.clone() else {
return div().into_any_element();
};
let nip05 = self
.directory
.read(cx)
.profile(&announcement.owner, cx)
.metadata()
.nip05
.clone()
.filter(|nip05| !nip05.trim().is_empty());
let nostr_url = nostr_clone_url(&announcement, nip05.as_deref());
let ngit_command = SharedString::from(format!("git clone {nostr_url}"));
let nak_command = SharedString::from(format!("nak git clone {nostr_url}"));
let git_commands: Vec<String> = announcement.clone_urls();
let name = repo_display_name(self.store.read(cx));
let description = announcement.description();
let avatar = Avatar::new(format!("{}:{}", announcement.owner, announcement.id));
let announcement_for_menu = announcement.clone();
let weak_menu_open = cx.entity().downgrade();
let weak_menu_items = cx.entity().downgrade();
let weak_clone = cx.entity().downgrade();
let weak_download = cx.entity().downgrade();
let ngit_for_popover = ngit_command.clone();
let nak_for_popover = nak_command.clone();
let git_for_popover = git_commands.clone();
h_flex()
.p_6()
.w_full()
.gap_6()
.items_start()
.justify_between()
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_2()
.child(
h_flex()
.gap_2()
.text_sm()
.font_semibold()
.child(avatar)
.child(name),
)
.child(
div()
.min_w_0()
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.line_clamp(3)
.child(description),
)
.when_some(fork_row(&announcement, cx), |this, row| this.child(row)),
)
.child(
h_flex()
.flex_none()
.gap_2()
.justify_end()
.child(
Popover::new("code-popover")
.open(self.clone_open)
.on_change(move |open, _, cx| {
if let Err(error) = weak_clone.update(cx, |this, cx| {
this.clone_open = open;
cx.notify();
}) {
log::warn!("failed to update clone popover: {error}");
}
})
.trigger(move |_, _| {
Button::new("code")
.label("Code")
.icon(Icon::named(IconRole::GitClone))
.tooltip(Tooltip::text("Clone repository"))
.loading(cloning)
.disabled(cloning)
.into_any_element()
})
.content(move |_, cx| {
v_flex()
.w(px(440.))
.p_3()
.gap_4()
.child(clone_group(
"Clone with ngit",
"copy-ngit".into(),
&ngit_for_popover,
cx,
))
.child(clone_group(
"Clone with nak",
"copy-nak".into(),
&nak_for_popover,
cx,
))
.child(
v_flex()
.gap_1()
.child(
div()
.text_xs()
.font_semibold()
.child("Grasp Servers"),
)
.when(git_for_popover.is_empty(), |this| {
this.child(
div()
.text_xs()
.text_center()
.text_color(
cx.theme().colors.muted_foreground,
)
.child("No git clone urls."),
)
})
.children(git_for_popover.iter().enumerate().map(
|(ix, command)| {
clone_row(
SharedString::from(format!(
"copy-git-{ix}"
)),
command.clone().into(),
cx,
)
},
)),
)
.child(
h_flex().justify_end().child(
Button::new("download")
.icon(Icon::named(IconRole::GitClone))
.label("Download")
.on_click({
let weak = weak_download.clone();
move |_, window, cx| {
if let Err(error) =
weak.update(cx, |this, cx| {
this.clone_to_folder(window, cx);
})
{
log::warn!("failed to clone: {error}");
}
}
}),
),
)
.into_any_element()
}),
)
.child(
DropdownMenu::new("repo-menu")
.icon(IconRole::EllipsisVertical)
.variant(ButtonVariant::Ghost)
.disabled(pushing)
.open(self.repo_menu_open)
.on_open_change(move |open, _, cx| {
if let Err(error) = weak_menu_open.update(cx, |this, cx| {
this.repo_menu_open = open;
cx.notify();
}) {
log::warn!("failed to update repo menu: {error}");
}
})
.items(move |_, cx| {
let owner = backend.read(cx).current_user()
== Some(announcement_for_menu.owner);
let mut items = vec![MenuItem::new("About").handler({
let weak = weak_menu_items.clone();
let announcement = announcement_for_menu.clone();
move |_, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.about = Some(dialogs::about::AboutDialog::new(
announcement.clone(),
this.directory.clone(),
cx,
));
cx.notify();
}) {
log::warn!("failed to open about: {error}");
}
}
})];
if owner {
items.push(MenuItem::new("Republish").handler({
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.push_repository(window, cx);
}) {
log::warn!("failed to republish: {error}");
}
}
}));
items.push(MenuItem::new("Reset remote to local").handler({
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.reset_remote(window, cx);
}) {
log::warn!("failed to reset remote: {error}");
}
}
}));
items.push(MenuItem::separator());
items.push(MenuItem::new("Delete").destructive(true).handler(
{
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.delete_repository(window, cx);
}) {
log::warn!("failed to delete: {error}");
}
}
},
));
}
items
}),
),
)
.into_any_element()
}
fn render_init_banner(&self, cx: &mut Context<Self>) -> AnyElement {
let binding = self
.store
.read(cx)
.nip34
.as_ref()
.filter(|binding| binding.kind == Nip34Kind::Initialized);
let path = self
.store
.read(cx)
.path
.as_ref()
.map(|path| path.display().to_string())
.unwrap_or_default();
v_flex()
.flex_none()
.p_6()
.h_32()
.w_full()
.items_center()
.justify_center()
.gap_2()
.map(|this| match binding {
Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)),
None => this.child(
Button::new("init")
.icon(Icon::named(IconRole::ArrowUp))
.label("Initialize on Nostr")
.tooltip(Tooltip::text("Publish this repository to Nostr"))
.on_click(cx.listener(|this, _, window, cx| {
this.open_init_dialog(window, cx);
})),
),
})
.child(
div()
.min_w_0()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(path),
)
.into_any_element()
}
pub(super) fn render_metadata(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.px_6()
.h_12()
.w_full()
.gap_4()
.items_center()
.justify_between()
.child(self.render_maintainers(cx))
.child(self.render_ref_controls(cx))
.into_any_element()
}
fn render_ref_controls(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.justify_end()
.flex_none()
.gap_2()
.when_some(self.render_last_commit(cx), |this, commit| {
this.child(commit)
})
.child(self.refs.branch_select.clone())
.child(self.refs.tag_select.clone())
.into_any_element()
}
fn render_last_commit(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
let commit = self.head_commit.as_ref()?;
let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned();
let history = self.history.clone();
let commit_id = commit.id.clone();
Some(
h_flex()
.id("last-commit")
.h_8()
.px_2()
.gap_2()
.min_w_0()
.rounded(cx.theme().radius.control)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.tooltip(Tooltip::text("View latest commit"))
.on_click(move |_, window, cx| {
history.update(cx, |history, cx| {
history.open_commit_diff(&commit_id, window, cx);
});
})
.child(Icon::named(IconRole::GitCommit).color(cx.theme().colors.muted_foreground))
.child(
div()
.font_family(cx.theme().mono_font)
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(short)),
)
.child(
div()
.max_w(px(220.))
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
)
.child(
div()
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(relative_time_secs(commit.time)),
)
.into_any_element(),
)
}
fn render_maintainers(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(announcement) = self.announcement(cx) else {
return div().into_any_element();
};
let mut seen = HashSet::new();
let rest: Vec<_> = announcement
.maintainers
.iter()
.copied()
.filter(|key| key != &announcement.owner && seen.insert(*key))
.collect();
let owner = self.directory.read(cx).profile(&announcement.owner, cx);
let owner_name = owner.name();
h_flex()
.min_w_0()
.gap_2()
.child(
h_flex()
.gap_2()
.child(
Avatar::new(announcement.owner)
.name(owner_name.clone())
.picture(owner.picture())
.small(),
)
.child(div().text_xs().whitespace_nowrap().child(owner_name)),
)
.when(!rest.is_empty(), |this| {
this.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(format!("+{}", rest.len()))),
)
})
.into_any_element()
}
}
+96 -147
View File
@@ -8,22 +8,92 @@ use gpui::{
}; };
use metadata::ProfileDirectory; use metadata::ProfileDirectory;
use nostr::prelude::{RelayUrl, ToBech32}; use nostr::prelude::{RelayUrl, ToBech32};
use signed_core::Announcement; use signed_core::{Announcement, RepoAddr};
use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo, WorktreeSnapshot}; use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo, WorktreeSnapshot};
use signed_state::{Nip34Binding, RepoListStore, RepoStore}; use signed_state::{Nip34Binding, RepoListStore, RepoStore};
use ui::avatar::Avatar; use ui::avatar::Avatar;
use ui::clipboard::CopyRow;
use ui::combobox::ComboboxState; use ui::combobox::ComboboxState;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use utils::relative_time_secs;
use super::RepoDetailView; use super::RepoDetailView;
use crate::shared::tree::{TreeItemSeed, build_tree_items, sorted_worktree_paths}; use ui::tree::TreeItemSeed;
const GUTTER_WIDTH: f32 = 44.; const GUTTER_WIDTH: f32 = 44.;
pub const DIFF_ROW_HEIGHT: f32 = 20.; pub const DIFF_ROW_HEIGHT: f32 = 20.;
pub const COMMIT_ROW_HEIGHT: f32 = 56.;
#[derive(Clone, Copy)]
pub(super) enum DiffRow {
Hunk {
old_start: u32,
old_lines: u32,
new_start: u32,
new_lines: u32,
},
Line {
hunk: usize,
line: usize,
},
}
impl DiffRow {
/// Renders one diff row against the file's hunks.
pub(super) fn render(self, hunks: &[DiffHunk], wrap: bool, cx: &App) -> AnyElement {
match self {
DiffRow::Hunk {
old_start,
old_lines,
new_start,
new_lines,
} => div()
.px_2()
.w_full()
.h(px(DIFF_ROW_HEIGHT))
.font_family(cx.theme().mono_font)
.text_xs()
.bg(cx.theme().colors.muted)
.border_y_1()
.border_color(cx.theme().colors.border)
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(format!(
"@@ -{},{} +{},{} @@",
old_start, old_lines, new_start, new_lines
)))
.into_any_element(),
DiffRow::Line { hunk, line } => {
match hunks.get(hunk).and_then(|h| h.lines.get(line)) {
Some(line) => render_diff_line(line, wrap, cx),
// A stale row index renders as a blank row rather than panicking.
None => div().w_full().h(px(DIFF_ROW_HEIGHT)).into_any_element(),
}
}
}
}
}
pub(super) struct RepoData {
pub(super) tree: Vec<TreeItemSeed>,
pub(super) entries: Vec<PathBuf>,
pub(super) readme_path: Option<PathBuf>,
pub(super) readme: Option<Vec<u8>>,
pub(super) worktree: Option<PathBuf>,
pub(super) branches: Vec<String>,
pub(super) tags: Vec<String>,
pub(super) current_branch: Option<String>,
pub(super) head_commit: Option<FileCommit>,
}
/// Sorted relative paths of a worktree snapshot.
pub(crate) fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec<String> {
let mut paths: Vec<String> = entries
.iter()
.map(|path| path.to_string_lossy().into_owned())
.collect();
paths.sort();
paths
}
/// The announcement's name, falling back to its id. /// The announcement's name, falling back to its id.
pub fn announcement_display_name(announcement: &Announcement) -> SharedString { pub fn announcement_display_name(announcement: &Announcement) -> SharedString {
@@ -67,43 +137,12 @@ pub(super) fn snapshot_worktree(
worktree: PathBuf, worktree: PathBuf,
) -> Result<(WorktreeSnapshot, Vec<TreeItemSeed>, Vec<String>), Error> { ) -> Result<(WorktreeSnapshot, Vec<TreeItemSeed>, Vec<String>), Error> {
let snapshot = Repo::open(&worktree)?.snapshot()?; let snapshot = Repo::open(&worktree)?.snapshot()?;
let tree = build_tree_items(&snapshot.entries); let tree = TreeItemSeed::from_paths(&snapshot.entries);
let paths = sorted_worktree_paths(&snapshot.entries); let paths = sorted_worktree_paths(&snapshot.entries);
Ok((snapshot, tree, paths)) Ok((snapshot, tree, paths))
} }
#[derive(Clone, Copy)] pub(super) fn clone_group(label: &str, id: SharedString, command: &SharedString) -> AnyElement {
pub(super) enum DiffRow {
Hunk {
old_start: u32,
old_lines: u32,
new_start: u32,
new_lines: u32,
},
Line {
hunk: usize,
line: usize,
},
}
pub(super) struct RepoData {
pub(super) tree: Vec<TreeItemSeed>,
pub(super) entries: Vec<PathBuf>,
pub(super) readme_path: Option<PathBuf>,
pub(super) readme: Option<Vec<u8>>,
pub(super) worktree: Option<PathBuf>,
pub(super) branches: Vec<String>,
pub(super) tags: Vec<String>,
pub(super) current_branch: Option<String>,
pub(super) head_commit: Option<FileCommit>,
}
pub(super) fn clone_group(
label: &str,
id: SharedString,
command: &SharedString,
cx: &App,
) -> AnyElement {
v_flex() v_flex()
.gap_1() .gap_1()
.min_w_0() .min_w_0()
@@ -113,7 +152,7 @@ pub(super) fn clone_group(
.font_semibold() .font_semibold()
.child(SharedString::from(label)), .child(SharedString::from(label)),
) )
.child(crate::shared::widgets::clone_row(id, command.clone(), cx)) .child(CopyRow::new(id, command.clone()))
.into_any_element() .into_any_element()
} }
@@ -134,17 +173,9 @@ pub(super) fn nostr_clone_url(announcement: &Announcement, nip05: Option<&str>)
SharedString::from(url) SharedString::from(url)
} }
pub(super) fn fork_row( /// The display name of the announcement addressing `addr`, falling back to its identifier.
announcement: &Announcement, pub(crate) fn upstream_display_name(addr: &RepoAddr, announcements: &[Announcement]) -> SharedString {
cx: &mut Context<RepoDetailView>, announcements
) -> Option<AnyElement> {
let upstream = announcement.upstream.as_ref()?;
let (label, clickable) = match &upstream.addr {
Some(addr) => {
let name = RepoListStore::global(cx)
.read(cx)
.announcements
.iter() .iter()
.find(|a| a.addr() == *addr) .find(|a| a.addr() == *addr)
.map(|a| { .map(|a| {
@@ -153,7 +184,21 @@ pub(super) fn fork_row(
.map(SharedString::from) .map(SharedString::from)
.unwrap_or_else(|| SharedString::from(a.id.clone())) .unwrap_or_else(|| SharedString::from(a.id.clone()))
}) })
.unwrap_or_else(|| SharedString::from(addr.identifier().to_owned())); .unwrap_or_else(|| SharedString::from(addr.identifier().to_owned()))
}
pub(super) fn fork_row(
announcement: &Announcement,
cx: &mut Context<RepoDetailView>,
) -> Option<AnyElement> {
let upstream = announcement.upstream.as_ref()?;
let (label, clickable) = match &upstream.addr {
Some(addr) => {
let name = upstream_display_name(
addr,
&RepoListStore::global(cx).read(cx).announcements,
);
(SharedString::from(format!("Forked from {name}")), true) (SharedString::from(format!("Forked from {name}")), true)
} }
None => (SharedString::from(upstream.display().as_str()), false), None => (SharedString::from(upstream.display().as_str()), false),
@@ -180,7 +225,7 @@ pub(super) fn fork_row(
pub(super) fn load_repo_data(repo: &Repo) -> Result<RepoData, Error> { pub(super) fn load_repo_data(repo: &Repo) -> Result<RepoData, Error> {
let snapshot = repo.snapshot()?; let snapshot = repo.snapshot()?;
let worktree = repo.workdir().map(Path::to_path_buf); let worktree = repo.workdir().map(Path::to_path_buf);
let tree = build_tree_items(&snapshot.entries); let tree = TreeItemSeed::from_paths(&snapshot.entries);
Ok(RepoData { Ok(RepoData {
tree, tree,
@@ -267,10 +312,6 @@ pub(super) fn source_hash(text: &str) -> u64 {
hasher.finish() hasher.finish()
} }
pub(super) fn preview_spinner() -> AnyElement {
crate::shared::widgets::centered_spinner("repo-preview-spinner")
}
/// The kit grammar for a path; only four languages are supported. /// The kit grammar for a path; only four languages are supported.
pub(super) fn code_language(path: &str) -> ui::highlight::Language { pub(super) fn code_language(path: &str) -> ui::highlight::Language {
use ui::highlight::Language; use ui::highlight::Language;
@@ -318,41 +359,6 @@ pub(super) fn diff_rows(file: &FileDiff) -> Vec<DiffRow> {
rows rows
} }
pub(super) fn render_diff_row(
hunks: &[DiffHunk],
row: DiffRow,
wrap: bool,
cx: &App,
) -> AnyElement {
match row {
DiffRow::Hunk {
old_start,
old_lines,
new_start,
new_lines,
} => div()
.px_2()
.w_full()
.h(px(DIFF_ROW_HEIGHT))
.font_family(cx.theme().mono_font)
.text_xs()
.bg(cx.theme().colors.muted)
.border_y_1()
.border_color(cx.theme().colors.border)
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(format!(
"@@ -{},{} +{},{} @@",
old_start, old_lines, new_start, new_lines
)))
.into_any_element(),
DiffRow::Line { hunk, line } => match hunks.get(hunk).and_then(|h| h.lines.get(line)) {
Some(line) => render_diff_line(line, wrap, cx),
// A stale row index renders as a blank row rather than panicking.
None => div().w_full().h(px(DIFF_ROW_HEIGHT)).into_any_element(),
},
}
}
fn render_diff_line(line: &DiffLine, wrap: bool, cx: &App) -> AnyElement { fn render_diff_line(line: &DiffLine, wrap: bool, cx: &App) -> AnyElement {
let bg = match line.kind { let bg = match line.kind {
DiffLineKind::Addition => Some(cx.theme().ramps.success.base.opacity(0.2)), DiffLineKind::Addition => Some(cx.theme().ramps.success.base.opacity(0.2)),
@@ -399,63 +405,6 @@ fn render_diff_line(line: &DiffLine, wrap: bool, cx: &App) -> AnyElement {
.into_any_element() .into_any_element()
} }
pub(crate) fn commit_row(
ix: usize,
commit: &FileCommit,
action: Option<AnyElement>,
on_click: impl Fn(&mut Window, &mut gpui::App) + 'static,
cx: &gpui::App,
) -> gpui::AnyElement {
h_flex()
.id(ix)
.px_4()
.h(px(COMMIT_ROW_HEIGHT))
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.justify_center()
.child(
h_flex()
.gap_2()
.overflow_hidden()
.child(
div()
.font_family(cx.theme().mono_font)
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(short_id(&commit.id)),
)
.child(
div()
.flex_1()
.min_w_0()
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
),
)
.child(
h_flex()
.gap_2()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(commit.author.clone())
.child(relative_time_secs(commit.time)),
),
)
.when_some(action, |row, action| row.child(action))
.on_click(move |_, window, cx| on_click(window, cx))
.into_any_element()
}
pub(super) fn sync_selector( pub(super) fn sync_selector(
select: &Entity<ComboboxState<SharedString>>, select: &Entity<ComboboxState<SharedString>>,
cached: &mut Vec<SharedString>, cached: &mut Vec<SharedString>,
+5 -4
View File
@@ -12,7 +12,9 @@ use signed_state::{Backend, RepoStore, SyncStatusDirectory};
use ui::alert::{Alert, AlertSeverity, AlertStyle}; use ui::alert::{Alert, AlertSeverity, AlertStyle};
use ui::button::{Button, ButtonVariant}; use ui::button::{Button, ButtonVariant};
use ui::common::{Sizable as _, v_flex}; use ui::common::{Sizable as _, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip; use ui::tooltip::Tooltip;
@@ -159,7 +161,7 @@ impl Render for RepoHistoryView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(list) = self.all_commits.as_ref() else { let Some(list) = self.all_commits.as_ref() else {
return if self.loading_all_commits { return if self.loading_all_commits {
crate::shared::widgets::centered_spinner("commits-loading") Spinner::centered("commits-loading")
} else if let Some(error) = self.error.clone() { } else if let Some(error) = self.error.clone() {
let weak = cx.entity().downgrade(); let weak = cx.entity().downgrade();
v_flex() v_flex()
@@ -183,12 +185,12 @@ impl Render for RepoHistoryView {
) )
.into_any_element() .into_any_element()
} else { } else {
crate::shared::widgets::empty_state("Failed to load commits") EmptyState::centered("Failed to load commits")
}; };
}; };
if self.commits.is_empty() { if self.commits.is_empty() {
return crate::shared::widgets::empty_state("No commits found"); return EmptyState::centered("No commits found");
} }
let commits = Arc::clone(&self.commits); let commits = Arc::clone(&self.commits);
@@ -261,7 +263,6 @@ impl Render for RepoHistoryView {
log::warn!("failed to open commit diff: {error}"); log::warn!("failed to open commit diff: {error}");
} }
}, },
cx,
); );
v_flex() v_flex()
+448 -11
View File
@@ -5,49 +5,58 @@ use anyhow::Error;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, PathPromptOptions, Render, SharedString, Styled as _, Subscription, ParentElement as _, PathPromptOptions, Render, SharedString, StatefulInteractiveElement as _,
SystemNotification, Task, WeakEntity, Window, div, Styled as _, Subscription, SystemNotification, Task, WeakEntity, Window, div, px,
}; };
use metadata::ProfileDirectory; use metadata::ProfileDirectory;
use nostr::prelude::{PublicKey, Url}; use nostr::prelude::{PublicKey, Url};
use signed_core::{Announcement, RepoAddr}; use signed_core::{Announcement, RepoAddr};
use signed_git::{FileCommit, GitCache, Repo}; use signed_git::{FileCommit, GitCache, Repo};
use signed_state::{ use signed_state::{
Backend, BackendEvent, LocalReposStore, Mirrors, Nip34Binding, PushStepStatus, RepoStore, Backend, BackendEvent, LocalReposStore, Mirrors, Nip34Binding, Nip34Kind, PushStepStatus,
SyncStatusDirectory, RepoStore, SyncStatusDirectory,
}; };
use ui::alert::{Alert, AlertSeverity}; use ui::alert::{Alert, AlertSeverity};
use ui::avatar::Avatar; use ui::avatar::Avatar;
use ui::badge::Badge; use ui::badge::Badge;
use ui::button::{Button, ButtonVariant}; use ui::button::{Button, ButtonVariant};
use ui::common::{Sizable as _, h_flex, v_flex}; use ui::clipboard::CopyRow;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::dialog::Dialog; use ui::dialog::Dialog;
use ui::dropdown_menu::DropdownMenu;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::menu::MenuItem;
use ui::popover::Popover;
use ui::sidebar::{Sidebar, SidebarEntry}; use ui::sidebar::{Sidebar, SidebarEntry};
use ui::spinner::Spinner; use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
pub mod actions; pub mod actions;
pub mod commit_diff; pub mod commit_diff;
pub mod dialogs; pub mod dialogs;
pub mod files; pub mod files;
mod header;
pub mod helpers; pub mod helpers;
pub mod history; pub mod history;
pub mod refs; pub mod refs;
use files::RepoFilesView; use files::RepoFilesView;
use helpers::{RepoData, announcement_display_name, load_repo_data, snapshot_worktree}; use helpers::{
RepoData, announcement_display_name, bound_repo_label, clone_group, fork_row,
load_repo_data, nostr_clone_url, repo_display_name, snapshot_worktree,
};
use history::RepoHistoryView; use history::RepoHistoryView;
use refs::RefSwitcher; use refs::RefSwitcher;
use utils::relative_time_secs;
use crate::issues::IssuesView; use crate::issues::IssuesView;
use crate::pull_requests::PullRequestsView; use crate::pull_requests::PullRequestsView;
use crate::shared::log_dropped; use crate::shared::log_dropped;
use crate::shared::tree::sorted_worktree_paths;
use crate::workspace::Workspace; use crate::workspace::Workspace;
use crate::repo::helpers::{short_id, sorted_worktree_paths};
#[derive(Clone, Copy, PartialEq, Eq)] #[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum RepoSection { pub(super) enum RepoSection {
Files, Files,
@@ -193,7 +202,7 @@ impl RepoDetailView {
let store_for_attach = store.clone(); let store_for_attach = store.clone();
window.defer(cx, move |window, cx| { window.defer(cx, move |window, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| { log_dropped(weak.update(cx, |this, cx| {
this.attach_store(&store_for_attach, window, cx); this.attach_store(&store_for_attach, window, cx);
this.load_repo(window, cx); this.load_repo(window, cx);
})); }));
@@ -828,7 +837,7 @@ impl RepoDetailView {
match result { match result {
Ok(()) => { Ok(()) => {
if let Some(tag) = &tag { if let Some(tag) = &tag {
let short = crate::repo::helpers::short_id(&commit); let short = short_id(&commit);
let (title, body) = match store.read(cx).last_push_warning.clone() { let (title, body) = match store.read(cx).last_push_warning.clone() {
Some(warning) => ("Sync partially failed", warning), Some(warning) => ("Sync partially failed", warning),
None => ("Sync complete", format!("Synced up to {short}")), None => ("Sync complete", format!("Synced up to {short}")),
@@ -978,7 +987,7 @@ impl RepoDetailView {
(Some(2), true) => RepoSection::PullRequests, (Some(2), true) => RepoSection::PullRequests,
_ => return, _ => return,
}; };
crate::shared::log_dropped(weak.update(cx, |this, cx| { log_dropped(weak.update(cx, |this, cx| {
this.active_section = section; this.active_section = section;
cx.notify(); cx.notify();
})); }));
@@ -1028,6 +1037,434 @@ impl RepoDetailView {
RepoSection::PullRequests => self.pulls.clone().into_any_element(), RepoSection::PullRequests => self.pulls.clone().into_any_element(),
} }
} }
pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(addr) = self
.announcement(cx)
.and_then(|announcement| announcement.upstream.as_ref())
.and_then(|upstream| upstream.addr.clone())
else {
return;
};
actions::open_repo_panel(&self.workspace, &addr, None, window, cx);
}
/// Open the dialog that publishes the local repository to NIP-34.
fn open_init_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(local_path) = self.store.read(cx).path.clone() else {
return;
};
self.init = Some(dialogs::init::InitRepoDialog::new(
local_path,
cx.entity().downgrade(),
window,
cx,
));
cx.notify();
}
pub(super) fn render_about(&mut self, cx: &mut Context<Self>) -> AnyElement {
if self.store.read(cx).addr().is_none() {
return self.render_init_banner(cx);
}
let backend = Backend::global(cx);
let store = self.store.read(cx);
let pushing = store.pushing;
let cloning = store.cloning;
let Some(announcement) = store.announcement.clone() else {
return div().into_any_element();
};
let nip05 = self
.directory
.read(cx)
.profile(&announcement.owner, cx)
.metadata()
.nip05
.clone()
.filter(|nip05| !nip05.trim().is_empty());
let nostr_url = nostr_clone_url(&announcement, nip05.as_deref());
let ngit_command = SharedString::from(format!("git clone {nostr_url}"));
let nak_command = SharedString::from(format!("nak git clone {nostr_url}"));
let git_commands: Vec<String> = announcement.clone_urls();
let name = repo_display_name(self.store.read(cx));
let description = announcement.description();
let avatar = Avatar::new(format!("{}:{}", announcement.owner, announcement.id));
let announcement_for_menu = announcement.clone();
let weak_menu_open = cx.entity().downgrade();
let weak_menu_items = cx.entity().downgrade();
let weak_clone = cx.entity().downgrade();
let weak_download = cx.entity().downgrade();
let ngit_for_popover = ngit_command.clone();
let nak_for_popover = nak_command.clone();
let git_for_popover = git_commands.clone();
h_flex()
.p_6()
.w_full()
.gap_6()
.items_start()
.justify_between()
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_2()
.child(
h_flex()
.gap_2()
.text_sm()
.font_semibold()
.child(avatar)
.child(name),
)
.child(
div()
.min_w_0()
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.line_clamp(3)
.child(description),
)
.when_some(fork_row(&announcement, cx), |this, row| this.child(row)),
)
.child(
h_flex()
.flex_none()
.gap_2()
.justify_end()
.child(
Popover::new("code-popover")
.open(self.clone_open)
.on_change(move |open, _, cx| {
if let Err(error) = weak_clone.update(cx, |this, cx| {
this.clone_open = open;
cx.notify();
}) {
log::warn!("failed to update clone popover: {error}");
}
})
.trigger(move |_, _| {
Button::new("code")
.label("Code")
.icon(Icon::named(IconRole::GitClone))
.tooltip(Tooltip::text("Clone repository"))
.loading(cloning)
.disabled(cloning)
.into_any_element()
})
.content(move |_, cx| {
v_flex()
.w(px(440.))
.p_3()
.gap_4()
.child(clone_group(
"Clone with ngit",
"copy-ngit".into(),
&ngit_for_popover,
))
.child(clone_group(
"Clone with nak",
"copy-nak".into(),
&nak_for_popover,
))
.child(
v_flex()
.gap_1()
.child(
div()
.text_xs()
.font_semibold()
.child("Grasp Servers"),
)
.when(git_for_popover.is_empty(), |this| {
this.child(
div()
.text_xs()
.text_center()
.text_color(
cx.theme().colors.muted_foreground,
)
.child("No git clone urls."),
)
})
.children(git_for_popover.iter().enumerate().map(
|(ix, command)| {
CopyRow::new(
SharedString::from(format!(
"copy-git-{ix}"
)),
command.clone(),
)
},
)),
)
.child(
h_flex().justify_end().child(
Button::new("download")
.icon(Icon::named(IconRole::GitClone))
.label("Download")
.on_click({
let weak = weak_download.clone();
move |_, window, cx| {
if let Err(error) =
weak.update(cx, |this, cx| {
this.clone_to_folder(window, cx);
})
{
log::warn!("failed to clone: {error}");
}
}
}),
),
)
.into_any_element()
}),
)
.child(
DropdownMenu::new("repo-menu")
.icon(IconRole::EllipsisVertical)
.variant(ButtonVariant::Ghost)
.disabled(pushing)
.open(self.repo_menu_open)
.on_open_change(move |open, _, cx| {
if let Err(error) = weak_menu_open.update(cx, |this, cx| {
this.repo_menu_open = open;
cx.notify();
}) {
log::warn!("failed to update repo menu: {error}");
}
})
.items(move |_, cx| {
let owner = backend.read(cx).current_user()
== Some(announcement_for_menu.owner);
let mut items = vec![MenuItem::new("About").handler({
let weak = weak_menu_items.clone();
let announcement = announcement_for_menu.clone();
move |_, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.about = Some(dialogs::about::AboutDialog::new(
announcement.clone(),
this.directory.clone(),
cx,
));
cx.notify();
}) {
log::warn!("failed to open about: {error}");
}
}
})];
if owner {
items.push(MenuItem::new("Republish").handler({
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.push_repository(window, cx);
}) {
log::warn!("failed to republish: {error}");
}
}
}));
items.push(MenuItem::new("Reset remote to local").handler({
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.reset_remote(window, cx);
}) {
log::warn!("failed to reset remote: {error}");
}
}
}));
items.push(MenuItem::separator());
items.push(MenuItem::new("Delete").destructive(true).handler(
{
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.delete_repository(window, cx);
}) {
log::warn!("failed to delete: {error}");
}
}
},
));
}
items
}),
),
)
.into_any_element()
}
fn render_init_banner(&self, cx: &mut Context<Self>) -> AnyElement {
let binding = self
.store
.read(cx)
.nip34
.as_ref()
.filter(|binding| binding.kind == Nip34Kind::Initialized);
let path = self
.store
.read(cx)
.path
.as_ref()
.map(|path| path.display().to_string())
.unwrap_or_default();
v_flex()
.flex_none()
.p_6()
.h_32()
.w_full()
.items_center()
.justify_center()
.gap_2()
.map(|this| match binding {
Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)),
None => this.child(
Button::new("init")
.icon(Icon::named(IconRole::ArrowUp))
.label("Initialize on Nostr")
.tooltip(Tooltip::text("Publish this repository to Nostr"))
.on_click(cx.listener(|this, _, window, cx| {
this.open_init_dialog(window, cx);
})),
),
})
.child(
div()
.min_w_0()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(path),
)
.into_any_element()
}
pub(super) fn render_metadata(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.px_6()
.h_12()
.w_full()
.gap_4()
.items_center()
.justify_between()
.child(self.render_maintainers(cx))
.child(self.render_ref_controls(cx))
.into_any_element()
}
fn render_ref_controls(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.justify_end()
.flex_none()
.gap_2()
.when_some(self.render_last_commit(cx), |this, commit| {
this.child(commit)
})
.child(self.refs.branch_select.clone())
.child(self.refs.tag_select.clone())
.into_any_element()
}
fn render_last_commit(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
let commit = self.head_commit.as_ref()?;
let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned();
let history = self.history.clone();
let commit_id = commit.id.clone();
Some(
h_flex()
.id("last-commit")
.h_8()
.px_2()
.gap_2()
.min_w_0()
.rounded(cx.theme().radius.control)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.tooltip(Tooltip::text("View latest commit"))
.on_click(move |_, window, cx| {
history.update(cx, |history, cx| {
history.open_commit_diff(&commit_id, window, cx);
});
})
.child(Icon::named(IconRole::GitCommit).color(cx.theme().colors.muted_foreground))
.child(
div()
.font_family(cx.theme().mono_font)
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(short)),
)
.child(
div()
.max_w(px(220.))
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
)
.child(
div()
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(relative_time_secs(commit.time)),
)
.into_any_element(),
)
}
fn render_maintainers(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(announcement) = self.announcement(cx) else {
return div().into_any_element();
};
let mut seen = HashSet::new();
let rest: Vec<_> = announcement
.maintainers
.iter()
.copied()
.filter(|key| key != &announcement.owner && seen.insert(*key))
.collect();
let owner = self.directory.read(cx).profile(&announcement.owner, cx);
let owner_name = owner.name();
h_flex()
.min_w_0()
.gap_2()
.child(
h_flex()
.gap_2()
.child(
Avatar::new(announcement.owner)
.name(owner_name.clone())
.picture(owner.picture())
.small(),
)
.child(div().text_xs().whitespace_nowrap().child(owner_name)),
)
.when(!rest.is_empty(), |this| {
this.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(format!("+{}", rest.len()))),
)
})
.into_any_element()
}
} }
impl Panel for RepoDetailView { impl Panel for RepoDetailView {
+71 -79
View File
@@ -1,11 +1,11 @@
use std::path::PathBuf; use std::path::PathBuf;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, PathPromptOptions, AnyElement, App, AppContext as _, Div, Entity, IntoElement, ParentElement as _,
SharedString, Styled as _, Window, div, px, PathPromptOptions, SharedString, Styled as _, Window, div, px,
}; };
use settings::{AppearanceMode, EventFetchingStrategy, SettingsStore}; use settings::{AppearanceMode, EventFetchingStrategy, SettingsStore};
use ui::button::Button; use ui::button::{Button, ButtonVariant};
use ui::common::{StyledExt as _, h_flex, v_flex}; use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState}; use ui::input::{Input, InputState};
@@ -13,8 +13,26 @@ use ui::select::{Select, SelectOption};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip; use ui::tooltip::Tooltip;
use crate::apply_appearance_mode;
use crate::repo::dialogs::grasp_servers::{normalize_server, server_host}; use crate::repo::dialogs::grasp_servers::{normalize_server, server_host};
/// The title and description a settings row or block opens with.
fn setting_header(
cx: &App,
title: impl Into<SharedString>,
description: impl Into<SharedString>,
) -> Div {
v_flex()
.gap_1()
.child(div().text_sm().font_semibold().child(title.into()))
.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(description.into()),
)
}
/// A settings row with the label and description on the left and the control on the right. /// A settings row with the label and description on the left and the control on the right.
pub fn setting_row( pub fn setting_row(
cx: &App, cx: &App,
@@ -26,19 +44,7 @@ pub fn setting_row(
.w_full() .w_full()
.justify_between() .justify_between()
.gap_4() .gap_4()
.child( .child(setting_header(cx, title, description))
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(div().text_sm().font_semibold().child(title.into()))
.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(description.into()),
),
)
.child(div().w(px(200.)).flex_shrink_0().child(control)) .child(div().w(px(200.)).flex_shrink_0().child(control))
.into_any_element() .into_any_element()
} }
@@ -53,17 +59,7 @@ pub fn setting_block(
v_flex() v_flex()
.w_full() .w_full()
.gap_3() .gap_3()
.child( .child(setting_header(cx, title, description))
v_flex()
.gap_1()
.child(div().text_sm().font_semibold().child(title.into()))
.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(description.into()),
),
)
.child(control) .child(control)
.into_any_element() .into_any_element()
} }
@@ -84,7 +80,7 @@ pub fn appearance_select(cx: &App) -> Select<AppearanceMode> {
SettingsStore::global(cx).update(cx, |store, cx| { SettingsStore::global(cx).update(cx, |store, cx| {
store.edit(|settings| settings.appearance = mode, cx); store.edit(|settings| settings.appearance = mode, cx);
}); });
crate::apply_appearance_mode(mode, cx); apply_appearance_mode(mode, cx);
}) })
} }
@@ -106,6 +102,36 @@ pub fn event_fetching_select(cx: &App) -> Select<EventFetchingStrategy> {
}) })
} }
/// One editable value: a muted row with a trailing remove button.
fn editor_value_row(
id: String,
text: SharedString,
on_remove: impl Fn(&mut App) + 'static,
cx: &App,
) -> AnyElement {
h_flex()
.gap_1()
.child(
h_flex()
.flex_1()
.h_8()
.px_2()
.bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground)
.text_xs()
.rounded(cx.theme().radius.control)
.child(text),
)
.child(
Button::new(id)
.icon(Icon::named(IconRole::Close))
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click(move |_, _, cx| on_remove(cx)),
)
.into_any_element()
}
pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement { pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement {
let store = SettingsStore::global(cx); let store = SettingsStore::global(cx);
let servers = store let servers = store
@@ -119,32 +145,15 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
.gap_2() .gap_2()
.children(servers.iter().enumerate().map(|(ix, server)| { .children(servers.iter().enumerate().map(|(ix, server)| {
let server = server.clone(); let server = server.clone();
h_flex() editor_value_row(
.gap_1() format!("settings-remove-server:{ix}"),
.child( display_server(&server),
h_flex() move |cx| {
.flex_1() let store = SettingsStore::global(cx);
.h_8()
.px_2()
.bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground)
.text_xs()
.rounded(cx.theme().radius.control)
.child(display_server(&server)),
)
.child(
Button::new(format!("settings-remove-server:{ix}"))
.icon(Icon::named(IconRole::Close))
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click({
let store = store.clone();
move |_, _, cx| {
store.update(cx, |store, cx| { store.update(cx, |store, cx| {
store.edit( store.edit(
|settings| { |settings| {
// A row's index can desync after a prior // A row's index can desync after a prior removal; match by value.
// removal; match by value.
if let Some(at) = settings if let Some(at) = settings
.grasp_servers .grasp_servers
.default_servers .default_servers
@@ -157,10 +166,9 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
cx, cx,
); );
}); });
} },
}), cx,
) )
.into_any_element()
})) }))
.child( .child(
h_flex() h_flex()
@@ -173,7 +181,7 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
.child( .child(
Button::new("settings-add-server") Button::new("settings-add-server")
.icon(Icon::named(IconRole::Plus)) .icon(Icon::named(IconRole::Plus))
.variant(ui::button::ButtonVariant::Ghost) .variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Add grasp server")) .tooltip(Tooltip::text("Add grasp server"))
.on_click({ .on_click({
let input = input.clone(); let input = input.clone();
@@ -229,31 +237,15 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement {
.gap_2() .gap_2()
.children(scan_paths.iter().enumerate().map(|(ix, path)| { .children(scan_paths.iter().enumerate().map(|(ix, path)| {
let path = path.clone(); let path = path.clone();
h_flex() editor_value_row(
.gap_1() format!("settings-remove-path:{ix}"),
.child( SharedString::from(path.display().to_string()),
h_flex() move |cx| {
.flex_1()
.h_8()
.px_2()
.bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground)
.text_xs()
.rounded(cx.theme().radius.control)
.child(path.display().to_string()),
)
.child(
Button::new(format!("settings-remove-path:{ix}"))
.icon(Icon::named(IconRole::Close))
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click(move |_, _, cx| {
let store = SettingsStore::global(cx); let store = SettingsStore::global(cx);
store.update(cx, |store, cx| { store.update(cx, |store, cx| {
store.edit( store.edit(
|settings| { |settings| {
// A row's index can desync after a prior // A row's index can desync after a prior removal; match by value.
// removal; match by value.
if let Some(at) = settings if let Some(at) = settings
.local_repos .local_repos
.scan_paths .scan_paths
@@ -266,9 +258,9 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement {
cx, cx,
); );
}); });
}), },
cx,
) )
.into_any_element()
})) }))
.child( .child(
h_flex().justify_end().child( h_flex().justify_end().child(
@@ -328,7 +320,7 @@ pub fn default_folder_selector(default_folder: &Entity<InputState>) -> AnyElemen
.child( .child(
Button::new("settings-choose-folder") Button::new("settings-choose-folder")
.icon(Icon::named(IconRole::Folder)) .icon(Icon::named(IconRole::Folder))
.variant(ui::button::ButtonVariant::Ghost) .variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Choose folder")) .tooltip(Tooltip::text("Choose folder"))
.on_click(move |_, window, cx| { .on_click(move |_, window, cx| {
choose_default_folder(&folder, window, cx); choose_default_folder(&folder, window, cx);
+137 -75
View File
@@ -15,30 +15,22 @@ use signed_core::RepoStatus;
use signed_git::FileCommit; use signed_git::FileCommit;
use ui::avatar::Avatar; use ui::avatar::Avatar;
use ui::common::{Sizable as _, h_flex, v_flex}; use ui::common::{Sizable as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::scrollbar::Scrollbar;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use utils::relative_time_secs;
use crate::repo::helpers::commit_row; use crate::repo::helpers::short_id;
use crate::shared::widgets::{empty_state, scroll_overlay, status_badge}; use crate::shared::widgets::status_badge;
/// The height of one issue or pull-request row. /// The height of one issue or pull-request row.
pub const ROW_HEIGHT: f32 = 73.; pub const ROW_HEIGHT: f32 = 73.;
/// The height of one commit row in the commit list.
pub const COMMIT_ROW_HEIGHT: f32 = 56.;
/// A row's activation handler. /// A row's activation handler.
pub type EventHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>; pub type EventHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
/// The toolbar above the issue and pull-request lists: a filter and its actions.
pub fn filter_toolbar(cx: &App, children: impl IntoIterator<Item = AnyElement>) -> AnyElement {
h_flex()
.px_4()
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.bg(cx.theme().colors.muted)
.children(children)
.into_any_element()
}
/// One issue or pull-request row's display data and click handler. /// One issue or pull-request row's display data and click handler.
pub struct EventRow { pub struct EventRow {
pub id: ElementId, pub id: ElementId,
@@ -52,8 +44,68 @@ pub struct EventRow {
pub on_click: EventHandler, pub on_click: EventHandler,
} }
/// The shared issue and pull-request list: toolbar, uniform rows, scrollbar impl EventRow {
/// overlay, and empty state. /// Renders one issue or pull-request row.
fn render(&self, row_height: Pixels, cx: &App) -> AnyElement {
h_flex()
.id(self.id.clone())
.w_full()
.h(row_height)
.gap_4()
.px_4()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.on_click({
let on_click = self.on_click.clone();
move |event, window, cx| on_click(event, window, cx)
})
.child(status_badge(self.status))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(
div()
.text_base()
.text_ellipsis()
.whitespace_nowrap()
.child(self.title.clone()),
)
.child(self.meta_row(cx)),
)
.into_any_element()
}
/// The author, age, and id line under a row's title.
fn meta_row(&self, cx: &App) -> AnyElement {
h_flex()
.gap_2()
.text_xs()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(self.pubkey)
.name(self.author.clone())
.picture(self.picture.clone())
.small(),
)
.child(div().child(self.author.clone())),
)
.child(SharedString::from("opened"))
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(self.short_id.clone()),
)
.child(self.age.clone())
.into_any_element()
}
}
/// The shared issue and pull-request list,
pub struct EventList { pub struct EventList {
id: ElementId, id: ElementId,
toolbar: Option<AnyElement>, toolbar: Option<AnyElement>,
@@ -118,86 +170,39 @@ impl EventList {
let Some(row) = rows.get(ix) else { let Some(row) = rows.get(ix) else {
return div().into_any_element(); return div().into_any_element();
}; };
event_row(row, row_height, cx) row.render(row_height, cx)
}) })
.collect() .collect()
}) })
.track_scroll(&self.scroll_handle) .track_scroll(&self.scroll_handle)
.size_full(), .size_full(),
) )
.child(scroll_overlay( .child(Scrollbar::vertical(
(self.id.clone(), "scroll"), (self.id.clone(), "scroll"),
self.scroll_handle.clone(), self.scroll_handle.clone(),
)) ))
}) })
.when(count == 0, |this| { .when(count == 0, |this| {
this.child(empty_state(self.empty_message)) this.child(EmptyState::centered(self.empty_message))
}) })
.into_any_element() .into_any_element()
} }
} }
/// Renders one issue or pull-request row. /// The toolbar above the issue and pull-request lists: a filter and its actions.
pub fn event_row(row: &EventRow, row_height: Pixels, cx: &App) -> AnyElement { pub fn filter_toolbar(cx: &App, children: impl IntoIterator<Item = AnyElement>) -> AnyElement {
h_flex() h_flex()
.id(row.id.clone())
.w_full()
.h(row_height)
.gap_4()
.px_4() .px_4()
.w_full()
.gap_3()
.border_b_1() .border_b_1()
.border_color(cx.theme().colors.border) .border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover)) .bg(cx.theme().colors.muted)
.on_click({ .children(children)
let on_click = row.on_click.clone();
move |event, window, cx| on_click(event, window, cx)
})
.child(status_badge(row.status))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(
div()
.text_base()
.text_ellipsis()
.whitespace_nowrap()
.child(row.title.clone()),
)
.child(event_meta_row(row, cx)),
)
.into_any_element()
}
/// The author, age, and id line under a row's title.
pub fn event_meta_row(row: &EventRow, cx: &App) -> AnyElement {
h_flex()
.gap_2()
.text_xs()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(row.pubkey)
.name(row.author.clone())
.picture(row.picture.clone())
.small(),
)
.child(div().child(row.author.clone())),
)
.child(SharedString::from("opened"))
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(row.short_id.clone()),
)
.child(row.age.clone())
.into_any_element() .into_any_element()
} }
/// A scrollable commit list: uniform `commit_row`s under a scrollbar overlay. /// A scrollable commit list: uniform `commit_row`s under a scrollbar overlay.
#[allow(clippy::too_many_arguments)]
pub fn commit_list( pub fn commit_list(
id: &'static str, id: &'static str,
scroll_id: &'static str, scroll_id: &'static str,
@@ -205,7 +210,6 @@ pub fn commit_list(
scroll_handle: UniformListScrollHandle, scroll_handle: UniformListScrollHandle,
action: impl Fn(usize, &FileCommit, &App) -> Option<AnyElement> + 'static, action: impl Fn(usize, &FileCommit, &App) -> Option<AnyElement> + 'static,
on_click: impl Fn(&FileCommit, &mut Window, &mut App) + Clone + 'static, on_click: impl Fn(&FileCommit, &mut Window, &mut App) + Clone + 'static,
_cx: &App,
) -> AnyElement { ) -> AnyElement {
let count = commits.len(); let count = commits.len();
@@ -234,6 +238,64 @@ pub fn commit_list(
.track_scroll(&scroll_handle) .track_scroll(&scroll_handle)
.size_full(), .size_full(),
) )
.child(scroll_overlay(scroll_id, scroll_handle)) .child(Scrollbar::vertical(scroll_id, scroll_handle))
.into_any_element()
}
/// One copyable commit summary row: id, subject, author, and age.
pub(crate) fn commit_row(
ix: usize,
commit: &FileCommit,
action: Option<AnyElement>,
on_click: impl Fn(&mut Window, &mut gpui::App) + 'static,
cx: &gpui::App,
) -> gpui::AnyElement {
h_flex()
.id(ix)
.px_4()
.h(px(COMMIT_ROW_HEIGHT))
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.justify_center()
.child(
h_flex()
.gap_2()
.overflow_hidden()
.child(
div()
.font_family(cx.theme().mono_font)
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(short_id(&commit.id)),
)
.child(
div()
.flex_1()
.min_w_0()
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
),
)
.child(
h_flex()
.gap_2()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(commit.author.clone())
.child(relative_time_secs(commit.time)),
),
)
.when_some(action, |row, action| row.child(action))
.on_click(move |_, window, cx| on_click(window, cx))
.into_any_element() .into_any_element()
} }
+1 -1
View File
@@ -5,7 +5,7 @@ use nostr::prelude::PublicKey;
pub mod event_list; pub mod event_list;
pub mod panels; pub mod panels;
pub mod progress; pub mod progress;
pub mod tree;
pub mod widgets; pub mod widgets;
/// Logs a discarded `Result` with its source location instead of dropping it silently. /// Logs a discarded `Result` with its source location instead of dropping it silently.
+96 -39
View File
@@ -5,6 +5,86 @@ use ui::layout::panel::{Panel, PanelView};
use crate::workspace::Workspace; use crate::workspace::Workspace;
/// Which slot of the workspace a panel opens into.
#[derive(Clone, Copy)]
enum PanelSlot {
Main,
Detail,
}
impl PanelSlot {
/// Whether the slot already holds a panel under `id`.
fn has(self, workspace: &WeakEntity<Workspace>, id: &SharedString, cx: &App) -> bool {
match self {
PanelSlot::Main => workspace
.read_with(cx, |workspace, _| workspace.has_main(id))
.unwrap_or(false),
PanelSlot::Detail => workspace
.read_with(cx, |workspace, _| workspace.has_detail(id))
.unwrap_or(false),
}
}
/// Activates the slot's cached panel under `id`.
fn activate(self, workspace: &WeakEntity<Workspace>, id: &SharedString, cx: &mut App) {
let result = match self {
PanelSlot::Main => {
workspace.update(cx, |workspace, cx| workspace.activate_main(id, cx))
}
PanelSlot::Detail => {
workspace.update(cx, |workspace, cx| workspace.activate_detail(id, cx))
}
};
if let Err(error) = result {
log::warn!("failed to activate panel {id}: {error}");
}
}
/// Shows the panel in the slot.
fn show(
self,
workspace: &WeakEntity<Workspace>,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut App,
) {
let result = match self {
PanelSlot::Main => {
workspace.update(cx, |workspace, cx| workspace.show_main(id, view, cx))
}
PanelSlot::Detail => {
workspace.update(cx, |workspace, cx| workspace.show_detail(id, view, cx))
}
};
if let Err(error) = result {
log::warn!("failed to open panel: {error}");
}
}
}
/// Opens a panel in `slot`, reusing it when it is already cached.
fn open_slot<P, F>(
slot: PanelSlot,
workspace: &WeakEntity<Workspace>,
id: impl Into<SharedString>,
build: F,
window: &mut Window,
cx: &mut App,
) where
P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{
let id = id.into();
if slot.has(workspace, &id, cx) {
slot.activate(workspace, &id, cx);
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
slot.show(workspace, id, view, cx);
}
/// Opens a repository in the main panel, reusing it when it is already cached. /// Opens a repository in the main panel, reusing it when it is already cached.
pub fn open_primary<P, F>( pub fn open_primary<P, F>(
workspace: &WeakEntity<Workspace>, workspace: &WeakEntity<Workspace>,
@@ -16,25 +96,14 @@ pub fn open_primary<P, F>(
P: Panel + 'static, P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static, F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{ {
let id = id.into(); open_slot(
PanelSlot::Main,
if workspace workspace,
.read_with(cx, |workspace, _| workspace.has_main(&id)) id,
.unwrap_or(false) build,
{ window,
if let Err(error) = workspace.update(cx, |workspace, cx| workspace.activate_main(&id, cx)) { cx,
log::warn!("failed to activate repository {id}: {error}"); );
}
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
if let Err(error) = workspace.update(cx, |workspace, cx| {
workspace.show_main(id.clone(), view, cx)
}) {
log::warn!("failed to open repository {id}: {error}");
}
} }
/// Opens a detail panel beside the main panel, reusing it when it is already cached. /// Opens a detail panel beside the main panel, reusing it when it is already cached.
@@ -48,24 +117,12 @@ pub fn open_detail<P, F>(
P: Panel + 'static, P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static, F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{ {
let id = id.into(); open_slot(
PanelSlot::Detail,
if workspace workspace,
.read_with(cx, |workspace, _| workspace.has_detail(&id)) id,
.unwrap_or(false) build,
{ window,
if let Err(error) = workspace.update(cx, |workspace, cx| workspace.activate_detail(&id, cx)) cx,
{ );
log::warn!("failed to activate detail panel {id}: {error}");
}
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
if let Err(error) = workspace.update(cx, |workspace, cx| {
workspace.show_detail(id.clone(), view, cx)
}) {
log::warn!("failed to open detail panel {id}: {error}");
}
} }
+31 -1
View File
@@ -1,15 +1,45 @@
use gpui::{ use gpui::{
AnyElement, App, AsyncApp, Context, Entity, IntoElement as _, ParentElement as _, SharedString, AnyElement, App, AsyncApp, Context, Entity, IntoElement as _, ParentElement as _, SharedString,
Styled as _, Subscription, Task, div, Styled as _, Subscription, Task, WeakEntity, Window, div,
}; };
use signed_core::RepoAddr; use signed_core::RepoAddr;
use signed_state::{Backend, BackendEvent, PushStepStatus}; use signed_state::{Backend, BackendEvent, PushStepStatus};
use ui::button::Button;
use ui::common::{h_flex, v_flex}; use ui::common::{h_flex, v_flex};
use ui::dialog::DialogHandle; use ui::dialog::DialogHandle;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::spinner::Spinner; use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use super::log_dropped;
/// The dialog's submit button: loading/disabled while busy, closing over the dialog's submit.
pub fn dialog_submit_button<T, F>(
id: &'static str,
label: impl Into<SharedString>,
icon: Option<IconRole>,
busy: bool,
this: &WeakEntity<T>,
submit: F,
) -> Button
where
T: 'static,
F: Fn(&mut T, &mut Window, &mut Context<T>) -> 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. /// Progress of an async dialog action: a busy flag that disables the form and an error shown below it.
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct DialogProgress { pub struct DialogProgress {
-188
View File
@@ -1,188 +0,0 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
pub struct TreeItemSeed {
/// Path of the node, relative to the worktree root.
pub id: String,
pub label: String,
pub children: Vec<TreeItemSeed>,
}
/// One visible row of the flattened tree.
#[derive(Clone)]
pub struct TreeRow {
pub id: String,
pub label: String,
pub depth: usize,
pub expandable: bool,
pub expanded: bool,
}
/// Flattens the seeds into the rows a flat tree renders, honoring `expanded`.
pub fn flatten(seeds: &[TreeItemSeed], expanded: &HashSet<String>) -> Vec<TreeRow> {
fn push(
seed: &TreeItemSeed,
depth: usize,
expanded: &HashSet<String>,
rows: &mut Vec<TreeRow>,
) {
let is_expanded = expanded.contains(&seed.id);
rows.push(TreeRow {
id: seed.id.clone(),
label: seed.label.clone(),
depth,
expandable: !seed.children.is_empty(),
expanded: is_expanded,
});
if is_expanded {
for child in &seed.children {
push(child, depth + 1, expanded, rows);
}
}
}
let mut rows = Vec::new();
for seed in seeds {
push(seed, 0, expanded, &mut rows);
}
rows
}
/// Every folder id, for starting with the tree fully expanded.
pub fn collect_expanded(seeds: &[TreeItemSeed]) -> HashSet<String> {
fn push(seed: &TreeItemSeed, expanded: &mut HashSet<String>) {
if !seed.children.is_empty() {
expanded.insert(seed.id.clone());
for child in &seed.children {
push(child, expanded);
}
}
}
let mut expanded = HashSet::new();
for seed in seeds {
push(seed, &mut expanded);
}
expanded
}
/// Build nested tree items from a flat entry list sorted dirs-first.
pub fn build_tree_items(entries: &[PathBuf]) -> Vec<TreeItemSeed> {
// Node indices by full path, so parents resolve in constant time while inserting.
let mut index: HashMap<String, usize> = HashMap::new();
let mut nodes: Vec<(String, String, Vec<usize>)> = Vec::new();
let mut roots: Vec<usize> = Vec::new();
for entry in entries {
let mut parent: Option<usize> = None;
let mut path = String::new();
for part in entry.components() {
let label = part.as_os_str().to_string_lossy().into_owned();
path = if path.is_empty() {
label.clone()
} else {
format!("{path}/{label}")
};
let ix = *index.entry(path.clone()).or_insert_with(|| {
let ix = nodes.len();
nodes.push((path.clone(), label.clone(), Vec::new()));
match parent {
Some(parent) => nodes[parent].2.push(ix),
None => roots.push(ix),
}
ix
});
parent = Some(ix);
}
}
fn assemble(ix: usize, nodes: &[(String, String, Vec<usize>)]) -> TreeItemSeed {
let (id, label, children) = &nodes[ix];
TreeItemSeed {
id: id.clone(),
label: label.clone(),
children: children
.iter()
.map(|child| assemble(*child, nodes))
.collect(),
}
}
roots.iter().map(|root| assemble(*root, &nodes)).collect()
}
/// Sorted relative paths of a worktree snapshot.
pub fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec<String> {
let mut paths: Vec<String> = entries
.iter()
.map(|path| path.to_string_lossy().into_owned())
.collect();
paths.sort();
paths
}
#[cfg(test)]
mod tests {
use super::*;
fn ids(rows: &[TreeRow]) -> Vec<(&str, usize)> {
rows.iter()
.map(|row| (row.id.as_str(), row.depth))
.collect()
}
#[test]
fn collapsed_folders_hide_children() {
let seeds = build_tree_items(&[
PathBuf::from("src"),
PathBuf::from("src/lib.rs"),
PathBuf::from("README.md"),
]);
let rows = flatten(&seeds, &HashSet::new());
assert_eq!(ids(&rows), vec![("src", 0), ("README.md", 0)]);
assert!(rows[0].expandable);
assert!(!rows[0].expanded);
}
#[test]
fn expanding_a_folder_shows_children_in_order() {
let seeds = build_tree_items(&[
PathBuf::from("src"),
PathBuf::from("src/lib.rs"),
PathBuf::from("src/views/mod.rs"),
PathBuf::from("README.md"),
]);
let expanded = HashSet::from(["src".to_owned(), "src/views".to_owned()]);
let rows = flatten(&seeds, &expanded);
assert_eq!(
ids(&rows),
vec![
("src", 0),
("src/lib.rs", 1),
("src/views", 1),
("src/views/mod.rs", 2),
("README.md", 0),
]
);
}
#[test]
fn indices_map_to_row_ids() {
let seeds = build_tree_items(&[
PathBuf::from("docs"),
PathBuf::from("docs/guide.md"),
PathBuf::from("README.md"),
]);
let expanded = HashSet::from(["docs".to_owned()]);
let rows = flatten(&seeds, &expanded);
assert_eq!(rows[0].id, "docs");
assert_eq!(rows[1].id, "docs/guide.md");
assert_eq!(rows[2].id, "README.md");
}
}
-81
View File
@@ -1,15 +1,6 @@
use gpui::{
AnyElement, App, ElementId, IntoElement, ParentElement as _, SharedString, Styled as _, div,
};
use signed_core::RepoStatus; use signed_core::RepoStatus;
use ui::badge::{Badge, BadgeVariant}; use ui::badge::{Badge, BadgeVariant};
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::scrollbar::{Scrollbar, ScrollbarHandle};
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip; use ui::tooltip::Tooltip;
/// The status pill shown on issue and pull-request rows. /// The status pill shown on issue and pull-request rows.
@@ -26,75 +17,3 @@ pub fn status_badge(status: RepoStatus) -> Badge {
.icon(Icon::named(icon)) .icon(Icon::named(icon))
.tooltip(Tooltip::text(label)) .tooltip(Tooltip::text(label))
} }
/// A centered empty-state message filling the available space.
pub fn empty_state(message: impl Into<SharedString>) -> AnyElement {
let message = message.into();
v_flex()
.size_full()
.items_center()
.justify_center()
.child(EmptyState::new(message))
.into_any_element()
}
/// A centered spinner filling the available space.
pub fn centered_spinner(id: impl Into<ElementId>) -> AnyElement {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new(id))
.into_any_element()
}
/// The vertical scrollbar pinned over a uniform list's full extent.
pub fn scroll_overlay<I, H>(id: I, handle: H) -> AnyElement
where
I: Into<ElementId>,
H: ScrollbarHandle,
{
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(id, handle))
.into_any_element()
}
/// One copyable clone command with its text visible next to the copy icon.
pub fn clone_row(id: SharedString, command: SharedString, cx: &App) -> AnyElement {
h_flex()
.h_8()
.px_2()
.gap_2()
.min_w_0()
.bg(cx.theme().colors.secondary)
.rounded(cx.theme().radius.control)
.text_color(cx.theme().colors.secondary_foreground)
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.font_family(cx.theme().mono_font)
.text_xs()
.child(command.clone()),
)
.child(ClipboardButton::new(id, command).xsmall())
.into_any_element()
}
/// A one-line muted label used by section headers.
pub fn section_label(text: impl Into<SharedString>, cx: &App) -> AnyElement {
div()
.text_xs()
.font_medium()
.text_color(cx.theme().colors.muted_foreground)
.child(text.into())
.into_any_element()
}
+43 -43
View File
@@ -56,49 +56,6 @@ pub(crate) struct SwitchRepository {
#[action(namespace = signed, no_json)] #[action(namespace = signed, no_json)]
pub(crate) struct CreateRepository; pub(crate) struct CreateRepository;
pub(crate) fn bind_repository_shortcuts(cx: &mut App) {
let context = match KeyBindingContextPredicate::parse(REPOSITORY_KEY_CONTEXT) {
Ok(context) => Some(Rc::new(context)),
Err(error) => {
log::error!("failed to parse repository key context: {error}");
return;
}
};
let bindings = REPOSITORY_KEYSTROKES
.into_iter()
.enumerate()
.map(|(index, keystroke)| {
KeyBinding::load(
keystroke,
Box::new(SwitchRepository { index }),
context.clone(),
false,
None,
cx,
)
})
.chain(std::iter::once(KeyBinding::load(
CREATE_KEYSTROKE,
Box::new(CreateRepository),
context.clone(),
false,
None,
cx,
)))
.collect::<Result<Vec<_>, _>>();
let bindings = match bindings {
Ok(bindings) => bindings,
Err(error) => {
log::error!("failed to parse repository shortcut keystrokes: {error}");
return;
}
};
cx.bind_keys(bindings);
}
pub struct TitlebarView { pub struct TitlebarView {
weak: WeakEntity<Self>, weak: WeakEntity<Self>,
workspace: WeakEntity<Workspace>, workspace: WeakEntity<Workspace>,
@@ -626,3 +583,46 @@ fn local_key(entry: &ResolvedLocalRepo) -> SharedString {
None => SharedString::from(format!("repo-local:{}", entry.path.display())), None => SharedString::from(format!("repo-local:{}", entry.path.display())),
} }
} }
pub(crate) fn bind_repository_shortcuts(cx: &mut App) {
let context = match KeyBindingContextPredicate::parse(REPOSITORY_KEY_CONTEXT) {
Ok(context) => Some(Rc::new(context)),
Err(error) => {
log::error!("failed to parse repository key context: {error}");
return;
}
};
let bindings = REPOSITORY_KEYSTROKES
.into_iter()
.enumerate()
.map(|(index, keystroke)| {
KeyBinding::load(
keystroke,
Box::new(SwitchRepository { index }),
context.clone(),
false,
None,
cx,
)
})
.chain(std::iter::once(KeyBinding::load(
CREATE_KEYSTROKE,
Box::new(CreateRepository),
context.clone(),
false,
None,
cx,
)))
.collect::<Result<Vec<_>, _>>();
let bindings = match bindings {
Ok(bindings) => bindings,
Err(error) => {
log::error!("failed to parse repository shortcut keystrokes: {error}");
return;
}
};
cx.bind_keys(bindings);
}
+2 -7
View File
@@ -269,7 +269,7 @@ impl RenderOnce for Alert {
/// One pushed alert, with its identity in the stack. /// One pushed alert, with its identity in the stack.
#[derive(Clone)] #[derive(Clone)]
pub struct AlertEntry { struct AlertEntry {
/// The id [`Alerts::push`] returned. /// The id [`Alerts::push`] returned.
pub id: usize, pub id: usize,
/// The alert as pushed. /// The alert as pushed.
@@ -338,14 +338,9 @@ impl Alerts {
} }
/// The stacked alerts, oldest first. /// The stacked alerts, oldest first.
pub fn entries(&self) -> &[AlertEntry] { fn entries(&self) -> &[AlertEntry] {
&self.entries &self.entries
} }
/// How many alerts are stacked.
pub fn count(&self) -> usize {
self.entries.len()
}
} }
/// The floating stack of pushed alerts, topmost right. /// The floating stack of pushed alerts, topmost right.
+95 -22
View File
@@ -14,6 +14,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt::Display; use std::fmt::Display;
use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div,
@@ -140,6 +141,78 @@ impl RenderOnce for Avatar {
} }
} }
/// An avatar with the display name beside it.
#[derive(IntoElement)]
#[must_use]
pub struct IdentityRow {
id: SharedString,
name: SharedString,
picture: Option<SharedString>,
size: Size,
truncate: bool,
style: StyleRefinement,
}
impl IdentityRow {
/// Creates the row for `id` (the pixel-fallback seed) showing `name`.
pub fn new<ID, N>(id: ID, name: N, picture: Option<SharedString>) -> Self
where
ID: Into<SharedString>,
N: Into<SharedString>,
{
Self {
id: id.into(),
name: name.into(),
picture,
size: Size::default(),
truncate: false,
style: StyleRefinement::default(),
}
}
/// Truncates the name to one line inside the available width.
pub fn truncate(mut self) -> Self {
self.truncate = true;
self
}
}
impl Sizable for IdentityRow {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl gpui::Styled for IdentityRow {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for IdentityRow {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
h_flex()
.refine_style(&self.style)
.child(
Avatar::new(self.id.clone())
.name(self.name.clone())
.picture(self.picture)
.with_size(self.size),
)
.child(
div()
.when(self.truncate, |name| {
name.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
})
.child(self.name),
)
}
}
/// A deterministic, offline pixel-art avatar. /// A deterministic, offline pixel-art avatar.
#[derive(IntoElement)] #[derive(IntoElement)]
struct PixelAvatar { struct PixelAvatar {
@@ -218,6 +291,28 @@ thread_local! {
std::cell::RefCell::new(HashMap::new()); std::cell::RefCell::new(HashMap::new());
} }
/// Tiny xorshift64* PRNG for deriving the pattern from the seed.
struct PixelRng(u64);
impl PixelRng {
fn new(seed: u64) -> Self {
Self(seed.max(1))
}
fn next(&mut self) -> u64 {
let mut x = self.0;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.0 = x;
x.wrapping_mul(0x2545_f491_4f6c_dd1d)
}
fn chance(&mut self, probability: f32) -> bool {
self.next() as f32 / (u64::MAX as f32) < probability
}
}
fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] { fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
let cached = PATTERN_CACHE.with(|cache| cache.borrow().get(&seed).copied()); let cached = PATTERN_CACHE.with(|cache| cache.borrow().get(&seed).copied());
if let Some(cached) = cached { if let Some(cached) = cached {
@@ -284,25 +379,3 @@ fn fnv1a(bytes: &[u8]) -> u64 {
} }
hash hash
} }
/// Tiny xorshift64* PRNG for deriving the pattern from the seed.
struct PixelRng(u64);
impl PixelRng {
fn new(seed: u64) -> Self {
Self(seed.max(1))
}
fn next(&mut self) -> u64 {
let mut x = self.0;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.0 = x;
x.wrapping_mul(0x2545_f491_4f6c_dd1d)
}
fn chance(&mut self, probability: f32) -> bool {
self.next() as f32 / (u64::MAX as f32) < probability
}
}
+12 -12
View File
@@ -46,18 +46,6 @@ pub enum ButtonVariant {
Destructive, Destructive,
} }
/// The variant colors a button paints with, resolved from the active theme.
pub struct ButtonChrome {
/// The resting background, `None` for unpainted variants like `Ghost`.
pub background: Option<Hsla>,
pub foreground: Hsla,
pub hover: Hsla,
pub pressed: Hsla,
pub border: Hsla,
pub hover_border: Hsla,
pub pressed_border: Hsla,
}
impl ButtonVariant { impl ButtonVariant {
/// The variant's colors from the active theme. /// The variant's colors from the active theme.
pub fn chrome(&self, cx: &App) -> ButtonChrome { pub fn chrome(&self, cx: &App) -> ButtonChrome {
@@ -117,6 +105,18 @@ pub enum ButtonSide {
Right, Right,
} }
/// The variant colors a button paints with, resolved from the active theme.
pub struct ButtonChrome {
/// The resting background, `None` for unpainted variants like `Ghost`.
pub background: Option<Hsla>,
pub foreground: Hsla,
pub hover: Hsla,
pub pressed: Hsla,
pub border: Hsla,
pub hover_border: Hsla,
pub pressed_border: Hsla,
}
/// A push button that renders a label, an icon, or both, and fires /// A push button that renders a label, an icon, or both, and fires
/// [`Button::on_click`] on click, Enter, or Space. /// [`Button::on_click`] on click, Enter, or Space.
#[derive(IntoElement)] #[derive(IntoElement)]
+70 -6
View File
@@ -15,21 +15,20 @@ use std::time::Duration;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyView, App, ClipboardItem, ElementId, Entity, IntoElement, RenderOnce, SharedString, AnyView, App, ClipboardItem, ElementId, Entity, IntoElement, ParentElement as _, RenderOnce,
StyleRefinement, Task, Window, SharedString, StyleRefinement, Styled as _, Task, Window, div,
}; };
use crate::components::button::{Button, ButtonVariant}; use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{ResultLogErr as _, Sizable, StyledExt as _}; use crate::components::common::{ResultLogErr as _, Sizable, StyledExt as _, h_flex};
use crate::icons::IconRole; use crate::icons::IconRole;
use crate::theme::Size; use crate::theme::{ActiveTheme as _, Size};
/// How long the check mark shows before reverting to the copy icon. /// How long the check mark shows before reverting to the copy icon.
pub const COPIED_DURATION: Duration = Duration::from_secs(1); const COPIED_DURATION: Duration = Duration::from_secs(1);
/// The tooltip view builder gpui's `.tooltip(...)` expects. /// The tooltip view builder gpui's `.tooltip(...)` expects.
type TooltipBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyView>; type TooltipBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyView>;
/// Runs after the value lands on the clipboard. /// Runs after the value lands on the clipboard.
type CopiedHandler = Box<dyn Fn(&mut App)>; type CopiedHandler = Box<dyn Fn(&mut App)>;
@@ -184,3 +183,68 @@ impl RenderOnce for ClipboardButton {
}) })
} }
} }
/// A copyable value shown as a boxed row with a trailing copy button.
#[derive(IntoElement)]
#[must_use]
pub struct CopyRow {
id: SharedString,
value: SharedString,
large_text: bool,
}
impl CopyRow {
/// Monospace `value` in a secondary-background row (the clone-command look).
pub fn new<ID, V>(id: ID, value: V) -> Self
where
ID: Into<SharedString>,
V: Into<SharedString>,
{
Self {
id: id.into(),
value: value.into(),
large_text: false,
}
}
/// Base-size label and default-size copy button (the about-dialog list look).
pub fn text_base(mut self) -> Self {
self.large_text = true;
self
}
}
impl RenderOnce for CopyRow {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
h_flex()
.h_8()
.px_2()
.gap_2()
.min_w_0()
.bg(theme.colors.secondary)
.rounded(theme.radius.control)
.text_color(theme.colors.secondary_foreground)
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.when(self.large_text, |text| text.text_base())
.when(!self.large_text, |text| {
text.font_family(theme.mono_font).text_xs()
})
.child(self.value.clone()),
)
.child(if self.large_text {
ClipboardButton::new(self.id, self.value).into_any_element()
} else {
ClipboardButton::new(self.id, self.value)
.xsmall()
.into_any_element()
})
}
}
+145 -161
View File
@@ -47,34 +47,13 @@ actions!(code_view, [Copy]);
/// The key context the code view declares while it holds focus. /// The key context the code view declares while it holds focus.
pub const CODE_VIEW_CONTEXT: &str = "CodeView"; pub const CODE_VIEW_CONTEXT: &str = "CodeView";
/// Binds the code view's copy chord: cmd-c on macOS, ctrl-c elsewhere.
///
/// Call once at startup. Without it, selection copy has no key.
pub fn bind_code_view_keys(cx: &mut App) {
let context = match KeyBindingContextPredicate::parse(CODE_VIEW_CONTEXT) {
Ok(context) => Some(Rc::new(context)),
Err(error) => {
log::error!("failed to parse code view key context: {error}");
return;
}
};
let binding = match KeyBinding::load("secondary-c", Box::new(Copy), context, false, None, cx) {
Ok(binding) => binding,
Err(error) => {
log::error!("failed to parse code view copy keystroke: {error}");
return;
}
};
cx.bind_keys([binding]);
}
/// A point in the source, in lines and characters (not bytes). /// A point in the source, in lines and characters (not bytes).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SelectionPoint { struct SelectionPoint {
/// The zero-based line index. /// The zero-based line index.
pub row: usize, row: usize,
/// The zero-based character offset within the line. /// The zero-based character offset within the line.
pub col: usize, col: usize,
} }
impl SelectionPoint { impl SelectionPoint {
@@ -235,24 +214,8 @@ impl CodeViewState {
self.active_line self.active_line
} }
/// Selects a range, endpoints in lines and characters.
pub fn select_range(
&mut self,
start: SelectionPoint,
end: SelectionPoint,
cx: &mut Context<Self>,
) {
self.selection = if start.earlier_than(&end) {
Some((start, end))
} else {
Some((end, start))
};
self.selecting = false;
cx.notify();
}
/// The selected range, endpoints in document order, when there is one. /// The selected range, endpoints in document order, when there is one.
pub fn selection(&self) -> Option<(SelectionPoint, SelectionPoint)> { fn selection(&self) -> Option<(SelectionPoint, SelectionPoint)> {
self.selection.map(|(anchor, head)| { self.selection.map(|(anchor, head)| {
if anchor.earlier_than(&head) { if anchor.earlier_than(&head) {
(anchor, head) (anchor, head)
@@ -263,7 +226,7 @@ impl CodeViewState {
} }
/// The selected text, or `None` when nothing is selected. /// The selected text, or `None` when nothing is selected.
pub fn selected_text(&self) -> Option<String> { fn selected_text(&self) -> Option<String> {
let (start, end) = self.selection()?; let (start, end) = self.selection()?;
let lines: Vec<&str> = self.source.split('\n').collect(); let lines: Vec<&str> = self.source.split('\n').collect();
@@ -325,6 +288,128 @@ impl CodeViewState {
SelectionPoint { row, col } SelectionPoint { row, col }
} }
#[allow(clippy::too_many_arguments)]
fn render_row(
&self,
id: &ElementId,
line_ix: usize,
active: bool,
selection: Option<(SelectionPoint, SelectionPoint)>,
mono_font: &'static str,
colors: ColorTokens,
ramps: Ramps,
text_size: Pixels,
line_height: Pixels,
cx: &App,
) -> gpui::AnyElement {
let layout = self.line_layouts.get(line_ix);
let text = layout.map_or("", |layout| layout.text.as_str());
let roles = layout.map_or(&[][..], |layout| layout.roles.as_slice());
let char_count = text.chars().count();
let mut selected = vec![false; char_count];
if let Some((start, end)) = selection
&& line_ix >= start.row
&& line_ix <= end.row
{
let start_col = if line_ix == start.row {
start.col.min(char_count)
} else {
0
};
let end_col = if line_ix == end.row {
end.col.min(char_count)
} else {
char_count
};
for slot in &mut selected[start_col..end_col] {
*slot = true;
}
}
let mut highlights: Vec<(std::ops::Range<usize>, HighlightStyle)> = Vec::new();
let mut run_start = 0usize;
let mut run_end = 0usize;
let mut run_role = Role::Text;
let mut run_selected = false;
for (char_ix, (byte_ix, character)) in text.char_indices().enumerate() {
let fresh =
char_ix == 0 || roles[char_ix] != run_role || selected[char_ix] != run_selected;
if fresh {
if char_ix > 0 {
highlights.push((
run_start..run_end,
run_role.run_style(run_selected, colors, ramps),
));
}
run_start = byte_ix;
run_role = roles[char_ix];
run_selected = selected[char_ix];
}
run_end = byte_ix + character.len_utf8();
}
if run_end > run_start || !text.is_empty() {
highlights.push((
run_start..run_end,
run_role.run_style(run_selected, colors, ramps),
));
}
let style = TextStyle {
color: colors.foreground,
font_family: SharedString::from(mono_font),
font_size: text_size.into(),
line_height: line_height.into(),
white_space: gpui::WhiteSpace::Nowrap,
..Default::default()
};
div()
.debug_selector(move || format!("{id}-row-{line_ix}"))
.id(("code-row", line_ix))
.w_full()
.text_xs()
.h(line_height)
.flex()
.items_center()
.overflow_hidden()
.when(active, |row| {
row.bg(Hsla {
a: colors.muted.a * WASH_ALPHA_SOFT,
..colors.muted
})
})
.child(
gutter_cell(
cx,
if active {
colors.foreground
} else {
colors.muted_foreground
},
format!("{}", line_ix + 1),
)
.justify_end()
.pr_2()
.whitespace_nowrap(),
)
.child(
div()
.flex_1()
.min_w_0()
.ml_4()
.overflow_hidden()
.whitespace_nowrap()
.child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)),
)
.into_any_element()
}
} }
impl gpui::Focusable for CodeViewState { impl gpui::Focusable for CodeViewState {
@@ -362,8 +447,7 @@ impl Render for CodeViewState {
range range
.map(|line_ix| { .map(|line_ix| {
render_row( code.render_row(
code,
&id, &id,
line_ix, line_ix,
active_line == Some(line_ix), active_line == Some(line_ix),
@@ -523,123 +607,23 @@ impl Render for CodeViewState {
} }
} }
#[allow(clippy::too_many_arguments)] /// Binds the code view's copy chord: cmd-c on macOS, ctrl-c elsewhere.
fn render_row( ///
code: &CodeViewState, /// Call once at startup. Without it, selection copy has no key.
id: &ElementId, pub fn bind_code_view_keys(cx: &mut App) {
line_ix: usize, let context = match KeyBindingContextPredicate::parse(CODE_VIEW_CONTEXT) {
active: bool, Ok(context) => Some(Rc::new(context)),
selection: Option<(SelectionPoint, SelectionPoint)>, Err(error) => {
mono_font: &'static str, log::error!("failed to parse code view key context: {error}");
colors: ColorTokens, return;
ramps: Ramps, }
text_size: Pixels,
line_height: Pixels,
cx: &App,
) -> gpui::AnyElement {
let layout = code.line_layouts.get(line_ix);
let text = layout.map_or("", |layout| layout.text.as_str());
let roles = layout.map_or(&[][..], |layout| layout.roles.as_slice());
let char_count = text.chars().count();
let mut selected = vec![false; char_count];
if let Some((start, end)) = selection
&& line_ix >= start.row
&& line_ix <= end.row
{
let start_col = if line_ix == start.row {
start.col.min(char_count)
} else {
0
}; };
let binding = match KeyBinding::load("secondary-c", Box::new(Copy), context, false, None, cx) {
let end_col = if line_ix == end.row { Ok(binding) => binding,
end.col.min(char_count) Err(error) => {
} else { log::error!("failed to parse code view copy keystroke: {error}");
char_count return;
}
}; };
cx.bind_keys([binding]);
for slot in &mut selected[start_col..end_col] {
*slot = true;
}
}
let mut highlights: Vec<(std::ops::Range<usize>, HighlightStyle)> = Vec::new();
let mut run_start = 0usize;
let mut run_end = 0usize;
let mut run_role = Role::Text;
let mut run_selected = false;
for (char_ix, (byte_ix, character)) in text.char_indices().enumerate() {
let fresh = char_ix == 0 || roles[char_ix] != run_role || selected[char_ix] != run_selected;
if fresh {
if char_ix > 0 {
highlights.push((
run_start..run_end,
run_role.run_style(run_selected, colors, ramps),
));
}
run_start = byte_ix;
run_role = roles[char_ix];
run_selected = selected[char_ix];
}
run_end = byte_ix + character.len_utf8();
}
if run_end > run_start || !text.is_empty() {
highlights.push((
run_start..run_end,
run_role.run_style(run_selected, colors, ramps),
));
}
let style = TextStyle {
color: colors.foreground,
font_family: SharedString::from(mono_font),
font_size: text_size.into(),
line_height: line_height.into(),
white_space: gpui::WhiteSpace::Nowrap,
..Default::default()
};
div()
.debug_selector(move || format!("{id}-row-{line_ix}"))
.id(("code-row", line_ix))
.w_full()
.text_xs()
.h(line_height)
.flex()
.items_center()
.overflow_hidden()
.when(active, |row| {
row.bg(Hsla {
a: colors.muted.a * WASH_ALPHA_SOFT,
..colors.muted
})
})
.child(
gutter_cell(
cx,
if active {
colors.foreground
} else {
colors.muted_foreground
},
format!("{}", line_ix + 1),
)
.justify_end()
.pr_2()
.whitespace_nowrap(),
)
.child(
div()
.flex_1()
.min_w_0()
.ml_4()
.overflow_hidden()
.whitespace_nowrap()
.child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)),
)
.into_any_element()
} }
+30 -122
View File
@@ -2,9 +2,8 @@
//! //!
//! The state is the view: [`ComboboxState`] owns the query field and the //! The state is the view: [`ComboboxState`] owns the query field and the
//! options, and the owner renders the entity itself. Typing filters, the //! options, and the owner renders the entity itself. Typing filters, the
//! arrow keys move a highlight, Enter commits, and what happens to unmatched //! arrow keys move a highlight, Enter commits, and unmatched text reverts to
//! text when the field loses focus is decided by [`UnmatchedText`], which //! the chosen option's label (or empties the field) when focus is lost.
//! reverts by default.
//! //!
//! # Examples //! # Examples
//! //!
@@ -33,13 +32,12 @@ use gpui::{
App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding,
MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, SharedString, MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, SharedString,
StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task, StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task,
UniformListScrollHandle, Window, actions, anchored, canvas, deferred, div, point, px, UniformListScrollHandle, Window, actions, canvas, div, uniform_list,
uniform_list,
}; };
use crate::components::common::{ use crate::components::common::{
ControlSizing, OVERLAY_LAYER, ResultLogErr as _, Sizable, StyledExt as _, floating_panel, ControlSizing, ResultLogErr as _, Sizable, StyledExt as _, floating_panel, h_flex,
h_flex, paint_highlighted_row, v_flex, wrapping_adjacent_selectable, paint_highlighted_row, v_flex, wrapping_adjacent_selectable,
}; };
use crate::components::empty_state::EmptyState; use crate::components::empty_state::EmptyState;
use crate::components::input::{Input, InputState, InputStateEvent}; use crate::components::input::{Input, InputState, InputStateEvent};
@@ -54,41 +52,10 @@ actions!(
/// The key context the combobox's wrapper declares. /// The key context the combobox's wrapper declares.
pub const COMBOBOX_CONTEXT: &str = "Combobox"; pub const COMBOBOX_CONTEXT: &str = "Combobox";
/// Binds the combobox's four keys: down, up, enter, and escape.
pub fn bind_combobox_keys(cx: &mut App) {
let under_input = Some("Combobox > Input");
cx.bind_keys([
KeyBinding::new("down", HighlightNext, under_input),
KeyBinding::new("up", HighlightPrevious, under_input),
KeyBinding::new("enter", Choose, under_input),
KeyBinding::new("escape", Dismiss, under_input),
KeyBinding::new("down", HighlightNext, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("up", HighlightPrevious, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("enter", Choose, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("escape", Dismiss, Some(COMBOBOX_CONTEXT)),
]);
}
/// What happens to text that matches no option when the field loses focus.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum UnmatchedText {
/// Restore the chosen option's label, or empty the field.
#[default]
Revert,
/// Leave the text and leave the value cleared.
Keep,
/// Hand the text to the `on_create` handler.
Create,
}
/// An option for a [`Combobox`]: a value and the label the filter matches on. /// An option for a [`Combobox`]: a value and the label the filter matches on.
pub type ComboboxOption<T> = (T, SharedString); pub type ComboboxOption<T> = (T, SharedString);
/// Reports the value whenever it changes. /// Reports the value whenever it changes.
pub type ComboboxHandler<T> = Rc<dyn Fn(Option<T>, &mut Window, &mut App)>; pub type ComboboxHandler<T> = Rc<dyn Fn(Option<T>, &mut Window, &mut App)>;
/// Receives unmatched text when the field loses focus in create mode.
pub type ComboboxCreateHandler = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
/// Decides which options survive a query: the query, the value, the label.
pub type ComboboxFilter<T> = Rc<dyn Fn(&str, &T, &SharedString) -> bool>;
/// Builder for a combobox, consumed by [`ComboboxState::new`]. /// Builder for a combobox, consumed by [`ComboboxState::new`].
#[must_use] #[must_use]
@@ -102,9 +69,6 @@ where
selected: Option<T>, selected: Option<T>,
placeholder: SharedString, placeholder: SharedString,
on_change: Option<ComboboxHandler<T>>, on_change: Option<ComboboxHandler<T>>,
on_create: Option<ComboboxCreateHandler>,
filter: Option<ComboboxFilter<T>>,
unmatched: UnmatchedText,
size: Size, size: Size,
/// Icon shown at the field's leading edge while a value is selected. /// Icon shown at the field's leading edge while a value is selected.
selected_icon: Option<Icon>, selected_icon: Option<Icon>,
@@ -127,9 +91,6 @@ where
selected: None, selected: None,
placeholder: SharedString::from("Select..."), placeholder: SharedString::from("Select..."),
on_change: None, on_change: None,
on_create: None,
filter: None,
unmatched: UnmatchedText::default(),
size: Size::default(), size: Size::default(),
selected_icon: None, selected_icon: None,
style: StyleRefinement::default(), style: StyleRefinement::default(),
@@ -169,31 +130,6 @@ where
self self
} }
/// Hands unmatched text to `handler` when the field loses focus.
pub fn on_create<F>(mut self, handler: F) -> Self
where
F: Fn(SharedString, &mut Window, &mut App) + 'static,
{
self.on_create = Some(Rc::new(handler));
self.unmatched = UnmatchedText::Create;
self
}
/// Sets the matcher that decides which options survive a query.
pub fn filter<F>(mut self, filter: F) -> Self
where
F: Fn(&str, &T, &SharedString) -> bool + 'static,
{
self.filter = Some(Rc::new(filter));
self
}
/// Leaves unmatched text in the field on blur.
pub fn keep_unmatched_text(mut self) -> Self {
self.unmatched = UnmatchedText::Keep;
self
}
/// Overrides the accessibility label. /// Overrides the accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self pub fn accessibility_label<L>(mut self, label: L) -> Self
where where
@@ -250,9 +186,6 @@ where
/// The highlighted popup *row*, when the popup is open. /// The highlighted popup *row*, when the popup is open.
highlight: Option<usize>, highlight: Option<usize>,
on_change: Option<ComboboxHandler<T>>, on_change: Option<ComboboxHandler<T>>,
on_create: Option<ComboboxCreateHandler>,
filter: ComboboxFilter<T>,
unmatched: UnmatchedText,
size: Size, size: Size,
/// Width refinements from the builder, applied to the wrapper each render. /// Width refinements from the builder, applied to the wrapper each render.
style: StyleRefinement, style: StyleRefinement,
@@ -312,11 +245,6 @@ where
visible, visible,
highlight: None, highlight: None,
on_change: combobox.on_change, on_change: combobox.on_change,
on_create: combobox.on_create,
filter: combobox.filter.unwrap_or_else(|| {
Rc::new(|query, _value, label| label.to_lowercase().contains(&query.to_lowercase()))
}),
unmatched: combobox.unmatched,
size: combobox.size, size: combobox.size,
style: combobox.style, style: combobox.style,
selected_icon: combobox.selected_icon, selected_icon: combobox.selected_icon,
@@ -326,21 +254,6 @@ where
} }
} }
/// The text currently in the field.
pub fn text(&self, cx: &App) -> String {
self.query.read(cx).value().to_string()
}
/// Focuses the query field.
pub fn focus(&self, window: &mut Window, cx: &mut App) {
window.focus(&self.query.read(cx).focus_handle(), cx);
}
/// Whether the option list is showing.
pub fn is_open(&self) -> bool {
self.highlight.is_some()
}
/// The chosen value. /// The chosen value.
pub fn selected(&self) -> Option<&T> { pub fn selected(&self) -> Option<&T> {
self.selected.as_ref() self.selected.as_ref()
@@ -367,11 +280,6 @@ where
cx.notify(); cx.notify();
} }
/// A copy of the current choice list.
pub fn options_snapshot(&self) -> Vec<ComboboxOption<T>> {
self.options.clone()
}
/// The label of the chosen option, if there is one. /// The label of the chosen option, if there is one.
fn selected_label(&self) -> Option<SharedString> { fn selected_label(&self) -> Option<SharedString> {
let selected = self.selected.as_ref()?; let selected = self.selected.as_ref()?;
@@ -383,12 +291,12 @@ where
/// Recomputes `visible` for `query` and clamps the highlight onto it. /// Recomputes `visible` for `query` and clamps the highlight onto it.
fn refilter(&mut self, query: &str) { fn refilter(&mut self, query: &str) {
let filter = self.filter.clone(); let needle = query.to_lowercase();
self.visible = self self.visible = self
.options .options
.iter() .iter()
.enumerate() .enumerate()
.filter(|(_, (value, label))| filter(query, value, label)) .filter(|(_, (_, label))| label.to_lowercase().contains(&needle))
.map(|(index, _)| index) .map(|(index, _)| index)
.collect(); .collect();
self.highlight = self.highlight.filter(|row| *row < self.visible.len()); self.highlight = self.highlight.filter(|row| *row < self.visible.len());
@@ -452,7 +360,7 @@ where
cx.notify(); cx.notify();
} }
/// Losing focus. [`UnmatchedText`] decides what the text becomes. /// Losing focus: unmatched text reverts to the chosen option's label.
fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) { fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.highlight = None; self.highlight = None;
let text = self.query_text(cx); let text = self.query_text(cx);
@@ -462,26 +370,10 @@ where
return; return;
} }
match self.unmatched {
UnmatchedText::Revert => {
let restored = self.selected_label().unwrap_or_default().to_string(); let restored = self.selected_label().unwrap_or_default().to_string();
self.query self.query.update(cx, |query, cx| {
.update(cx, |query, cx| query.set_value_silent(restored, window, cx)); query.set_value_silent(restored, window, cx);
}
UnmatchedText::Keep => {}
UnmatchedText::Create => {
if !text.is_empty()
&& let Some(on_create) = self.on_create.clone()
{
let text = SharedString::from(text);
let task = window.spawn(cx, async move |cx| {
cx.update(|window, cx| on_create(text, window, cx))
.log_err();
}); });
self.task.replace(task);
}
}
}
cx.notify(); cx.notify();
} }
@@ -798,10 +690,26 @@ where
.inset_0(), .inset_0(),
); );
wrapper.child( wrapper.child(crate::components::menu::anchored_overlay(
deferred(anchored().offset(point(px(0.), px(4.))).child(panel)) None,
.with_priority(OVERLAY_LAYER), panel.into_any_element(),
) None,
))
}) })
} }
} }
/// Binds the combobox's four keys: down, up, enter, and escape.
pub fn bind_combobox_keys(cx: &mut App) {
let under_input = Some("Combobox > Input");
cx.bind_keys([
KeyBinding::new("down", HighlightNext, under_input),
KeyBinding::new("up", HighlightPrevious, under_input),
KeyBinding::new("enter", Choose, under_input),
KeyBinding::new("escape", Dismiss, under_input),
KeyBinding::new("down", HighlightNext, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("up", HighlightPrevious, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("enter", Choose, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("escape", Dismiss, Some(COMBOBOX_CONTEXT)),
]);
}
+24 -32
View File
@@ -30,7 +30,7 @@ use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding,
MouseButton, ParentElement as _, Render, Role, SharedString, StatefulInteractiveElement as _, MouseButton, ParentElement as _, Render, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Subscription, UniformListScrollHandle, Window, actions, canvas, StyleRefinement, Styled as _, Subscription, UniformListScrollHandle, Window, actions,
deferred, div, relative, rems, uniform_list, deferred, div, relative, rems, uniform_list,
}; };
@@ -51,20 +51,10 @@ actions!(
/// The key context the palette's panel declares. /// The key context the palette's panel declares.
pub const COMMAND_PALETTE_CONTEXT: &str = "CommandPalette"; pub const COMMAND_PALETTE_CONTEXT: &str = "CommandPalette";
/// Binds the palette's four keys: down, up, enter, and escape. /// Filters and ranks the commands for a query.
pub fn bind_command_palette_keys(cx: &mut App) { pub type CommandMatcher = Rc<dyn Fn(&str, &[Command]) -> Vec<Command>>;
let under_input = Some("CommandPalette > Input"); /// Runs the chosen command.
cx.bind_keys([ pub type CommandHandler = Rc<dyn Fn(&Command, &mut Window, &mut App)>;
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)),
]);
}
/// A command the palette can run: a stable id and the label the matcher sees. /// A command the palette can run: a stable id and the label the matcher sees.
#[derive(Clone)] #[derive(Clone)]
@@ -117,11 +107,6 @@ impl Command {
// Command is a data builder, not an element, adopt the combinators explicitly. // Command is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for Command {} impl FluentBuilder for Command {}
/// Filters and ranks the commands for a query.
pub type CommandMatcher = Rc<dyn Fn(&str, &[Command]) -> Vec<Command>>;
/// Runs the chosen command.
pub type CommandHandler = Rc<dyn Fn(&Command, &mut Window, &mut App)>;
/// Builder for a command palette, consumed by [`CommandPaletteState::new`]. /// Builder for a command palette, consumed by [`CommandPaletteState::new`].
#[must_use] #[must_use]
pub struct CommandPalette { pub struct CommandPalette {
@@ -525,18 +510,10 @@ impl Render for CommandPaletteState {
.placeholder(self.placeholder.clone()), .placeholder(self.placeholder.clone()),
) )
.child(rows) .child(rows)
.child( .child(crate::components::menu::focus_capture(
canvas(|_, _, _| {}, { query_focus.clone(),
let focus = query_focus.clone(); move |window, cx| !query_focus.contains_focused(window, cx),
move |_, _, window, cx| { ));
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
let scrim = div() let scrim = div()
.absolute() .absolute()
@@ -566,3 +543,18 @@ impl Render for CommandPaletteState {
.into_any_element() .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)),
]);
}
+27 -29
View File
@@ -19,8 +19,33 @@ use gpui::{
WindowId, div, px, rems, WindowId, div, px, rems,
}; };
pub use crate::theme::Size; use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD, Size};
use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD};
/// Deferred draw priority of window-modal surfaces; default layer 0 stays for in-flow chrome like resize handles.
pub const DIALOG_LAYER: usize = 1;
/// Deferred draw priority of floating panels, so controls inside a dialog open above it.
pub const OVERLAY_LAYER: usize = 2;
/// Deferred draw priority of passive notifications, so they stay visible over dialogs.
pub const TOAST_LAYER: usize = 3;
/// A handler told to clean up after a dismissed surface.
pub type DismissHandler = std::rc::Rc<dyn Fn(&mut gpui::App)>;
/// The painted bounds of elements that tooltips anchor to, per window and element id.
#[derive(Default)]
struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds<Pixels>>);
impl Global for AnchorBoundsRegistry {}
impl AnchorBoundsRegistry {
fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds<Pixels>) {
self.0.insert((window, id), bounds);
}
fn get(&self, window: WindowId, id: &ElementId) -> Option<Bounds<Pixels>> {
self.0.get(&(window, id.clone())).copied()
}
}
/// A row whose children center on the cross axis. /// A row whose children center on the cross axis.
#[must_use] #[must_use]
@@ -87,23 +112,6 @@ pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusH
.clone() .clone()
} }
/// The painted bounds of elements that tooltips anchor to, per window and element id.
/// Entries are never evicted: bounds are bounded by live windows, though long-lived processes minting dynamic per-item ids could accumulate.
#[derive(Default)]
struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds<Pixels>>);
impl Global for AnchorBoundsRegistry {}
impl AnchorBoundsRegistry {
fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds<Pixels>) {
self.0.insert((window, id), bounds);
}
fn get(&self, window: WindowId, id: &ElementId) -> Option<Bounds<Pixels>> {
self.0.get(&(window, id.clone())).copied()
}
}
/// The last bounds an element painted at, in the given window. /// The last bounds an element painted at, in the given window.
pub fn anchor_bounds(window: WindowId, id: &ElementId, cx: &App) -> Option<Bounds<Pixels>> { pub fn anchor_bounds(window: WindowId, id: &ElementId, cx: &App) -> Option<Bounds<Pixels>> {
cx.try_global::<AnchorBoundsRegistry>() cx.try_global::<AnchorBoundsRegistry>()
@@ -250,16 +258,6 @@ where
}) })
} }
/// A handler told to clean up after a dismissed surface.
pub type DismissHandler = std::rc::Rc<dyn Fn(&mut gpui::App)>;
/// Deferred draw priority of window-modal surfaces; default layer 0 stays for in-flow chrome like resize handles.
pub const DIALOG_LAYER: usize = 1;
/// Deferred draw priority of floating panels, so controls inside a dialog open above it.
pub const OVERLAY_LAYER: usize = 2;
/// Deferred draw priority of passive notifications, so they stay visible over dialogs.
pub const TOAST_LAYER: usize = 3;
/// A component that can be told which size to render at. /// A component that can be told which size to render at.
pub trait Sizable: Sized { pub trait Sizable: Sized {
/// Sets the size. /// Sets the size.
-145
View File
@@ -1,145 +0,0 @@
//! Renders a menu at the pointer when its target element is right-clicked.
//!
//! # Examples
//!
//! ```no_run
//! use gpui::{IntoElement as _, ParentElement as _, SharedString, div};
//! use ui::context_menu::ContextMenu;
//! use ui::menu::MenuItem;
//!
//! let context = ContextMenu::new("project-context")
//! .target(|_window, _cx| {
//! div()
//! .child(SharedString::from("project.el"))
//! .into_any_element()
//! })
//! .items(|_window, _cx| vec![MenuItem::new("Delete").handler(|_window, _cx| {})]);
//! ```
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,
ParentElement as _, RenderOnce, SharedString, StyleRefinement, Window, div,
};
use crate::components::common::StyledExt as _;
use crate::components::menu::{Menu, MenuItem};
/// Builds the element that opens the menu on right-click.
type TargetFn = Box<dyn Fn(&mut Window, &mut App) -> gpui::AnyElement>;
/// Builds the menu's items fresh each render.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<MenuItem>>;
/// A menu that opens at the pointer when its target is right-clicked.
///
/// Open state is owned internally by design, unlike the controlled [`Menu`].
#[derive(IntoElement)]
#[must_use]
pub struct ContextMenu {
id: ElementId,
target: Option<TargetFn>,
items: Option<ItemsFn>,
a11y_label: Option<SharedString>,
style: StyleRefinement,
}
impl ContextMenu {
/// Creates a context menu over a target set with [`ContextMenu::target`].
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
target: None,
items: None,
a11y_label: None,
style: StyleRefinement::default(),
}
}
/// Sets the element that opens the menu on right-click.
pub fn target<F>(mut self, target: F) -> Self
where
F: Fn(&mut Window, &mut App) -> gpui::AnyElement + 'static,
{
self.target = Some(Box::new(target));
self
}
/// Sets the menu's items, built fresh each render.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<MenuItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Overrides the menu's accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl RenderOnce for ContextMenu {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let open = window.with_element_namespace(self.id.clone(), |window| {
window
.use_keyed_state("context-open", cx, |_, _| false)
.clone()
});
let at = window.with_element_namespace(self.id.clone(), |window| {
window
.use_keyed_state("context-position", cx, |_, _| None)
.clone()
});
let is_open = *open.read(cx);
let position = *at.read(cx);
let target = self.target;
let at_for_target = at.clone();
let trigger = move |window: &mut Window, cx: &mut App| {
let base = target
.as_ref()
.map(|build| build(window, cx))
.unwrap_or_else(|| div().into_any_element());
div()
.on_mouse_down(MouseButton::Right, {
let at = at_for_target.clone();
move |event: &MouseDownEvent, _window, cx| {
at.update(cx, |at, _| *at = Some(event.position));
}
})
.child(base)
.into_any_element()
};
let items = move |window: &mut Window, cx: &mut App| {
self.items
.as_ref()
.map(|build| build(window, cx))
.unwrap_or_default()
};
Menu::new(self.id)
.open(is_open)
.on_change(move |next, _window, cx| open.update(cx, |open, _| *open = next))
.open_at(position)
.trigger_button(MouseButton::Right)
.trigger(trigger)
.items(items)
.refine_style(&self.style)
.when_some(self.a11y_label.clone(), |menu, label| {
menu.accessibility_label(label)
})
}
}
+1 -1
View File
@@ -42,7 +42,7 @@ use crate::icons::IconRole;
use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH}; use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH};
/// Requests the dialog's close: `false` closes. /// Requests the dialog's close: `false` closes.
pub type ChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>; type ChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type ContentFn = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>; type ContentFn = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>;
type ActionsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<AnyElement>>; type ActionsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<AnyElement>>;
-720
View File
@@ -1,720 +0,0 @@
//! Renders a unified, syntax-highlighted diff of two versions of a file:
//! change bars or `+`/`-` markers, tinted number gutters, word-level
//! intra-line highlights, and collapsed hunk separators.
//!
//! Rows reuse the code view's highlighting. Consumers that already hold a
//! git diff can build [`DiffRow`]s themselves instead of calling
//! [`DiffViewState::diff_rows`].
//!
//! # Examples
//!
//! ```no_run
//! use gpui::{App, AppContext as _};
//! use ui::diff::{DiffIndicators, DiffViewState};
//! use ui::highlight::Language;
//!
//! fn patch(cx: &mut App) -> gpui::Entity<DiffViewState> {
//! let state = DiffViewState::new(
//! "patch",
//! "# gpui\nA UI kit for gpui.",
//! "# gpui\nA UI toolkit for gpui.",
//! Language::Rust,
//! )
//! .indicators(DiffIndicators::Bars);
//!
//! cx.new(|_| state)
//! }
//! ```
use std::ops::Range;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Context, ElementId, HighlightStyle, InteractiveElement as _, IntoElement,
ListHorizontalSizingBehavior, ParentElement as _, Pixels, Render, ScrollStrategy, SharedString,
StatefulInteractiveElement as _, Styled as _, TextStyle, UniformListScrollHandle, Window, div,
point, px, rems, uniform_list,
};
use similar::{Change, ChangeTag, TextDiff};
use crate::components::highlight::{HighlightedCode, Language, Line, Role, highlight};
use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility};
use crate::components::utils::{gutter_cell, wash, wash_gutter, wash_strong};
use crate::theme::{ActiveTheme as _, CODE_GUTTER_WIDTH, CODE_LINE_HEIGHT, MONO_ADVANCE_RATIO};
/// The left change-indicator bar's width, four hairlines.
const CHANGE_BAR_WIDTH: Pixels = px(4.0);
/// What a diff row did to the file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DiffRowKind {
/// Present in both versions.
Context,
/// Only in the new version.
Added,
/// Only in the old version.
Removed,
/// A hunk separator introducing the rows after it.
Hunk,
}
/// One row of a unified diff: a diff line or a hunk separator.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DiffRow {
pub kind: DiffRowKind,
/// The highlighted line content; empty for hunk separators.
pub content: Line,
/// 1-based line number in the old version, when the row exists there.
pub old_number: Option<usize>,
/// 1-based line number in the new version, when the row exists there.
pub new_number: Option<usize>,
/// Byte ranges of intra-line word changes, tinted on changed rows.
pub changed_ranges: Vec<Range<usize>>,
/// The `@@ -a,b +c,d @@` header, for hunk separator rows.
pub header: SharedString,
/// Unchanged lines collapsed into this separator row; zero elsewhere.
pub hidden_lines: usize,
}
/// How changed rows are marked.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DiffIndicators {
/// A two-pixel bar on the row's left edge.
#[default]
Bars,
/// Classic `+`/`-` glyphs in a marker column.
Classic,
/// Only the background washes.
None,
}
/// How collapsed regions between hunks render.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HunkSeparator {
/// The collapsed unchanged line count, centered.
#[default]
LineInfo,
/// The patch-style `@@ -a,b +c,d @@` header.
Metadata,
/// A minimal `···` bar.
Simple,
}
/// Presentation options for the diff view.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DiffViewOptions {
/// How changed rows are marked.
pub indicators: DiffIndicators,
/// How collapsed regions between hunks render.
pub separator: HunkSeparator,
/// Whether the line-number gutter renders.
pub line_numbers: bool,
}
impl Default for DiffViewOptions {
fn default() -> Self {
Self {
indicators: DiffIndicators::Bars,
separator: HunkSeparator::LineInfo,
line_numbers: true,
}
}
}
impl DiffRow {
/// Assembles a diff line row from a `similar` change.
pub(crate) fn from_change(
change: &Change<&str>,
code: &HighlightedCode,
changed_ranges: Vec<Range<usize>>,
) -> DiffRow {
let content = match change.tag() {
ChangeTag::Equal => change
.new_index()
.and_then(|ix| code.lines.get(ix))
.cloned()
.unwrap_or_default(),
ChangeTag::Delete => change
.old_index()
.and_then(|ix| code.lines.get(ix))
.cloned()
.unwrap_or_default(),
ChangeTag::Insert => change
.new_index()
.and_then(|ix| code.lines.get(ix))
.cloned()
.unwrap_or_default(),
};
let (old_number, new_number) = match change.tag() {
ChangeTag::Equal => (
change.old_index().map(|ix| ix + 1),
change.new_index().map(|ix| ix + 1),
),
ChangeTag::Delete => (change.old_index().map(|ix| ix + 1), None),
ChangeTag::Insert => (None, change.new_index().map(|ix| ix + 1)),
};
DiffRow {
kind: match change.tag() {
ChangeTag::Equal => DiffRowKind::Context,
ChangeTag::Delete => DiffRowKind::Removed,
ChangeTag::Insert => DiffRowKind::Added,
},
content,
old_number,
new_number,
changed_ranges,
header: Default::default(),
hidden_lines: 0,
}
}
/// The row's text length, in characters.
fn char_count(&self) -> usize {
self.content.text().chars().count()
}
/// Stable element id: the kind and line numbers packed into one integer.
fn element_id(&self, hunk_ordinal: usize) -> ElementId {
let kind = match self.kind {
DiffRowKind::Context => 0u64,
DiffRowKind::Added => 1,
DiffRowKind::Removed => 2,
DiffRowKind::Hunk => {
return ElementId::named_usize("diff-hunk", hunk_ordinal);
}
};
// Line numbers saturate at 2^31 so the two fields never overlap.
let old = self.old_number.unwrap_or(0).min((1 << 31) - 1) as u64;
let new = self.new_number.unwrap_or(0).min((1 << 31) - 1) as u64;
ElementId::named_usize("diff-row", ((kind << 62) | (old << 31) | new) as usize)
}
}
/// Retained state for a diff view.
///
/// Build one in a [`gpui::Entity`], render the entity, and call its setters
/// to update the rendered view.
pub struct DiffViewState {
id: ElementId,
rows: Vec<DiffRow>,
/// Cached per-row id and text length, parallel to `rows`.
row_layouts: Vec<RowLayout>,
/// The row whose width drives horizontal scroll extent, `rows`-derived.
widest_row: Option<usize>,
options: DiffViewOptions,
/// Drives both scroll axes of the virtualized row list.
handle: UniformListScrollHandle,
a11y_label: Option<SharedString>,
}
/// Cached per-row render data, computed once when the rows are set.
struct RowLayout {
id: ElementId,
char_count: usize,
}
impl DiffViewState {
/// Builds the state, diffing `old` against `new`.
pub fn new<I, O, N>(id: I, old: O, new: N, language: Language) -> Self
where
I: Into<ElementId>,
O: AsRef<str>,
N: AsRef<str>,
{
let mut state = Self {
id: id.into(),
rows: Vec::new(),
row_layouts: Vec::new(),
widest_row: None,
options: DiffViewOptions::default(),
handle: UniformListScrollHandle::new(),
a11y_label: None,
};
state.set_rows(old, new, language);
state
}
/// Replaces the rows, recomputing the per-row layout cache with them.
fn set_rows<O, N>(&mut self, old: O, new: N, language: Language)
where
O: AsRef<str>,
N: AsRef<str>,
{
self.rows = Self::diff_rows(old.as_ref(), new.as_ref(), language);
let mut hunk_ordinal = 0usize;
self.row_layouts = self
.rows
.iter()
.map(|row| {
let ordinal = if row.kind == DiffRowKind::Hunk {
hunk_ordinal += 1;
hunk_ordinal
} else {
0
};
RowLayout {
id: row.element_id(ordinal),
char_count: row.char_count(),
}
})
.collect();
self.widest_row = self
.rows
.iter()
.zip(&self.row_layouts)
.enumerate()
.filter(|(_, (row, _))| row.kind != DiffRowKind::Hunk)
.max_by_key(|(_, (_, layout))| layout.char_count)
.map(|(widest, _)| widest);
}
/// Computes unified rows between two texts, highlighting every line with
/// `language`. Rows include [`DiffRowKind::Hunk`] separators between
/// hunks.
pub fn diff_rows(old: &str, new: &str, language: Language) -> Vec<DiffRow> {
let old_code = highlight(old, language);
let new_code = highlight(new, language);
let diff = TextDiff::from_lines(old, new);
let mut rows = Vec::new();
let mut collapsed_before = 0usize;
for group in diff.grouped_ops(3) {
let (Some(first), Some(last)) = (group.first(), group.last()) else {
continue;
};
let old_range = first.old_range().start..last.old_range().end;
let new_range = first.new_range().start..last.new_range().end;
// git prints the line before a pure insertion when the count is zero.
let old_start = if old_range.is_empty() {
old_range.start
} else {
old_range.start + 1
};
let new_start = if new_range.is_empty() {
new_range.start
} else {
new_range.start + 1
};
let collapsed = first.old_range().start.saturating_sub(collapsed_before);
if collapsed > 0 {
rows.push(DiffRow {
kind: DiffRowKind::Hunk,
content: Line::default(),
old_number: None,
new_number: None,
changed_ranges: Vec::new(),
header: format!(
"@@ -{},{} +{},{} @@",
old_start,
old_range.len(),
new_start,
new_range.len()
)
.into(),
hidden_lines: collapsed,
});
}
collapsed_before = last.old_range().end;
for op in &group {
let changes: Vec<_> = diff.iter_changes(op).collect();
let mut index = 0;
while index < changes.len() {
if changes[index].tag() == ChangeTag::Equal {
rows.push(DiffRow::from_change(&changes[index], &new_code, Vec::new()));
index += 1;
continue;
}
let deletions = changes[index..]
.iter()
.take_while(|change| change.tag() == ChangeTag::Delete)
.count();
let insertions = changes[index + deletions..]
.iter()
.take_while(|change| change.tag() == ChangeTag::Insert)
.count();
let mut deletion_ranges = vec![Vec::new(); deletions];
let mut insertion_ranges = vec![Vec::new(); insertions];
for pair in 0..deletions.min(insertions) {
let old_text = changes[index + pair].value().trim_end_matches('\n');
let new_text = changes[index + deletions + pair]
.value()
.trim_end_matches('\n');
let words = TextDiff::from_words(old_text, new_text);
let (mut old_offset, mut new_offset) = (0usize, 0usize);
for word in words.iter_all_changes() {
let len = word.value().len();
match word.tag() {
ChangeTag::Delete => {
deletion_ranges[pair].push(old_offset..old_offset + len);
old_offset += len;
}
ChangeTag::Insert => {
insertion_ranges[pair].push(new_offset..new_offset + len);
new_offset += len;
}
ChangeTag::Equal => {
old_offset += len;
new_offset += len;
}
}
}
}
for pair in 0..deletions {
rows.push(DiffRow::from_change(
&changes[index + pair],
&old_code,
deletion_ranges[pair].clone(),
));
}
for pair in 0..insertions {
rows.push(DiffRow::from_change(
&changes[index + deletions + pair],
&new_code,
insertion_ranges[pair].clone(),
));
}
index += deletions + insertions;
}
}
}
rows
}
/// Sets how changed rows are marked.
pub fn indicators(mut self, indicators: DiffIndicators) -> Self {
self.options.indicators = indicators;
self
}
/// Sets how collapsed regions between hunks render.
pub fn hunk_separator(mut self, separator: HunkSeparator) -> Self {
self.options.separator = separator;
self
}
/// Shows or hides the line-number gutter.
pub fn line_numbers(mut self, show: bool) -> Self {
self.options.line_numbers = show;
self
}
/// Replaces the versions and re-diffs them.
pub fn set_versions<O, N>(&mut self, old: O, new: N, language: Language, cx: &mut Context<Self>)
where
O: AsRef<str>,
N: AsRef<str>,
{
self.set_rows(old, new, language);
self.handle.scroll_to_item(0, ScrollStrategy::Top);
// The replaced versions rarely share the old width; start at the left.
let offset = ScrollbarHandle::offset(&self.handle);
ScrollbarHandle::set_offset(&self.handle, point(Pixels::ZERO, offset.y));
cx.notify();
}
/// The diff rows.
pub fn rows(&self) -> &[DiffRow] {
&self.rows
}
/// Scrolls the first added or removed row to the top of the view.
pub fn scroll_to_first_change(&self) {
let Some(row) = self
.rows
.iter()
.position(|row| matches!(row.kind, DiffRowKind::Added | DiffRowKind::Removed))
else {
return;
};
self.handle.scroll_to_item(row, ScrollStrategy::Top);
}
/// Overrides the accessibility label of the view.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl Render for DiffViewState {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let text_size = rems(0.75).to_pixels(window.rem_size());
let id = self.id.clone();
let state = cx.entity();
let row_count = self.rows.len();
let options = self.options;
let widest_row = self.widest_row;
let mut rows = uniform_list((id.clone(), "rows"), row_count, {
move |range, _window, cx| {
let diff = state.read(cx);
range
.map(|row_index| {
render_row(
&diff.rows[row_index],
&diff.row_layouts[row_index],
row_index,
options,
text_size,
cx,
)
})
.collect()
}
})
.with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
.with_width_from_item(widest_row)
.track_scroll(&self.handle)
.h_full();
// Lock each gesture to its initial axis
rows.interactivity().base_style.restrict_scroll_to_axis = Some(true);
div()
.id((id.clone(), "view"))
.relative()
.size_full()
.text_xs()
.when_some(self.a11y_label.clone(), |view, label| {
view.aria_label(label)
})
.child(rows)
.child(
Scrollbar::vertical((self.id.clone(), "v-scrollbar"), self.handle.clone())
.visibility(ScrollbarVisibility::Platform),
)
.child(
Scrollbar::horizontal((self.id.clone(), "h-scrollbar"), self.handle.clone())
.visibility(ScrollbarVisibility::Platform),
)
}
}
fn render_row(
row: &DiffRow,
layout: &RowLayout,
row_index: usize,
options: DiffViewOptions,
text_size: Pixels,
cx: &App,
) -> gpui::AnyElement {
let theme = cx.theme();
let mono_font = theme.mono_font;
let colors = theme.colors;
let ramps = theme.ramps;
let line_height = text_size * CODE_LINE_HEIGHT;
let char_width = text_size * MONO_ADVANCE_RATIO;
let frame = div()
.debug_selector(move || format!("diff-row-{row_index}"))
.id(layout.id.clone())
.w_full()
.h(line_height)
.font_family(mono_font)
.text_xs()
.overflow_hidden();
if row.kind == DiffRowKind::Hunk {
let content = match options.separator {
HunkSeparator::LineInfo => {
SharedString::from(format!("{} unchanged lines", row.hidden_lines))
}
HunkSeparator::Metadata => row.header.clone(),
HunkSeparator::Simple => SharedString::from("···"),
};
return frame
.flex()
.items_center()
.text_color(colors.muted_foreground)
.when(
options.indicators == DiffIndicators::Classic,
|row_element| row_element.child(div().w(CODE_GUTTER_WIDTH).flex_none()),
)
.when(options.line_numbers, |row_element| {
row_element.child(div().w(CODE_GUTTER_WIDTH).flex_none())
})
.when(
options.indicators == DiffIndicators::Bars && !options.line_numbers,
|row_element| {
row_element.child(
div()
.flex_none()
.border_l(CHANGE_BAR_WIDTH)
.border_color(gpui::transparent_black()),
)
},
)
.child(div().flex_none().ml_2().child(content))
.into_any_element();
}
let change_color = match row.kind {
DiffRowKind::Added => ramps.success.base,
DiffRowKind::Removed => ramps.destructive.base,
DiffRowKind::Context | DiffRowKind::Hunk => gpui::transparent_black(),
};
let wash = match row.kind {
DiffRowKind::Added => Some(wash(ramps.success.base)),
DiffRowKind::Removed => Some(wash(ramps.destructive.base)),
DiffRowKind::Context | DiffRowKind::Hunk => None,
};
let mut text = String::new();
let mut spans: Vec<(Range<usize>, Role)> = Vec::new();
for span in &row.content.spans {
let start = text.len();
text.push_str(&span.text);
if span.role != Role::Text {
spans.push((start..text.len(), span.role));
}
}
let mut boundaries: Vec<usize> = spans
.iter()
.flat_map(|(range, _)| [range.start, range.end])
.chain(
row.changed_ranges
.iter()
.flat_map(|range| [range.start, range.end]),
)
.collect();
boundaries.sort_unstable();
boundaries.dedup();
let mut highlights: Vec<(std::ops::Range<usize>, HighlightStyle)> = Vec::new();
let mut span_ix = 0;
for window in boundaries.windows(2) {
let (start, end) = (window[0], window[1]);
while span_ix < spans.len() && spans[span_ix].0.end <= start {
span_ix += 1;
}
let mut segment = HighlightStyle::default();
if let Some((range, role)) = spans.get(span_ix)
&& range.contains(&start)
&& *role != Role::Text
{
segment = segment.highlight(HighlightStyle {
color: Some(role.color(colors, ramps)),
..Default::default()
});
}
if row
.changed_ranges
.iter()
.any(|range| range.contains(&start))
{
segment = segment.highlight(HighlightStyle {
background_color: Some(wash_strong(change_color)),
..Default::default()
});
}
highlights.push((start..end, segment));
}
let style = TextStyle {
color: colors.foreground,
font_family: SharedString::from(mono_font),
font_size: text_size.into(),
line_height: line_height.into(),
..Default::default()
};
frame
.flex()
.items_center()
.when_some(wash, |row_element, tint| row_element.bg(tint))
.when(
options.indicators == DiffIndicators::Classic,
|row_element| {
row_element.child(gutter_cell(
cx,
if row.kind == DiffRowKind::Context {
gpui::transparent_black()
} else {
change_color
},
match row.kind {
DiffRowKind::Added => "+",
DiffRowKind::Removed => "-",
_ => "",
},
))
},
)
.when(options.line_numbers, |row_element| {
row_element.child(
gutter_cell(
cx,
colors.muted_foreground,
row.new_number
.or(row.old_number)
.map(|number| number.to_string())
.unwrap_or_default(),
)
.w(CODE_GUTTER_WIDTH)
.whitespace_nowrap()
.bg(match row.kind {
DiffRowKind::Context => wash_gutter(&colors),
_ => wash_strong(change_color),
})
.when(options.indicators == DiffIndicators::Bars, |number| {
number.border_l(CHANGE_BAR_WIDTH).border_color(change_color)
}),
)
})
.when(
options.indicators == DiffIndicators::Bars && !options.line_numbers,
|row_element| {
row_element.child(
div()
.h_full()
.flex_none()
.border_l(CHANGE_BAR_WIDTH)
.border_color(change_color),
)
},
)
.child(
div()
.flex_none()
.ml_2()
.w(char_width * layout.char_count as f32)
.whitespace_nowrap()
.child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)),
)
.into_any_element()
}
+15 -2
View File
@@ -11,8 +11,8 @@
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _, AnyElement, App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement,
Window, div, rems, Styled as _, Window, div, rems,
}; };
use crate::components::common::{StyledExt, v_flex}; use crate::components::common::{StyledExt, v_flex};
@@ -45,6 +45,19 @@ impl EmptyState {
} }
} }
/// The empty state centered in the full available space.
pub fn centered<L>(message: L) -> AnyElement
where
L: Into<SharedString>,
{
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Self::new(message))
.into_any_element()
}
/// Sets a large muted icon above the headline. /// Sets a large muted icon above the headline.
pub fn icon<I>(mut self, icon: I) -> Self pub fn icon<I>(mut self, icon: I) -> Self
where where
+5 -5
View File
@@ -29,11 +29,6 @@ const TILE_PX: u32 = 256;
#[must_use] #[must_use]
pub struct Grain; pub struct Grain;
/// Creates a grain overlay.
pub fn grain() -> Grain {
Grain
}
impl RenderOnce for Grain { impl RenderOnce for Grain {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
let texture = texture(); let texture = texture();
@@ -74,6 +69,11 @@ impl RenderOnce for Grain {
} }
} }
/// Creates a grain overlay.
pub fn grain() -> Grain {
Grain
}
/// Returns the shared noise tile so every tile reuses one atlas entry. /// Returns the shared noise tile so every tile reuses one atlas entry.
fn texture() -> Arc<RenderImage> { fn texture() -> Arc<RenderImage> {
static TEXTURE: OnceLock<Arc<RenderImage>> = OnceLock::new(); static TEXTURE: OnceLock<Arc<RenderImage>> = OnceLock::new();
+8 -8
View File
@@ -28,14 +28,6 @@ thread_local! {
RefCell::new(HashMap::new()); RefCell::new(HashMap::new());
} }
/// A grammar's parser and compiled highlight query.
#[cfg(not(target_arch = "wasm32"))]
struct Highlighter {
parser: tree_sitter::Parser,
query: tree_sitter::Query,
roles: Vec<Option<Role>>,
}
/// A language source can highlight as. /// A language source can highlight as.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Language { pub enum Language {
@@ -64,6 +56,14 @@ pub enum Role {
Escape, Escape,
} }
/// A grammar's parser and compiled highlight query.
#[cfg(not(target_arch = "wasm32"))]
struct Highlighter {
parser: tree_sitter::Parser,
query: tree_sitter::Query,
roles: Vec<Option<Role>>,
}
/// A run of text sharing one role. /// A run of text sharing one role.
#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Span { pub struct Span {
+56 -100
View File
@@ -12,7 +12,7 @@
//! use ui::input::{Input, InputState, bind_input_keys}; //! use ui::input::{Input, InputState, bind_input_keys};
//! //!
//! # let mut cx: gpui::App = unimplemented!(); //! # let mut cx: gpui::App = unimplemented!();
//! bind_input_keys(&mut cx, None); //! bind_input_keys(&mut cx);
//! //!
//! let state = InputState::builder() //! let state = InputState::builder()
//! .text("Ada Lovelace") //! .text("Ada Lovelace")
@@ -131,10 +131,9 @@ actions!(
/// The keybindings [`bind_input_keys`] registers on the application. /// The keybindings [`bind_input_keys`] registers on the application.
/// ///
/// A `None` field leaves its action unbound. Start from [`InputBindings::default`] /// A `None` field leaves its action unbound. Start from [`InputBindings::default`]
/// to rebind one action and keep the platform defaults, or from /// to rebind one action and keep the platform defaults.
/// [`InputBindings::empty`] to bind only what you set.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct InputBindings { pub(crate) struct InputBindings {
pub escape: Option<KeyBinding>, pub escape: Option<KeyBinding>,
pub submit: Option<KeyBinding>, pub submit: Option<KeyBinding>,
pub secondary_submit: Option<KeyBinding>, pub secondary_submit: Option<KeyBinding>,
@@ -260,43 +259,6 @@ impl Default for InputBindings {
} }
impl InputBindings { impl InputBindings {
/// A table with every key unbound, for building custom bindings.
pub fn empty() -> Self {
Self {
escape: None,
submit: None,
secondary_submit: None,
insert_newline: None,
backspace: None,
delete: None,
delete_word_left: None,
delete_word_right: None,
delete_to_beginning_of_line: None,
left: None,
right: None,
up: None,
down: None,
select_left: None,
select_right: None,
select_up: None,
select_down: None,
word_left: None,
word_right: None,
select_word_left: None,
select_word_right: None,
home: None,
end: None,
select_home: None,
select_end: None,
select_all: None,
copy: None,
cut: None,
paste: None,
undo: None,
redo: None,
}
}
/// Collects the table into keybindings. /// Collects the table into keybindings.
pub(crate) fn into_bindings(self) -> Vec<KeyBinding> { pub(crate) fn into_bindings(self) -> Vec<KeyBinding> {
let mut bindings: Vec<KeyBinding> = [ let mut bindings: Vec<KeyBinding> = [
@@ -508,55 +470,6 @@ impl HistoryEntry {
} }
} }
/// The application-owned state of a text field that [`Input`] renders.
pub struct InputState {
text: String,
/// The caret's byte offset.
cursor: usize,
/// The byte offset the selection extends from.
anchor: usize,
/// The byte range of in-progress IME composition, if any.
marked_range: Option<Range<usize>>,
/// Whether the field had focus at the last paint, for focus transitions.
focused: bool,
focus_handle: gpui::FocusHandle,
/// The key-down handler, bound to this entity with `cx.listener`.
key_down_handler: KeyDownHandler,
/// The mouse-down handler, bound to this entity with `cx.listener`.
mouse_down_handler: MouseDownHandler,
/// Whether a drag-select is in progress.
dragging: bool,
/// Patch history. `redo_stack` holds undone entries awaiting redo.
undo_stack: Vec<HistoryEntry>,
redo_stack: Vec<HistoryEntry>,
/// Consecutive edits within this interval merge into one undo entry.
group_interval: Duration,
/// When set, user edits are refused; focus, movement, selection, and copy still work.
read_only: bool,
/// When set, the field is a password field.
password: bool,
/// Whether a password field currently shows its content.
revealed: bool,
/// Whether the field holds multiple lines of text.
multiline: bool,
/// Which keystroke submits a multiline field.
submit_on: SubmitOn,
/// The x the caret keeps across vertical movement, reset on any other move.
goal_x: Option<Pixels>,
/// Content scroll inside the field: x for single-line, y for multiline, clamped at paint.
scroll_offset: gpui::Point<Pixels>,
/// Set by every caret-affecting change.
scroll_to_caret_pending: bool,
/// Bumped on every edit.
caret_epoch: usize,
/// When the current caret epoch started.
caret_epoch_started: Instant,
/// The shaped line and element bounds, recorded during each paint.
layout: Option<InputLayout>,
/// The last shaped buffer, reused while no shaping input changed.
shaped_cache: std::cell::RefCell<Option<(ShapeCacheKey, ShapedText)>>,
}
/// Everything `shape_text` consumes, for cache reuse between frames. /// Everything `shape_text` consumes, for cache reuse between frames.
#[derive(Clone, PartialEq)] #[derive(Clone, PartialEq)]
struct ShapeCacheKey { struct ShapeCacheKey {
@@ -567,8 +480,6 @@ struct ShapeCacheKey {
color: gpui::Hsla, color: gpui::Hsla,
} }
impl EventEmitter<InputStateEvent> for InputState {}
/// Builder for [`InputState`] settings that are fixed at creation. /// Builder for [`InputState`] settings that are fixed at creation.
#[derive(Default)] #[derive(Default)]
pub struct InputStateBuilder { pub struct InputStateBuilder {
@@ -628,6 +539,57 @@ impl InputStateBuilder {
} }
} }
/// The application-owned state of a text field that [`Input`] renders.
pub struct InputState {
text: String,
/// The caret's byte offset.
cursor: usize,
/// The byte offset the selection extends from.
anchor: usize,
/// The byte range of in-progress IME composition, if any.
marked_range: Option<Range<usize>>,
/// Whether the field had focus at the last paint, for focus transitions.
focused: bool,
focus_handle: gpui::FocusHandle,
/// The key-down handler, bound to this entity with `cx.listener`.
key_down_handler: KeyDownHandler,
/// The mouse-down handler, bound to this entity with `cx.listener`.
mouse_down_handler: MouseDownHandler,
/// Whether a drag-select is in progress.
dragging: bool,
/// Patch history. `redo_stack` holds undone entries awaiting redo.
undo_stack: Vec<HistoryEntry>,
redo_stack: Vec<HistoryEntry>,
/// Consecutive edits within this interval merge into one undo entry.
group_interval: Duration,
/// When set, user edits are refused; focus, movement, selection, and copy still work.
read_only: bool,
/// When set, the field is a password field.
password: bool,
/// Whether a password field currently shows its content.
revealed: bool,
/// Whether the field holds multiple lines of text.
multiline: bool,
/// Which keystroke submits a multiline field.
submit_on: SubmitOn,
/// The x the caret keeps across vertical movement, reset on any other move.
goal_x: Option<Pixels>,
/// Content scroll inside the field: x for single-line, y for multiline, clamped at paint.
scroll_offset: gpui::Point<Pixels>,
/// Set by every caret-affecting change.
scroll_to_caret_pending: bool,
/// Bumped on every edit.
caret_epoch: usize,
/// When the current caret epoch started.
caret_epoch_started: Instant,
/// The shaped line and element bounds, recorded during each paint.
layout: Option<InputLayout>,
/// The last shaped buffer, reused while no shaping input changed.
shaped_cache: std::cell::RefCell<Option<(ShapeCacheKey, ShapedText)>>,
}
impl EventEmitter<InputStateEvent> for InputState {}
impl InputState { impl InputState {
fn new_inner(cx: &mut Context<Self>) -> Self { fn new_inner(cx: &mut Context<Self>) -> Self {
Self { Self {
@@ -2517,14 +2479,8 @@ impl RenderOnce for Input {
} }
/// Registers the input keybindings on the application, once at startup. /// Registers the input keybindings on the application, once at startup.
/// pub fn bind_input_keys(cx: &mut App) {
/// Pass `None` for the platform defaults or an [`InputBindings`] table for cx.bind_keys(InputBindings::default().into_bindings());
/// custom ones.
pub fn bind_input_keys<B>(cx: &mut App, bindings: B)
where
B: Into<Option<InputBindings>>,
{
cx.bind_keys(bindings.into().unwrap_or_default().into_bindings());
} }
/// The row holding `display`. /// The row holding `display`.
+8 -79
View File
@@ -3,23 +3,19 @@
//! # Examples //! # Examples
//! //!
//! ```no_run //! ```no_run
//! use gpui::{Keystroke, ParentElement as _}; //! use gpui::Keystroke;
//! use ui::kbd::{Kbd, KbdGroup}; //! use ui::kbd::Kbd;
//! //!
//! let save = Kbd::new(Keystroke::parse("cmd-s").unwrap()); //! let save = Kbd::new(Keystroke::parse("cmd-s").unwrap());
//! let combo = KbdGroup::new()
//! .child(Kbd::new(Keystroke::parse("ctrl-b").unwrap()))
//! .child(Kbd::new(Keystroke::parse("ctrl-k").unwrap()));
//! ``` //! ```
use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
Action, AnyElement, App, FocusHandle, InteractiveElement as _, IntoElement, KeyBinding, Action, App, InteractiveElement as _, IntoElement, KeyBinding, KeyContext, Keystroke,
KeyContext, Keystroke, OperatingSystem, ParentElement as _, RenderOnce, SharedString, OperatingSystem, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _,
StyleRefinement, Styled as _, Window, div, relative, Window, div, relative,
}; };
use crate::components::common::{StyledExt as _, h_flex}; use crate::components::common::StyledExt as _;
use crate::theme::ActiveTheme as _; use crate::theme::ActiveTheme as _;
/// A key or shortcut shown as a small key cap, like `⌘S` or `Ctrl+S`. /// A key or shortcut shown as a small key cap, like `⌘S` or `Ctrl+S`.
@@ -27,7 +23,6 @@ use crate::theme::ActiveTheme as _;
#[must_use] #[must_use]
pub struct Kbd { pub struct Kbd {
stroke: Keystroke, stroke: Keystroke,
appearance: bool,
style: StyleRefinement, style: StyleRefinement,
} }
@@ -42,7 +37,6 @@ impl Kbd {
pub fn new(stroke: Keystroke) -> Self { pub fn new(stroke: Keystroke) -> Self {
Self { Self {
stroke, stroke,
appearance: true,
style: StyleRefinement::default(), style: StyleRefinement::default(),
} }
} }
@@ -52,12 +46,6 @@ impl Kbd {
&self.stroke &self.stroke
} }
/// When false, paints the formatted shortcut as plain text without the key cap.
pub fn appearance(mut self, appearance: bool) -> Self {
self.appearance = appearance;
self
}
/// Returns a key cap for the highest-precedence binding of `action`. /// Returns a key cap for the highest-precedence binding of `action`.
pub fn binding_for_action( pub fn binding_for_action(
action: &dyn Action, action: &dyn Action,
@@ -73,23 +61,6 @@ impl Kbd {
Self::from_binding(&binding) Self::from_binding(&binding)
} }
/// Returns a key cap for the binding of `action`.
pub fn binding_for_action_in(
action: &dyn Action,
focus_handle: &FocusHandle,
window: &Window,
) -> Option<Self> {
let binding = window.highest_precedence_binding_for_action_in(action, focus_handle)?;
Self::from_binding(&binding)
}
/// Returns a key cap for the binding of `action` registered without a key context.
pub fn global_binding_for_action(action: &dyn Action, window: &Window) -> Option<Self> {
let binding = window
.highest_precedence_binding_for_action_in_context(action, KeyContext::default())?;
Self::from_binding(&binding)
}
/// Shows the binding's keystroke as the keymap holds it. /// Shows the binding's keystroke as the keymap holds it.
fn from_binding(binding: &KeyBinding) -> Option<Self> { fn from_binding(binding: &KeyBinding) -> Option<Self> {
binding.keystrokes().first().map(|stroke| { binding.keystrokes().first().map(|stroke| {
@@ -102,7 +73,7 @@ impl Kbd {
} }
/// Formats `stroke` for `os`: modifier symbols on macOS, `Ctrl+` words elsewhere. /// Formats `stroke` for `os`: modifier symbols on macOS, `Ctrl+` words elsewhere.
pub fn format(stroke: &Keystroke, os: OperatingSystem) -> String { fn format(stroke: &Keystroke, os: OperatingSystem) -> String {
let mac = os == OperatingSystem::Mac; let mac = os == OperatingSystem::Mac;
let separator = if mac { "" } else { "+" }; let separator = if mac { "" } else { "+" };
let mut parts: Vec<&str> = Vec::new(); let mut parts: Vec<&str> = Vec::new();
@@ -253,12 +224,8 @@ impl RenderOnce for Kbd {
let label = SharedString::from(Self::format(&self.stroke, os)); let label = SharedString::from(Self::format(&self.stroke, os));
div() div()
// Lets a test ask whether this shortcut hint was painted this frame.
.debug_selector(move || selector) .debug_selector(move || selector)
.when(self.appearance, |key| { .flex_none()
key.flex_none()
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.muted) .bg(theme.colors.muted)
.text_color(theme.colors.muted_foreground) .text_color(theme.colors.muted_foreground)
.py_0p5() .py_0p5()
@@ -268,45 +235,7 @@ impl RenderOnce for Kbd {
.text_center() .text_center()
.line_height(relative(1.)) .line_height(relative(1.))
.text_xs() .text_xs()
})
.refine_style(&self.style) .refine_style(&self.style)
.child(label) .child(label)
} }
} }
/// A row of key caps, grouping the keys of a multi-key hint.
#[derive(IntoElement, Default)]
#[must_use]
pub struct KbdGroup {
style: StyleRefinement,
children: Vec<AnyElement>,
}
impl KbdGroup {
/// Creates an empty group.
pub fn new() -> Self {
Self::default()
}
}
impl gpui::ParentElement for KbdGroup {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl gpui::Styled for KbdGroup {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for KbdGroup {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
h_flex()
.flex_none()
.gap_1()
.refine_style(&self.style)
.children(self.children)
}
}
-154
View File
@@ -1,154 +0,0 @@
//! Renders a link that opens a URL or fires a click handler.
//!
//! # Examples
//!
//! ```no_run
//! use ui::link::Link;
//!
//! let docs = Link::new("docs-link")
//! .label("Documentation")
//! .href("https://example.com/docs");
//!
//! let settings = Link::new("settings-link")
//! .label("Open settings")
//! .on_click(|_event, _window, _cx| println!("open settings"));
//! ```
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ClickEvent, ElementId, InteractiveElement as _, IntoElement, ParentElement as _,
RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Window,
};
use crate::components::common::{ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex};
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
/// The handler called with the [`gpui::ClickEvent`], replacing the default `href` opening.
type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
/// A hyperlink that opens a URL or fires a click handler.
#[derive(IntoElement)]
#[must_use]
pub struct Link {
id: ElementId,
label: Option<SharedString>,
href: Option<SharedString>,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
on_click: Option<ClickHandler>,
style: StyleRefinement,
}
impl Link {
/// Creates a link without a label or target.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
href: None,
size: Size::default(),
disabled: false,
a11y_label: None,
on_click: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Sets the URL the link opens through the platform.
pub fn href<U>(mut self, href: U) -> Self
where
U: Into<SharedString>,
{
self.href = Some(href.into());
self
}
/// Renders the link inert, unfocusable, and dimmed; disabled always wins.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Replaces the default `href` opening with this handler.
pub fn on_click<F>(mut self, handler: F) -> Self
where
F: Fn(&ClickEvent, &mut Window, &mut App) + 'static,
{
self.on_click = Some(Box::new(handler));
self
}
}
impl gpui::Styled for Link {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Link {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Link {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let size = self.size;
let on_click = self.on_click;
let href = self.href;
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
h_flex()
.id(self.id)
.control_text(size)
.text_color(ramps.primary.base)
.underline()
.refine_style(&self.style)
.role(Role::Link)
.when_some(a11y_label, |link, label| link.aria_label(label))
.when(self.disabled, |link| link.opacity(DISABLED_OPACITY))
.when(!self.disabled, |link| {
link.cursor_pointer()
.focusable()
.tab_stop(true)
.hover(move |style| style.text_color(ramps.primary.hover))
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.on_click(move |event, window, cx| match on_click.as_ref() {
Some(on_click) => on_click(event, window, cx),
None => {
if let Some(href) = href.as_ref() {
cx.open_url(href);
}
}
})
})
.when_some(self.label, |link, label| link.child(label))
}
}
-290
View File
@@ -1,290 +0,0 @@
//! Renders a single-selection list of [`ListItem`] rows with keyboard navigation.
//!
//! # Examples
//!
//! ```no_run
//! use ui::list::{List, ListItem};
//!
//! let folders = List::new("folders")
//! .selected(Some(0))
//! .items(|_, _| {
//! vec![
//! ListItem::new("documents", "Documents").detail("24 files"),
//! ListItem::new("downloads", "Downloads"),
//! ]
//! })
//! .on_change(|_selected, _window, _cx| println!("selection changed"));
//! ```
use std::rc::Rc;
use gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent,
ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, div, rems,
};
use crate::common::focus_handle;
use crate::components::common::{
StyledExt as _, nav_key, paint_selectable_row, selectable_label_color, v_flex,
};
use crate::icons::Icon;
use crate::theme::ActiveTheme as _;
/// The change reporter, fired with the next selection by pointer and keys.
type ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
/// The row builder, run during render.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<ListItem>>;
/// One row of a [`List`].
#[must_use]
pub struct ListItem {
key: ElementId,
label: SharedString,
icon: Option<Icon>,
detail: Option<SharedString>,
disabled: bool,
}
impl ListItem {
/// Creates a row shown as `label`, identified by `key`.
pub fn new<K, L>(key: K, label: L) -> Self
where
K: Into<ElementId>,
L: Into<SharedString>,
{
Self {
key: key.into(),
label: label.into(),
icon: None,
detail: None,
disabled: false,
}
}
/// Shows an icon leading the label, a role or any custom [`crate::icons::IconNamed`].
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Shows muted trailing text.
pub fn detail<D>(mut self, detail: D) -> Self
where
D: Into<SharedString>,
{
self.detail = Some(detail.into());
self
}
/// Renders the row dimmed; clicks and keyboard skip it.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
// ListItem is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for ListItem {}
/// A single-selection list of [`ListItem`] rows.
#[derive(IntoElement)]
#[must_use]
pub struct List {
id: ElementId,
selected: Option<usize>,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
items: Option<ItemsFn>,
style: StyleRefinement,
}
impl List {
/// Creates a list with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
selected: None,
a11y_label: None,
on_change: None,
items: None,
style: StyleRefinement::default(),
}
}
/// Sets the current selection.
pub fn selected(mut self, selected: Option<usize>) -> Self {
self.selected = selected;
self
}
/// Reports the next selection, from clicks and keys alike.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<usize>, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Sets the rows; the closure runs during render and must not mutate entities or notify.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<ListItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Overrides the accessibility label, which defaults to the id.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl gpui::Styled for List {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for List {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let items = match self.items {
Some(build) => build(window, cx),
None => Vec::new(),
};
let selectable: Vec<usize> = items
.iter()
.enumerate()
.filter(|(_, item)| !item.disabled)
.map(|(index, _)| index)
.collect();
let focus = focus_handle(&self.id, window, cx);
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let rows: Vec<AnyElement> = items
.iter()
.enumerate()
.map(|(index, item)| {
item.render_row(
cx,
index,
items.len(),
self.selected == Some(index),
&self.on_change,
&focus,
)
})
.collect();
v_flex()
.id(self.id)
.gap_0p5()
.text_sm()
.refine_style(&self.style)
.track_focus(&focus)
.focusable()
.tab_stop(true)
.role(Role::List)
.aria_label(label)
.on_key_down({
let selected = self.selected;
let on_change = self.on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if nav_key(&selectable, selected, &event.keystroke.key, |next| {
if let Some(on_change) = &on_change {
on_change(next, window, cx);
}
}) {
cx.stop_propagation();
}
}
})
.children(rows)
}
}
impl ListItem {
fn render_row(
&self,
cx: &App,
index: usize,
count: usize,
selected: bool,
on_change: &Option<ChangeHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
let label_color = selectable_label_color(cx, selected, self.disabled);
let disabled = self.disabled;
div()
.id((self.key.clone(), "list-item"))
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.min_h_8()
.rounded(theme.radius.sm)
.role(Role::ListItem)
.aria_selected(selected)
.aria_position_in_set(index + 1)
.aria_size_of_set(count)
.map(|row| paint_selectable_row(cx, row, selected, disabled))
.when(!disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
}
})
})
.when_some(self.icon.clone(), |row, icon| {
row.child(icon.size(rems(1.0)).color(label_color))
})
.child(
div()
.flex_1()
.text_color(label_color)
.child(self.label.clone()),
)
.when_some(self.detail.clone(), |row, detail| {
row.child(
div()
.flex_none()
.text_sm()
.text_color(if selected {
theme.colors.primary_foreground
} else {
theme.colors.muted_foreground
})
.child(detail),
)
})
.into_any_element()
}
}
+99 -191
View File
@@ -19,8 +19,6 @@
//! fn notes(cx: &mut App) -> TextView { //! fn notes(cx: &mut App) -> TextView {
//! let state = cx.new(|_| MarkdownViewState::new("notes", "# Notes\n- [x] shipped")); //! let state = cx.new(|_| MarkdownViewState::new("notes", "# Notes\n- [x] shipped"));
//! TextView::new(&state) //! TextView::new(&state)
//! .on_link_click(|destination, _window, _cx| println!("{destination}"))
//! .on_task_toggle(|index, checked, _window, _cx| println!("{index}: {checked}"))
//! } //! }
//! ``` //! ```
@@ -29,7 +27,6 @@ use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher}; use std::hash::{DefaultHasher, Hash, Hasher};
use std::ops::Range; use std::ops::Range;
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
@@ -56,11 +53,6 @@ const BODY_LINE_HEIGHT: f32 = 1.6;
/// The key context the text view declares while it holds focus. /// The key context the text view declares while it holds focus.
pub const TEXT_VIEW_CONTEXT: &str = "TextView"; pub const TEXT_VIEW_CONTEXT: &str = "TextView";
/// The callback a view invokes when the user clicks a markdown link.
pub type LinkClickHandler = Arc<dyn Fn(&SharedString, &mut Window, &mut App)>;
/// The callback a view invokes when the user toggles a task checkbox.
pub type TaskToggleHandler = Arc<dyn Fn(usize, bool, &mut Window, &mut App)>;
actions!(text_view, [Copy]); actions!(text_view, [Copy]);
/// A heading level, 1 to 6. /// A heading level, 1 to 6.
@@ -191,6 +183,94 @@ impl MarkdownBlock {
self.hash(&mut hasher); self.hash(&mut hasher);
hasher.finish() hasher.finish()
} }
/// The block's selectable text units, in render order.
fn block_text_units(&self) -> Vec<String> {
match self {
MarkdownBlock::Heading { spans, .. } => vec![spans_text_of(spans)],
MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => {
let mut units: Vec<String> = Vec::new();
for item in items {
match item {
InlineItem::Text(span) => match units.last_mut() {
// Consecutive text items share the unit between images.
Some(unit) => unit.push_str(&span.text),
None => units.push(span.text.as_ref().to_string()),
},
// An image starts the next unit; the render emits no
// element for it.
InlineItem::Image { .. } => units.push(String::new()),
}
}
units
}
MarkdownBlock::Code { lines, .. } => {
lines.lines.iter().map(|line| line.text()).collect()
}
MarkdownBlock::Table { table, .. } => table
.rows
.iter()
.flat_map(|row| row.cells.iter())
.map(|cell| spans_text_of(&cell.spans))
.collect(),
MarkdownBlock::Image { .. } | MarkdownBlock::ThematicBreak { .. } => Vec::new(),
}
}
/// Renders one parsed block as a list row.
fn render_block(&self, block_index: usize, ctx: &BlockContext, cx: &App) -> AnyElement {
let gap = rems(0.75);
match self {
MarkdownBlock::Heading {
level,
spans,
indent,
quote,
} => heading_row(
*level,
spans,
*indent,
*quote,
if block_index == 0 {
Rems::ZERO
} else {
rems(0.375)
},
ctx,
cx,
),
MarkdownBlock::Paragraph {
items,
indent,
quote,
} => text_row(items, *indent, *quote, gap, None, ctx, cx),
MarkdownBlock::ListItem {
marker,
items,
indent,
quote,
} => text_row(items, *indent, *quote, rems(0.2), Some(*marker), ctx, cx),
MarkdownBlock::Image {
source,
alt,
indent,
quote,
} => image_row(source, alt, *indent, *quote, ctx, cx),
MarkdownBlock::Code {
language,
lines,
indent,
quote,
} => code_row(lines, language.as_ref(), *indent, *quote, ctx, cx),
MarkdownBlock::ThematicBreak { indent, quote } => rule_row(*indent, *quote, ctx, cx),
MarkdownBlock::Table {
table,
indent,
quote,
} => table_row(table, *indent, *quote, ctx, cx),
}
}
} }
/// One run of inline text sharing a style. /// One run of inline text sharing a style.
@@ -235,8 +315,6 @@ pub struct MarkdownViewState {
/// Drives the vertical scroll of the virtualized block list. /// Drives the vertical scroll of the virtualized block list.
handle: ListState, handle: ListState,
a11y_label: Option<SharedString>, a11y_label: Option<SharedString>,
link_handler: Option<LinkClickHandler>,
task_toggle_handler: Option<TaskToggleHandler>,
/// `(anchor, head)` in the order they were set, over the rendered text. /// `(anchor, head)` in the order they were set, over the rendered text.
selection: Option<(usize, usize)>, selection: Option<(usize, usize)>,
/// Whether a drag is still extending the selection. /// Whether a drag is still extending the selection.
@@ -265,8 +343,6 @@ impl MarkdownViewState {
highlight_code: true, highlight_code: true,
handle: ListState::new(count, ListAlignment::Top, CODE_OVERSCROLL_MAX), handle: ListState::new(count, ListAlignment::Top, CODE_OVERSCROLL_MAX),
a11y_label: None, a11y_label: None,
link_handler: None,
task_toggle_handler: None,
selection: None, selection: None,
selecting: false, selecting: false,
focus_handle: None, focus_handle: None,
@@ -360,34 +436,6 @@ impl MarkdownViewState {
self self
} }
/// Invokes `handler` when the user clicks a link, instead of opening it.
pub fn on_link_click<F>(mut self, handler: F) -> Self
where
F: Fn(&SharedString, &mut Window, &mut App) + 'static,
{
self.link_handler = Some(Arc::new(handler));
self
}
/// Replaces the link click handler.
pub fn set_link_handler(&mut self, handler: LinkClickHandler) {
self.link_handler = Some(handler);
}
/// Invokes `handler(block, checked)` when the user toggles a task checkbox.
pub fn on_task_toggle<F>(mut self, handler: F) -> Self
where
F: Fn(usize, bool, &mut Window, &mut App) + 'static,
{
self.task_toggle_handler = Some(Arc::new(handler));
self
}
/// Replaces the task toggle handler.
pub fn set_task_toggle_handler(&mut self, handler: TaskToggleHandler) {
self.task_toggle_handler = Some(handler);
}
/// Selects a range over the rendered text, endpoints in byte offsets. /// Selects a range over the rendered text, endpoints in byte offsets.
pub fn select_range(&mut self, start: usize, end: usize, cx: &mut Context<Self>) { pub fn select_range(&mut self, start: usize, end: usize, cx: &mut Context<Self>) {
self.selection = Some((start, end)); self.selection = Some((start, end));
@@ -430,8 +478,6 @@ impl Render for MarkdownViewState {
let focus_handle = self.focus_handle(cx); let focus_handle = self.focus_handle(cx);
let frame = std::rc::Rc::new(ViewFrame { let frame = std::rc::Rc::new(ViewFrame {
state: state.clone(), state: state.clone(),
link_handler: self.link_handler.clone(),
task_toggle: self.task_toggle_handler.clone(),
selection: self.selection(), selection: self.selection(),
focus_handle, focus_handle,
pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)), pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)),
@@ -455,7 +501,7 @@ impl Render for MarkdownViewState {
block_index, block_index,
block_id, block_id,
}; };
render_block(block, block_index, &ctx, cx) block.render_block(block_index, &ctx, cx)
} }
None => div().into_any_element(), None => div().into_any_element(),
} }
@@ -481,8 +527,6 @@ impl Render for MarkdownViewState {
/// The per-frame context the view's renderers wire themselves from. /// The per-frame context the view's renderers wire themselves from.
struct ViewFrame { struct ViewFrame {
state: Entity<MarkdownViewState>, state: Entity<MarkdownViewState>,
link_handler: Option<LinkClickHandler>,
task_toggle: Option<TaskToggleHandler>,
/// The selection over the rendered text, endpoints in document order. /// The selection over the rendered text, endpoints in document order.
selection: Option<(usize, usize)>, selection: Option<(usize, usize)>,
focus_handle: gpui::FocusHandle, focus_handle: gpui::FocusHandle,
@@ -525,7 +569,6 @@ impl BlockContext<'_> {
Some(PieceContext { Some(PieceContext {
state: self.frame.state.clone(), state: self.frame.state.clone(),
link_handler: self.frame.link_handler.clone(),
doc_range: piece.range.clone(), doc_range: piece.range.clone(),
selected, selected,
pressed_on_piece: self.frame.pressed_on_piece.clone(), pressed_on_piece: self.frame.pressed_on_piece.clone(),
@@ -536,7 +579,6 @@ impl BlockContext<'_> {
/// What one selectable text element wires itself from. /// What one selectable text element wires itself from.
struct PieceContext { struct PieceContext {
state: Entity<MarkdownViewState>, state: Entity<MarkdownViewState>,
link_handler: Option<LinkClickHandler>,
/// The piece's byte range in the rendered text. /// The piece's byte range in the rendered text.
doc_range: Range<usize>, doc_range: Range<usize>,
/// The selection overlap, in piece-local bytes. /// The selection overlap, in piece-local bytes.
@@ -579,7 +621,7 @@ impl TextDocument {
.iter() .iter()
.position(|piece| piece.block_index != block_index) .position(|piece| piece.block_index != block_index)
.map_or(self.pieces.len(), |offset| piece_ix + offset); .map_or(self.pieces.len(), |offset| piece_ix + offset);
let units = block_text_units(block); let units = block.block_text_units();
for piece in &self.pieces[piece_ix..block_end] { for piece in &self.pieces[piece_ix..block_end] {
let Some(unit) = units.get(piece.sub_index).filter(|unit| !unit.is_empty()) else { let Some(unit) = units.get(piece.sub_index).filter(|unit| !unit.is_empty()) else {
@@ -602,8 +644,6 @@ pub struct TextView {
id: ElementId, id: ElementId,
source: Option<SharedString>, source: Option<SharedString>,
state: Option<Entity<MarkdownViewState>>, state: Option<Entity<MarkdownViewState>>,
link_handler: Option<LinkClickHandler>,
task_toggle_handler: Option<TaskToggleHandler>,
style: StyleRefinement, style: StyleRefinement,
} }
@@ -618,8 +658,6 @@ impl TextView {
id: id.into(), id: id.into(),
source: Some(source.into()), source: Some(source.into()),
state: None, state: None,
link_handler: None,
task_toggle_handler: None,
style: StyleRefinement::default(), style: StyleRefinement::default(),
} }
} }
@@ -630,29 +668,9 @@ impl TextView {
id: ElementId::from(SharedString::from(format!("{}", state.entity_id()))), id: ElementId::from(SharedString::from(format!("{}", state.entity_id()))),
source: None, source: None,
state: Some(state.clone()), state: Some(state.clone()),
link_handler: None,
task_toggle_handler: None,
style: StyleRefinement::default(), style: StyleRefinement::default(),
} }
} }
/// Invokes `handler` when the user clicks a link, instead of opening it.
pub fn on_link_click<F>(mut self, handler: F) -> Self
where
F: Fn(&SharedString, &mut Window, &mut App) + 'static,
{
self.link_handler = Some(Arc::new(handler));
self
}
/// Invokes `handler(block, checked)` when the user toggles a task checkbox.
pub fn on_task_toggle<F>(mut self, handler: F) -> Self
where
F: Fn(usize, bool, &mut Window, &mut App) + 'static,
{
self.task_toggle_handler = Some(Arc::new(handler));
self
}
} }
impl Styled for TextView { impl Styled for TextView {
@@ -693,8 +711,6 @@ impl Element for TextView {
}; };
let source = self.source.clone(); let source = self.source.clone();
let link_handler = self.link_handler.clone();
let task_toggle = self.task_toggle_handler.clone();
let (selection, focus_handle) = let (selection, focus_handle) =
state.update(cx, |view, cx| (view.selection(), view.focus_handle(cx))); state.update(cx, |view, cx| (view.selection(), view.focus_handle(cx)));
@@ -703,19 +719,11 @@ impl Element for TextView {
if let Some(source) = source { if let Some(source) = source {
view.set_source(source, cx); view.set_source(source, cx);
} }
if let Some(link_handler) = link_handler {
view.set_link_handler(link_handler);
}
if let Some(task_toggle) = task_toggle {
view.set_task_toggle_handler(task_toggle);
}
}); });
let view = state.read(cx); let view = state.read(cx);
let frame = ViewFrame { let frame = ViewFrame {
state: state.clone(), state: state.clone(),
link_handler: view.link_handler.clone(),
task_toggle: view.task_toggle_handler.clone(),
selection, selection,
focus_handle, focus_handle,
pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)), pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)),
@@ -908,7 +916,7 @@ fn render_blocks(
block_index, block_index,
block_id, block_id,
}; };
render_block(block, block_index, &ctx, cx) block.render_block(block_index, &ctx, cx)
}, },
)) ))
} }
@@ -917,37 +925,6 @@ fn spans_text_of(spans: &[InlineSpan]) -> String {
spans.iter().map(|span| span.text.as_ref()).collect() spans.iter().map(|span| span.text.as_ref()).collect()
} }
/// The selectable text units of a block.
fn block_text_units(block: &MarkdownBlock) -> Vec<String> {
match block {
MarkdownBlock::Heading { spans, .. } => vec![spans_text_of(spans)],
MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => {
let mut units: Vec<String> = Vec::new();
for item in items {
match item {
InlineItem::Text(span) => match units.last_mut() {
// Consecutive text items share the unit between images.
Some(unit) => unit.push_str(&span.text),
None => units.push(span.text.as_ref().to_string()),
},
// An image starts the next unit; the render emits no
// element for it.
InlineItem::Image { .. } => units.push(String::new()),
}
}
units
}
MarkdownBlock::Code { lines, .. } => lines.lines.iter().map(|line| line.text()).collect(),
MarkdownBlock::Table { table, .. } => table
.rows
.iter()
.flat_map(|row| row.cells.iter())
.map(|cell| spans_text_of(&cell.spans))
.collect(),
MarkdownBlock::Image { .. } | MarkdownBlock::ThematicBreak { .. } => Vec::new(),
}
}
/// Enumerates the selectable text pieces of `blocks`, in render order. /// Enumerates the selectable text pieces of `blocks`, in render order.
fn text_document(blocks: &[MarkdownBlock]) -> TextDocument { fn text_document(blocks: &[MarkdownBlock]) -> TextDocument {
let mut pieces = Vec::new(); let mut pieces = Vec::new();
@@ -960,7 +937,7 @@ fn text_document(blocks: &[MarkdownBlock]) -> TextDocument {
MarkdownBlock::Paragraph { .. } | MarkdownBlock::ListItem { .. } MarkdownBlock::Paragraph { .. } | MarkdownBlock::ListItem { .. }
); );
for (sub_index, unit) in block_text_units(block).into_iter().enumerate() { for (sub_index, unit) in block.block_text_units().into_iter().enumerate() {
if unit.is_empty() && skip_empty { if unit.is_empty() && skip_empty {
continue; continue;
} }
@@ -1405,66 +1382,6 @@ fn flush_item_inline(
}); });
} }
/// Renders one parsed block as a list row.
fn render_block(
block: &MarkdownBlock,
block_index: usize,
ctx: &BlockContext,
cx: &App,
) -> AnyElement {
let gap = rems(0.75);
match block {
MarkdownBlock::Heading {
level,
spans,
indent,
quote,
} => heading_row(
*level,
spans,
*indent,
*quote,
if block_index == 0 {
Rems::ZERO
} else {
rems(0.375)
},
ctx,
cx,
),
MarkdownBlock::Paragraph {
items,
indent,
quote,
} => text_row(items, *indent, *quote, gap, None, ctx, cx),
MarkdownBlock::ListItem {
marker,
items,
indent,
quote,
} => text_row(items, *indent, *quote, rems(0.2), Some(*marker), ctx, cx),
MarkdownBlock::Image {
source,
alt,
indent,
quote,
} => image_row(source, alt, *indent, *quote, ctx, cx),
MarkdownBlock::Code {
language,
lines,
indent,
quote,
} => code_row(lines, language.as_ref(), *indent, *quote, ctx, cx),
MarkdownBlock::ThematicBreak { indent, quote } => rule_row(*indent, *quote, ctx, cx),
MarkdownBlock::Table {
table,
indent,
quote,
} => table_row(table, *indent, *quote, ctx, cx),
}
}
/// The shared block frame: ambient text style, spacing, quote bar. /// The shared block frame: ambient text style, spacing, quote bar.
fn block_frame(quote: bool, top: Rems, bottom: Rems, id: &ElementId, cx: &App) -> Div { fn block_frame(quote: bool, top: Rems, bottom: Rems, id: &ElementId, cx: &App) -> Div {
let theme = cx.theme(); let theme = cx.theme();
@@ -1579,22 +1496,17 @@ fn text_row(
.into_any_element() .into_any_element()
} }
/// The task marker: a checkbox that reports toggles when a handler is set. /// The task marker: a checkbox that renders the state without toggling.
fn task_toggle(checked: bool, label: SharedString, ctx: &BlockContext) -> AnyElement { fn task_toggle(checked: bool, label: SharedString, ctx: &BlockContext) -> AnyElement {
let block_index = ctx.block_index; let block_index = ctx.block_index;
let selector = SharedString::from(format!("task-toggle-{block_index}")); let selector = SharedString::from(format!("task-toggle-{block_index}"));
let checkbox = Checkbox::new((ctx.block_id.clone(), "task")) Checkbox::new((ctx.block_id.clone(), "task"))
.debug_selector(move || selector.to_string()) .debug_selector(move || selector.to_string())
.checked(checked) .checked(checked)
.with_size(Size::Small) .with_size(Size::Small)
.accessibility_label(label); .accessibility_label(label)
.disabled(true)
match ctx.frame.task_toggle.clone() { .into_any_element()
Some(handler) => checkbox
.on_change(move |next, window, cx| handler(block_index, next, window, cx))
.into_any_element(),
None => checkbox.disabled(true).into_any_element(),
}
} }
/// The item's plain text, for the checkbox's accessibility label. /// The item's plain text, for the checkbox's accessibility label.
@@ -2016,16 +1928,12 @@ where
let inner = if destinations.is_empty() { let inner = if destinations.is_empty() {
styled.into_any_element() styled.into_any_element()
} else { } else {
let link_handler = piece.as_ref().and_then(|piece| piece.link_handler.clone());
InteractiveText::new(id.clone(), styled) InteractiveText::new(id.clone(), styled)
.on_click(link_ranges, move |range_ix, window, cx| { .on_click(link_ranges, move |range_ix, _window, cx| {
let Some(destination) = destinations.get(range_ix) else { let Some(destination) = destinations.get(range_ix) else {
return; return;
}; };
match link_handler.as_ref() { cx.open_url(destination.as_ref());
Some(handler) => handler(destination, window, cx),
None => cx.open_url(destination.as_ref()),
}
}) })
.into_any_element() .into_any_element()
}; };
+344 -334
View File
@@ -54,6 +54,14 @@ type TriggerFn = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>;
/// The menu's rows, rebuilt on each render while open. /// The menu's rows, rebuilt on each render while open.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<MenuItem>>; type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<MenuItem>>;
/// One row of a [`Menu`]: an action, a checkable action, a submenu, or a separator.
#[derive(Clone)]
enum MenuItemKind {
Action,
Separator,
Submenu(Rc<[MenuItem]>),
}
/// One row of a [`Menu`]: an action, a checkable action, a submenu, or a separator. /// One row of a [`Menu`]: an action, a checkable action, a submenu, or a separator.
#[derive(Clone)] #[derive(Clone)]
#[must_use] #[must_use]
@@ -62,20 +70,12 @@ pub struct MenuItem {
kind: MenuItemKind, kind: MenuItemKind,
label: SharedString, label: SharedString,
icon: Option<Icon>, icon: Option<Icon>,
shortcut: Option<SharedString>,
handler: Option<ItemHandler>, handler: Option<ItemHandler>,
disabled: bool, disabled: bool,
destructive: bool, destructive: bool,
checked: bool, checked: bool,
} }
#[derive(Clone)]
enum MenuItemKind {
Action,
Separator,
Submenu(Rc<[MenuItem]>),
}
impl MenuItem { impl MenuItem {
/// Creates an action row with this label. /// Creates an action row with this label.
pub fn new<L>(label: L) -> Self pub fn new<L>(label: L) -> Self
@@ -87,7 +87,6 @@ impl MenuItem {
kind: MenuItemKind::Action, kind: MenuItemKind::Action,
label: label.into(), label: label.into(),
icon: None, icon: None,
shortcut: None,
handler: None, handler: None,
disabled: false, disabled: false,
destructive: false, destructive: false,
@@ -102,7 +101,6 @@ impl MenuItem {
kind: MenuItemKind::Separator, kind: MenuItemKind::Separator,
label: SharedString::default(), label: SharedString::default(),
icon: None, icon: None,
shortcut: None,
handler: None, handler: None,
disabled: false, disabled: false,
destructive: false, destructive: false,
@@ -137,15 +135,6 @@ impl MenuItem {
self self
} }
/// Shows a shortcut hint after the label.
pub fn shortcut<S>(mut self, shortcut: S) -> Self
where
S: Into<SharedString>,
{
self.shortcut = Some(shortcut.into());
self
}
/// Marks the item non-selectable and non-activatable. /// Marks the item non-selectable and non-activatable.
pub fn disabled(mut self, disabled: bool) -> Self { pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled; self.disabled = disabled;
@@ -185,6 +174,226 @@ impl MenuItem {
fn selectable(&self) -> bool { fn selectable(&self) -> bool {
matches!(self.kind, MenuItemKind::Action | MenuItemKind::Submenu(_)) && !self.disabled matches!(self.kind, MenuItemKind::Action | MenuItemKind::Submenu(_)) && !self.disabled
} }
/// Renders one menu row.
fn render_item(
&self,
window: &mut Window,
cx: &mut App,
index: usize,
selected: bool,
env: &RowEnv,
) -> AnyElement {
match &self.kind {
MenuItemKind::Separator => div()
.h_px()
.debug_selector(move || format!("{}-separator-{index}", env.debug_prefix))
.mx_2()
.my_1()
.bg(env.chrome.border)
.into_any_element(),
MenuItemKind::Action => {
let label_color = self.row_color(selected, false, env.chrome);
let disabled = self.disabled;
let checked = self.checked;
let icon = self.icon.clone();
self.row_shell(cx, index, selected, env)
.on_click({
let handler = self.handler.clone();
let on_activate = env.on_activate.clone();
move |_, window, cx| {
if disabled {
return;
}
if let Some(on_activate) = &on_activate {
on_activate(false, window, cx);
}
if let Some(handler) = &handler {
handler(window, cx);
}
}
})
.when_some(icon, |row, icon| {
row.child(icon.size(rems(1.0)).color(label_color))
})
.child(
div()
.flex_1()
.text_color(label_color)
.child(self.label.clone()),
)
.when(checked, |row| {
row.child(
icon_glyph(IconRole::Check)
.size(rems(0.75))
.color(label_color),
)
})
.into_any_element()
}
MenuItemKind::Submenu(items) => {
let chrome = env.chrome;
let flyout = env.flyout;
let disabled = self.disabled;
let open = *flyout.open.read(cx) == Some(index);
let label_color = self.row_color(selected, open, chrome);
let row_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None));
self.row_shell(cx, index, selected, env)
.on_click({
let set_flyout = flyout.set_flyout.clone();
move |_, _window, cx| {
if disabled {
return;
}
// Hover already opens the flyout; a click never closes it.
set_flyout(Some(index), false, cx);
}
})
.child(
div()
.flex_1()
.text_color(label_color)
.child(self.label.clone()),
)
.child(
icon_glyph(IconRole::ChevronRight)
.size(rems(0.75))
.color(label_color),
)
.aria_expanded(open)
.when(open, |row| {
row.child(
canvas(
{
let cell = row_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
.child(
deferred(div().absolute().left_full().top_0().child(menu_panel(
window,
cx,
flyout.state,
MenuPanelParams {
id: &flyout.id,
items: items.clone(),
initial_selection: None,
preselect: *flyout.preselect.read(cx),
min_width: flyout.min_width,
label: self.label.clone(),
dismiss_bounds: &row_bounds,
bounds_sink: Some(flyout.bounds),
outer_stack: Some(flyout.stack),
on_dismiss: Some(flyout.dismiss.clone()),
on_activate: flyout.on_activate.clone(),
is_flyout: true,
chrome,
enter_duration: flyout.enter_duration,
debug_prefix: "submenu",
},
)))
.with_priority(OVERLAY_LAYER),
)
})
.into_any_element()
}
}
}
/// The shared row shell: dimensions, highlight, and hover-selection.
fn row_shell(
&self,
cx: &App,
index: usize,
selected: bool,
env: &RowEnv,
) -> gpui::Stateful<gpui::Div> {
let chrome = env.chrome;
let selectable = self.selectable();
let opens_submenu = self.submenu_items().is_some();
let flyout_open = *env.flyout.open.read(cx) == Some(index);
let row_id = self
.id
.clone()
.unwrap_or_else(|| ("menu-item", index).into());
div()
.id(row_id)
.role(Role::MenuItem)
.debug_selector(move || format!("{}-item-{index}", env.debug_prefix))
.flex()
.items_center()
.gap_2()
.min_h_8()
.px_4()
.text_sm()
.line_height(relative(1.0))
.rounded(chrome.radius_full)
.map(|row| {
if self.disabled {
row
} else if selected && flyout_open {
row.bg(chrome.muted_hover)
} else if selected {
let highlight = if self.destructive {
chrome.destructive
} else {
chrome.primary
};
row.bg(highlight)
} else {
row.hover(|row| row.bg(chrome.muted_hover))
}
})
.on_mouse_move({
let selection = env.selection.clone();
let flyout_open = env.flyout.open.clone();
let set_flyout = env.flyout.set_flyout.clone();
let dismiss = env.flyout.dismiss.clone();
move |_, window, cx| {
if !selectable {
return;
}
if *selection.read(cx) != Some(index) {
selection.update(cx, |selection, _| *selection = Some(index));
}
if opens_submenu {
set_flyout(Some(index), false, cx);
} else if flyout_open.read(cx).is_some() {
dismiss(false, window, cx);
}
}
})
}
/// The row's label/icon color.
fn row_color(&self, selected: bool, flyout_open: bool, chrome: &MenuChrome) -> gpui::Hsla {
if self.disabled {
return chrome.muted_foreground;
}
if self.destructive {
return if selected && !flyout_open {
chrome.destructive_foreground
} else {
chrome.destructive
};
}
if selected && !flyout_open {
chrome.primary_foreground
} else {
chrome.foreground
}
}
} }
// MenuItem is a data builder, not an element, adopt the combinators explicitly. // MenuItem is a data builder, not an element, adopt the combinators explicitly.
@@ -378,49 +587,12 @@ impl RenderOnce for Menu {
div() div()
.relative() .relative()
.refine_style(&self.style) .refine_style(&self.style)
.child( .child(trigger_toggle(
canvas( &trigger_bounds,
{ self.open,
let cell = trigger_bounds.clone(); on_change.clone(),
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) self.trigger_button,
}, ))
{
let on_change = on_change;
let open = self.open;
let trigger_button = self.trigger_button;
let cell = trigger_bounds.clone();
move |_, _, window, _cx| {
let trigger_bounds = cell;
window.on_mouse_event({
let on_change = on_change.clone();
move |event: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble
|| event.button != trigger_button
{
return;
}
let on_trigger = trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !on_trigger {
return;
}
if let Some(on_change) = &on_change {
on_change(!open, window, cx);
}
cx.stop_propagation();
}
});
}
},
)
.absolute()
.inset_0(),
)
.when_some(self.trigger, |wrapper, trigger| { .when_some(self.trigger, |wrapper, trigger| {
wrapper.child(trigger(window, cx)) wrapper.child(trigger(window, cx))
}) })
@@ -455,15 +627,6 @@ struct MenuPanelState {
selection: Entity<Option<usize>>, selection: Entity<Option<usize>>,
} }
fn create_menu_panel_state(id: &ElementId, window: &mut Window, cx: &mut App) -> MenuPanelState {
MenuPanelState {
focus: focus_handle(&(id.clone(), "panel").into(), window, cx),
was_open: window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false),
scroll: window.use_keyed_state((id.clone(), "menu-scroll"), cx, |_, _| ScrollHandle::new()),
selection: window.use_keyed_state((id.clone(), "menu-selection"), cx, |_, _| None),
}
}
struct MenuPanelParams<'a> { struct MenuPanelParams<'a> {
id: &'a ElementId, id: &'a ElementId,
items: Rc<[MenuItem]>, items: Rc<[MenuItem]>,
@@ -513,6 +676,104 @@ struct RowEnv<'a> {
debug_prefix: &'static str, debug_prefix: &'static str,
} }
/// Everything key navigation needs from the panel.
struct MenuKeyEnv<'a> {
items: &'a [MenuItem],
selection: &'a Entity<Option<usize>>,
set_flyout: &'a FlyoutSetter,
on_dismiss: &'a Option<ChangeHandler>,
on_activate: &'a Option<ChangeHandler>,
left_dismisses: bool,
}
/// Canvas that records the trigger's painted bounds and toggles `open` on click.
pub(crate) fn trigger_toggle(
bounds: &TriggerBoundsCell,
open: bool,
on_change: Option<ChangeHandler>,
button: MouseButton,
) -> AnyElement {
let painted = bounds.clone();
canvas(
{
let cell = bounds.clone();
move |painted, _window, _cx| *cell.borrow_mut() = Some(painted)
},
move |_, _, window, _cx| {
let cell = painted.clone();
window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble || event.button != button {
return;
}
let on_trigger = cell
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !on_trigger {
return;
}
if let Some(on_change) = &on_change {
on_change(!open, window, cx);
}
cx.stop_propagation();
});
},
)
.absolute()
.inset_0()
.into_any_element()
}
/// Deferred anchored overlay on OVERLAY_LAYER, optionally fading in.
pub(crate) fn anchored_overlay(
position: Option<Point<Pixels>>,
panel: AnyElement,
fade: Option<(&'static str, std::time::Duration)>,
) -> AnyElement {
let anchored = match position {
Some(position) => anchored().position(position),
None => anchored(),
}
.offset(point(px(0.), px(4.)));
// AnyElement lacks `Styled`, so the opacity animation rides a wrapper.
let panel = match fade {
Some((id, duration)) => div()
.child(panel)
.with_animation(
id,
Animation::new(duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
)
.into_any_element(),
None => panel,
};
deferred(anchored.child(panel))
.with_priority(OVERLAY_LAYER)
.into_any_element()
}
/// Canvas that grabs focus when `should_grab` holds.
pub(crate) fn focus_capture(
focus: FocusHandle,
should_grab: impl Fn(&mut Window, &mut App) -> bool + 'static,
) -> AnyElement {
canvas(
|_, _, _| {},
move |_, _, window, cx| {
if should_grab(window, cx) {
window.focus(&focus, cx);
}
},
)
.absolute()
.inset_0()
.into_any_element()
}
/// Assembles the floating menu panel anchored to its trigger. /// Assembles the floating menu panel anchored to its trigger.
pub(crate) fn anchored_menu_panel( pub(crate) fn anchored_menu_panel(
window: &mut Window, window: &mut Window,
@@ -524,8 +785,6 @@ pub(crate) fn anchored_menu_panel(
) -> Option<AnyElement> { ) -> Option<AnyElement> {
let was_open = window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false); let was_open = window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false);
// Render-phase residue: trigger-toggle and owner-driven closes bypass every
// dismissal handler, so this closed frame is the only universal close hook.
if !spec.open { if !spec.open {
was_open.update(cx, |was_open, _| *was_open = false); was_open.update(cx, |was_open, _| *was_open = false);
// A closed menu drops any open flyout; fresh state on the next open. // A closed menu drops any open flyout; fresh state on the next open.
@@ -562,17 +821,7 @@ pub(crate) fn anchored_menu_panel(
}, },
); );
let anchored = match spec.position { Some(anchored_overlay(spec.position, panel, None))
Some(position) => anchored().position(position),
None => anchored(),
}
.offset(point(px(0.), px(4.)));
Some(
deferred(anchored.child(panel))
.with_priority(OVERLAY_LAYER)
.into_any_element(),
)
} }
/// Builds one menu panel: chrome, rows, focus, navigation, and dismissals. /// Builds one menu panel: chrome, rows, focus, navigation, and dismissals.
@@ -668,10 +917,9 @@ fn menu_panel(
.iter() .iter()
.enumerate() .enumerate()
.map(|(index, item)| { .map(|(index, item)| {
render_item( item.render_item(
window, window,
cx, cx,
item,
index, index,
selected == Some(index), selected == Some(index),
&RowEnv { &RowEnv {
@@ -791,254 +1039,6 @@ fn menu_panel(
.into_any_element() .into_any_element()
} }
/// Renders one menu row.
fn render_item(
window: &mut Window,
cx: &mut App,
item: &MenuItem,
index: usize,
selected: bool,
env: &RowEnv,
) -> AnyElement {
match &item.kind {
MenuItemKind::Separator => div()
.h_px()
.debug_selector(move || format!("{}-separator-{index}", env.debug_prefix))
.mx_2()
.my_1()
.bg(env.chrome.border)
.into_any_element(),
MenuItemKind::Action => {
let label_color = row_color(item, selected, false, env.chrome);
let disabled = item.disabled;
let destructive = item.destructive;
let checked = item.checked;
let shortcut = item.shortcut.clone();
let icon = item.icon.clone();
row_shell(cx, item, index, selected, env)
.on_click({
let handler = item.handler.clone();
let on_activate = env.on_activate.clone();
move |_, window, cx| {
if disabled {
return;
}
if let Some(on_activate) = &on_activate {
on_activate(false, window, cx);
}
if let Some(handler) = &handler {
handler(window, cx);
}
}
})
.when_some(icon, |row, icon| {
row.child(icon.size(rems(1.0)).color(label_color))
})
.child(
div()
.flex_1()
.text_color(label_color)
.child(item.label.clone()),
)
.when_some(shortcut, |row, shortcut| {
row.child(
div()
.text_color(if selected && !destructive && !disabled {
env.chrome.primary_foreground
} else {
env.chrome.muted_foreground
})
.child(shortcut),
)
})
.when(checked, |row| {
row.child(
icon_glyph(IconRole::Check)
.size(rems(0.75))
.color(label_color),
)
})
.into_any_element()
}
MenuItemKind::Submenu(items) => {
let chrome = env.chrome;
let flyout = env.flyout;
let disabled = item.disabled;
let open = *flyout.open.read(cx) == Some(index);
let label_color = row_color(item, selected, open, chrome);
let row_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None));
row_shell(cx, item, index, selected, env)
.on_click({
let set_flyout = flyout.set_flyout.clone();
move |_, _window, cx| {
if disabled {
return;
}
// Hover already opens the flyout; a click never closes it.
set_flyout(Some(index), false, cx);
}
})
.child(
div()
.flex_1()
.text_color(label_color)
.child(item.label.clone()),
)
.child(
icon_glyph(IconRole::ChevronRight)
.size(rems(0.75))
.color(label_color),
)
.aria_expanded(open)
.when(open, |row| {
row.child(
canvas(
{
let cell = row_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
.child(
deferred(div().absolute().left_full().top_0().child(menu_panel(
window,
cx,
flyout.state,
MenuPanelParams {
id: &flyout.id,
items: items.clone(),
initial_selection: None,
preselect: *flyout.preselect.read(cx),
min_width: flyout.min_width,
label: item.label.clone(),
dismiss_bounds: &row_bounds,
bounds_sink: Some(flyout.bounds),
outer_stack: Some(flyout.stack),
on_dismiss: Some(flyout.dismiss.clone()),
on_activate: flyout.on_activate.clone(),
is_flyout: true,
chrome,
enter_duration: flyout.enter_duration,
debug_prefix: "submenu",
},
)))
.with_priority(OVERLAY_LAYER),
)
})
.into_any_element()
}
}
}
/// The shared row shell: dimensions, highlight, and hover-selection.
fn row_shell(
cx: &App,
item: &MenuItem,
index: usize,
selected: bool,
env: &RowEnv,
) -> gpui::Stateful<gpui::Div> {
let chrome = env.chrome;
let selectable = item.selectable();
let opens_submenu = item.submenu_items().is_some();
let flyout_open = *env.flyout.open.read(cx) == Some(index);
let row_id = item
.id
.clone()
.unwrap_or_else(|| ("menu-item", index).into());
div()
.id(row_id)
.role(Role::MenuItem)
.debug_selector(move || format!("{}-item-{index}", env.debug_prefix))
.flex()
.items_center()
.gap_2()
.min_h_8()
.px_4()
.text_sm()
.line_height(relative(1.0))
.rounded(chrome.radius_full)
.map(|row| {
if item.disabled {
row
} else if selected && flyout_open {
row.bg(chrome.muted_hover)
} else if selected {
let highlight = if item.destructive {
chrome.destructive
} else {
chrome.primary
};
row.bg(highlight)
} else {
row.hover(|row| row.bg(chrome.muted_hover))
}
})
.on_mouse_move({
let selection = env.selection.clone();
let flyout_open = env.flyout.open.clone();
let set_flyout = env.flyout.set_flyout.clone();
let dismiss = env.flyout.dismiss.clone();
move |_, window, cx| {
if !selectable {
return;
}
if *selection.read(cx) != Some(index) {
selection.update(cx, |selection, _| *selection = Some(index));
}
if opens_submenu {
set_flyout(Some(index), false, cx);
} else if flyout_open.read(cx).is_some() {
dismiss(false, window, cx);
}
}
})
}
/// The row's label/icon color.
fn row_color(
item: &MenuItem,
selected: bool,
flyout_open: bool,
chrome: &MenuChrome,
) -> gpui::Hsla {
if item.disabled {
return chrome.muted_foreground;
}
if item.destructive {
return if selected && !flyout_open {
chrome.destructive_foreground
} else {
chrome.destructive
};
}
if selected && !flyout_open {
chrome.primary_foreground
} else {
chrome.foreground
}
}
/// Everything key navigation needs from the panel.
struct MenuKeyEnv<'a> {
items: &'a [MenuItem],
selection: &'a Entity<Option<usize>>,
set_flyout: &'a FlyoutSetter,
on_dismiss: &'a Option<ChangeHandler>,
on_activate: &'a Option<ChangeHandler>,
left_dismisses: bool,
}
/// Handles the panel's navigation keys. /// Handles the panel's navigation keys.
fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, cx: &mut App) { fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, cx: &mut App) {
let selectable: Vec<usize> = env let selectable: Vec<usize> = env
@@ -1111,3 +1111,13 @@ fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, c
cx.stop_propagation(); 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),
}
}
-8
View File
@@ -10,9 +10,7 @@ pub mod code;
pub mod combobox; pub mod combobox;
pub mod command_palette; pub mod command_palette;
pub mod common; pub mod common;
pub mod context_menu;
pub mod dialog; pub mod dialog;
pub mod diff;
pub mod dropdown_menu; pub mod dropdown_menu;
pub mod empty_state; pub mod empty_state;
pub mod field; pub mod field;
@@ -20,21 +18,15 @@ pub mod grain;
pub mod highlight; pub mod highlight;
pub mod input; pub mod input;
pub mod kbd; pub mod kbd;
pub mod link;
pub mod list;
pub mod markdown; pub mod markdown;
pub mod menu; pub mod menu;
pub mod popover; pub mod popover;
pub mod progress;
pub mod radio;
pub mod scroll_area; pub mod scroll_area;
pub mod scrollbar; pub mod scrollbar;
pub mod segmented; pub mod segmented;
pub mod select; pub mod select;
pub mod separator; pub mod separator;
pub mod sidebar; pub mod sidebar;
pub mod slider;
pub mod speech;
pub mod spinner; pub mod spinner;
pub mod status_dot; pub mod status_dot;
pub mod switch; pub mod switch;
+22 -75
View File
@@ -24,24 +24,21 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
Animation, AnimationExt as _, AnyElement, App, Bounds, DispatchPhase, ElementId, AnyElement, App, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton,
InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
ParentElement as _, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div,
StyleRefinement, Styled as _, Window, anchored, canvas, deferred, div, ease_out_quint, point,
px,
}; };
use crate::components::common::{OVERLAY_LAYER, StyledExt as _, floating_panel, v_flex}; use crate::components::menu::{
ChangeHandler, TriggerBoundsCell, anchored_overlay, focus_capture, trigger_toggle,
};
use crate::components::common::{StyledExt as _, floating_panel, v_flex};
use crate::theme::{ActiveTheme as _, POPOVER_MIN_WIDTH}; use crate::theme::{ActiveTheme as _, POPOVER_MIN_WIDTH};
/// Reports the next open state of a [`Popover`]: `true` to open, `false` to close.
type ChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
/// The element the panel anchors below, built during render. /// The element the panel anchors below, built during render.
type TriggerFn = Box<dyn FnOnce(&mut Window, &mut App) -> AnyElement>; type TriggerFn = Box<dyn FnOnce(&mut Window, &mut App) -> AnyElement>;
/// The panel's contents, built when it opens. /// The panel's contents, built when it opens.
type ContentFn = Box<dyn FnOnce(&mut Window, &mut App) -> AnyElement>; type ContentFn = Box<dyn FnOnce(&mut Window, &mut App) -> AnyElement>;
/// Bounds captured during the last paint, shared with the dismissal listener.
type BoundsCell = Rc<RefCell<Option<Bounds<Pixels>>>>;
/// A floating panel anchored below its trigger. /// A floating panel anchored below its trigger.
#[derive(IntoElement)] #[derive(IntoElement)]
@@ -134,7 +131,7 @@ impl RenderOnce for Popover {
) )
}; };
let trigger_bounds: BoundsCell = Rc::new(RefCell::new(None)); let trigger_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None));
let fallback_label = self let fallback_label = self
.a11y_label .a11y_label
@@ -144,49 +141,12 @@ impl RenderOnce for Popover {
div() div()
.relative() .relative()
.refine_style(&self.style) .refine_style(&self.style)
.child( .child(trigger_toggle(
canvas( &trigger_bounds,
{ self.open,
let cell = trigger_bounds.clone(); self.on_change.clone(),
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) MouseButton::Left,
}, ))
{
let on_change = self.on_change.clone();
let open = self.open;
let cell = trigger_bounds.clone();
move |_, _, window, _cx| {
window.on_mouse_event({
let on_change = on_change.clone();
let trigger_bounds = cell;
move |event: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble
|| event.button != MouseButton::Left
{
return;
}
let on_trigger = trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !on_trigger {
return;
}
if let Some(on_change) = &on_change {
on_change(!open, window, cx);
}
cx.stop_propagation();
}
});
}
},
)
.absolute()
.inset_0(),
)
.when_some(self.trigger, |wrapper, trigger| { .when_some(self.trigger, |wrapper, trigger| {
wrapper.child(trigger(window, cx)) wrapper.child(trigger(window, cx))
}) })
@@ -238,29 +198,16 @@ impl RenderOnce for Popover {
} }
}) })
.when_some(content, |panel, content| panel.child(content)) .when_some(content, |panel, content| panel.child(content))
.child( .child(focus_capture(
canvas(|_, _, _| {}, { focus.clone(),
let focus = focus; move |window, cx| !focus.contains_focused(window, cx),
move |_, _, window, cx| { ));
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
wrapper.child( wrapper.child(anchored_overlay(
deferred(anchored().offset(point(Pixels::ZERO, px(4.))).child( None,
panel.with_animation( panel.into_any_element(),
"popover-enter", Some(("popover-enter", enter_duration)),
Animation::new(enter_duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
),
)) ))
.with_priority(OVERLAY_LAYER),
)
}) })
} }
} }
-132
View File
@@ -1,132 +0,0 @@
//! Renders a progress bar with a determinate fill or an indeterminate sweep.
//!
//! # Examples
//!
//! ```no_run
//! use ui::progress::Progress;
//!
//! let upload = Progress::new("upload", 0.4);
//! let loading = Progress::new("loading", 0.0).indeterminate(true);
//! ```
use gpui::prelude::FluentBuilder as _;
use gpui::{
Animation, AnimationExt as _, App, ElementId, InteractiveElement as _, IntoElement,
ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, div, relative,
};
use crate::components::common::{Sizable, StyledExt as _};
use crate::theme::{ActiveTheme as _, PROGRESS_ANIMATION_PERIOD, Size};
/// A bar that paints a determinate fill from its `value`, or an indeterminate sweep.
#[derive(IntoElement)]
#[must_use]
pub struct Progress {
id: ElementId,
value: f32,
indeterminate: bool,
size: Size,
a11y_label: Option<SharedString>,
style: StyleRefinement,
}
impl Progress {
/// Creates a determinate progress bar at `value` (`0..=1`).
pub fn new<I>(id: I, value: f32) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
value,
indeterminate: false,
size: Size::default(),
a11y_label: None,
style: StyleRefinement::default(),
}
}
/// Sweeps instead of painting a fill, for work of unknown length.
pub fn indeterminate(mut self, indeterminate: bool) -> Self {
self.indeterminate = indeterminate;
self
}
/// Sets the accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl gpui::Styled for Progress {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Progress {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Progress {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let radius = theme.radius;
let size = self.size;
let value = self.value.clamp(0.0, 1.0);
let track = div().w_full().rounded(radius.full).bg(colors.border);
let track = match size {
Size::XSmall => track.h_0p5(),
Size::Small | Size::Medium => track.h_1(),
Size::Large => track.h_1p5(),
};
div()
.id(self.id)
.w_full()
.refine_style(&self.style)
.role(Role::ProgressIndicator)
.when_some(self.a11y_label, |progress, label| {
progress.aria_label(label)
})
.when(!self.indeterminate, |progress| {
progress
.aria_numeric_value(f64::from(value))
.aria_min_numeric_value(0.0)
.aria_max_numeric_value(1.0)
})
.child(track.child(if self.indeterminate {
div()
.h_full()
.w(relative(0.3))
.rounded(radius.full)
.bg(ramps.primary.base)
.with_animation(
"indeterminate",
Animation::new(PROGRESS_ANIMATION_PERIOD)
.repeat()
.with_max_fps(30.),
|pill, delta| pill.ml(relative(delta * 0.7)),
)
.into_any_element()
} else {
div()
.h_full()
.w(relative(value))
.rounded(radius.full)
.bg(ramps.primary.base)
.into_any_element()
}))
}
}
-259
View File
@@ -1,259 +0,0 @@
//! Renders a group of radio buttons that reports the clicked choice.
//!
//! # Examples
//!
//! ```no_run
//! use ui::radio::{Radio, RadioGroup};
//!
//! let plan = RadioGroup::new("plan")
//! .selected(Some("monthly"))
//! .child(Radio::new("monthly", "monthly").label("Monthly"))
//! .child(Radio::new("yearly", "yearly").label("Yearly"))
//! .on_change(|value, _window, _cx| println!("selected: {value}"));
//! ```
use gpui::prelude::FluentBuilder;
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window,
div,
};
use crate::components::common::{
ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex, v_flex,
};
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
/// The group's change reporter, fired with the clicked radio's value.
type ChangeHandler<V> = std::rc::Rc<dyn Fn(V, &mut Window, &mut App)>;
/// A single choice in a [`RadioGroup`].
///
/// Each radio is its own tab stop; the full ARIA radiogroup pattern (single
/// stop plus arrow-key roving focus) needs a group owner that does not exist yet.
#[must_use]
pub struct Radio<V> {
id: ElementId,
value: V,
label: Option<SharedString>,
disabled: bool,
a11y_label: Option<SharedString>,
}
impl<V> Radio<V>
where
V: Clone + PartialEq + 'static,
{
/// Creates a radio representing `value`.
pub fn new<I>(id: I, value: V) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
value,
label: None,
disabled: false,
a11y_label: None,
}
}
/// Sets the visible label; clicking it selects the radio too.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Renders the radio inert, unfocusable, and dimmed.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
// Radio is a data builder, not an element, adopt the combinators explicitly.
impl<V> FluentBuilder for Radio<V> {}
/// A set of [`Radio`] choices that reports clicks through [`RadioGroup::on_change`].
#[derive(IntoElement)]
#[must_use]
pub struct RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
id: ElementId,
selected: Option<V>,
children: Vec<Radio<V>>,
size: Size,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler<V>>,
style: StyleRefinement,
}
impl<V> RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
/// Creates an empty group with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
selected: None,
children: Vec::new(),
size: Size::default(),
a11y_label: None,
on_change: None,
style: StyleRefinement::default(),
}
}
/// Sets the currently selected value.
pub fn selected(mut self, selected: Option<V>) -> Self {
self.selected = selected;
self
}
/// Adds a radio to the group.
pub fn child(mut self, radio: Radio<V>) -> Self {
self.children.push(radio);
self
}
/// Sets the group's accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the handler fired with the clicked radio's value.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(V, &mut Window, &mut App) + 'static,
{
self.on_change = Some(std::rc::Rc::new(handler));
self
}
}
impl<V> Sizable for RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl<V> gpui::Styled for RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl<V> RenderOnce for RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let radius = theme.radius;
let size = self.size;
let selected = self.selected;
let on_change = self.on_change;
let group_label = self.a11y_label;
v_flex()
.id(self.id)
.gap_2()
.control_text(size)
.refine_style(&self.style)
.role(Role::RadioGroup)
.when_some(group_label.clone(), |group, label| group.aria_label(label))
.children(self.children.into_iter().map(move |radio| {
let is_selected = selected.as_ref() == Some(&radio.value);
let disabled = radio.disabled;
let row_on_change = on_change.clone();
let a11y_label = radio
.a11y_label
.or(radio.label.clone())
.or_else(|| group_label.clone());
h_flex()
.id(radio.id)
.gap_2()
.role(Role::RadioButton)
.when_some(a11y_label, |row, label| row.aria_label(label))
.aria_toggled(Toggled::from(is_selected))
.when(disabled, |row| row.opacity(DISABLED_OPACITY))
.when(!disabled, move |row| {
let value = radio.value.clone();
row.cursor_pointer()
.focusable()
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.when_some(row_on_change, |row, on_change| {
row.on_click(move |_, window, cx| {
on_change(value.clone(), window, cx)
})
})
})
.child(
h_flex()
.justify_center()
.flex_none()
.control_indicator(size)
.rounded(radius.full)
.border_1()
.when(is_selected, |indicator| {
indicator
.bg(ramps.primary.base)
.border_color(ramps.primary.base)
.hover(|style| {
style
.bg(ramps.primary.hover)
.border_color(ramps.primary.hover)
})
.child({
let dot = match size {
Size::XSmall => div().size_1p5(),
Size::Small | Size::Medium => div().size_2(),
Size::Large => div().size_2p5(),
};
dot.rounded(radius.full).bg(colors.primary_foreground)
})
})
.when(!is_selected, |indicator| {
indicator
.bg(colors.input)
.border_color(colors.border)
.hover(|style| style.border_color(colors.muted_foreground))
}),
)
.when_some(radio.label, |row, label| row.child(label))
}))
}
}
+47 -49
View File
@@ -42,6 +42,39 @@ pub enum ScrollbarVisibility {
/// How often the autohide fade repaints while it runs. /// How often the autohide fade repaints while it runs.
const FADE_STEP: Duration = Duration::from_millis(50); 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>) -> Pixels {
match self {
Axis::Vertical => position.y,
Axis::Horizontal => position.x,
}
}
fn with_along(self, position: Point<Pixels>, along: Pixels) -> Point<Pixels> {
match self {
Axis::Vertical => point(position.x, along),
Axis::Horizontal => point(along, position.y),
}
}
fn viewport_along(self, viewport: &Bounds<Pixels>) -> Pixels {
match self {
Axis::Vertical => viewport.size.height,
Axis::Horizontal => viewport.size.width,
}
}
}
/// The shared autohide timeline for an overlay scrollbar. /// The shared autohide timeline for an overlay scrollbar.
#[derive(Clone)] #[derive(Clone)]
struct Autohide { struct Autohide {
@@ -199,36 +232,6 @@ impl ScrollbarHandle for ListState {
} }
} }
/// Which direction the scrollbar lies along.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Axis {
Vertical,
Horizontal,
}
impl Axis {
fn along(self, position: Point<Pixels>) -> Pixels {
match self {
Axis::Vertical => position.y,
Axis::Horizontal => position.x,
}
}
fn with_along(self, position: Point<Pixels>, along: Pixels) -> Point<Pixels> {
match self {
Axis::Vertical => point(position.x, along),
Axis::Horizontal => point(along, position.y),
}
}
fn viewport_along(self, viewport: &Bounds<Pixels>) -> Pixels {
match self {
Axis::Vertical => viewport.size.height,
Axis::Horizontal => viewport.size.width,
}
}
}
/// An overlay scrollbar, rendered over the scrolled surface. /// An overlay scrollbar, rendered over the scrolled surface.
#[derive(IntoElement)] #[derive(IntoElement)]
#[must_use] #[must_use]
@@ -239,6 +242,20 @@ pub struct Scrollbar {
id: ElementId, id: ElementId,
} }
impl RenderOnce for Scrollbar {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
canvas(|_, _, _| {}, {
let handle = self.handle;
let axis = self.axis;
let visibility = self.visibility;
let id = self.id;
move |_, _, window, cx| Self::paint(&handle, axis, visibility, &id, window, cx)
})
.absolute()
.inset_0()
}
}
impl Scrollbar { impl Scrollbar {
/// Creates a vertical scrollbar named by `id`, driven by `handle`. /// Creates a vertical scrollbar named by `id`, driven by `handle`.
pub fn vertical<I, H>(id: I, handle: H) -> Self pub fn vertical<I, H>(id: I, handle: H) -> Self
@@ -304,26 +321,7 @@ impl Scrollbar {
..color ..color
}) })
} }
}
impl RenderOnce for Scrollbar {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
canvas(|_, _, _| {}, {
let handle = self.handle;
let axis = self.axis;
let visibility = self.visibility;
let id = self.id;
move |_, _, window, cx| Self::paint(&handle, axis, visibility, &id, window, cx)
})
.absolute()
.inset_0()
}
}
/// The drag state shared between the scrollbar's mouse handlers.
type Drag = Option<(Pixels, Pixels)>;
impl Scrollbar {
fn paint( fn paint(
handle: &Rc<dyn ScrollbarHandle>, handle: &Rc<dyn ScrollbarHandle>,
axis: Axis, axis: Axis,
+1 -1
View File
@@ -29,7 +29,7 @@ use crate::icons::{Icon, IconRole, icon};
use crate::theme::{ActiveTheme as _, Size}; use crate::theme::{ActiveTheme as _, Size};
/// Reports the value the user chose. `None` means the select holds no value. /// Reports the value the user chose. `None` means the select holds no value.
pub type SelectHandler<T> = Rc<dyn Fn(Option<T>, &mut Window, &mut App)>; type SelectHandler<T> = Rc<dyn Fn(Option<T>, &mut Window, &mut App)>;
/// Select option for a [`Select`] control. /// Select option for a [`Select`] control.
#[derive(Clone)] #[derive(Clone)]
+123 -161
View File
@@ -143,6 +143,129 @@ impl SidebarEntry {
} }
self self
} }
#[allow(clippy::too_many_arguments)]
fn render_entry(
self,
cx: &App,
index: usize,
position_in_set: usize,
size_of_set: usize,
selected: bool,
material: bool,
on_change: &Option<ChangeHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
match self {
SidebarEntry::Header {
label,
prefix,
suffix,
} => {
// The id is required for the role to surface in the a11y tree.
div()
.id(("sidebar-header".into(), label.clone()))
.flex()
.items_center()
.gap_2()
.px_2()
.pt_2()
.pb_1()
.text_sm()
.font_semibold()
.text_color(theme.colors.muted_foreground)
.role(Role::Heading)
.when_some(prefix, |header, prefix| header.child(prefix))
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.when_some(suffix, |header, suffix| header.child(suffix))
.into_any_element()
}
SidebarEntry::Custom(element) => element,
SidebarEntry::Row {
key,
label,
detail,
prefix,
suffix,
disabled: row_disabled,
} => {
let label_color = selectable_label_color(cx, selected, row_disabled);
div()
.id((key.clone(), "sidebar-row"))
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.min_h_8()
.rounded(theme.radius.sm)
.text_color(label_color)
.role(Role::ListItem)
.aria_selected(selected)
.aria_position_in_set(position_in_set)
.aria_size_of_set(size_of_set)
.map(|row| {
if material && !row_disabled {
if selected {
row.bg(theme.material.selection)
} else {
row.hover(|row| row.bg(theme.material.hover))
}
} else {
paint_selectable_row(cx, row, selected, row_disabled)
}
})
.when(!row_disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
}
})
})
.when_some(prefix, |row, prefix| row.child(prefix))
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.when_some(detail, |row, detail| {
row.child(
div()
.flex_none()
.text_sm()
.text_color(if selected {
theme.colors.primary_foreground
} else {
theme.colors.muted_foreground
})
.child(detail),
)
})
.when_some(suffix, |row, suffix| row.child(suffix))
.into_any_element()
}
}
}
} }
// SidebarEntry is a data builder, not an element, adopt the combinators explicitly. // SidebarEntry is a data builder, not an element, adopt the combinators explicitly.
@@ -198,48 +321,12 @@ impl Sidebar {
self self
} }
/// Whether translucent material fills are painted.
pub fn is_transparent(&self) -> bool {
self.transparent
}
/// Textures the sidebar with a film-grain overlay.
pub fn grain(mut self, grain: bool) -> Self {
self.grain = grain;
self
}
/// Paints a hairline border on the sidebar's right edge. /// Paints a hairline border on the sidebar's right edge.
pub fn border_right(mut self, border_right: bool) -> Self { pub fn border_right(mut self, border_right: bool) -> Self {
self.border_right = border_right; self.border_right = border_right;
self self
} }
/// Whether the right-edge border is painted.
pub fn has_border_right(&self) -> bool {
self.border_right
}
/// Insets the entry list from the sidebar's edges; the scrollbar stays on the edge.
pub fn padded(mut self, padded: bool) -> Self {
self.padded = padded;
self
}
/// Whether the entry list is inset from the sidebar's edges.
pub fn is_padded(&self) -> bool {
self.padded
}
/// Sets the sidebar's width, overriding the default.
pub fn width<W>(mut self, width: W) -> Self
where
W: Into<Pixels>,
{
self.width = width.into();
self
}
/// Reports the next selected row, from clicks and keys alike. /// Reports the next selected row, from clicks and keys alike.
pub fn on_change<F>(mut self, handler: F) -> Self pub fn on_change<F>(mut self, handler: F) -> Self
where where
@@ -404,128 +491,3 @@ impl RenderOnce for Sidebar {
.when(material && grain, |sidebar| sidebar.child(grain_overlay())) .when(material && grain, |sidebar| sidebar.child(grain_overlay()))
} }
} }
impl SidebarEntry {
#[allow(clippy::too_many_arguments)]
fn render_entry(
self,
cx: &App,
index: usize,
position_in_set: usize,
size_of_set: usize,
selected: bool,
material: bool,
on_change: &Option<ChangeHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
match self {
SidebarEntry::Header {
label,
prefix,
suffix,
} => {
// The id is required for the role to surface in the a11y tree.
div()
.id(("sidebar-header".into(), label.clone()))
.flex()
.items_center()
.gap_2()
.px_2()
.pt_2()
.pb_1()
.text_sm()
.font_semibold()
.text_color(theme.colors.muted_foreground)
.role(Role::Heading)
.when_some(prefix, |header, prefix| header.child(prefix))
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.when_some(suffix, |header, suffix| header.child(suffix))
.into_any_element()
}
SidebarEntry::Custom(element) => element,
SidebarEntry::Row {
key,
label,
detail,
prefix,
suffix,
disabled: row_disabled,
} => {
let label_color = selectable_label_color(cx, selected, row_disabled);
div()
.id((key.clone(), "sidebar-row"))
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.min_h_8()
.rounded(theme.radius.sm)
.text_color(label_color)
.role(Role::ListItem)
.aria_selected(selected)
.aria_position_in_set(position_in_set)
.aria_size_of_set(size_of_set)
.map(|row| {
if material && !row_disabled {
if selected {
row.bg(theme.material.selection)
} else {
row.hover(|row| row.bg(theme.material.hover))
}
} else {
paint_selectable_row(cx, row, selected, row_disabled)
}
})
.when(!row_disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
}
})
})
.when_some(prefix, |row, prefix| row.child(prefix))
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.when_some(detail, |row, detail| {
row.child(
div()
.flex_none()
.text_sm()
.text_color(if selected {
theme.colors.primary_foreground
} else {
theme.colors.muted_foreground
})
.child(detail),
)
})
.when_some(suffix, |row, suffix| row.child(suffix))
.into_any_element()
}
}
}
}
-341
View File
@@ -1,341 +0,0 @@
//! Renders a controlled slider that reports its next value on click, drag, and arrow keys.
//!
//! # Examples
//!
//! ```no_run
//! use ui::slider::Slider;
//!
//! let opacity = Slider::new("opacity", 1.0)
//! .step(0.25)
//! .on_change(|value, _window, _cx| println!("opacity: {value}"));
//! ```
use std::cell::Cell;
use std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Bounds, DispatchPhase, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent,
MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas,
div, relative,
};
use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex};
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
/// The change reporter, fired with the next value by click, drag, and arrows.
type ChangeHandler = Rc<dyn Fn(f32, &mut Window, &mut App)>;
/// The pointer→value setter shared by the click and drag listeners.
type ValueSetter = Rc<dyn Fn(Pixels, &mut Window, &mut App)>;
/// The arrow-key stride as a share of the range when the slider is continuous.
const FALLBACK_STEP_FRACTION: f32 = 0.05;
impl Slider {
/// Clamps `value` into `[min, max]` and snaps it to `step` when stepped.
fn constrain(min: f32, max: f32, step: f32, value: f32) -> f32 {
let clamped = value.clamp(min, max);
if step > 0.0 {
(min + ((clamped - min) / step).round() * step).clamp(min, max)
} else {
clamped
}
}
}
/// A controlled slider over `[min, max]`.
#[derive(IntoElement)]
#[must_use]
pub struct Slider {
id: ElementId,
min: f32,
max: f32,
step: f32,
value: f32,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
style: StyleRefinement,
}
impl Slider {
/// Creates a slider over `0..=1` with no stepping, at `value`.
pub fn new<I>(id: I, value: f32) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
min: 0.0,
max: 1.0,
step: 0.0,
value,
size: Size::default(),
disabled: false,
a11y_label: None,
on_change: None,
style: StyleRefinement::default(),
}
}
/// Sets the range's lower bound.
pub fn min(mut self, min: f32) -> Self {
self.min = min;
self
}
/// Sets the range's upper bound.
pub fn max(mut self, max: f32) -> Self {
self.max = max;
self
}
/// Sets the step; values snap to `min + n * step`. `0` is continuous.
pub fn step(mut self, step: f32) -> Self {
self.step = step;
self
}
/// Renders the slider inert, unfocusable, and dimmed; disabled always wins.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Sets the accessibility label, required for an unlabeled slider.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the change handler, fired with the next value by click, drag, and arrows.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(f32, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
}
impl gpui::Styled for Slider {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Slider {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Slider {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let radius = theme.radius;
let rem = window.rem_size();
let row_height = self.size.slider_row_rems() * rem;
let track_height = self.size.slider_track_rems() * rem;
let knob = self.size.indicator_rems() * rem;
let value = self.value.clamp(self.min, self.max);
let fraction = if self.max > self.min {
(value - self.min) / (self.max - self.min)
} else {
0.0
};
let bounds_cell = Rc::new(Cell::new(None::<Bounds<Pixels>>));
let focus_handle = crate::components::common::focus_handle(&self.id, window, cx);
let dragging =
window.use_keyed_state((self.id.clone(), "slider-dragging"), cx, |_, _| false);
let set_value: ValueSetter = {
let bounds_cell = bounds_cell.clone();
let on_change = self.on_change.clone();
let (min, max, step) = (self.min, self.max, self.step);
Rc::new(move |x: Pixels, window: &mut Window, cx: &mut App| {
if let (Some(bounds), Some(on_change)) = (bounds_cell.get(), on_change.as_ref())
&& bounds.size.width > Pixels::ZERO
{
let fraction = ((x - bounds.origin.x) / bounds.size.width).clamp(0.0, 1.0);
on_change(
Self::constrain(min, max, step, min + fraction * (max - min)),
window,
cx,
);
}
})
};
let down_dragging = dragging.clone();
let down_set_value = set_value.clone();
let disabled = self.disabled;
h_flex()
.id(self.id)
.relative()
.w_full()
.map(|slider| match self.size {
Size::XSmall => slider.h_6(),
Size::Small => slider.h_9(),
Size::Medium => slider.h_10(),
Size::Large => slider.h_12(),
})
.refine_style(&self.style)
.role(Role::Slider)
.when_some(self.a11y_label.clone(), |slider, label| {
slider.aria_label(label)
})
.aria_numeric_value(f64::from(value))
.aria_min_numeric_value(f64::from(self.min))
.aria_max_numeric_value(f64::from(self.max))
.when(self.disabled, |slider| slider.opacity(DISABLED_OPACITY))
.when(!self.disabled, |slider| {
slider
.track_focus(&focus_handle)
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.on_mouse_down(MouseButton::Left, move |event, window, cx| {
down_dragging.update(cx, |dragging, _| *dragging = true);
down_set_value(event.position.x, window, cx);
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if !focus_handle.contains_focused(window, cx) {
return;
}
let single_step = if self.step > 0.0 {
self.step
} else {
(self.max - self.min) * FALLBACK_STEP_FRACTION
};
let next = match event.keystroke.key.as_str() {
"left" | "down" => Some(value - single_step),
"right" | "up" => Some(value + single_step),
"home" => Some(self.min),
"end" => Some(self.max),
_ => None,
};
if let Some(next) = next
&& let Some(on_change) = self.on_change.as_ref()
{
on_change(
Self::constrain(self.min, self.max, self.step, next),
window,
cx,
);
cx.stop_propagation();
}
})
})
.child(
canvas(
{
let bounds_cell = bounds_cell.clone();
move |bounds, _, _| bounds_cell.set(Some(bounds))
},
{
let dragging = dragging.clone();
let set_value = set_value.clone();
move |_, _, window, _cx| {
if disabled {
return;
}
window.on_mouse_event({
let dragging = dragging.clone();
let set_value = set_value.clone();
move |event: &MouseMoveEvent, phase, window, cx| {
if phase == DispatchPhase::Bubble
&& *dragging.read(cx)
&& event.pressed_button == Some(MouseButton::Left)
{
set_value(event.position.x, window, cx);
}
}
});
window.on_mouse_event({
let dragging = dragging.clone();
move |event: &MouseUpEvent, phase, _window, cx| {
if phase == DispatchPhase::Bubble
&& event.button == MouseButton::Left
{
dragging.update(cx, |dragging, _| *dragging = false);
}
}
});
}
},
)
.absolute()
.inset_0(),
)
.child(
div()
.absolute()
.left_0()
.top((row_height - track_height) / 2.0)
.map(|track| match self.size {
Size::XSmall => track.h_0p5(),
Size::Small | Size::Medium => track.h_1(),
Size::Large => track.h_1p5(),
})
.w_full()
.rounded(radius.full)
.bg(colors.border),
)
.child(
div()
.absolute()
.left_0()
.top((row_height - track_height) / 2.0)
.map(|track| match self.size {
Size::XSmall => track.h_0p5(),
Size::Small | Size::Medium => track.h_1(),
Size::Large => track.h_1p5(),
})
.w(relative(fraction))
.rounded(radius.full)
.bg(ramps.primary.base),
)
.child(
h_flex()
.absolute()
.left_0()
.top_0()
.h_full()
.w(relative(fraction))
.justify_end()
.items_center()
.child(
div()
.map(|dot| match self.size {
Size::XSmall => dot.size_2p5(),
Size::Small => dot.size_3p5(),
Size::Medium => dot.size_4(),
Size::Large => dot.size_5(),
})
.flex_none()
.rounded(radius.full)
.bg(colors.primary_foreground)
.border_1()
.border_color(colors.border)
.mr(-knob / 2.0),
),
)
}
}
File diff suppressed because it is too large Load Diff
+17 -3
View File
@@ -10,11 +10,12 @@
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, AnyElement, App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _,
Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Window, div,
}; };
use crate::components::common::{Sizable, StyledExt as _}; use crate::components::common::{Sizable, StyledExt as _, v_flex};
use crate::icons::{IconRole, icon}; use crate::icons::{IconRole, icon};
use crate::theme::{ActiveTheme as _, SPINNER_PERIOD, Size}; use crate::theme::{ActiveTheme as _, SPINNER_PERIOD, Size};
@@ -44,6 +45,19 @@ impl Spinner {
} }
} }
/// The spinner centered in the full available space.
pub fn centered<I>(id: I) -> AnyElement
where
I: Into<ElementId>,
{
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Self::new(id))
.into_any_element()
}
/// Overrides the icon color, for accent-filled surfaces. /// Overrides the icon color, for accent-filled surfaces.
pub fn color(mut self, color: Hsla) -> Self { pub fn color(mut self, color: Hsla) -> Self {
self.color = Some(color); self.color = Some(color);
+286 -287
View File
@@ -388,6 +388,292 @@ impl Tab {
self.wrap = Some(Box::new(wrap)); self.wrap = Some(Box::new(wrap));
self self
} }
fn render_tab(mut self, ctx: &StripCtx, cx: &App, index: usize) -> AnyElement {
let selected = index == ctx.selected;
// A pinned tab always wears the active treatment, selected or not.
let active = selected || self.pinned;
let theme = cx.theme();
let label_color = tab_label_color(ctx.variant, active, self.disabled, cx);
let titlebar = ctx.variant == TabsVariant::Titlebar;
let group = SharedString::from(format!("{}-tab-{}", ctx.id, self.key));
let close = (self.closeable && ctx.on_close.is_some() && !self.disabled)
.then(|| self.render_tab_close(&ctx.id, index, &ctx.on_close));
let label = div()
.flex_grow(1.0)
.when(titlebar, |label| {
let fade = if active {
theme.colors.background
} else {
theme.colors.muted
};
let hover_fade = if active {
theme.colors.background
} else {
theme.colors.muted_hover
};
let fade_width = rems(0.75);
let hover_fade_width = rems(1.5);
label
.min_w_0()
.relative()
.overflow_hidden()
.child(
div()
.w_full()
.whitespace_nowrap()
.text_overflow(TextOverflow::Truncate(SharedString::default()))
.child(self.label.clone()),
)
.child(
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(fade_width)
.bg(linear_gradient(
90.,
linear_color_stop(fade.opacity(0.), 0.),
linear_color_stop(fade, 1.),
)),
)
.child(
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(hover_fade_width)
.bg(linear_gradient(
90.,
linear_color_stop(hover_fade.opacity(0.), 0.),
linear_color_stop(hover_fade, 1.),
))
.invisible()
.group_hover(group.clone(), |style| style.visible()),
)
})
.when(!titlebar, |label| label.child(self.label.clone()));
let strip_tab = div()
.id((self.key.clone(), "tab"))
.debug_selector({
let tabs_id = ctx.id.clone();
let label = self.label.clone();
move || format!("{tabs_id}-tab-{}", label)
})
.flex()
.items_center()
.gap_2()
.role(Role::Tab)
.aria_selected(selected)
.text_color(label_color)
.when(titlebar, |strip_tab| strip_tab.group(group.clone()))
.when(!self.disabled && !active, |strip_tab| {
strip_tab.hover(|strip_tab| {
strip_tab.bg(match ctx.variant {
TabsVariant::Titlebar => theme.colors.muted_hover,
_ => theme.colors.muted,
})
})
})
.map(|strip_tab| {
apply_tab_chrome(strip_tab, ctx.variant, active, cx).when(titlebar, |strip_tab| {
strip_tab.min_w(TAB_MIN_WIDTH).max_w(TAB_MAX_WIDTH)
})
})
.when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead))
.child(label)
.when(ctx.variant == TabsVariant::Pill, |strip_tab| {
strip_tab.child(div().flex_none().w_4())
})
.when(self.busy && !self.disabled, |strip_tab| {
strip_tab.child(
Spinner::new((self.key.clone(), "tab-busy"))
.small()
.accessibility_label("Loading"),
)
})
.when_some(close, |strip_tab, close| {
if titlebar {
strip_tab.child(
div()
.flex_none()
.invisible()
.group_hover(group, |style| style.visible())
.child(close),
)
} else {
strip_tab.child(close)
}
})
.when(
{
let drop = ctx.drop_at.read(cx);
drop.onto == Some(index) && !drop.canceled()
},
|strip_tab| {
strip_tab.child(
div()
.absolute()
.left_0()
.top_0p5()
.bottom_0p5()
.w_0p5()
.rounded(theme.radius.sm)
.bg(theme.ramps.primary.base),
)
},
)
.when_some(ctx.measure.clone(), |strip_tab, measure| {
let key = measure.key.clone();
let root_bounds = measure.root_bounds.clone();
let tab_key = self.key.to_string();
strip_tab.child(
canvas(
move |bounds, _, cx| {
let root = root_bounds.borrow();
if let Some(root) = root.as_ref() {
cx.default_global::<TabsMeasurements>().record_tab(
&key,
tab_key,
TabMeasure {
left: bounds.origin.x - root.origin.x,
width: bounds.size.width,
},
);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
})
.when(!self.disabled, |strip_tab| {
strip_tab.cursor_pointer().on_click({
let selected = ctx.selected;
let on_change = ctx.on_change.clone();
let focus = ctx.focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if index != selected
&& let Some(on_change) = &on_change
{
on_change(index, window, cx);
}
}
})
})
.when(ctx.draggable && !self.disabled, |strip_tab| {
strip_tab
.on_mouse_down(MouseButton::Left, {
let drop_at = ctx.drop_at.clone();
move |event, _, cx| {
cx.stop_propagation();
drop_at.update(cx, |drop, cx| {
let fresh = TabDrop {
origin: Some(event.position),
..TabDrop::default()
};
if *drop != fresh {
*drop = fresh;
cx.notify();
}
});
}
})
.on_drag(TabDrag { index }, {
let label = self.label.clone();
move |_, _, _, cx| {
cx.new(|_| TabDragPreview {
label: label.clone(),
})
}
})
.drag_over::<TabDrag>({
let drop_at = ctx.drop_at.clone();
move |style, drag, _, cx| {
let drop = *drop_at.read(cx);
let hovered = drag.index != index && !drop.canceled();
drop_at.update(cx, |drop, cx| match (hovered, drop.onto) {
(true, current) if current != Some(index) => {
drop.onto = Some(index);
cx.notify();
}
(false, Some(_)) => {
drop.onto = None;
cx.notify();
}
_ => {}
});
style
}
})
.on_drop::<TabDrag>({
let on_reorder = ctx.on_reorder.clone();
let drop_at = ctx.drop_at.clone();
move |drag, window, cx| {
let canceled = drop_at.read(cx).canceled();
drop_at.update(cx, |drop, cx| {
if drop.onto.is_some() {
drop.onto = None;
cx.notify();
}
});
let target = (!canceled)
.then(|| reorder_target(drag.index, index))
.flatten();
if let (Some(to), Some(on_reorder)) = (target, on_reorder.as_ref()) {
on_reorder(drag.index, to, window, cx);
}
}
})
});
match self.wrap {
Some(wrap) => wrap(strip_tab),
None => strip_tab.into_any_element(),
}
}
fn render_tab_close(
&self,
tabs_id: &ElementId,
index: usize,
on_close: &Option<CloseHandler>,
) -> AnyElement {
Button::new((self.key.clone(), "tab-close"))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.xsmall()
.fully_rounded(true)
.tab_stop(false)
.debug_selector({
let tabs_id = tabs_id.clone();
let label = self.label.clone();
move || format!("{tabs_id}-close-{}", label)
})
.tooltip(Tooltip::text("Close"))
.accessibility_label(SharedString::from(format!("Close {}", self.label)))
.on_click({
let on_close = on_close.clone();
move |_, window, cx| {
cx.stop_propagation();
if let Some(on_close) = &on_close {
on_close(index, window, cx);
}
}
})
.into_any_element()
}
} }
// Tab is a data builder, not an element, adopt the combinators explicitly. // Tab is a data builder, not an element, adopt the combinators explicitly.
@@ -1060,290 +1346,3 @@ impl RenderOnce for Tabs {
} }
} }
impl Tab {
fn render_tab(mut self, ctx: &StripCtx, cx: &App, index: usize) -> AnyElement {
let selected = index == ctx.selected;
// A pinned tab always wears the active treatment, selected or not.
let active = selected || self.pinned;
let theme = cx.theme();
let label_color = tab_label_color(ctx.variant, active, self.disabled, cx);
let titlebar = ctx.variant == TabsVariant::Titlebar;
let group = SharedString::from(format!("{}-tab-{}", ctx.id, self.key));
let close = (self.closeable && ctx.on_close.is_some() && !self.disabled)
.then(|| self.render_tab_close(&ctx.id, index, &ctx.on_close));
let label = div()
.flex_grow(1.0)
.when(titlebar, |label| {
let fade = if active {
theme.colors.background
} else {
theme.colors.muted
};
let hover_fade = if active {
theme.colors.background
} else {
theme.colors.muted_hover
};
let fade_width = rems(0.75);
let hover_fade_width = rems(1.5);
label
.min_w_0()
.relative()
.overflow_hidden()
.child(
div()
.w_full()
.whitespace_nowrap()
.text_overflow(TextOverflow::Truncate(SharedString::default()))
.child(self.label.clone()),
)
.child(
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(fade_width)
.bg(linear_gradient(
90.,
linear_color_stop(fade.opacity(0.), 0.),
linear_color_stop(fade, 1.),
)),
)
.child(
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(hover_fade_width)
.bg(linear_gradient(
90.,
linear_color_stop(hover_fade.opacity(0.), 0.),
linear_color_stop(hover_fade, 1.),
))
.invisible()
.group_hover(group.clone(), |style| style.visible()),
)
})
.when(!titlebar, |label| label.child(self.label.clone()));
let strip_tab = div()
.id((self.key.clone(), "tab"))
.debug_selector({
let tabs_id = ctx.id.clone();
let label = self.label.clone();
move || format!("{tabs_id}-tab-{}", label)
})
.flex()
.items_center()
.gap_2()
.role(Role::Tab)
.aria_selected(selected)
.text_color(label_color)
.when(titlebar, |strip_tab| strip_tab.group(group.clone()))
.when(!self.disabled && !active, |strip_tab| {
strip_tab.hover(|strip_tab| {
strip_tab.bg(match ctx.variant {
TabsVariant::Titlebar => theme.colors.muted_hover,
_ => theme.colors.muted,
})
})
})
.map(|strip_tab| {
apply_tab_chrome(strip_tab, ctx.variant, active, cx).when(titlebar, |strip_tab| {
strip_tab.min_w(TAB_MIN_WIDTH).max_w(TAB_MAX_WIDTH)
})
})
.when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead))
.child(label)
.when(ctx.variant == TabsVariant::Pill, |strip_tab| {
strip_tab.child(div().flex_none().w_4())
})
.when(self.busy && !self.disabled, |strip_tab| {
strip_tab.child(
Spinner::new((self.key.clone(), "tab-busy"))
.small()
.accessibility_label("Loading"),
)
})
.when_some(close, |strip_tab, close| {
if titlebar {
strip_tab.child(
div()
.flex_none()
.invisible()
.group_hover(group, |style| style.visible())
.child(close),
)
} else {
strip_tab.child(close)
}
})
.when(
{
let drop = ctx.drop_at.read(cx);
drop.onto == Some(index) && !drop.canceled()
},
|strip_tab| {
strip_tab.child(
div()
.absolute()
.left_0()
.top_0p5()
.bottom_0p5()
.w_0p5()
.rounded(theme.radius.sm)
.bg(theme.ramps.primary.base),
)
},
)
.when_some(ctx.measure.clone(), |strip_tab, measure| {
let key = measure.key.clone();
let root_bounds = measure.root_bounds.clone();
let tab_key = self.key.to_string();
strip_tab.child(
canvas(
move |bounds, _, cx| {
let root = root_bounds.borrow();
if let Some(root) = root.as_ref() {
cx.default_global::<TabsMeasurements>().record_tab(
&key,
tab_key,
TabMeasure {
left: bounds.origin.x - root.origin.x,
width: bounds.size.width,
},
);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
})
.when(!self.disabled, |strip_tab| {
strip_tab.cursor_pointer().on_click({
let selected = ctx.selected;
let on_change = ctx.on_change.clone();
let focus = ctx.focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if index != selected
&& let Some(on_change) = &on_change
{
on_change(index, window, cx);
}
}
})
})
.when(ctx.draggable && !self.disabled, |strip_tab| {
strip_tab
.on_mouse_down(MouseButton::Left, {
let drop_at = ctx.drop_at.clone();
move |event, _, cx| {
cx.stop_propagation();
drop_at.update(cx, |drop, cx| {
let fresh = TabDrop {
origin: Some(event.position),
..TabDrop::default()
};
if *drop != fresh {
*drop = fresh;
cx.notify();
}
});
}
})
.on_drag(TabDrag { index }, {
let label = self.label.clone();
move |_, _, _, cx| {
cx.new(|_| TabDragPreview {
label: label.clone(),
})
}
})
.drag_over::<TabDrag>({
let drop_at = ctx.drop_at.clone();
move |style, drag, _, cx| {
let drop = *drop_at.read(cx);
let hovered = drag.index != index && !drop.canceled();
drop_at.update(cx, |drop, cx| match (hovered, drop.onto) {
(true, current) if current != Some(index) => {
drop.onto = Some(index);
cx.notify();
}
(false, Some(_)) => {
drop.onto = None;
cx.notify();
}
_ => {}
});
style
}
})
.on_drop::<TabDrag>({
let on_reorder = ctx.on_reorder.clone();
let drop_at = ctx.drop_at.clone();
move |drag, window, cx| {
let canceled = drop_at.read(cx).canceled();
drop_at.update(cx, |drop, cx| {
if drop.onto.is_some() {
drop.onto = None;
cx.notify();
}
});
let target = (!canceled)
.then(|| reorder_target(drag.index, index))
.flatten();
if let (Some(to), Some(on_reorder)) = (target, on_reorder.as_ref()) {
on_reorder(drag.index, to, window, cx);
}
}
})
});
match self.wrap {
Some(wrap) => wrap(strip_tab),
None => strip_tab.into_any_element(),
}
}
fn render_tab_close(
&self,
tabs_id: &ElementId,
index: usize,
on_close: &Option<CloseHandler>,
) -> AnyElement {
Button::new((self.key.clone(), "tab-close"))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.xsmall()
.fully_rounded(true)
.tab_stop(false)
.debug_selector({
let tabs_id = tabs_id.clone();
let label = self.label.clone();
move || format!("{tabs_id}-close-{}", label)
})
.tooltip(Tooltip::text("Close"))
.accessibility_label(SharedString::from(format!("Close {}", self.label)))
.on_click({
let on_close = on_close.clone();
move |_, window, cx| {
cx.stop_propagation();
if let Some(on_close) = &on_close {
on_close(index, window, cx);
}
}
})
.into_any_element()
}
}
+64 -164
View File
@@ -2,17 +2,7 @@
//! //!
//! A [`Toasts`] entity holds the raised toast, and a [`ToastsView`] renders //! A [`Toasts`] entity holds the raised toast, and a [`ToastsView`] renders
//! it; mount the view at the window root. //! it; mount the view at the window root.
//!
//! # Examples
//!
//! ```no_run
//! use ui::toast::{Toast, ToastAction};
//!
//! let toast = Toast::new("Copied to clipboard")
//! .action(ToastAction::new("Undo", |_cx| println!("undo")));
//! ```
use std::rc::Rc;
use std::time::Duration; use std::time::Duration;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
@@ -25,45 +15,18 @@ use gpui::{
use crate::components::button::{Button, ButtonVariant}; use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{ use crate::components::common::{
DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, floating_panel, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, floating_panel, v_flex,
v_flex,
}; };
use crate::icons::{Icon, IconRole}; use crate::icons::{Icon, IconRole};
use crate::theme::{ActiveTheme as _, TOAST_MAX_WIDTH}; use crate::theme::{ActiveTheme as _, TOAST_MAX_WIDTH};
/// The action handler of a [`Toast`].
pub type ActionHandler = Rc<dyn Fn(&mut App)>;
/// One user action offered by a toast.
#[derive(Clone)]
pub struct ToastAction {
label: SharedString,
handler: ActionHandler,
}
impl ToastAction {
/// Creates an action with this label.
pub fn new<L, F>(label: L, handler: F) -> Self
where
L: Into<SharedString>,
F: Fn(&mut App) + 'static,
{
Self {
label: label.into(),
handler: Rc::new(handler),
}
}
}
/// A toast notification. /// A toast notification.
#[derive(Clone)] #[derive(Clone)]
#[must_use] #[must_use]
pub struct Toast { pub struct Toast {
message: SharedString, message: SharedString,
icon: Option<Icon>, icon: Option<Icon>,
action: Option<ToastAction>,
duration: Option<Duration>, duration: Option<Duration>,
on_dismiss: Option<DismissHandler>,
style: StyleRefinement, style: StyleRefinement,
} }
@@ -79,9 +42,7 @@ impl Toast {
Self { Self {
message: message.into(), message: message.into(),
icon: None, icon: None,
action: None,
duration: Some(Self::DURATION), duration: Some(Self::DURATION),
on_dismiss: None,
style: StyleRefinement::default(), style: StyleRefinement::default(),
} }
} }
@@ -94,27 +55,6 @@ impl Toast {
self.icon = Some(icon.into()); self.icon = Some(icon.into());
self self
} }
/// Offers the user this action.
pub fn action(mut self, action: ToastAction) -> Self {
self.action = Some(action);
self
}
/// Sets the time before the toast dismisses itself.
pub fn duration(mut self, duration: Duration) -> Self {
self.duration = Some(duration);
self
}
/// Runs when the toast is dismissed by any means, once it is fully gone.
pub fn on_dismiss<F>(mut self, handler: F) -> Self
where
F: Fn(&mut App) + 'static,
{
self.on_dismiss = Some(Rc::new(handler));
self
}
} }
// Toast is a data builder, not an element, adopt the combinators explicitly. // Toast is a data builder, not an element, adopt the combinators explicitly.
@@ -127,6 +67,68 @@ pub struct ToastEntry {
pub toast: Toast, pub toast: Toast,
} }
impl ToastEntry {
/// The rendered pill for this toast.
fn pill(&self, toasts: &Entity<Toasts>, cx: &App) -> gpui::Stateful<gpui::Div> {
let theme = cx.theme();
let foreground = theme.colors.foreground;
let radius = theme.radius.full;
let toast = &self.toast;
let toasts = toasts.clone();
let id = self.id;
floating_panel(
cx,
radius,
div()
.id(("toast", id))
.debug_selector(|| "toast-pill".to_string())
.role(Role::Alert)
.aria_label(toast.message.clone())
.max_w(TOAST_MAX_WIDTH)
.flex()
.items_center()
.gap_2()
.py_1p5()
.px_3(),
theme.elevations.popover.shadows(),
)
.refine_style(&toast.style)
.when_some(toast.icon.clone(), |pill, icon| {
pill.child(
div()
.flex_none()
.flex()
.items_center()
.child(icon.size(rems(1.0)).color(foreground)),
)
})
.child(
div()
.flex_1()
.min_w(px(0.))
.truncate()
.text_sm()
.text_color(foreground)
.child(toast.message.clone()),
)
.child(
div().flex_none().child(
Button::new(("toast-close", id))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.small()
.accessibility_label("Dismiss")
.on_click(move |_, _window, cx| {
toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx);
});
}),
),
)
}
}
/// The store of raised toasts. /// The store of raised toasts.
#[derive(Default)] #[derive(Default)]
pub struct Toasts { pub struct Toasts {
@@ -177,33 +179,13 @@ impl Toasts {
} }
} }
/// Dismisses the toast on screen.
pub fn clear(&mut self, cx: &mut Context<Self>) {
if let Some(entry) = self.current.take() {
self.start_exit(entry, cx);
} else {
self.finish_exit(cx);
}
}
/// The toast now showing, if any. /// The toast now showing, if any.
pub fn current(&self) -> Option<&ToastEntry> { pub fn current(&self) -> Option<&ToastEntry> {
self.current.as_ref() self.current.as_ref()
} }
/// How many toasts are on screen, including one fading out.
pub fn count(&self) -> usize {
usize::from(self.current.is_some()) + usize::from(self.exiting.is_some())
}
/// Moves a toast into the fade-out phase. /// Moves a toast into the fade-out phase.
fn start_exit(&mut self, entry: ToastEntry, cx: &mut Context<Self>) { fn start_exit(&mut self, entry: ToastEntry, cx: &mut Context<Self>) {
if let Some(previous) = self.exiting.take()
&& let Some(on_dismiss) = &previous.toast.on_dismiss
{
on_dismiss(cx);
}
self.exiting = Some(entry); self.exiting = Some(entry);
cx.notify(); cx.notify();
@@ -217,11 +199,8 @@ impl Toasts {
} }
fn finish_exit(&mut self, cx: &mut Context<Self>) { fn finish_exit(&mut self, cx: &mut Context<Self>) {
if let Some(entry) = self.exiting.take() { if self.exiting.take().is_some() {
cx.notify(); cx.notify();
if let Some(on_dismiss) = &entry.toast.on_dismiss {
on_dismiss(cx);
}
} }
} }
} }
@@ -282,82 +261,3 @@ impl RenderOnce for ToastsView {
.with_priority(TOAST_LAYER) .with_priority(TOAST_LAYER)
} }
} }
impl ToastEntry {
/// The rendered pill for this toast.
fn pill(&self, toasts: &Entity<Toasts>, cx: &App) -> gpui::Stateful<gpui::Div> {
let theme = cx.theme();
let foreground = theme.colors.foreground;
let radius = theme.radius.full;
let toast = &self.toast;
let toasts = toasts.clone();
let id = self.id;
floating_panel(
cx,
radius,
div()
.id(("toast", id))
.debug_selector(|| "toast-pill".to_string())
.role(Role::Alert)
.aria_label(toast.message.clone())
.max_w(TOAST_MAX_WIDTH)
.flex()
.items_center()
.gap_2()
.py_1p5()
.px_3(),
theme.elevations.popover.shadows(),
)
.refine_style(&toast.style)
.when_some(toast.icon.clone(), |pill, icon| {
pill.child(
div()
.flex_none()
.flex()
.items_center()
.child(icon.size(rems(1.0)).color(foreground)),
)
})
.child(
div()
.flex_1()
.min_w(px(0.))
.truncate()
.text_sm()
.text_color(foreground)
.child(toast.message.clone()),
)
.when_some(toast.action.clone(), |pill, action| {
let toasts = toasts.clone();
pill.child(
div().flex_none().child(
Button::new(("toast-action", id))
.label(action.label.clone())
.variant(ButtonVariant::Primary)
.small()
.on_click(move |_, _window, cx| {
(action.handler)(cx);
toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx);
});
}),
),
)
})
.child(
div().flex_none().child(
Button::new(("toast-close", id))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.small()
.accessibility_label("Dismiss")
.on_click(move |_, _window, cx| {
toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx);
});
}),
),
)
}
}
+300 -113
View File
@@ -15,6 +15,8 @@
//! .on_change(|_selected, _window, _cx| println!("selection changed")); //! .on_change(|_selected, _window, _cx| println!("selection changed"));
//! ``` //! ```
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::rc::Rc; use std::rc::Rc;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
@@ -71,6 +73,16 @@ impl TreeItem {
} }
} }
/// The row's key: the path-like id its builder passed.
pub fn key(&self) -> &ElementId {
&self.key
}
/// Whether the row has children and paints a chevron.
pub fn is_expandable(&self) -> bool {
self.expandable
}
/// Shows a custom icon leading the label. /// Shows a custom icon leading the label.
pub fn icon<I>(mut self, icon: I) -> Self pub fn icon<I>(mut self, icon: I) -> Self
where where
@@ -103,11 +115,299 @@ impl TreeItem {
self.disabled = disabled; self.disabled = disabled;
self self
} }
#[allow(clippy::too_many_arguments)]
fn render_row(
&self,
cx: &App,
index: usize,
position_in_set: usize,
size_of_set: usize,
selected: bool,
on_change: &Option<ChangeHandler>,
on_disclosure: &Option<DisclosureHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
let label_color = selectable_label_color(cx, selected, self.disabled);
let disabled = self.disabled;
let depth = self.depth.min(TREE_MAX_DEPTH) as f32;
let indent = rems(0.75 * if self.depth == 0 { 0.5 } else { depth + 1.0 });
div()
.id((self.key.clone(), "tree-item"))
.relative()
.flex()
.items_center()
.gap_2()
.pl(indent)
.pr_2()
.py_1()
.min_h_8()
.rounded(theme.radius.sm)
.role(Role::TreeItem)
.aria_selected(selected)
.aria_level(self.depth + 1)
.aria_position_in_set(position_in_set)
.aria_size_of_set(size_of_set)
.when(self.expandable, |row| row.aria_expanded(self.expanded))
.map(|row| paint_selectable_row(cx, row, selected, disabled))
.when(!disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let on_disclosure = on_disclosure.clone();
let expandable = self.expandable;
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
// A folder row toggles with its own click, not just its chevron.
if expandable && let Some(on_disclosure) = &on_disclosure {
on_disclosure(index, window, cx);
}
}
})
})
.children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| {
let step = level as f32;
div()
.absolute()
.left(rems(0.75 * (step + 0.5)))
.top_0()
.bottom_0()
.border_l_1()
.border_color(theme.colors.border)
}))
.child(self.render_disclosure(cx, selected))
.when_some(
self.icon
.clone()
.or_else(|| (!self.expandable).then(|| icon(IconRole::File))),
|row, icon| row.child(icon.size(rems(1.0)).color(label_color)),
)
.child(
div()
.flex_1()
.text_color(label_color)
.child(self.label.clone()),
)
.into_any_element()
}
fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement {
let theme = cx.theme();
let glyph_color = if self.disabled || !selected {
theme.colors.muted_foreground
} else {
theme.colors.primary_foreground
};
// Only expandable rows draw a chevron; the empty cell keeps labels aligned with folders.
div()
.flex_none()
.size_4()
.flex()
.items_center()
.justify_center()
.when(self.expandable, |cell| {
cell.child(
icon(if self.expanded {
IconRole::ChevronDown
} else {
IconRole::ChevronRight
})
.size(rems(0.75))
.color(glyph_color),
)
})
.into_any_element()
}
} }
// TreeItem is a data builder, not an element, adopt the combinators explicitly. // TreeItem is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for TreeItem {} impl FluentBuilder for TreeItem {}
/// A nested path node; `flatten_all` turns a forest of these into rows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TreeItemSeed {
/// Path of the node, relative to the worktree root.
pub id: String,
pub label: String,
pub children: Vec<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<String>) -> Vec<TreeItem> {
fn push(
seed: &TreeItemSeed,
depth: usize,
expanded: &HashSet<String>,
rows: &mut Vec<TreeItem>,
) {
let is_expanded = expanded.contains(&seed.id);
let mut item = TreeItem::new(seed.id.clone(), seed.label.clone())
.depth(depth)
.expandable(!seed.children.is_empty())
.expanded(is_expanded);
if !seed.children.is_empty() {
item = item.icon(Icon::named(IconRole::Folder));
}
rows.push(item);
if is_expanded {
for child in &seed.children {
push(child, depth + 1, expanded, rows);
}
}
}
let mut rows = Vec::new();
for seed in seeds {
push(seed, 0, expanded, &mut rows);
}
rows
}
/// Every folder id, for starting with the tree fully expanded.
pub fn collect_expanded(seeds: &[TreeItemSeed]) -> HashSet<String> {
fn push(seed: &TreeItemSeed, expanded: &mut HashSet<String>) {
if !seed.children.is_empty() {
expanded.insert(seed.id.clone());
for child in &seed.children {
push(child, expanded);
}
}
}
let mut expanded = HashSet::new();
for seed in seeds {
push(seed, &mut expanded);
}
expanded
}
/// Builds nested tree items from a flat entry list sorted dirs-first.
pub fn from_paths(paths: &[PathBuf]) -> Vec<TreeItemSeed> {
// Node indices by full path, so parents resolve in constant time while inserting.
let mut index: HashMap<String, usize> = HashMap::new();
let mut nodes: Vec<(String, String, Vec<usize>)> = Vec::new();
let mut roots: Vec<usize> = Vec::new();
for entry in paths {
let mut parent: Option<usize> = None;
let mut path = String::new();
for part in entry.components() {
let label = part.as_os_str().to_string_lossy().into_owned();
path = if path.is_empty() {
label.clone()
} else {
format!("{path}/{label}")
};
let ix = *index.entry(path.clone()).or_insert_with(|| {
let ix = nodes.len();
nodes.push((path.clone(), label.clone(), Vec::new()));
match parent {
Some(parent) => nodes[parent].2.push(ix),
None => roots.push(ix),
}
ix
});
parent = Some(ix);
}
}
fn assemble(ix: usize, nodes: &[(String, String, Vec<usize>)]) -> TreeItemSeed {
let (id, label, children) = &nodes[ix];
TreeItemSeed {
id: id.clone(),
label: label.clone(),
children: children
.iter()
.map(|child| assemble(*child, nodes))
.collect(),
}
}
roots.iter().map(|root| assemble(*root, &nodes)).collect()
}
}
#[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. /// A tree of [`TreeItem`] rows with single selection and disclosure handling.
#[derive(IntoElement)] #[derive(IntoElement)]
#[must_use] #[must_use]
@@ -345,116 +645,3 @@ impl RenderOnce for Tree {
.children(rows) .children(rows)
} }
} }
impl TreeItem {
#[allow(clippy::too_many_arguments)]
fn render_row(
&self,
cx: &App,
index: usize,
position_in_set: usize,
size_of_set: usize,
selected: bool,
on_change: &Option<ChangeHandler>,
on_disclosure: &Option<DisclosureHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
let label_color = selectable_label_color(cx, selected, self.disabled);
let disabled = self.disabled;
let depth = self.depth.min(TREE_MAX_DEPTH) as f32;
let indent = rems(0.75 * if self.depth == 0 { 0.5 } else { depth + 1.0 });
div()
.id((self.key.clone(), "tree-item"))
.relative()
.flex()
.items_center()
.gap_2()
.pl(indent)
.pr_2()
.py_1()
.min_h_8()
.rounded(theme.radius.sm)
.role(Role::TreeItem)
.aria_selected(selected)
.aria_level(self.depth + 1)
.aria_position_in_set(position_in_set)
.aria_size_of_set(size_of_set)
.when(self.expandable, |row| row.aria_expanded(self.expanded))
.map(|row| paint_selectable_row(cx, row, selected, disabled))
.when(!disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let on_disclosure = on_disclosure.clone();
let expandable = self.expandable;
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
// A folder row toggles with its own click, not just its chevron.
if expandable && let Some(on_disclosure) = &on_disclosure {
on_disclosure(index, window, cx);
}
}
})
})
.children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| {
let step = level as f32;
div()
.absolute()
.left(rems(0.75 * (step + 0.5)))
.top_0()
.bottom_0()
.border_l_1()
.border_color(theme.colors.border)
}))
.child(self.render_disclosure(cx, selected))
.when_some(
self.icon
.clone()
.or_else(|| (!self.expandable).then(|| icon(IconRole::File))),
|row, icon| row.child(icon.size(rems(1.0)).color(label_color)),
)
.child(
div()
.flex_1()
.text_color(label_color)
.child(self.label.clone()),
)
.into_any_element()
}
fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement {
let theme = cx.theme();
let glyph_color = if self.disabled || !selected {
theme.colors.muted_foreground
} else {
theme.colors.primary_foreground
};
// Only expandable rows draw a chevron; the empty cell keeps labels aligned with folders.
div()
.flex_none()
.size_4()
.flex()
.items_center()
.justify_center()
.when(self.expandable, |cell| {
cell.child(
icon(if self.expanded {
IconRole::ChevronDown
} else {
IconRole::ChevronRight
})
.size(rems(0.75))
.color(glyph_color),
)
})
.into_any_element()
}
}
+2 -29
View File
@@ -1,5 +1,5 @@
//! Shared helpers for the editor's views: gutter cells, role colors and run //! Shared helpers for the editor's views: gutter cells, role colors and run
//! styles, code line text, language mapping and change washes. //! styles, code line text and language mapping.
use std::ops::Range; use std::ops::Range;
@@ -8,10 +8,7 @@ use gpui::{
}; };
use crate::components::highlight::{Language, Line, Role}; use crate::components::highlight::{Language, Line, Role};
use crate::theme::{ use crate::theme::{ActiveTheme as _, CODE_GUTTER_WIDTH, ColorTokens, Ramps};
ActiveTheme as _, CODE_GUTTER_WIDTH, ColorTokens, Ramps, WASH_ALPHA, WASH_ALPHA_GUTTER,
WASH_ALPHA_STRONG,
};
impl Role { impl Role {
/// Maps the role to the theme's semantic palette. /// Maps the role to the theme's semantic palette.
@@ -78,30 +75,6 @@ where
.child(content) .child(content)
} }
/// A change wash: the ramp color at the alpha rows tint with.
pub(crate) fn wash(color: Hsla) -> Hsla {
Hsla {
a: color.a * WASH_ALPHA,
..color
}
}
/// The stronger wash under number gutters and intra-line word changes.
pub(crate) fn wash_strong(color: Hsla) -> Hsla {
Hsla {
a: color.a * WASH_ALPHA_STRONG,
..color
}
}
/// The subtle wash that sets the number gutter off from the code.
pub(crate) fn wash_gutter(colors: &ColorTokens) -> Hsla {
Hsla {
a: colors.muted.a * WASH_ALPHA_GUTTER,
..colors.muted
}
}
/// One highlighted code line as styled text, roles resolved from the theme. /// One highlighted code line as styled text, roles resolved from the theme.
pub(crate) fn code_line(line: &Line, colors: ColorTokens, ramps: Ramps) -> StyledText { pub(crate) fn code_line(line: &Line, colors: ColorTokens, ramps: Ramps) -> StyledText {
let mut highlights: Vec<(Range<usize>, HighlightStyle)> = Vec::new(); let mut highlights: Vec<(Range<usize>, HighlightStyle)> = Vec::new();
+11 -11
View File
@@ -150,17 +150,6 @@ pub struct Icon {
rotation_period: Option<Duration>, rotation_period: Option<Duration>,
} }
/// Creates an icon for the role at the default size.
pub fn icon(role: IconRole) -> Icon {
Icon {
glyph: Glyph::Role(role),
size: AbsoluteLength::Rems(DEFAULT_ICON_SIZE),
color: None,
transformation: None,
rotation_period: None,
}
}
impl Icon { impl Icon {
/// Creates an icon from an application-defined icon set. /// Creates an icon from an application-defined icon set.
pub fn named<I>(named: I) -> Self pub fn named<I>(named: I) -> Self
@@ -306,3 +295,14 @@ impl AssetSource for Assets {
.collect()) .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,
}
}
+13 -13
View File
@@ -116,6 +116,19 @@ impl<P: PanelView + ?Sized> PanelView for Arc<P> {
} }
} }
/// The panel row drawn under the titlebar.
#[derive(IntoElement)]
#[must_use]
pub struct PanelRow {
id: ElementId,
main: Option<AnyElement>,
split: Option<AnyElement>,
/// The main pane's width when split; `None` splits the row in half.
split_width: Option<Pixels>,
resizable: bool,
style: StyleRefinement,
}
/// The layout the cached panel content lays out with. /// The layout the cached panel content lays out with.
fn content_style() -> StyleRefinement { fn content_style() -> StyleRefinement {
StyleRefinement::default().size_full() StyleRefinement::default().size_full()
@@ -135,19 +148,6 @@ fn island(panel: Div, cx: &App) -> Div {
.overflow_hidden() .overflow_hidden()
} }
/// The panel row drawn under the titlebar.
#[derive(IntoElement)]
#[must_use]
pub struct PanelRow {
id: ElementId,
main: Option<AnyElement>,
split: Option<AnyElement>,
/// The main pane's width when split; `None` splits the row in half.
split_width: Option<Pixels>,
resizable: bool,
style: StyleRefinement,
}
impl PanelRow { impl PanelRow {
/// Creates the panel row. /// Creates the panel row.
pub fn new<I>(id: I) -> Self pub fn new<I>(id: I) -> Self
+1 -1
View File
@@ -12,7 +12,7 @@ pub use icons::{Assets, Icon, IconRole};
/// Initializes the theme and every key binding the UI layer owns. /// Initializes the theme and every key binding the UI layer owns.
pub fn init(cx: &mut App) { pub fn init(cx: &mut App) {
theme::Theme::init(cx); theme::Theme::init(cx);
components::input::bind_input_keys(cx, None); components::input::bind_input_keys(cx);
components::combobox::bind_combobox_keys(cx); components::combobox::bind_combobox_keys(cx);
components::command_palette::bind_command_palette_keys(cx); components::command_palette::bind_command_palette_keys(cx);
components::code::bind_code_view_keys(cx); components::code::bind_code_view_keys(cx);
+14 -14
View File
@@ -7,14 +7,12 @@ use crate::theme::{
DEFAULT_TRANSPARENCY, MIN_MATERIAL_FILL_DARK, MIN_MATERIAL_FILL_LIGHT, ThemeVariant, DEFAULT_TRANSPARENCY, MIN_MATERIAL_FILL_DARK, MIN_MATERIAL_FILL_LIGHT, ThemeVariant,
}; };
fn hex(hex: u32) -> Hsla { /// Windows paints its caption close-button hover red in every theme.
rgb(hex).into() 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 dim scrim behind modal layers; always a translucent black. /// The close glyph's color over the red hover.
pub(crate) fn scrim(alpha: f32) -> Hsla { pub const WINDOWS_CLOSE_FOREGROUND: Hsla = gpui::white();
hsla(0., 0., 0., alpha)
}
/// The semantic color roles components paint from. /// The semantic color roles components paint from.
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
@@ -165,9 +163,11 @@ impl MaterialTokens {
} }
} }
/// Windows paints its caption close-button hover red in every theme. fn hex(hex: u32) -> Hsla {
pub const WINDOWS_CLOSE_HOVER: Hsla = hsla(0.986043, 0.863406, 0.488235, 1.0); rgb(hex).into()
/// 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. /// The dim scrim behind modal layers; always a translucent black.
pub const WINDOWS_CLOSE_FOREGROUND: Hsla = gpui::white(); pub(crate) fn scrim(alpha: f32) -> Hsla {
hsla(0., 0., 0., alpha)
}
-6
View File
@@ -113,12 +113,6 @@ pub const PROGRESS_ANIMATION_PERIOD: Duration = Duration::from_millis(1500);
pub const SCROLLBAR_AUTOHIDE_DELAY: Duration = Duration::from_millis(700); pub const SCROLLBAR_AUTOHIDE_DELAY: Duration = Duration::from_millis(700);
/// How long the autohide scrollbar's fade runs. /// How long the autohide scrollbar's fade runs.
pub const SCROLLBAR_FADE_DURATION: Duration = Duration::from_millis(250); pub const SCROLLBAR_FADE_DURATION: Duration = Duration::from_millis(250);
/// How much a change wash tints the rows it covers.
pub const WASH_ALPHA: f32 = 0.14;
/// The stronger wash under number gutters and intra-line word changes.
pub const WASH_ALPHA_STRONG: f32 = 0.34;
/// The subtle wash that sets the number gutter off from the code.
pub const WASH_ALPHA_GUTTER: f32 = 0.18;
/// The soft wash that marks the active code row. /// The soft wash that marks the active code row.
pub const WASH_ALPHA_SOFT: f32 = 0.45; pub const WASH_ALPHA_SOFT: f32 = 0.45;
/// How far a scrolling list renders past its viewport. /// How far a scrolling list renders past its viewport.
+10 -10
View File
@@ -40,6 +40,16 @@ impl Oklch {
} }
} }
/// The state shades components paint from for one accent color.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AccentShades {
pub base: Hsla,
pub hover: Hsla,
pub pressed: Hsla,
pub subtle: Hsla,
pub foreground: Hsla,
}
/// Mixes `a` toward `b` by `t` in OKLCH, taking the shortest arc between hues. /// Mixes `a` toward `b` by `t` in OKLCH, taking the shortest arc between hues.
/// ///
/// `t = 0` returns `a`, `t = 1` returns `b`. /// `t = 0` returns `a`, `t = 1` returns `b`.
@@ -152,16 +162,6 @@ pub fn contrast_foreground(background: Hsla) -> Hsla {
} }
} }
/// The state shades components paint from for one accent color.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AccentShades {
pub base: Hsla,
pub hover: Hsla,
pub pressed: Hsla,
pub subtle: Hsla,
pub foreground: Hsla,
}
/// Derives hover/pressed/subtle shades for an accent against its background. /// Derives hover/pressed/subtle shades for an accent against its background.
/// ///
/// Where a platform states ramps (WinUI, KDE) those are used instead, /// Where a platform states ramps (WinUI, KDE) those are used instead,
+89 -89
View File
@@ -31,33 +31,6 @@ enum Backend {
Fallback, Fallback,
} }
fn home_dir() -> Option<PathBuf> {
std::env::var_os("HOME").map(PathBuf::from)
}
/// Whether the session runs on Wayland, where compositors state blur protocols.
fn wayland_session() -> bool {
std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland")
}
fn detect(home: &Path, portal_reachable: bool, gsettings_reachable: bool) -> Backend {
let omarchy_marker = home
.join(".local/state/omarchy/current/theme.name")
.exists()
|| home.join(".local/state/omarchy/current/theme").is_dir()
|| home.join(".config/omarchy").is_dir();
if omarchy_marker {
Backend::Omarchy
} else if home.join(".config/kdeglobals").exists() {
Backend::Kde
} else if portal_reachable || gsettings_reachable {
Backend::Portal
} else {
Backend::Fallback
}
}
/// What `gsettings` states for GNOME sessions. /// What `gsettings` states for GNOME sessions.
#[derive(Clone, Copy, Debug, Default, PartialEq)] #[derive(Clone, Copy, Debug, Default, PartialEq)]
struct GSettingsSnapshot { struct GSettingsSnapshot {
@@ -65,68 +38,6 @@ struct GSettingsSnapshot {
accent: Option<Hsla>, accent: Option<Hsla>,
} }
fn gsettings_value(args: &[&str]) -> Option<String> {
let output = std::process::Command::new("gsettings")
.args(args)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout).ok()
}
/// The named accent colors GNOME ships (libadwaita's background variants).
fn accent_rgb(name: &str) -> Option<Hsla> {
let hex = match name {
"blue" => 0x3584e4,
"teal" => 0x2190a4,
"green" => 0x3a944a,
"yellow" => 0xc88800,
"orange" => 0xed5b00,
"red" => 0xe62d42,
"pink" => 0xd56199,
"purple" => 0x9141ac,
"slate" => 0x6f8396,
_ => return None,
};
Some(Hsla::from(gpui::rgb(hex)))
}
fn read_gsettings() -> Option<GSettingsSnapshot> {
let variant = gsettings_value(&["get", "org.gnome.desktop.interface", "color-scheme"])
.and_then(|value| match value.trim().trim_matches('\'') {
"prefer-dark" => Some(ThemeVariant::Dark),
"prefer-light" => Some(ThemeVariant::Light),
_ => None,
});
let accent = gsettings_value(&["get", "org.gnome.desktop.interface", "accent-color"])
.and_then(|value| accent_rgb(value.trim().trim_matches('\'')));
if variant.is_none() && accent.is_none() {
return None;
}
Some(GSettingsSnapshot { variant, accent })
}
pub(crate) fn platform_source() -> Box<dyn ThemeSource> {
let portal = portal::io::PortalClient::connect();
let gsettings = read_gsettings();
let backend = home_dir()
.map(|home| detect(&home, portal.is_some(), gsettings.is_some()))
.unwrap_or(Backend::Fallback);
Box::new(LinuxSource {
backend,
portal,
gsettings,
file_watcher: None,
_signal: None,
})
}
impl LinuxSource { impl LinuxSource {
fn gnome_snapshot( fn gnome_snapshot(
&self, &self,
@@ -280,3 +191,92 @@ impl ThemeSource for LinuxSource {
} }
} }
} }
fn home_dir() -> Option<PathBuf> {
std::env::var_os("HOME").map(PathBuf::from)
}
/// Whether the session runs on Wayland, where compositors state blur protocols.
fn wayland_session() -> bool {
std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland")
}
fn detect(home: &Path, portal_reachable: bool, gsettings_reachable: bool) -> Backend {
let omarchy_marker = home
.join(".local/state/omarchy/current/theme.name")
.exists()
|| home.join(".local/state/omarchy/current/theme").is_dir()
|| home.join(".config/omarchy").is_dir();
if omarchy_marker {
Backend::Omarchy
} else if home.join(".config/kdeglobals").exists() {
Backend::Kde
} else if portal_reachable || gsettings_reachable {
Backend::Portal
} else {
Backend::Fallback
}
}
fn gsettings_value(args: &[&str]) -> Option<String> {
let output = std::process::Command::new("gsettings")
.args(args)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout).ok()
}
/// The named accent colors GNOME ships (libadwaita's background variants).
fn accent_rgb(name: &str) -> Option<Hsla> {
let hex = match name {
"blue" => 0x3584e4,
"teal" => 0x2190a4,
"green" => 0x3a944a,
"yellow" => 0xc88800,
"orange" => 0xed5b00,
"red" => 0xe62d42,
"pink" => 0xd56199,
"purple" => 0x9141ac,
"slate" => 0x6f8396,
_ => return None,
};
Some(Hsla::from(gpui::rgb(hex)))
}
fn read_gsettings() -> Option<GSettingsSnapshot> {
let variant = gsettings_value(&["get", "org.gnome.desktop.interface", "color-scheme"])
.and_then(|value| match value.trim().trim_matches('\'') {
"prefer-dark" => Some(ThemeVariant::Dark),
"prefer-light" => Some(ThemeVariant::Light),
_ => None,
});
let accent = gsettings_value(&["get", "org.gnome.desktop.interface", "accent-color"])
.and_then(|value| accent_rgb(value.trim().trim_matches('\'')));
if variant.is_none() && accent.is_none() {
return None;
}
Some(GSettingsSnapshot { variant, accent })
}
pub(crate) fn platform_source() -> Box<dyn ThemeSource> {
let portal = portal::io::PortalClient::connect();
let gsettings = read_gsettings();
let backend = home_dir()
.map(|home| detect(&home, portal.is_some(), gsettings.is_some()))
.unwrap_or(Backend::Fallback);
Box::new(LinuxSource {
backend,
portal,
gsettings,
file_watcher: None,
_signal: None,
})
}
+9 -9
View File
@@ -44,15 +44,6 @@ define_class!(
} }
); );
impl ThemeObserver {
fn new(reapply: async_channel::Sender<()>) -> Retained<Self> {
let this = Self::alloc().set_ivars(reapply);
// SAFETY: `this` is freshly allocated with ivars set and not yet
// initialized, which is exactly the receiver `init` requires.
unsafe { msg_send![super(this), init] }
}
}
/// One watcher registration, kept so [`Drop`] can undo it. /// One watcher registration, kept so [`Drop`] can undo it.
enum Watcher { enum Watcher {
/// A distributed notification, registered by name. /// A distributed notification, registered by name.
@@ -82,6 +73,15 @@ pub(crate) struct MacosSource {
_signal: Option<ReapplySignal>, _signal: Option<ReapplySignal>,
} }
impl ThemeObserver {
fn new(reapply: async_channel::Sender<()>) -> Retained<Self> {
let this = Self::alloc().set_ivars(reapply);
// SAFETY: `this` is freshly allocated with ivars set and not yet initialized,
// which is exactly the receiver `init` requires.
unsafe { msg_send![super(this), init] }
}
}
impl MacosSource { impl MacosSource {
fn color_to_hsla(color: &NSColor) -> Option<gpui::Hsla> { fn color_to_hsla(color: &NSColor) -> Option<gpui::Hsla> {
let srgb = NSColorSpace::sRGBColorSpace(); let srgb = NSColorSpace::sRGBColorSpace();
+19 -19
View File
@@ -55,25 +55,6 @@ pub(crate) struct WindowsSource {
_signal: Option<ReapplySignal>, _signal: Option<ReapplySignal>,
} }
pub(crate) fn platform_source() -> Box<dyn ThemeSource> {
// SAFETY: WinRT activation requires COM on this thread; the STA matches
// the UI thread's message pump, and RPC_E_CHANGED_MODE means COM is
// already initialized in another apartment.
let initialized = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
if initialized.is_err() && initialized != RPC_E_CHANGED_MODE {
log::error!("theme: COM initialization failed: {initialized:?}");
}
match WindowsSource::new() {
Some(source) => Box::new(source),
None => {
log::warn!("theme: Windows system theme unavailable; using fallback");
Box::new(super::fallback::FallbackSource)
}
}
}
impl WindowsSource { impl WindowsSource {
fn new() -> Option<Self> { fn new() -> Option<Self> {
let ui_settings = match UISettings::new() { let ui_settings = match UISettings::new() {
@@ -206,3 +187,22 @@ impl ThemeSource for WindowsSource {
SourceKind::Windows.label() SourceKind::Windows.label()
} }
} }
pub(crate) fn platform_source() -> Box<dyn ThemeSource> {
// 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)
}
}
}
+8 -2
View File
@@ -46,30 +46,36 @@ fn main() {
KeyBinding::new("cmd-q", Quit, None), KeyBinding::new("cmd-q", Quit, None),
KeyBinding::new("ctrl-q", Quit, None), KeyBinding::new("ctrl-q", Quit, None),
]); ]);
cx.on_action(|_: &Quit, cx| cx.quit()); cx.on_action(|_: &Quit, cx| cx.quit());
cx.set_app_identity("info.reya.signed", "Signed");
let store = cx.new(|cx| SettingsStore::new(paths::settings_file(), cx)); let store = cx.new(|cx| SettingsStore::new(paths::settings_file(), cx));
SettingsStore::set_global(store.clone(), cx); SettingsStore::set_global(store.clone(), cx);
let settings = store.read(cx).settings().clone(); let settings = store.read(cx).settings().clone();
signed_app::apply_appearance(&settings, cx); signed_app::apply_appearance_mode(settings.appearance, cx);
if let Err(error) = std::fs::create_dir_all(paths::nostr_dir()) { if let Err(error) = std::fs::create_dir_all(paths::nostr_dir()) {
tracing::warn!("failed to create nostr dir: {error}"); tracing::warn!("failed to create nostr dir: {error}");
} }
if let Err(error) = std::fs::create_dir_all(paths::repos_dir()) { if let Err(error) = std::fs::create_dir_all(paths::repos_dir()) {
tracing::warn!("failed to create repos dir: {error}"); tracing::warn!("failed to create repos dir: {error}");
} }
signed_state::init( signed_state::init(
paths::nostr_dir(), paths::nostr_dir(),
paths::repos_dir().clone(), paths::repos_dir().clone(),
settings.local_repos.scan_paths.clone(), settings.local_repos.scan_paths.clone(),
cx, cx,
); );
metadata::init(cx); metadata::init(cx);
cx.set_app_identity("info.reya.signed", "Signed");
let theme = cx.theme(); let theme = cx.theme();
let bounds = Bounds::centered(None, size(px(1120.0), px(750.0)), cx); let bounds = Bounds::centered(None, size(px(1120.0), px(750.0)), cx);
let options = WindowOptions { let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)), window_bounds: Some(WindowBounds::Windowed(bounds)),
window_min_size: Some(size(px(960.0), px(640.0))), window_min_size: Some(size(px(960.0), px(640.0))),
+5
View File
@@ -4,3 +4,8 @@ Vendored `crates/ui` shortcomings recorded here instead of patched in place.
- `PanelRow` (`src/layout/panel.rs`) seeds its split panes from `window.viewport_size()` during the first render frame. On some launches that size is not yet the window's final bounds, so the divider freezes at a wrong position (observed ~24% instead of the intended 50%) until a drag or a double-click reset. Seeding from the canvas-measured extent, or re-seeding while no user resize has happened, would fix it. - `PanelRow` (`src/layout/panel.rs`) seeds its split panes from `window.viewport_size()` during the first render frame. On some launches that size is not yet the window's final bounds, so the divider freezes at a wrong position (observed ~24% instead of the intended 50%) until a drag or a double-click reset. Seeding from the canvas-measured extent, or re-seeding while no user resize has happened, would fix it.
- `island()` (`src/layout/panel.rs`) rounds and paints `overflow_hidden`, but gpui's `ContentMask` is rectangular only: children are never clipped to the rounded corners. Full-bleed panel content (photos, backgrounds) paints square over the island chrome and must apply the matching `theme.radius.overlay` itself — see the signed-out banner in `signed_app`. - `island()` (`src/layout/panel.rs`) rounds and paints `overflow_hidden`, but gpui's `ContentMask` is rectangular only: children are never clipped to the rounded corners. Full-bleed panel content (photos, backgrounds) paints square over the island chrome and must apply the matching `theme.radius.overlay` itself — see the signed-out banner in `signed_app`.
- The popup primitives extracted into `menu.rs` (`trigger_toggle`, `anchored_overlay`, `focus_capture`) cover the trigger-button, anchored-panel, and focus-grab surfaces. They do not cover lists: `ComboboxState` and `CommandPaletteState` keep their own entity-backed virtualized rows outside the `MenuItem` engine because menu rows are built per frame from a `Vec`, while both hold stateful selections the `uniform_list` drives. Any future row engine should absorb those two.
- `toast.rs` and `alert.rs` each re-implement the same scaffolding: a store entity with push/dismiss ids, an entry wrapper, a floating stack view with fade-out. Unification was declined for now; if either gains behavior the other lacks, extract the shared store/stack shell first.
- The toggle family (`checkbox.rs`, `switch.rs`, `toggle.rs`) restates the same control scaffolding three times: sizing, disabled handling, a `when(checked)` style fork, and an on-change handler with optimistic paint. A shared toggle base would shrink the trio.
- `StatusDot` and `Badge` both map a `*Variant` enum onto the same theme tokens (primary/success/warning/destructive ramps plus muted foreground). The tables are duplicated rather than shared.
- `ControlSizing` (`common.rs`) and the `Size::*_rems` methods (`theme`) are parallel lookup tables: one maps `Size` to control metrics, the other to glyph metrics. Adding a size means touching both.