chore: Improve Request Screening (#101)

* open chat while screening

* close panel on ignore

* bypass screening

* .

* improve settings

* refine modal

* .

* .

* .

* .

* .
This commit is contained in:
reya
2025-07-27 07:22:31 +07:00
committed by GitHub
parent 91cca37d69
commit 3cf9dde882
40 changed files with 1038 additions and 2035 deletions

View File

@@ -1,6 +1,10 @@
use std::sync::Arc;
use anyhow::{anyhow, Error};
use global::constants::IMAGE_RESIZE_SERVICE;
use gpui::SharedString;
use gpui::{Image, ImageFormat, SharedString};
use nostr_sdk::prelude::*;
use qrcode_generator::QrCodeEcc;
const FALLBACK_IMG: &str = "https://image.nostr.build/c30703b48f511c293a9003be8100cdad37b8798b77a1dc3ec6eb8a20443d5dea.png";
@@ -45,6 +49,53 @@ impl DisplayProfile for Profile {
}
}
pub trait TextUtils {
fn to_public_key(&self) -> Result<PublicKey, Error>;
fn to_qr(&self) -> Option<Arc<Image>>;
}
impl TextUtils for String {
fn to_public_key(&self) -> Result<PublicKey, Error> {
if self.starts_with("nprofile1") {
Ok(Nip19Profile::from_bech32(self)?.public_key)
} else if self.starts_with("npub1") {
Ok(PublicKey::parse(self)?)
} else {
Err(anyhow!("Invalid public key"))
}
}
fn to_qr(&self) -> Option<Arc<Image>> {
let Ok(bytes) = qrcode_generator::to_png_to_vec_from_str(self, QrCodeEcc::Medium, 256)
else {
return None;
};
Some(Arc::new(Image::from_bytes(ImageFormat::Png, bytes)))
}
}
impl TextUtils for &str {
fn to_public_key(&self) -> Result<PublicKey, Error> {
if self.starts_with("nprofile1") {
Ok(Nip19Profile::from_bech32(self)?.public_key)
} else if self.starts_with("npub1") {
Ok(PublicKey::parse(self)?)
} else {
Err(anyhow!("Invalid public key"))
}
}
fn to_qr(&self) -> Option<Arc<Image>> {
let Ok(bytes) = qrcode_generator::to_png_to_vec_from_str(self, QrCodeEcc::Medium, 256)
else {
return None;
};
Some(Arc::new(Image::from_bytes(ImageFormat::Png, bytes)))
}
}
pub fn shorten_pubkey(public_key: PublicKey, len: usize) -> SharedString {
let Ok(pubkey) = public_key.to_bech32();

View File

@@ -0,0 +1,47 @@
use std::collections::HashSet;
use std::hash::{DefaultHasher, Hash, Hasher};
use itertools::Itertools;
use nostr_sdk::prelude::*;
pub trait EventUtils {
fn uniq_id(&self) -> u64;
fn all_pubkeys(&self) -> Vec<PublicKey>;
fn compare_pubkeys(&self, other: &[PublicKey]) -> bool;
}
impl EventUtils for Event {
fn uniq_id(&self) -> u64 {
let mut hasher = DefaultHasher::new();
let mut pubkeys: Vec<PublicKey> = vec![];
// Add all public keys from event
pubkeys.push(self.pubkey);
pubkeys.extend(self.tags.public_keys().collect::<Vec<_>>());
// Generate unique hash
pubkeys
.into_iter()
.unique()
.sorted()
.collect::<Vec<_>>()
.hash(&mut hasher);
hasher.finish()
}
fn all_pubkeys(&self) -> Vec<PublicKey> {
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().copied().collect();
public_keys.push(self.pubkey);
public_keys
}
fn compare_pubkeys(&self, other: &[PublicKey]) -> bool {
let pubkeys = self.all_pubkeys();
let a: HashSet<_> = pubkeys.iter().collect();
let b: HashSet<_> = other.iter().collect();
a == b
}
}

View File

@@ -1,62 +1,6 @@
use std::collections::HashSet;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::Arc;
use anyhow::anyhow;
use gpui::{Image, ImageFormat};
use itertools::Itertools;
use nostr_sdk::prelude::*;
use qrcode_generator::QrCodeEcc;
pub mod debounced_delay;
pub mod display;
pub mod event;
pub mod handle_auth;
pub mod nip05;
pub mod nip96;
pub fn room_hash(event: &Event) -> u64 {
let mut hasher = DefaultHasher::new();
let mut pubkeys: Vec<PublicKey> = vec![];
// Add all public keys from event
pubkeys.push(event.pubkey);
pubkeys.extend(event.tags.public_keys().collect::<Vec<_>>());
// Generate unique hash
pubkeys
.into_iter()
.unique()
.sorted()
.collect::<Vec<_>>()
.hash(&mut hasher);
hasher.finish()
}
pub fn parse_pubkey_from_str(content: &str) -> Result<PublicKey, anyhow::Error> {
if content.starts_with("nprofile1") {
Ok(Nip19Profile::from_bech32(content)?.public_key)
} else if content.starts_with("npub1") {
Ok(PublicKey::parse(content)?)
} else {
Err(anyhow!("Invalid public key"))
}
}
pub fn string_to_qr(data: &str) -> Option<Arc<Image>> {
let Ok(bytes) = qrcode_generator::to_png_to_vec_from_str(data, QrCodeEcc::Medium, 256) else {
return None;
};
Some(Arc::new(Image::from_bytes(ImageFormat::Png, bytes)))
}
pub fn compare<T>(a: &[T], b: &[T]) -> bool
where
T: Eq + Hash,
{
let a: HashSet<_> = a.iter().collect();
let b: HashSet<_> = b.iter().collect();
a == b
}

View File

@@ -20,15 +20,14 @@ use ui::actions::OpenProfile;
use ui::button::{Button, ButtonVariants};
use ui::dock_area::dock::DockPlacement;
use ui::dock_area::panel::PanelView;
use ui::dock_area::{DockArea, DockItem};
use ui::dock_area::{ClosePanel, DockArea, DockItem};
use ui::modal::ModalButtonProps;
use ui::{ContextModal, IconName, Root, Sizable, StyledExt, TitleBar};
use crate::views::chat::{self, Chat};
use crate::views::screening::Screening;
use crate::views::user_profile::UserProfile;
use crate::views::{
login, new_account, onboarding, preferences, sidebar, startup, user_profile, welcome,
chat, login, new_account, onboarding, preferences, sidebar, startup, user_profile, welcome,
};
pub fn init(window: &mut Window, cx: &mut App) -> Entity<ChatSpace> {
@@ -74,7 +73,7 @@ pub struct ChatSpace {
dock: Entity<DockArea>,
toolbar: bool,
#[allow(unused)]
subscriptions: SmallVec<[Subscription; 6]>,
subscriptions: SmallVec<[Subscription; 5]>,
}
impl ChatSpace {
@@ -112,7 +111,6 @@ impl ChatSpace {
)
.child(
div()
.px_10()
.w_full()
.h_40()
.flex()
@@ -166,13 +164,6 @@ impl ChatSpace {
},
));
// Automatically load messages when chat panel opens
subscriptions.push(cx.observe_new::<Chat>(|this, window, cx| {
if let Some(window) = window {
this.load_messages(window, cx);
}
}));
// Automatically run on_load function when UserProfile is created
subscriptions.push(cx.observe_new::<UserProfile>(|this, window, cx| {
if let Some(window) = window {
@@ -183,7 +174,7 @@ impl ChatSpace {
// Automatically run on_load function when Screening is created
subscriptions.push(cx.observe_new::<Screening>(|this, window, cx| {
if let Some(window) = window {
this.on_load(window, cx);
this.load(window, cx);
}
}));
@@ -192,17 +183,33 @@ impl ChatSpace {
&registry,
window,
|this: &mut Self, _state, event, window, cx| {
if let RoomEmitter::Open(room) = event {
if let Some(room) = room.upgrade() {
this.dock.update(cx, |this, cx| {
let panel = chat::init(room, window, cx);
let placement = DockPlacement::Center;
match event {
RoomEmitter::Open(room) => {
if let Some(room) = room.upgrade() {
this.dock.update(cx, |this, cx| {
let panel = chat::init(room, window, cx);
// Load messages on panel creation
panel.update(cx, |this, cx| {
this.load_messages(window, cx);
});
this.add_panel(panel, placement, window, cx);
});
} else {
window.push_notification(t!("chatspace.failed_to_open_room"), cx);
this.add_panel(panel, DockPlacement::Center, window, cx);
});
} else {
window.push_notification(t!("chatspace.failed_to_open_room"), cx);
}
}
RoomEmitter::Close(..) => {
this.dock.update(cx, |this, cx| {
this.focus_tab_panel(window, cx);
cx.defer_in(window, |_, window, cx| {
window.dispatch_action(Box::new(ClosePanel), cx);
window.close_all_modals(cx);
});
});
}
_ => {}
}
},
));
@@ -283,10 +290,11 @@ impl ChatSpace {
pub fn open_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let settings = preferences::init(window, cx);
let title = SharedString::new(t!("chatspace.preferences_title"));
window.open_modal(cx, move |modal, _, _| {
modal
.title(SharedString::new(t!("chatspace.preferences_title")))
.title(title.clone())
.width(px(DEFAULT_MODAL_WIDTH))
.child(settings.clone())
});

View File

@@ -94,19 +94,23 @@ impl Chat {
subscriptions.push(cx.subscribe_in(
&input,
window,
move |this: &mut Self, input, event, window, cx| match event {
InputEvent::PressEnter { .. } => {
this.send_message(window, cx);
}
InputEvent::Change(text) => {
this.mention_popup(text, input, cx);
}
_ => {}
move |this: &mut Self, input, event, window, cx| {
match event {
InputEvent::PressEnter { .. } => {
this.send_message(window, cx);
}
InputEvent::Change(text) => {
this.mention_popup(text, input, cx);
}
_ => {}
};
},
));
subscriptions.push(
cx.subscribe_in(&room, window, move |this, _, incoming, _w, cx| {
subscriptions.push(cx.subscribe_in(
&room,
window,
move |this, _, incoming, _window, cx| {
// Check if the incoming message is the same as the new message created by optimistic update
if this.prevent_duplicate_message(&incoming.0, cx) {
return;
@@ -121,8 +125,8 @@ impl Chat {
});
this.list_state.splice(old_len..old_len, 1);
}),
);
},
));
// Initialize list state
// [item_count] always equal to 1 at the beginning
@@ -251,7 +255,7 @@ impl Chat {
// Get the message which includes all attachments
let content = self.input_content(cx);
// Get the backup setting
let backup = AppSettings::get_global(cx).settings.backup_messages;
let backup = AppSettings::get_backup_messages(cx);
// Return if message is empty
if content.trim().is_empty() {
@@ -397,7 +401,7 @@ impl Chat {
self.uploading(true, cx);
// Get the user's configured NIP96 server
let nip96_server = AppSettings::get_global(cx).settings.media_server.clone();
let nip96_server = AppSettings::get_media_server(cx);
// Open native file dialog
let paths = cx.prompt_for_paths(PathPromptOptions {
@@ -575,8 +579,8 @@ impl Chat {
return div().id(ix);
};
let proxy = AppSettings::get_global(cx).settings.proxy_user_avatars;
let hide_avatar = AppSettings::get_global(cx).settings.hide_user_avatars;
let proxy = AppSettings::get_proxy_user_avatars(cx);
let hide_avatar = AppSettings::get_hide_user_avatars(cx);
let registry = Registry::read_global(cx);
let author = registry.get_person(&message.author, cx);
@@ -715,8 +719,6 @@ impl Chat {
.flex()
.flex_col()
.gap_2()
.px_3()
.pb_3()
.children(errors.iter().map(|error| {
div()
.text_sm()
@@ -792,7 +794,7 @@ impl Panel for Chat {
fn title(&self, cx: &App) -> AnyElement {
self.room.read_with(cx, |this, cx| {
let proxy = AppSettings::get_global(cx).settings.proxy_user_avatars;
let proxy = AppSettings::get_proxy_user_avatars(cx);
let label = this.display_name(cx);
let url = this.display_image(proxy, cx);

View File

@@ -1,6 +1,6 @@
use gpui::{
div, App, AppContext, Context, Entity, FocusHandle, InteractiveElement, IntoElement,
ParentElement, Render, SharedString, Styled, Window,
div, App, AppContext, Context, Entity, IntoElement, ParentElement, Render, SharedString,
Styled, Window,
};
use i18n::t;
use registry::Registry;
@@ -21,7 +21,6 @@ pub fn init(
pub struct Subject {
id: u64,
input: Entity<InputState>,
focus_handle: FocusHandle,
}
impl Subject {
@@ -39,11 +38,7 @@ impl Subject {
this
});
cx.new(|cx| Self {
id,
input,
focus_handle: cx.focus_handle(),
})
cx.new(|_| Self { id, input })
}
pub fn update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -65,13 +60,9 @@ impl Subject {
impl Render for Subject {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.track_focus(&self.focus_handle)
.size_full()
.flex()
.flex_col()
.gap_3()
.px_3()
.pb_3()
.child(
div()
.flex()

View File

@@ -2,7 +2,7 @@ use std::ops::Range;
use std::time::Duration;
use anyhow::{anyhow, Error};
use common::display::DisplayProfile;
use common::display::{DisplayProfile, TextUtils};
use common::nip05::nip05_profile;
use global::constants::BOOTSTRAP_RELAYS;
use global::nostr_client;
@@ -24,7 +24,7 @@ use theme::ActiveTheme;
use ui::button::{Button, ButtonVariants};
use ui::input::{InputEvent, InputState, TextInput};
use ui::notification::Notification;
use ui::{ContextModal, Disableable, Icon, IconName, Sizable, StyledExt};
use ui::{v_flex, ContextModal, Disableable, Icon, IconName, Sizable, StyledExt};
pub fn init(window: &mut Window, cx: &mut App) -> Entity<Compose> {
cx.new(|cx| Compose::new(window, cx))
@@ -278,7 +278,7 @@ impl Compose {
Err(anyhow!(t!("common.not_found")))
}
})
} else if let Ok(public_key) = common::parse_pubkey_from_str(&content) {
} else if let Ok(public_key) = content.to_public_key() {
cx.background_spawn(async move {
let client = nostr_client();
let contact = Contact::new(public_key).select();
@@ -357,7 +357,7 @@ impl Compose {
}
fn list_items(&self, range: Range<usize>, cx: &Context<Self>) -> Vec<impl IntoElement> {
let proxy = AppSettings::get_global(cx).settings.proxy_user_avatars;
let proxy = AppSettings::get_proxy_user_avatars(cx);
let registry = Registry::read_global(cx);
let mut items = Vec::with_capacity(self.contacts.len());
@@ -420,22 +420,19 @@ impl Render for Compose {
t!("compose.create_dm_button")
};
div()
.flex()
.flex_col()
v_flex()
.gap_1()
.child(
div()
.px_3()
.text_sm()
.text_color(cx.theme().text_muted)
.child(SharedString::new(t!("compose.description"))),
)
.when_some(self.error_message.read(cx).as_ref(), |this, msg| {
this.child(div().px_3().text_xs().text_color(red()).child(msg.clone()))
this.child(div().text_xs().text_color(red()).child(msg.clone()))
})
.child(
div().px_3().flex().flex_col().child(
div().flex().flex_col().child(
div()
.h_10()
.border_b_1()
@@ -460,7 +457,6 @@ impl Render for Compose {
.mt_1()
.child(
div()
.px_3()
.flex()
.flex_col()
.gap_2()
@@ -535,17 +531,15 @@ impl Render for Compose {
}),
)
.child(
div().p_3().child(
Button::new("create_dm_btn")
.label(label)
.primary()
.w_full()
.loading(self.submitting)
.disabled(self.submitting || self.adding)
.on_click(cx.listener(move |this, _event, window, cx| {
this.compose(window, cx);
})),
),
Button::new("create_dm_btn")
.label(label)
.primary()
.w_full()
.loading(self.submitting)
.disabled(self.submitting || self.adding)
.on_click(cx.listener(move |this, _event, window, cx| {
this.compose(window, cx);
})),
)
}
}

View File

@@ -106,7 +106,7 @@ impl EditProfile {
}
fn upload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let nip96 = AppSettings::get_global(cx).settings.media_server.clone();
let nip96 = AppSettings::get_media_server(cx);
let avatar_input = self.avatar_input.downgrade();
let paths = cx.prompt_for_paths(PathPromptOptions {
files: true,
@@ -233,7 +233,6 @@ impl EditProfile {
impl Render for EditProfile {
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.flex()
.flex_col()
.gap_3()

View File

@@ -2,8 +2,8 @@ use std::sync::Arc;
use std::time::Duration;
use client_keys::ClientKeys;
use common::display::TextUtils;
use common::handle_auth::CoopAuthUrlHandler;
use common::string_to_qr;
use global::constants::{APP_NAME, NOSTR_CONNECT_RELAY, NOSTR_CONNECT_TIMEOUT};
use gpui::prelude::FluentBuilder;
use gpui::{
@@ -99,7 +99,7 @@ impl Login {
// Update the QR Image with the new connection string
this.qr_image.update(cx, |this, cx| {
*this = string_to_qr(&connection_string.to_string());
*this = connection_string.to_string().to_qr();
cx.notify();
});
@@ -234,8 +234,6 @@ impl Login {
})
.child(
div()
.pt_4()
.px_4()
.w_full()
.flex()
.flex_col()

View File

@@ -118,8 +118,6 @@ impl NewAccount {
})
.child(
div()
.pt_4()
.px_4()
.w_full()
.flex()
.flex_col()
@@ -132,7 +130,7 @@ impl NewAccount {
}
fn upload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let nip96 = AppSettings::get_global(cx).settings.media_server.clone();
let nip96 = AppSettings::get_media_server(cx);
let avatar_input = self.avatar_input.downgrade();
let paths = cx.prompt_for_paths(PathPromptOptions {
files: true,

View File

@@ -134,8 +134,8 @@ impl Focusable for Onboarding {
impl Render for Onboarding {
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
let auto_login = AppSettings::get_global(cx).settings.auto_login;
let proxy = AppSettings::get_global(cx).settings.proxy_user_avatars;
let auto_login = AppSettings::get_auto_login(cx);
let proxy = AppSettings::get_proxy_user_avatars(cx);
div()
.py_4()
@@ -239,11 +239,8 @@ impl Render for Onboarding {
Checkbox::new("auto_login")
.label(SharedString::new(t!("onboarding.auto_login")))
.checked(auto_login)
.on_click(|_, _window, cx| {
AppSettings::global(cx).update(cx, |this, cx| {
this.settings.auto_login = !this.settings.auto_login;
cx.notify();
})
.on_click(move |_, _window, cx| {
AppSettings::update_auto_login(!auto_login, cx);
}),
)
.child(

View File

@@ -3,8 +3,8 @@ use global::constants::{DEFAULT_MODAL_WIDTH, NIP96_SERVER};
use gpui::http_client::Url;
use gpui::prelude::FluentBuilder;
use gpui::{
div, px, relative, rems, App, AppContext, Context, Entity, FocusHandle, InteractiveElement,
IntoElement, ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, Window,
div, px, relative, rems, App, AppContext, Context, Entity, InteractiveElement, IntoElement,
ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, Window,
};
use i18n::t;
use identity::Identity;
@@ -15,7 +15,7 @@ use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariants};
use ui::input::{InputState, TextInput};
use ui::switch::Switch;
use ui::{ContextModal, IconName, Sizable, Size, StyledExt};
use ui::{v_flex, ContextModal, IconName, Sizable, Size, StyledExt};
use crate::views::{edit_profile, relays};
@@ -25,27 +25,19 @@ pub fn init(window: &mut Window, cx: &mut App) -> Entity<Preferences> {
pub struct Preferences {
media_input: Entity<InputState>,
focus_handle: FocusHandle,
}
impl Preferences {
pub fn new(window: &mut Window, cx: &mut App) -> Entity<Self> {
cx.new(|cx| {
let media_server = AppSettings::get_global(cx)
.settings
.media_server
.to_string();
let media_server = AppSettings::get_media_server(cx).to_string();
let media_input = cx.new(|cx| {
InputState::new(window, cx)
.default_value(media_server)
.placeholder(NIP96_SERVER)
});
Self {
media_input,
focus_handle: cx.focus_handle(),
}
Self { media_input }
})
}
@@ -75,22 +67,18 @@ impl Preferences {
impl Render for Preferences {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let registry = Registry::read_global(cx);
let settings = AppSettings::get_global(cx).settings.as_ref();
let input_state = self.media_input.downgrade();
let profile = Identity::read_global(cx)
.public_key()
.map(|pk| registry.get_person(&pk, cx));
.map(|pk| Registry::read_global(cx).get_person(&pk, cx));
let input_state = self.media_input.downgrade();
let backup_messages = AppSettings::get_backup_messages(cx);
let screening = AppSettings::get_screening(cx);
let contact_bypass = AppSettings::get_contact_bypass(cx);
let proxy_avatar = AppSettings::get_proxy_user_avatars(cx);
let hide_avatar = AppSettings::get_hide_user_avatars(cx);
div()
.track_focus(&self.focus_handle)
.size_full()
.px_3()
.pb_3()
.flex()
.flex_col()
v_flex()
.child(
div()
.py_2()
@@ -118,10 +106,8 @@ impl Render for Preferences {
.items_center()
.gap_2()
.child(
Avatar::new(
profile.avatar_url(settings.proxy_user_avatars),
)
.size(rems(2.4)),
Avatar::new(profile.avatar_url(proxy_avatar))
.size(rems(2.4)),
)
.child(
div()
@@ -187,19 +173,14 @@ impl Render for Preferences {
.with_size(Size::Size(px(26.)))
.on_click(move |_, window, cx| {
if let Some(input) = input_state.upgrade() {
let value = input.read(cx).value();
let Ok(url) = Url::parse(value) else {
let Ok(url) = Url::parse(input.read(cx).value()) else {
window.push_notification(
t!("preferences.url_not_valid"),
cx,
);
return;
};
AppSettings::global(cx).update(cx, |this, cx| {
this.settings.media_server = url;
cx.notify();
});
AppSettings::update_media_server(url, cx);
}
}),
),
@@ -227,19 +208,37 @@ impl Render for Preferences {
.child(SharedString::new(t!("preferences.messages_header"))),
)
.child(
div().flex().flex_col().gap_2().child(
Switch::new("backup_messages")
.label(t!("preferences.backup_messages_label"))
.description(t!("preferences.backup_description"))
.checked(settings.backup_messages)
.on_click(|_, _window, cx| {
AppSettings::global(cx).update(cx, |this, cx| {
this.settings.backup_messages =
!this.settings.backup_messages;
cx.notify();
})
}),
),
div()
.flex()
.flex_col()
.gap_2()
.child(
Switch::new("screening")
.label(t!("preferences.screening_label"))
.description(t!("preferences.screening_description"))
.checked(screening)
.on_click(move |_, _window, cx| {
AppSettings::update_screening(!screening, cx);
}),
)
.child(
Switch::new("bypass")
.label(t!("preferences.bypass_label"))
.description(t!("preferences.bypass_description"))
.checked(contact_bypass)
.on_click(move |_, _window, cx| {
AppSettings::update_contact_bypass(!contact_bypass, cx);
}),
)
.child(
Switch::new("backup_messages")
.label(t!("preferences.backup_messages_label"))
.description(t!("preferences.backup_description"))
.checked(backup_messages)
.on_click(move |_, _window, cx| {
AppSettings::update_backup_messages(!backup_messages, cx);
}),
),
),
)
.child(
@@ -266,26 +265,18 @@ impl Render for Preferences {
Switch::new("hide_user_avatars")
.label(t!("preferences.hide_avatars_label"))
.description(t!("preferences.hide_avatar_description"))
.checked(settings.hide_user_avatars)
.on_click(|_, _window, cx| {
AppSettings::global(cx).update(cx, |this, cx| {
this.settings.hide_user_avatars =
!this.settings.hide_user_avatars;
cx.notify();
})
.checked(hide_avatar)
.on_click(move |_, _window, cx| {
AppSettings::update_hide_user_avatars(!hide_avatar, cx);
}),
)
.child(
Switch::new("proxy_user_avatars")
.label(t!("preferences.proxy_avatars_label"))
.description(t!("preferences.proxy_description"))
.checked(settings.proxy_user_avatars)
.on_click(|_, _window, cx| {
AppSettings::global(cx).update(cx, |this, cx| {
this.settings.proxy_user_avatars =
!this.settings.proxy_user_avatars;
cx.notify();
})
.checked(proxy_avatar)
.on_click(move |_, _window, cx| {
AppSettings::update_proxy_user_avatars(!proxy_avatar, cx);
}),
),
),

View File

@@ -1,13 +1,12 @@
use common::display::{shorten_pubkey, DisplayProfile};
use common::nip05::nip05_verify;
use global::nostr_client;
use gpui::prelude::FluentBuilder;
use gpui::{
div, relative, rems, App, AppContext, Context, Entity, IntoElement, ParentElement, Render,
div, relative, rems, App, AppContext, Context, Div, Entity, IntoElement, ParentElement, Render,
SharedString, Styled, Task, Window,
};
use gpui_tokio::Tokio;
use i18n::t;
use i18n::{shared_t, t};
use identity::Identity;
use nostr_sdk::prelude::*;
use registry::Registry;
@@ -23,30 +22,31 @@ pub fn init(public_key: PublicKey, window: &mut Window, cx: &mut App) -> Entity<
pub struct Screening {
public_key: PublicKey,
followed: bool,
connections: usize,
verified: bool,
followed: bool,
dm_relays: bool,
mutual_contacts: usize,
}
impl Screening {
pub fn new(public_key: PublicKey, _window: &mut Window, cx: &mut App) -> Entity<Self> {
cx.new(|_| Self {
public_key,
followed: false,
connections: 0,
verified: false,
followed: false,
dm_relays: false,
mutual_contacts: 0,
})
}
pub fn on_load(&mut self, window: &mut Window, cx: &mut Context<Self>) {
pub fn load(&mut self, window: &mut Window, cx: &mut Context<Self>) {
// Skip if user isn't logged in
let Some(identity) = Identity::read_global(cx).public_key() else {
return;
};
let public_key = self.public_key;
let check_trust_score: Task<(bool, usize)> = cx.background_spawn(async move {
let check_trust_score: Task<(bool, usize, bool)> = cx.background_spawn(async move {
let client = nostr_client();
let follow = Filter::new()
@@ -55,15 +55,21 @@ impl Screening {
.pubkey(public_key)
.limit(1);
let connection = Filter::new()
let contacts = Filter::new()
.kind(Kind::ContactList)
.pubkey(public_key)
.limit(1);
let is_follow = client.database().count(follow).await.unwrap_or(0) >= 1;
let connects = client.database().count(connection).await.unwrap_or(0);
let relays = Filter::new()
.kind(Kind::InboxRelays)
.author(public_key)
.limit(1);
(is_follow, connects)
let is_follow = client.database().count(follow).await.unwrap_or(0) >= 1;
let mutual_contacts = client.database().count(contacts).await.unwrap_or(0);
let dm_relays = client.database().count(relays).await.unwrap_or(0) >= 1;
(is_follow, mutual_contacts, dm_relays)
});
let verify_nip05 = if let Some(address) = self.address(cx) {
@@ -75,11 +81,12 @@ impl Screening {
};
cx.spawn_in(window, async move |this, cx| {
let (followed, connections) = check_trust_score.await;
let (followed, mutual_contacts, dm_relays) = check_trust_score.await;
this.update(cx, |this, cx| {
this.followed = followed;
this.connections = connections;
this.mutual_contacts = mutual_contacts;
this.dm_relays = dm_relays;
cx.notify();
})
.ok();
@@ -140,15 +147,11 @@ impl Screening {
impl Render for Screening {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let proxy = AppSettings::get_global(cx).settings.proxy_user_avatars;
let proxy = AppSettings::get_proxy_user_avatars(cx);
let profile = self.profile(cx);
let shorten_pubkey = shorten_pubkey(profile.public_key(), 8);
v_flex()
.w_full()
.px_4()
.pt_8()
.pb_4()
.gap_4()
.child(
v_flex()
@@ -166,7 +169,7 @@ impl Render for Screening {
)
.child(
h_flex()
.gap_1()
.gap_3()
.child(
div()
.p_1()
@@ -176,7 +179,7 @@ impl Render for Screening {
.items_center()
.justify_center()
.rounded_full()
.bg(cx.theme().elevated_surface_background)
.bg(cx.theme().surface_background)
.text_sm()
.truncate()
.text_ellipsis()
@@ -185,104 +188,138 @@ impl Render for Screening {
.child(shorten_pubkey),
)
.child(
Button::new("njump")
.label(t!("profile.njump"))
.secondary()
.small()
.rounded(ButtonRounded::Full)
.on_click(cx.listener(move |this, _e, window, cx| {
this.open_njump(window, cx);
})),
)
.child(
Button::new("report")
.tooltip(t!("screening.report"))
.icon(IconName::Info)
.danger_alt()
.small()
.rounded(ButtonRounded::Full)
.on_click(cx.listener(move |this, _e, window, cx| {
this.report(window, cx);
})),
h_flex()
.gap_1()
.child(
Button::new("njump")
.label(t!("profile.njump"))
.secondary()
.small()
.rounded(ButtonRounded::Full)
.on_click(cx.listener(move |this, _e, window, cx| {
this.open_njump(window, cx);
})),
)
.child(
Button::new("report")
.tooltip(t!("screening.report"))
.icon(IconName::Report)
.danger()
.rounded(ButtonRounded::Full)
.on_click(cx.listener(move |this, _e, window, cx| {
this.report(window, cx);
})),
),
),
)
.child(
v_flex()
.gap_2()
.when_some(self.address(cx), |this, address| {
this.child(h_flex().gap_2().map(|this| {
if self.verified {
this.text_sm()
.child(
Icon::new(IconName::CheckCircleFill)
.small()
.flex_shrink_0()
.text_color(cx.theme().icon_accent),
)
.child(div().flex_1().child(SharedString::new(t!(
"screening.verified",
address = address
))))
} else {
this.text_sm()
.child(
Icon::new(IconName::CheckCircleFill)
.small()
.text_color(cx.theme().icon_muted),
)
.child(div().flex_1().child(SharedString::new(t!(
"screening.not_verified",
address = address
))))
}
}))
})
.child(h_flex().gap_2().map(|this| {
if !self.followed {
this.text_sm()
.child(
Icon::new(IconName::CheckCircleFill)
.small()
.text_color(cx.theme().icon_muted),
)
.child(SharedString::new(t!("screening.not_contact")))
} else {
this.text_sm()
.child(
Icon::new(IconName::CheckCircleFill)
.small()
.text_color(cx.theme().icon_accent),
)
.child(SharedString::new(t!("screening.contact")))
}
}))
.gap_3()
.child(
h_flex()
.items_start()
.gap_2()
.text_sm()
.child(status_badge(self.followed, cx))
.child(
Icon::new(IconName::CheckCircleFill)
.small()
.flex_shrink_0()
.text_color({
if self.connections > 0 {
cx.theme().icon_accent
v_flex()
.text_sm()
.child(shared_t!("screening.contact_label"))
.child(div().text_color(cx.theme().text_muted).child({
if self.followed {
shared_t!("screening.contact")
} else {
cx.theme().icon_muted
shared_t!("screening.not_contact")
}
}),
)
.map(|this| {
if self.connections > 0 {
this.child(SharedString::new(t!(
"screening.total_connections",
u = self.connections
)))
} else {
this.child(SharedString::new(t!("screening.no_connections")))
}
}),
})),
),
)
.child(
h_flex()
.items_start()
.gap_2()
.child(status_badge(self.verified, cx))
.child(
v_flex()
.text_sm()
.child({
if let Some(addr) = self.address(cx) {
shared_t!("screening.nip05_addr", addr = addr)
} else {
shared_t!("screening.nip05_label")
}
})
.child(div().text_color(cx.theme().text_muted).child({
if self.address(cx).is_some() {
if self.verified {
shared_t!("screening.nip05_ok")
} else {
shared_t!("screening.nip05_failed")
}
} else {
shared_t!("screening.nip05_empty")
}
})),
),
)
.child(
h_flex()
.items_start()
.gap_2()
.child(status_badge(self.mutual_contacts > 0, cx))
.child(
v_flex()
.text_sm()
.child(shared_t!("screening.mutual_label"))
.child(div().text_color(cx.theme().text_muted).child({
if self.mutual_contacts > 0 {
shared_t!("screening.mutual", u = self.mutual_contacts)
} else {
shared_t!("screening.no_mutual")
}
})),
),
)
.child(
h_flex()
.items_start()
.gap_2()
.child(status_badge(self.dm_relays, cx))
.child(
v_flex()
.w_full()
.text_sm()
.child({
if self.dm_relays {
shared_t!("screening.relay_found")
} else {
shared_t!("screening.relay_empty")
}
})
.child(div().w_full().text_color(cx.theme().text_muted).child(
{
if self.dm_relays {
shared_t!("screening.relay_found_desc")
} else {
shared_t!("screening.relay_empty_desc")
}
},
)),
),
),
)
}
}
fn status_badge(status: bool, cx: &App) -> Div {
div()
.pt_1()
.flex_shrink_0()
.child(Icon::new(IconName::CheckCircleFill).small().text_color({
if status {
cx.theme().icon_accent
} else {
cx.theme().icon_muted
}
}))
}

View File

@@ -2,12 +2,13 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder;
use gpui::{
div, img, rems, App, ClickEvent, Div, InteractiveElement, IntoElement,
ParentElement as _, RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window,
div, rems, App, ClickEvent, Div, InteractiveElement, IntoElement, ParentElement as _,
RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window,
};
use i18n::t;
use nostr_sdk::prelude::*;
use registry::room::RoomKind;
use registry::Registry;
use settings::AppSettings;
use theme::ActiveTheme;
use ui::actions::OpenProfile;
@@ -22,49 +23,39 @@ use crate::views::screening;
pub struct RoomListItem {
ix: usize,
base: Div,
room_id: u64,
public_key: PublicKey,
name: Option<SharedString>,
avatar: Option<SharedString>,
created_at: Option<SharedString>,
kind: Option<RoomKind>,
name: SharedString,
avatar: SharedString,
created_at: SharedString,
kind: RoomKind,
#[allow(clippy::type_complexity)]
handler: Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>,
}
impl RoomListItem {
pub fn new(ix: usize, public_key: PublicKey) -> Self {
pub fn new(
ix: usize,
room_id: u64,
public_key: PublicKey,
name: SharedString,
avatar: SharedString,
created_at: SharedString,
kind: RoomKind,
) -> Self {
Self {
ix,
public_key,
room_id,
name,
avatar,
created_at,
kind,
base: h_flex().h_9().w_full().px_1p5(),
name: None,
avatar: None,
created_at: None,
kind: None,
handler: Rc::new(|_, _, _| {}),
}
}
pub fn name(mut self, name: impl Into<SharedString>) -> Self {
self.name = Some(name.into());
self
}
pub fn created_at(mut self, created_at: impl Into<SharedString>) -> Self {
self.created_at = Some(created_at.into());
self
}
pub fn avatar(mut self, avatar: impl Into<SharedString>) -> Self {
self.avatar = Some(avatar.into());
self
}
pub fn kind(mut self, kind: RoomKind) -> Self {
self.kind = Some(kind);
self
}
pub fn on_click(
mut self,
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
@@ -77,10 +68,11 @@ impl RoomListItem {
impl RenderOnce for RoomListItem {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let public_key = self.public_key;
let room_id = self.room_id;
let kind = self.kind;
let handler = self.handler.clone();
let hide_avatar = AppSettings::get_global(cx).settings.hide_user_avatars;
let screening = AppSettings::get_global(cx).settings.screening;
let hide_avatar = AppSettings::get_hide_user_avatars(cx);
let require_screening = AppSettings::get_screening(cx);
self.base
.id(self.ix)
@@ -94,18 +86,7 @@ impl RenderOnce for RoomListItem {
.size_6()
.rounded_full()
.overflow_hidden()
.map(|this| {
if let Some(img) = self.avatar {
this.child(Avatar::new(img).size(rems(1.5)))
} else {
this.child(
img("brand/avatar.png")
.rounded_full()
.size_6()
.into_any_element(),
)
}
}),
.child(Avatar::new(self.avatar).size(rems(1.5))),
)
})
.child(
@@ -114,26 +95,22 @@ impl RenderOnce for RoomListItem {
.flex()
.items_center()
.justify_between()
.when_some(self.name, |this, name| {
this.child(
div()
.flex_1()
.line_clamp(1)
.text_ellipsis()
.truncate()
.font_medium()
.child(name),
)
})
.when_some(self.created_at, |this, ago| {
this.child(
div()
.flex_shrink_0()
.text_xs()
.text_color(cx.theme().text_placeholder)
.child(ago),
)
}),
.child(
div()
.flex_1()
.line_clamp(1)
.text_ellipsis()
.truncate()
.font_medium()
.child(self.name),
)
.child(
div()
.flex_shrink_0()
.text_xs()
.text_color(cx.theme().text_placeholder)
.child(self.created_at),
),
)
.context_menu(move |this, _window, _cx| {
// TODO: add share chat room
@@ -141,33 +118,28 @@ impl RenderOnce for RoomListItem {
})
.hover(|this| this.bg(cx.theme().elevated_surface_background))
.on_click(move |event, window, cx| {
let handler = handler.clone();
handler(event, window, cx);
if let Some(kind) = kind {
if kind != RoomKind::Ongoing && screening {
let screening = screening::init(public_key, window, cx);
if kind != RoomKind::Ongoing && require_screening {
let screening = screening::init(public_key, window, cx);
window.open_modal(cx, move |this, _window, _cx| {
let handler_clone = handler.clone();
this.confirm()
.child(screening.clone())
.button_props(
ModalButtonProps::default()
.cancel_text(t!("screening.ignore"))
.ok_text(t!("screening.response")),
)
.on_ok(move |event, window, cx| {
handler_clone(event, window, cx);
// true to close the modal
true
})
});
} else {
handler(event, window, cx)
}
} else {
handler(event, window, cx)
window.open_modal(cx, move |this, _window, _cx| {
this.confirm()
.child(screening.clone())
.button_props(
ModalButtonProps::default()
.cancel_text(t!("screening.ignore"))
.ok_text(t!("screening.response")),
)
.on_cancel(move |_event, _window, cx| {
Registry::global(cx).update(cx, |this, cx| {
this.close_room(room_id, cx);
});
// false to prevent closing the modal
// modal will be closed after closing panel
false
})
});
}
})
}

View File

@@ -4,7 +4,7 @@ use std::time::Duration;
use anyhow::{anyhow, Error};
use common::debounced_delay::DebouncedDelay;
use common::display::DisplayProfile;
use common::display::{DisplayProfile, TextUtils};
use global::constants::{BOOTSTRAP_RELAYS, DEFAULT_MODAL_WIDTH, SEARCH_RELAYS};
use global::nostr_client;
use gpui::prelude::FluentBuilder;
@@ -32,7 +32,7 @@ use ui::indicator::Indicator;
use ui::input::{InputEvent, InputState, TextInput};
use ui::popup_menu::PopupMenu;
use ui::skeleton::Skeleton;
use ui::{ContextModal, IconName, Selectable, Sizable, StyledExt};
use ui::{v_flex, ContextModal, IconName, Selectable, Sizable, StyledExt};
use crate::views::compose;
@@ -146,6 +146,8 @@ impl Sidebar {
.subscribe_to(BOOTSTRAP_RELAYS, filter, Some(opts))
.await?;
log::info!("Subscribe to get metadata for: {public_key}");
Ok(())
}
@@ -334,7 +336,7 @@ impl Sidebar {
}
fn search_by_pubkey(&mut self, query: &str, window: &mut Window, cx: &mut Context<Self>) {
let Ok(public_key) = common::parse_pubkey_from_str(query) else {
let Ok(public_key) = query.to_public_key() else {
window.push_notification(t!("common.pubkey_invalid"), cx);
self.set_finding(false, window, cx);
return;
@@ -568,36 +570,34 @@ impl Sidebar {
let desc = SharedString::new(t!("sidebar.loading_modal_description"));
window.open_modal(cx, move |this, _window, cx| {
this.child(
div()
.pt_8()
.px_4()
.pb_4()
.flex()
.flex_col()
.gap_2()
.child(div().font_semibold().child(title.clone()))
.child(
div()
.flex()
.flex_col()
.gap_2()
.text_sm()
.child(text_1.clone())
.child(text_2.clone()),
)
.child(
div()
.text_xs()
.text_color(cx.theme().text_muted)
.child(desc.clone()),
),
)
this.show_close(true)
.keyboard(true)
.title(title.clone())
.child(
v_flex()
.pb_4()
.gap_2()
.child(
div()
.flex()
.flex_col()
.gap_2()
.text_sm()
.child(text_1.clone())
.child(text_2.clone()),
)
.child(
div()
.text_xs()
.text_color(cx.theme().text_muted)
.child(desc.clone()),
),
)
});
}
fn account(&self, profile: &Profile, cx: &Context<Self>) -> impl IntoElement {
let proxy = AppSettings::get_global(cx).settings.proxy_user_avatars;
let proxy = AppSettings::get_proxy_user_avatars(cx);
div()
.px_3()
@@ -666,26 +666,30 @@ impl Sidebar {
range: Range<usize>,
cx: &Context<Self>,
) -> Vec<impl IntoElement> {
let proxy = AppSettings::get_global(cx).settings.proxy_user_avatars;
let proxy = AppSettings::get_proxy_user_avatars(cx);
let mut items = Vec::with_capacity(range.end - range.start);
for ix in range {
if let Some(room) = rooms.get(ix) {
let this = room.read(cx);
let room_id = this.id;
let handler = cx.listener({
let id = this.id;
move |this, _, window, cx| {
this.open_room(id, window, cx);
this.open_room(room_id, window, cx);
}
});
items.push(
RoomListItem::new(ix, this.members[0])
.avatar(this.display_image(proxy, cx))
.name(this.display_name(cx))
.created_at(this.ago())
.kind(this.kind)
.on_click(handler),
RoomListItem::new(
ix,
room_id,
this.members[0],
this.display_name(cx),
this.display_image(proxy, cx),
this.ago(),
this.kind,
)
.on_click(handler),
)
}
}

View File

@@ -136,16 +136,13 @@ impl UserProfile {
impl Render for UserProfile {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let proxy = AppSettings::get_global(cx).settings.proxy_user_avatars;
let proxy = AppSettings::get_proxy_user_avatars(cx);
let profile = self.profile(cx);
let Ok(bech32) = profile.public_key().to_bech32();
let shared_bech32 = SharedString::new(bech32);
v_flex()
.px_4()
.pt_8()
.pb_4()
.gap_4()
.child(
v_flex()

View File

@@ -26,5 +26,14 @@ macro_rules! init {
};
}
pub use rust_i18n::set_locale;
pub use rust_i18n::t;
#[macro_export]
macro_rules! shared_t {
($key:expr) => {
SharedString::new(t!($key))
};
($key:expr, $($param:ident = $value:expr),+) => {
SharedString::new(t!($key, $($param = $value),+))
};
}
pub use rust_i18n::{set_locale, t};

View File

@@ -58,7 +58,7 @@ impl Identity {
subscriptions.push(
cx.observe_in(&client_keys, window, |this, state, window, cx| {
let auto_login = AppSettings::get_global(cx).settings.auto_login;
let auto_login = AppSettings::get_auto_login(cx);
let has_client_keys = state.read(cx).has_keys();
// Skip auto login if the user hasn't enabled auto login
@@ -264,8 +264,6 @@ impl Identity {
})
.child(
div()
.pt_4()
.px_4()
.w_full()
.flex()
.flex_col()

View File

@@ -7,6 +7,7 @@ publish.workspace = true
[dependencies]
common = { path = "../common" }
global = { path = "../global" }
settings = { path = "../settings" }
rust-i18n.workspace = true
i18n.workspace = true

View File

@@ -2,7 +2,7 @@ use std::cmp::Reverse;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use anyhow::Error;
use common::room_hash;
use common::event::EventUtils;
use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher;
use global::nostr_client;
@@ -12,6 +12,7 @@ use gpui::{
use itertools::Itertools;
use nostr_sdk::prelude::*;
use room::RoomKind;
use settings::AppSettings;
use smallvec::{smallvec, SmallVec};
use crate::room::Room;
@@ -32,6 +33,7 @@ impl Global for GlobalRegistry {}
#[derive(Debug)]
pub enum RoomEmitter {
Open(WeakEntity<Room>),
Close(u64),
Request(RoomKind),
}
@@ -202,6 +204,13 @@ impl Registry {
cx.notify();
}
/// Close a room.
pub fn close_room(&mut self, id: u64, cx: &mut Context<Self>) {
if self.rooms.iter().any(|r| r.read(cx).id == id) {
cx.emit(RoomEmitter::Close(id));
}
}
/// Sort rooms by their created at.
pub fn sort(&mut self, cx: &mut Context<Self>) {
self.rooms.sort_by_key(|ev| Reverse(ev.read(cx).created_at));
@@ -238,15 +247,12 @@ impl Registry {
cx.notify();
}
/// Load all rooms from the lmdb.
///
/// This method:
/// 1. Fetches all private direct messages from the lmdb
/// 2. Groups them by ID
/// 3. Determines each room's type based on message frequency and trust status
/// 4. Creates Room entities for each unique room
/// Load all rooms from the database.
pub fn load_rooms(&mut self, window: &mut Window, cx: &mut Context<Self>) {
log::info!("Starting to load rooms from database...");
log::info!("Starting to load chat rooms...");
// Get the contact bypass setting
let contact_bypass = AppSettings::get_contact_bypass(cx);
let task: Task<Result<BTreeSet<Room>, Error>> = cx.background_spawn(async move {
let client = nostr_client();
@@ -275,14 +281,22 @@ impl Registry {
.sorted_by_key(|event| Reverse(event.created_at))
.filter(|ev| ev.tags.public_keys().peekable().peek().is_some())
{
let hash = room_hash(&event);
if rooms.iter().any(|room| room.id == hash) {
if rooms.iter().any(|room| room.id == event.uniq_id()) {
continue;
}
let mut public_keys = event.tags.public_keys().copied().collect_vec();
public_keys.push(event.pubkey);
// Get all public keys from the event
let public_keys = event.all_pubkeys();
// Bypass screening flag
let mut bypass = false;
// If user enabled bypass screening for contacts
// Check if room's members are in contact with current user
if contact_bypass {
let contacts = client.database().contacts_public_keys(public_key).await?;
bypass = public_keys.iter().any(|k| contacts.contains(k));
}
// Check if the current user has sent at least one message to this room
let filter = Filter::new()
@@ -296,7 +310,7 @@ impl Registry {
// Create a new room
let room = Room::new(&event).rearrange_by(public_key);
if is_ongoing {
if is_ongoing || bypass {
rooms.insert(room.kind(RoomKind::Ongoing));
} else {
rooms.insert(room);
@@ -375,7 +389,7 @@ impl Registry {
window: &mut Window,
cx: &mut Context<Self>,
) {
let id = room_hash(&event);
let id = event.uniq_id();
let author = event.pubkey;
if let Some(room) = self.rooms.iter().find(|room| room.read(cx).id == id) {

View File

@@ -3,6 +3,7 @@ use std::cmp::Ordering;
use anyhow::{anyhow, Error};
use chrono::{Local, TimeZone};
use common::display::DisplayProfile;
use common::event::EventUtils;
use global::nostr_client;
use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task, Window};
use itertools::Itertools;
@@ -72,16 +73,12 @@ impl EventEmitter<Incoming> for Room {}
impl Room {
pub fn new(event: &Event) -> Self {
let id = common::room_hash(event);
let id = event.uniq_id();
let created_at = event.created_at;
// Get all pubkeys from the event's tags
let mut pubkeys: Vec<PublicKey> = event.tags.public_keys().cloned().collect();
// The author is always put at the end of the vector
pubkeys.push(event.pubkey);
let public_keys = event.all_pubkeys();
// Convert pubkeys into members
let members = pubkeys.into_iter().unique().sorted().collect();
let members = public_keys.into_iter().unique().sorted().collect();
// Get the subject from the event's tags
let subject = if let Some(tag) = event.tags.find(TagKind::Subject) {
@@ -363,12 +360,7 @@ impl Room {
.await?
.into_iter()
.sorted_by_key(|ev| ev.created_at)
.filter(|ev| {
let mut other_pubkeys = ev.tags.public_keys().copied().collect::<Vec<_>>();
other_pubkeys.push(ev.pubkey);
// Check if the event is belong to a member of the current room
common::compare(&other_pubkeys, &pubkeys)
})
.filter(|ev| ev.compare_pubkeys(&pubkeys))
.collect::<Vec<_>>();
for event in events.into_iter() {

View File

@@ -14,3 +14,5 @@ log.workspace = true
smallvec.workspace = true
serde.workspace = true
serde_json.workspace = true
paste = "1.0.15"

View File

@@ -1,5 +1,6 @@
use anyhow::anyhow;
use global::{constants::SETTINGS_D, nostr_client};
use global::constants::SETTINGS_D;
use global::nostr_client;
use gpui::{App, AppContext, Context, Entity, Global, Subscription, Task};
use nostr_sdk::prelude::*;
use serde::{Deserialize, Serialize};
@@ -19,6 +20,37 @@ pub fn init(cx: &mut App) {
AppSettings::set_global(state, cx);
}
macro_rules! setting_accessors {
($(pub $field:ident: $type:ty),* $(,)?) => {
impl AppSettings {
$(
paste::paste! {
pub fn [<get_ $field>](cx: &App) -> $type {
Self::read_global(cx).setting_values.$field.clone()
}
pub fn [<update_ $field>](value: $type, cx: &mut App) {
Self::global(cx).update(cx, |this, cx| {
this.setting_values.$field = value;
cx.notify();
});
}
}
)*
}
};
}
setting_accessors! {
pub media_server: Url,
pub proxy_user_avatars: bool,
pub hide_user_avatars: bool,
pub backup_messages: bool,
pub screening: bool,
pub contact_bypass: bool,
pub auto_login: bool,
}
#[derive(Serialize, Deserialize)]
pub struct Settings {
pub media_server: Url,
@@ -26,9 +58,24 @@ pub struct Settings {
pub hide_user_avatars: bool,
pub backup_messages: bool,
pub screening: bool,
pub contact_bypass: bool,
pub auto_login: bool,
}
impl Default for Settings {
fn default() -> Self {
Self {
media_server: Url::parse("https://nostrmedia.com").unwrap(),
proxy_user_avatars: true,
hide_user_avatars: false,
backup_messages: true,
screening: true,
contact_bypass: true,
auto_login: false,
}
}
}
impl AsRef<Settings> for Settings {
fn as_ref(&self) -> &Settings {
self
@@ -40,7 +87,7 @@ struct GlobalAppSettings(Entity<AppSettings>);
impl Global for GlobalAppSettings {}
pub struct AppSettings {
pub settings: Settings,
setting_values: Settings,
#[allow(dead_code)]
subscriptions: SmallVec<[Subscription; 1]>,
}
@@ -52,7 +99,7 @@ impl AppSettings {
}
/// Retrieve the Settings instance
pub fn get_global(cx: &App) -> &Self {
pub fn read_global(cx: &App) -> &Self {
cx.global::<GlobalAppSettings>().0.read(cx)
}
@@ -62,23 +109,15 @@ impl AppSettings {
}
fn new(cx: &mut Context<Self>) -> Self {
let settings = Settings {
media_server: Url::parse("https://nostrmedia.com").unwrap(),
proxy_user_avatars: true,
hide_user_avatars: false,
backup_messages: true,
screening: true,
auto_login: false,
};
let setting_values = Settings::default();
let mut subscriptions = smallvec![];
subscriptions.push(cx.observe_new::<Self>(|this, _window, cx| {
subscriptions.push(cx.observe_new::<Self>(move |this, _window, cx| {
this.get_settings_from_db(cx);
}));
Self {
settings,
setting_values,
subscriptions,
}
}
@@ -92,7 +131,7 @@ impl AppSettings {
if let Some(event) = nostr_client().database().query(filter).await?.first_owned() {
log::info!("Successfully loaded settings from database");
Ok(serde_json::from_str(&event.content)?)
Ok(serde_json::from_str(&event.content).unwrap_or(Settings::default()))
} else {
Err(anyhow!("Not found"))
}
@@ -101,7 +140,7 @@ impl AppSettings {
cx.spawn(async move |this, cx| {
if let Ok(settings) = task.await {
this.update(cx, |this, cx| {
this.settings = settings;
this.setting_values = settings;
cx.notify();
})
.ok();
@@ -111,13 +150,11 @@ impl AppSettings {
}
pub(crate) fn set_settings(&self, cx: &mut Context<Self>) {
if let Ok(content) = serde_json::to_string(&self.settings) {
if let Ok(content) = serde_json::to_string(&self.setting_values) {
cx.background_spawn(async move {
let keys = Keys::generate();
if let Ok(event) = EventBuilder::new(Kind::ApplicationSpecificData, content)
.tags(vec![Tag::identifier(SETTINGS_D)])
.sign(&keys)
.sign(&Keys::generate())
.await
{
if let Err(e) = nostr_client().database().save_event(&event).await {

View File

@@ -143,18 +143,18 @@ impl ThemeColor {
element_selected: brand().light().step_11(),
element_disabled: brand().light_alpha().step_3(),
secondary_foreground: brand().light().step_12(),
secondary_foreground: brand().light().step_11(),
secondary_background: brand().light().step_3(),
secondary_hover: brand().light_alpha().step_4(),
secondary_active: brand().light().step_5(),
secondary_selected: brand().light().step_5(),
secondary_disabled: brand().light_alpha().step_3(),
danger_foreground: danger().light().step_1(),
danger_background: danger().light().step_9(),
danger_hover: danger().light_alpha().step_10(),
danger_active: danger().light().step_10(),
danger_selected: danger().light().step_11(),
danger_foreground: danger().light().step_12(),
danger_background: danger().light().step_3(),
danger_hover: danger().light_alpha().step_4(),
danger_active: danger().light().step_5(),
danger_selected: danger().light().step_5(),
danger_disabled: danger().light_alpha().step_3(),
warning_foreground: warning().light().step_12(),
@@ -231,11 +231,11 @@ impl ThemeColor {
secondary_selected: brand().dark().step_5(),
secondary_disabled: brand().dark_alpha().step_3(),
danger_foreground: danger().dark().step_1(),
danger_background: danger().dark().step_9(),
danger_hover: danger().dark_alpha().step_10(),
danger_active: danger().dark().step_10(),
danger_selected: danger().dark().step_11(),
danger_foreground: danger().dark().step_12(),
danger_background: danger().dark().step_3(),
danger_hover: danger().dark_alpha().step_4(),
danger_active: danger().dark().step_5(),
danger_selected: danger().dark().step_5(),
danger_disabled: danger().dark_alpha().step_3(),
warning_foreground: warning().dark().step_12(),
@@ -309,6 +309,24 @@ impl From<WindowAppearance> for ThemeMode {
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ScrollBarMode {
#[default]
Scrolling,
Hover,
Always,
}
impl ScrollBarMode {
pub fn is_hover(&self) -> bool {
matches!(self, Self::Hover)
}
pub fn is_always(&self) -> bool {
matches!(self, Self::Always)
}
}
#[derive(Debug, Clone)]
pub struct Theme {
pub colors: ThemeColor,
@@ -316,6 +334,7 @@ pub struct Theme {
pub font_family: SharedString,
pub font_size: Pixels,
pub radius: Pixels,
pub scrollbar_mode: ScrollBarMode,
}
impl Deref for Theme {
@@ -392,6 +411,7 @@ impl From<ThemeColor> for Theme {
font_size: px(15.),
font_family: ".SystemUIFont".into(),
radius: px(5.),
scrollbar_mode: ScrollBarMode::default(),
mode,
colors,
}

View File

@@ -41,11 +41,6 @@ pub trait ButtonVariants: Sized {
self.with_variant(ButtonVariant::Danger)
}
/// With the danger alternate style for the Button.
fn danger_alt(self) -> Self {
self.with_variant(ButtonVariant::DangerAlt)
}
/// With the warning style for the Button.
fn warning(self) -> Self {
self.with_variant(ButtonVariant::Warning)
@@ -104,7 +99,6 @@ pub enum ButtonVariant {
Primary,
Secondary,
Danger,
DangerAlt,
Warning,
Ghost,
Transparent,
@@ -286,6 +280,7 @@ impl RenderOnce for Button {
let normal_style = style.normal(window, cx);
let icon_size = match self.size {
Size::Size(v) => Size::Size(v * 0.75),
Size::Medium => Size::Small,
_ => self.size,
};
@@ -307,6 +302,7 @@ impl RenderOnce for Button {
Size::Size(px) => this.size(px),
Size::XSmall => this.size_5(),
Size::Small => this.size_6(),
Size::Medium => this.size_7(),
_ => this.size_9(),
}
} else {
@@ -321,8 +317,8 @@ impl RenderOnce for Button {
this.h_7().px_3()
}
}
Size::Medium => this.h_8().px_3(),
Size::Large => this.h_10().px_4(),
_ => this.h_9().px_2(),
}
}
})
@@ -342,21 +338,6 @@ impl RenderOnce for Button {
this.bg(active_style.bg).text_color(active_style.fg)
})
})
.when_some(
self.on_click.filter(|_| !self.disabled && !self.loading),
|this, on_click| {
let stop_propagation = self.stop_propagation;
this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
window.prevent_default();
if stop_propagation {
cx.stop_propagation();
}
})
.on_click(move |event, window, cx| {
(on_click)(event, window, cx);
})
},
)
.when(self.disabled, |this| {
let disabled_style = style.disabled(window, cx);
this.cursor_not_allowed()
@@ -403,6 +384,21 @@ impl RenderOnce for Button {
.when_some(self.tooltip.clone(), |this, tooltip| {
this.tooltip(move |window, cx| Tooltip::new(tooltip.clone(), window, cx).into())
})
.when_some(
self.on_click.filter(|_| !self.disabled && !self.loading),
|this, on_click| {
let stop_propagation = self.stop_propagation;
this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
window.prevent_default();
if stop_propagation {
cx.stop_propagation();
}
})
.on_click(move |event, window, cx| {
(on_click)(event, window, cx);
})
},
)
}
}
@@ -435,7 +431,6 @@ impl ButtonVariant {
ButtonVariant::Primary => cx.theme().element_foreground,
ButtonVariant::Secondary => cx.theme().text_muted,
ButtonVariant::Danger => cx.theme().danger_foreground,
ButtonVariant::DangerAlt => cx.theme().danger_background,
ButtonVariant::Warning => cx.theme().warning_foreground,
ButtonVariant::Transparent => cx.theme().text_placeholder,
ButtonVariant::Ghost => cx.theme().text_muted,
@@ -448,7 +443,6 @@ impl ButtonVariant {
ButtonVariant::Primary => cx.theme().element_hover,
ButtonVariant::Secondary => cx.theme().secondary_hover,
ButtonVariant::Danger => cx.theme().danger_hover,
ButtonVariant::DangerAlt => gpui::transparent_black(),
ButtonVariant::Warning => cx.theme().warning_hover,
ButtonVariant::Ghost => cx.theme().ghost_element_hover,
ButtonVariant::Transparent => gpui::transparent_black(),
@@ -470,7 +464,6 @@ impl ButtonVariant {
ButtonVariant::Primary => cx.theme().element_active,
ButtonVariant::Secondary => cx.theme().secondary_active,
ButtonVariant::Danger => cx.theme().danger_active,
ButtonVariant::DangerAlt => gpui::transparent_black(),
ButtonVariant::Warning => cx.theme().warning_active,
ButtonVariant::Ghost => cx.theme().ghost_element_active,
ButtonVariant::Transparent => gpui::transparent_black(),
@@ -491,7 +484,6 @@ impl ButtonVariant {
ButtonVariant::Primary => cx.theme().element_selected,
ButtonVariant::Secondary => cx.theme().secondary_selected,
ButtonVariant::Danger => cx.theme().danger_selected,
ButtonVariant::DangerAlt => gpui::transparent_black(),
ButtonVariant::Warning => cx.theme().warning_selected,
ButtonVariant::Ghost => cx.theme().ghost_element_selected,
ButtonVariant::Transparent => gpui::transparent_black(),

View File

@@ -3,8 +3,8 @@ use std::sync::Arc;
use gpui::prelude::FluentBuilder;
use gpui::{
actions, canvas, div, px, AnyElement, AnyView, App, AppContext, Axis, Bounds, Context, Edges,
Entity, EntityId, EventEmitter, InteractiveElement as _, IntoElement, ParentElement as _,
Pixels, Render, Styled, Subscription, WeakEntity, Window,
Entity, EntityId, EventEmitter, Focusable, InteractiveElement as _, IntoElement,
ParentElement as _, Pixels, Render, Styled, Subscription, WeakEntity, Window,
};
use crate::dock_area::dock::{Dock, DockPlacement};
@@ -39,7 +39,7 @@ pub enum DockEvent {
pub struct DockArea {
pub(crate) bounds: Bounds<Pixels>,
/// The center view of the dockarea.
items: DockItem,
pub items: DockItem,
/// The entity_id of the [`TabPanel`](TabPanel) where each toggle button should be displayed,
toggle_button_panels: Edges<Option<EntityId>>,
/// The left dock of the dock_area.
@@ -73,7 +73,7 @@ pub enum DockItem {
active_ix: usize,
view: Entity<TabPanel>,
},
/// Panel layout
/// Single panel layout
Panel { view: Arc<dyn PanelView> },
}
@@ -286,6 +286,12 @@ impl DockItem {
DockItem::Panel { .. } => None,
}
}
pub(crate) fn focus_tab_panel(&self, window: &mut Window, cx: &mut App) {
if let DockItem::Tabs { view, .. } = self {
window.focus(&view.read(cx).focus_handle(cx));
}
}
}
impl DockArea {
@@ -572,12 +578,8 @@ impl DockArea {
}
}
DockPlacement::Center => {
let focus_handle = panel.focus_handle(cx);
// Add panel
self.items
.add_panel(panel, &cx.entity().downgrade(), window, cx);
// Focus to the newly added panel
window.focus(&focus_handle);
}
}
}
@@ -707,6 +709,10 @@ impl DockArea {
.and_then(|dock| dock.read(cx).panel.left_top_tab_panel(cx))
.map(|view| view.entity_id());
}
pub fn focus_tab_panel(&mut self, window: &mut Window, cx: &mut App) {
self.items.focus_tab_panel(window, cx);
}
}
impl EventEmitter<DockEvent> for DockArea {}

View File

@@ -13,7 +13,6 @@ use super::panel::PanelView;
use super::stack_panel::StackPanel;
use super::{ClosePanel, DockArea, PanelEvent, PanelStyle, ToggleZoom};
use crate::button::{Button, ButtonVariants as _};
use crate::dock_area::dock::DockPlacement;
use crate::dock_area::panel::Panel;
use crate::popup_menu::{PopupMenu, PopupMenuExt};
use crate::tab::tab_bar::TabBar;
@@ -454,89 +453,6 @@ impl TabPanel {
)
}
fn _render_dock_toggle_button(
&self,
placement: DockPlacement,
_window: &mut Window,
cx: &mut Context<Self>,
) -> Option<impl IntoElement> {
if self.is_zoomed {
return None;
}
let dock_area = self.dock_area.upgrade()?.read(cx);
if !dock_area.is_dock_collapsible(placement, cx) {
return None;
}
let view_entity_id = cx.entity().entity_id();
let toggle_button_panels = dock_area.toggle_button_panels;
// Check if current TabPanel's entity_id matches the one stored in DockArea for this placement
if !match placement {
DockPlacement::Left => {
dock_area.left_dock.is_some() && toggle_button_panels.left == Some(view_entity_id)
}
DockPlacement::Right => {
dock_area.right_dock.is_some() && toggle_button_panels.right == Some(view_entity_id)
}
DockPlacement::Bottom => {
dock_area.bottom_dock.is_some()
&& toggle_button_panels.bottom == Some(view_entity_id)
}
DockPlacement::Center => unreachable!(),
} {
return None;
}
let is_open = dock_area.is_dock_open(placement, cx);
let icon = match placement {
DockPlacement::Left => {
if is_open {
IconName::PanelLeft
} else {
IconName::PanelLeftOpen
}
}
DockPlacement::Right => {
if is_open {
IconName::PanelRight
} else {
IconName::PanelRightOpen
}
}
DockPlacement::Bottom => {
if is_open {
IconName::PanelBottom
} else {
IconName::PanelBottomOpen
}
}
DockPlacement::Center => unreachable!(),
};
Some(
Button::new(SharedString::from(format!("toggle-dock:{placement:?}")))
.icon(icon)
.small()
.ghost()
.tooltip(match is_open {
true => "Collapse",
false => "Expand",
})
.on_click(cx.listener({
let dock_area = self.dock_area.clone();
move |_, _, window, cx| {
_ = dock_area.update(cx, |dock_area, cx| {
dock_area.toggle_dock(placement, window, cx);
});
}
})),
)
}
fn render_title_bar(
&self,
state: &TabState,
@@ -1038,6 +954,7 @@ impl Render for TabPanel {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl gpui::IntoElement {
let focus_handle = self.focus_handle(cx);
let active_panel = self.active_panel(cx);
let mut state = TabState {
closable: self.closable(cx),
draggable: self.draggable(cx),

View File

@@ -57,6 +57,7 @@ pub enum IconName {
Relays,
ResizeCorner,
Reply,
Report,
Forward,
Search,
SearchFill,
@@ -128,6 +129,7 @@ impl IconName {
Self::Relays => "icons/relays.svg",
Self::ResizeCorner => "icons/resize-corner.svg",
Self::Reply => "icons/reply.svg",
Self::Report => "icons/report.svg",
Self::Forward => "icons/forward.svg",
Self::Search => "icons/search.svg",
Self::SearchFill => "icons/search-fill.svg",

View File

@@ -1,4 +1,3 @@
use std::cell::Cell;
use std::ops::{Deref, Range};
use std::rc::Rc;
use std::time::Duration;
@@ -358,7 +357,7 @@ pub struct InputState {
#[allow(clippy::type_complexity)]
pub(super) validate: Option<Box<dyn Fn(&str) -> bool + 'static>>,
pub(crate) scroll_handle: ScrollHandle,
pub(super) scrollbar_state: Rc<Cell<ScrollbarState>>,
pub(super) scrollbar_state: ScrollbarState,
/// The size of the scrollable content.
pub(crate) scroll_size: gpui::Size<Pixels>,
pub(crate) line_number_width: Pixels,
@@ -434,7 +433,7 @@ impl InputState {
last_selected_range: None,
last_cursor_offset: None,
scroll_handle: ScrollHandle::new(),
scrollbar_state: Rc::new(Cell::new(ScrollbarState::default())),
scrollbar_state: ScrollbarState::default(),
scroll_size: gpui::size(px(0.), px(0.)),
line_number_width: px(0.),
preferred_x_offset: None,

View File

@@ -276,8 +276,6 @@ impl RenderOnce for TextInput {
.children(suffix),
)
.when(state.is_multi_line(), |this| {
let entity_id = self.state.entity_id();
if state.last_layout.is_some() {
this.relative().child(
div()
@@ -287,13 +285,8 @@ impl RenderOnce for TextInput {
.right(px(1.))
.bottom_0()
.child(
Scrollbar::vertical(
entity_id,
state.scrollbar_state.clone(),
state.scroll_handle.clone(),
state.scroll_size,
)
.axis(ScrollbarAxis::Vertical),
Scrollbar::vertical(&state.scrollbar_state, &state.scroll_handle)
.axis(ScrollbarAxis::Vertical),
),
)
} else {

View File

@@ -1,6 +1,4 @@
use std::cell::Cell;
use std::ops::Range;
use std::rc::Rc;
use std::time::Duration;
use gpui::prelude::FluentBuilder;
@@ -154,7 +152,7 @@ pub struct List<D: ListDelegate> {
querying: bool,
scrollbar_visible: bool,
vertical_scroll_handle: UniformListScrollHandle,
scrollbar_state: Rc<Cell<ScrollbarState>>,
scrollbar_state: ScrollbarState,
pub(crate) size: Size,
selected_index: Option<usize>,
right_clicked_index: Option<usize>,
@@ -181,7 +179,7 @@ where
selected_index: None,
right_clicked_index: None,
vertical_scroll_handle: UniformListScrollHandle::new(),
scrollbar_state: Rc::new(Cell::new(ScrollbarState::new())),
scrollbar_state: ScrollbarState::default(),
max_height: None,
scrollbar_visible: true,
selectable: true,
@@ -265,15 +263,18 @@ where
self.selected_index
}
fn render_scrollbar(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<impl IntoElement> {
fn render_scrollbar(
&self,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<impl IntoElement> {
if !self.scrollbar_visible {
return None;
}
Some(Scrollbar::uniform_scroll(
cx.entity().entity_id(),
self.scrollbar_state.clone(),
self.vertical_scroll_handle.clone(),
&self.scrollbar_state,
&self.vertical_scroll_handle,
))
}

View File

@@ -3,9 +3,10 @@ use std::time::Duration;
use gpui::prelude::FluentBuilder;
use gpui::{
anchored, div, hsla, point, px, relative, Animation, AnimationExt as _, AnyElement, App,
Bounds, BoxShadow, ClickEvent, Div, FocusHandle, InteractiveElement, IntoElement, KeyBinding,
MouseButton, ParentElement, Pixels, Point, RenderOnce, SharedString, Styled, Window,
anchored, div, hsla, point, px, Animation, AnimationExt as _, AnyElement, App, Axis, Bounds,
BoxShadow, ClickEvent, Div, FocusHandle, InteractiveElement, IntoElement, KeyBinding,
MouseButton, ParentElement, Pixels, Point, RenderOnce, SharedString, StyleRefinement, Styled,
Window,
};
use theme::ActiveTheme;
@@ -77,7 +78,7 @@ impl ModalButtonProps {
#[derive(IntoElement)]
pub struct Modal {
base: Div,
style: StyleRefinement,
title: Option<AnyElement>,
footer: Option<FooterFn>,
content: Div,
@@ -88,11 +89,12 @@ pub struct Modal {
on_close: OnClose,
on_ok: OnOk,
on_cancel: OnCancel,
button_props: ModalButtonProps,
show_close: bool,
overlay: bool,
overlay_closable: bool,
keyboard: bool,
show_close: bool,
button_props: ModalButtonProps,
/// This will be change when open the modal, the focus handle is create when open the modal.
pub(crate) focus_handle: FocusHandle,
@@ -102,18 +104,8 @@ pub struct Modal {
impl Modal {
pub fn new(_window: &mut Window, cx: &mut App) -> Self {
let radius = (cx.theme().radius * 2.).min(px(20.));
let base = v_flex()
.bg(cx.theme().background)
.border_1()
.border_color(cx.theme().border)
.rounded(radius)
.shadow_xl()
.min_h_24();
Self {
base,
style: StyleRefinement::default(),
focus_handle: cx.focus_handle(),
title: None,
footer: None,
@@ -276,7 +268,7 @@ impl ParentElement for Modal {
impl Styled for Modal {
fn style(&mut self) -> &mut gpui::StyleRefinement {
self.base.style()
&mut self.style
}
}
@@ -350,6 +342,7 @@ impl RenderOnce for Modal {
});
let window_paddings = crate::window_border::window_paddings(window, cx);
let radius = (cx.theme().radius * 2.).min(px(20.));
let view_size = window.viewport_size()
- gpui::size(
@@ -366,6 +359,17 @@ impl RenderOnce for Modal {
let y = self.margin_top.unwrap_or(view_size.height / 10.) + offset_top;
let x = bounds.center().x - self.width / 2.;
let mut padding_right = px(16.);
let mut padding_left = px(16.);
if let Some(pl) = self.style.padding.left {
padding_left = pl.to_pixels(self.width.into(), window.rem_size());
}
if let Some(pr) = self.style.padding.right {
padding_right = pr.to_pixels(self.width.into(), window.rem_size());
}
let animation = Animation::new(Duration::from_secs_f64(0.25))
.with_easing(cubic_bezier(0.32, 0.72, 0., 1.));
@@ -374,6 +378,7 @@ impl RenderOnce for Modal {
.snap_to_window()
.child(
div()
.id("modal")
.w(view_size.width)
.h(view_size.height)
.when(self.overlay_visible, |this| {
@@ -396,10 +401,17 @@ impl RenderOnce for Modal {
})
})
.child(
self.base
.id(SharedString::from(format!("modal-{layer_ix}")))
v_flex()
.id(layer_ix)
.bg(cx.theme().background)
.border_1()
.border_color(cx.theme().border.alpha(0.4))
.rounded(radius)
.shadow_xl()
.min_h_24()
.key_context(CONTEXT)
.track_focus(&self.focus_handle)
.refine_style(&self.style)
.when(self.keyboard, |this| {
this.on_action({
let on_cancel = on_cancel.clone();
@@ -430,6 +442,7 @@ impl RenderOnce for Modal {
}
})
})
// There style is high priority, can't be overridden.
.absolute()
.occlude()
.relative()
@@ -437,57 +450,59 @@ impl RenderOnce for Modal {
.top(y)
.w(self.width)
.when_some(self.max_width, |this, w| this.max_w(w))
.when_some(self.title, |this, title| {
this.child(
div()
.h_12()
.px_3()
.mb_2()
.flex()
.items_center()
.font_semibold()
.border_b_1()
.border_color(cx.theme().border)
.line_height(relative(1.))
.child(title),
)
})
.child(h_flex().h_4().px_3().justify_center().when_some(
self.title,
|this, title| {
this.h_12().font_semibold().text_center().child(title)
},
))
.when(self.show_close, |this| {
this.child(
Button::new(SharedString::from(format!(
"modal-close-{layer_ix}"
)))
.icon(IconName::CloseCircleFill)
.absolute()
.top_1p5()
.right_2()
.custom(
ButtonCustomVariant::new(window, cx)
.foreground(cx.theme().icon_muted)
.color(cx.theme().ghost_element_background)
.hover(cx.theme().ghost_element_background)
.active(cx.theme().ghost_element_background),
)
.on_click(
move |_, window, cx| {
Button::new("close")
.icon(IconName::CloseCircleFill)
.absolute()
.top_1p5()
.right_2()
.custom(
ButtonCustomVariant::new(window, cx)
.foreground(cx.theme().icon_muted)
.color(cx.theme().ghost_element_background)
.hover(cx.theme().ghost_element_background)
.active(cx.theme().ghost_element_background),
)
.on_click(move |_, window, cx| {
on_cancel(&ClickEvent::default(), window, cx);
on_close(&ClickEvent::default(), window, cx);
window.close_modal(cx);
},
),
}),
)
})
.child(div().relative().w_full().flex_1().child(self.content))
.when(self.footer.is_some(), |this| {
let footer = self.footer.unwrap();
.child(
div()
.pt_px()
.w_full()
.h_auto()
.flex_1()
.relative()
.overflow_hidden()
.child(
v_flex()
.pr(padding_right)
.pl(padding_left)
.scrollable(Axis::Vertical)
.child(self.content),
),
)
.when_some(self.footer, |this, footer| {
this.child(
h_flex().p_4().gap_1p5().justify_center().children(footer(
render_ok,
render_cancel,
window,
cx,
)),
h_flex()
.gap_2()
.pt(padding_left)
.pr(padding_right)
.pb(padding_left)
.pl(padding_right)
.justify_end()
.children(footer(render_ok, render_cancel, window, cx)),
)
})
.with_animation("slide-down", animation.clone(), move |this, delta| {

View File

@@ -1,4 +1,3 @@
use std::cell::Cell;
use std::ops::Deref;
use std::rc::Rc;
@@ -125,7 +124,7 @@ pub struct PopupMenu {
scrollable: bool,
scroll_handle: ScrollHandle,
scroll_state: Rc<Cell<ScrollbarState>>,
scroll_state: ScrollbarState,
action_focus_handle: Option<FocusHandle>,
#[allow(dead_code)]
@@ -159,7 +158,7 @@ impl PopupMenu {
bounds: Bounds::default(),
scrollable: false,
scroll_handle: ScrollHandle::default(),
scroll_state: Rc::new(Cell::new(ScrollbarState::default())),
scroll_state: ScrollbarState::default(),
subscriptions,
};
@@ -714,12 +713,7 @@ impl Render for PopupMenu {
.left_0()
.right_0p5()
.bottom_0()
.child(Scrollbar::vertical(
cx.entity_id(),
self.scroll_state.clone(),
self.scroll_handle.clone(),
self.bounds.size,
)),
.child(Scrollbar::vertical(&self.scroll_state, &self.scroll_handle)),
)
})
}

View File

@@ -1,10 +1,8 @@
use std::cell::Cell;
use std::rc::Rc;
use gpui::{
canvas, div, relative, AnyElement, App, Div, Element, ElementId, EntityId, GlobalElementId,
InteractiveElement, IntoElement, ParentElement, Pixels, Position, ScrollHandle, SharedString,
Size, Stateful, StatefulInteractiveElement, Style, StyleRefinement, Styled, Window,
div, relative, AnyElement, App, Bounds, Div, Element, ElementId, GlobalElementId,
InspectorElementId, InteractiveElement, Interactivity, IntoElement, LayoutId, ParentElement,
Pixels, Position, ScrollHandle, SharedString, Size, Stateful, StatefulInteractiveElement,
Style, StyleRefinement, Styled, Window,
};
use super::{Scrollbar, ScrollbarAxis, ScrollbarState};
@@ -13,7 +11,6 @@ use super::{Scrollbar, ScrollbarAxis, ScrollbarState};
pub struct Scrollable<E> {
id: ElementId,
element: Option<E>,
view_id: EntityId,
axis: ScrollbarAxis,
/// This is a fake element to handle Styled, InteractiveElement, not used.
_element: Stateful<Div>,
@@ -23,19 +20,16 @@ impl<E> Scrollable<E>
where
E: Element,
{
pub(crate) fn new(view_id: EntityId, element: E, axis: ScrollbarAxis) -> Self {
let id = ElementId::Name(SharedString::from(format!(
"ScrollView:{}-{:?}",
view_id,
element.id(),
)));
pub(crate) fn new(axis: impl Into<ScrollbarAxis>, element: E) -> Self {
let id = ElementId::Name(SharedString::from(
format!("scrollable-{:?}", element.id(),),
));
Self {
element: Some(element),
_element: div().id("fake"),
id,
view_id,
axis,
axis: axis.into(),
}
}
@@ -53,8 +47,8 @@ where
}
/// Set the axis of the scroll view.
pub fn set_axis(&mut self, axis: ScrollbarAxis) {
self.axis = axis;
pub fn set_axis(&mut self, axis: impl Into<ScrollbarAxis>) {
self.axis = axis.into();
}
fn with_element_state<R>(
@@ -76,8 +70,7 @@ where
}
pub struct ScrollViewState {
scroll_size: Rc<Cell<Size<Pixels>>>,
state: Rc<Cell<ScrollbarState>>,
state: ScrollbarState,
handle: ScrollHandle,
}
@@ -85,8 +78,7 @@ impl Default for ScrollViewState {
fn default() -> Self {
Self {
handle: ScrollHandle::new(),
scroll_size: Rc::new(Cell::new(Size::default())),
state: Rc::new(Cell::new(ScrollbarState::default())),
state: ScrollbarState::default(),
}
}
}
@@ -119,7 +111,7 @@ impl<E> InteractiveElement for Scrollable<E>
where
E: Element + InteractiveElement,
{
fn interactivity(&mut self) -> &mut gpui::Interactivity {
fn interactivity(&mut self) -> &mut Interactivity {
if let Some(element) = &mut self.element {
element.interactivity()
} else {
@@ -127,7 +119,6 @@ where
}
}
}
impl<E> StatefulInteractiveElement for Scrollable<E> where E: Element + StatefulInteractiveElement {}
impl<E> IntoElement for Scrollable<E>
@@ -148,7 +139,7 @@ where
type PrepaintState = ScrollViewState;
type RequestLayoutState = AnyElement;
fn id(&self) -> Option<gpui::ElementId> {
fn id(&self) -> Option<ElementId> {
Some(self.id.clone())
}
@@ -158,11 +149,11 @@ where
fn request_layout(
&mut self,
id: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
id: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (gpui::LayoutId, Self::RequestLayoutState) {
) -> (LayoutId, Self::RequestLayoutState) {
let style = Style {
position: Position::Relative,
flex_grow: 1.0,
@@ -175,16 +166,10 @@ where
};
let axis = self.axis;
let view_id = self.view_id;
let scroll_id = self.id.clone();
let content = self.element.take().map(|c| c.into_any_element());
self.with_element_state(id.unwrap(), window, cx, |_, element_state, window, cx| {
let handle = element_state.handle.clone();
let state = element_state.state.clone();
let scroll_size = element_state.scroll_size.clone();
let mut element = div()
.relative()
.size_full()
@@ -192,16 +177,11 @@ where
.child(
div()
.id(scroll_id)
.track_scroll(&handle)
.track_scroll(&element_state.handle)
.overflow_scroll()
.relative()
.size_full()
.child(div().children(content).child({
let scroll_size = element_state.scroll_size.clone();
canvas(move |b, _, _| scroll_size.set(b.size), |_, _, _, _| {})
.absolute()
.size_full()
})),
.child(div().children(content)),
)
.child(
div()
@@ -211,8 +191,7 @@ where
.right_0()
.bottom_0()
.child(
Scrollbar::both(view_id, state, handle.clone(), scroll_size.get())
.axis(axis),
Scrollbar::both(&element_state.state, &element_state.handle).axis(axis),
),
)
.into_any_element();
@@ -226,9 +205,9 @@ where
fn prepaint(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
_: gpui::Bounds<Pixels>,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: Bounds<Pixels>,
element: &mut Self::RequestLayoutState,
window: &mut Window,
cx: &mut App,
@@ -240,9 +219,9 @@ where
fn paint(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
_: gpui::Bounds<Pixels>,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: Bounds<Pixels>,
element: &mut Self::RequestLayoutState,
_: &mut Self::PrepaintState,
window: &mut Window,

View File

@@ -1,7 +1,7 @@
use gpui::{
px, relative, App, Axis, BorderStyle, Bounds, ContentMask, Corners, Edges, Element, ElementId,
EntityId, GlobalElementId, Hitbox, HitboxBehavior, Hsla, IntoElement, IsZero as _, LayoutId,
PaintQuad, Pixels, Point, Position, ScrollHandle, ScrollWheelEvent, Size, Style, Window,
EntityId, GlobalElementId, Hitbox, Hsla, IntoElement, IsZero as _, LayoutId, PaintQuad, Pixels,
Point, Position, ScrollHandle, ScrollWheelEvent, Size, Style, Window,
};
use crate::AxisExt;
@@ -96,7 +96,7 @@ impl Element for ScrollableMask {
size: bounds.size,
};
window.insert_hitbox(cover_bounds, HitboxBehavior::Normal)
window.insert_hitbox(cover_bounds, gpui::HitboxBehavior::Normal)
}
fn paint(
@@ -118,9 +118,9 @@ impl Element for ScrollableMask {
bounds,
border_widths: Edges::all(px(1.0)),
border_color: color,
border_style: BorderStyle::Solid,
background: gpui::transparent_white().into(),
corner_radii: Corners::all(px(0.)),
border_style: BorderStyle::default(),
});
}

View File

@@ -1,22 +1,31 @@
use std::cell::Cell;
use std::ops::Deref;
use std::rc::Rc;
use std::time::{Duration, Instant};
use gpui::{
fill, point, px, relative, App, BorderStyle, Bounds, ContentMask, CursorStyle, Edges, Element,
EntityId, Hitbox, HitboxBehavior, Hsla, IntoElement, MouseDownEvent, MouseMoveEvent,
MouseUpEvent, PaintQuad, Pixels, Point, Position, ScrollHandle, ScrollWheelEvent,
UniformListScrollHandle, Window,
fill, point, px, relative, size, App, Axis, BorderStyle, Bounds, ContentMask, Corner,
CursorStyle, Edges, Element, GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId,
IntoElement, LayoutId, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, Pixels, Point,
Position, ScrollHandle, ScrollWheelEvent, Size, UniformListScrollHandle, Window,
};
use theme::ActiveTheme;
use theme::{ActiveTheme, ScrollBarMode};
const WIDTH: Pixels = px(12.);
const BORDER_WIDTH: Pixels = px(0.);
const MIN_THUMB_SIZE: f32 = 80.;
const THUMB_RADIUS: Pixels = Pixels(4.0);
const THUMB_INSET: Pixels = Pixels(3.);
const FADE_OUT_DURATION: f32 = 2.0;
const FADE_OUT_DELAY: f32 = 1.2;
use crate::AxisExt;
const WIDTH: Pixels = px(2. * 2. + 8.);
const MIN_THUMB_SIZE: f32 = 48.;
const THUMB_WIDTH: Pixels = px(6.);
const THUMB_RADIUS: Pixels = Pixels(6. / 2.);
const THUMB_INSET: Pixels = Pixels(2.);
const THUMB_ACTIVE_WIDTH: Pixels = px(8.);
const THUMB_ACTIVE_RADIUS: Pixels = Pixels(8. / 2.);
const THUMB_ACTIVE_INSET: Pixels = Pixels(2.);
const FADE_OUT_DURATION: f32 = 3.0;
const FADE_OUT_DELAY: f32 = 2.0;
pub trait ScrollHandleOffsetable {
fn offset(&self) -> Point<Pixels>;
@@ -24,6 +33,8 @@ pub trait ScrollHandleOffsetable {
fn is_uniform_list(&self) -> bool {
false
}
/// The full size of the content, including padding.
fn content_size(&self) -> Size<Pixels>;
}
impl ScrollHandleOffsetable for ScrollHandle {
@@ -34,6 +45,10 @@ impl ScrollHandleOffsetable for ScrollHandle {
fn set_offset(&self, offset: Point<Pixels>) {
self.set_offset(offset);
}
fn content_size(&self) -> Size<Pixels> {
self.max_offset() + self.bounds().size
}
}
impl ScrollHandleOffsetable for UniformListScrollHandle {
@@ -48,13 +63,21 @@ impl ScrollHandleOffsetable for UniformListScrollHandle {
fn is_uniform_list(&self) -> bool {
true
}
fn content_size(&self) -> Size<Pixels> {
let base_handle = &self.0.borrow().base_handle;
base_handle.max_offset() + base_handle.bounds().size
}
}
#[derive(Debug, Clone)]
pub struct ScrollbarState(Rc<Cell<ScrollbarStateInner>>);
#[derive(Debug, Clone, Copy)]
pub struct ScrollbarState {
hovered_axis: Option<ScrollbarAxis>,
hovered_on_thumb: Option<ScrollbarAxis>,
dragged_axis: Option<ScrollbarAxis>,
pub struct ScrollbarStateInner {
hovered_axis: Option<Axis>,
hovered_on_thumb: Option<Axis>,
dragged_axis: Option<Axis>,
drag_pos: Point<Pixels>,
last_scroll_offset: Point<Pixels>,
last_scroll_time: Option<Instant>,
@@ -64,7 +87,7 @@ pub struct ScrollbarState {
impl Default for ScrollbarState {
fn default() -> Self {
Self {
Self(Rc::new(Cell::new(ScrollbarStateInner {
hovered_axis: None,
hovered_on_thumb: None,
dragged_axis: None,
@@ -72,16 +95,20 @@ impl Default for ScrollbarState {
last_scroll_offset: point(px(0.), px(0.)),
last_scroll_time: None,
last_update: Instant::now(),
}
})))
}
}
impl ScrollbarState {
pub fn new() -> Self {
Self::default()
}
impl Deref for ScrollbarState {
type Target = Rc<Cell<ScrollbarStateInner>>;
fn with_drag_pos(&self, axis: ScrollbarAxis, pos: Point<Pixels>) -> Self {
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ScrollbarStateInner {
fn with_drag_pos(&self, axis: Axis, pos: Point<Pixels>) -> Self {
let mut state = *self;
if axis.is_vertical() {
state.drag_pos.y = pos.y;
@@ -99,7 +126,7 @@ impl ScrollbarState {
state
}
fn with_hovered(&self, axis: Option<ScrollbarAxis>) -> Self {
fn with_hovered(&self, axis: Option<Axis>) -> Self {
let mut state = *self;
state.hovered_axis = axis;
if axis.is_some() {
@@ -108,10 +135,10 @@ impl ScrollbarState {
state
}
fn with_hovered_on_thumb(&self, axis: Option<ScrollbarAxis>) -> Self {
fn with_hovered_on_thumb(&self, axis: Option<Axis>) -> Self {
let mut state = *self;
state.hovered_on_thumb = axis;
if axis.is_some() {
if self.is_scrollbar_visible() && axis.is_some() {
state.last_scroll_time = Some(std::time::Instant::now());
}
state
@@ -162,14 +189,28 @@ pub enum ScrollbarAxis {
Both,
}
impl From<Axis> for ScrollbarAxis {
fn from(axis: Axis) -> Self {
match axis {
Axis::Vertical => Self::Vertical,
Axis::Horizontal => Self::Horizontal,
}
}
}
impl ScrollbarAxis {
#[inline]
fn is_vertical(&self) -> bool {
/// Return true if the scrollbar axis is vertical.
pub fn is_vertical(&self) -> bool {
matches!(self, Self::Vertical)
}
#[inline]
fn is_both(&self) -> bool {
/// Return true if the scrollbar axis is horizontal.
pub fn is_horizontal(&self) -> bool {
matches!(self, Self::Horizontal)
}
/// Return true if the scrollbar axis is both vertical and horizontal.
pub fn is_both(&self) -> bool {
matches!(self, Self::Both)
}
@@ -184,24 +225,23 @@ impl ScrollbarAxis {
}
#[inline]
fn all(&self) -> Vec<ScrollbarAxis> {
fn all(&self) -> Vec<Axis> {
match self {
Self::Vertical => vec![Self::Vertical],
Self::Horizontal => vec![Self::Horizontal],
Self::Vertical => vec![Axis::Vertical],
Self::Horizontal => vec![Axis::Horizontal],
// This should keep Horizontal first, Vertical is the primary axis
// if Vertical not need display, then Horizontal will not keep right margin.
Self::Both => vec![Self::Horizontal, Self::Vertical],
Self::Both => vec![Axis::Horizontal, Axis::Vertical],
}
}
}
/// Scrollbar control for scroll-area or a uniform-list.
pub struct Scrollbar {
view_id: EntityId,
axis: ScrollbarAxis,
scroll_handle: Rc<Box<dyn ScrollHandleOffsetable>>,
scroll_size: gpui::Size<Pixels>,
state: Rc<Cell<ScrollbarState>>,
state: ScrollbarState,
scroll_size: Option<Size<Pixels>>,
/// Maximum frames per second for scrolling by drag. Default is 120 FPS.
///
/// This is used to limit the update rate of the scrollbar when it is
@@ -211,95 +251,62 @@ pub struct Scrollbar {
impl Scrollbar {
fn new(
view_id: EntityId,
state: Rc<Cell<ScrollbarState>>,
axis: ScrollbarAxis,
scroll_handle: impl ScrollHandleOffsetable + 'static,
scroll_size: gpui::Size<Pixels>,
axis: impl Into<ScrollbarAxis>,
state: &ScrollbarState,
scroll_handle: &(impl ScrollHandleOffsetable + Clone + 'static),
) -> Self {
Self {
view_id,
state,
axis,
scroll_size,
scroll_handle: Rc::new(Box::new(scroll_handle)),
state: state.clone(),
axis: axis.into(),
scroll_handle: Rc::new(Box::new(scroll_handle.clone())),
max_fps: 120,
scroll_size: None,
}
}
/// Create with vertical and horizontal scrollbar.
pub fn both(
view_id: EntityId,
state: Rc<Cell<ScrollbarState>>,
scroll_handle: impl ScrollHandleOffsetable + 'static,
scroll_size: gpui::Size<Pixels>,
state: &ScrollbarState,
scroll_handle: &(impl ScrollHandleOffsetable + Clone + 'static),
) -> Self {
Self::new(
view_id,
state,
ScrollbarAxis::Both,
scroll_handle,
scroll_size,
)
Self::new(ScrollbarAxis::Both, state, scroll_handle)
}
/// Create with horizontal scrollbar.
pub fn horizontal(
view_id: EntityId,
state: Rc<Cell<ScrollbarState>>,
scroll_handle: impl ScrollHandleOffsetable + 'static,
scroll_size: gpui::Size<Pixels>,
state: &ScrollbarState,
scroll_handle: &(impl ScrollHandleOffsetable + Clone + 'static),
) -> Self {
Self::new(
view_id,
state,
ScrollbarAxis::Horizontal,
scroll_handle,
scroll_size,
)
Self::new(ScrollbarAxis::Horizontal, state, scroll_handle)
}
/// Create with vertical scrollbar.
pub fn vertical(
view_id: EntityId,
state: Rc<Cell<ScrollbarState>>,
scroll_handle: impl ScrollHandleOffsetable + 'static,
scroll_size: gpui::Size<Pixels>,
state: &ScrollbarState,
scroll_handle: &(impl ScrollHandleOffsetable + Clone + 'static),
) -> Self {
Self::new(
view_id,
state,
ScrollbarAxis::Vertical,
scroll_handle,
scroll_size,
)
Self::new(ScrollbarAxis::Vertical, state, scroll_handle)
}
/// Create vertical scrollbar for uniform list.
pub fn uniform_scroll(
view_id: EntityId,
state: Rc<Cell<ScrollbarState>>,
scroll_handle: UniformListScrollHandle,
state: &ScrollbarState,
scroll_handle: &(impl ScrollHandleOffsetable + Clone + 'static),
) -> Self {
let scroll_size = scroll_handle
.0
.borrow()
.last_item_size
.map(|size| size.contents)
.unwrap_or_default();
Self::new(ScrollbarAxis::Vertical, state, scroll_handle)
}
Self::new(
view_id,
state,
ScrollbarAxis::Vertical,
scroll_handle,
scroll_size,
)
/// Set a special scroll size of the content area, default is None.
///
/// Default will sync the `content_size` from `scroll_handle`.
pub fn scroll_size(mut self, scroll_size: Size<Pixels>) -> Self {
self.scroll_size = Some(scroll_size);
self
}
/// Set scrollbar axis.
pub fn axis(mut self, axis: ScrollbarAxis) -> Self {
self.axis = axis;
pub fn axis(mut self, axis: impl Into<ScrollbarAxis>) -> Self {
self.axis = axis.into();
self
}
@@ -313,47 +320,54 @@ impl Scrollbar {
self
}
fn style_for_active(cx: &App) -> (Hsla, Hsla, Hsla, Pixels, Pixels) {
fn style_for_active(cx: &App) -> (Hsla, Hsla, Hsla, Pixels, Pixels, Pixels) {
(
cx.theme().scrollbar_thumb_hover_background,
cx.theme().scrollbar_thumb_background,
cx.theme().scrollbar_thumb_border,
THUMB_INSET - px(1.),
THUMB_RADIUS,
THUMB_ACTIVE_WIDTH,
THUMB_ACTIVE_INSET,
THUMB_ACTIVE_RADIUS,
)
}
fn style_for_hovered_thumb(cx: &App) -> (Hsla, Hsla, Hsla, Pixels, Pixels) {
fn style_for_hovered_thumb(cx: &App) -> (Hsla, Hsla, Hsla, Pixels, Pixels, Pixels) {
(
cx.theme().scrollbar_thumb_hover_background,
cx.theme().scrollbar_thumb_background,
cx.theme().scrollbar_thumb_border,
THUMB_INSET - px(1.),
THUMB_RADIUS,
THUMB_ACTIVE_WIDTH,
THUMB_ACTIVE_INSET,
THUMB_ACTIVE_RADIUS,
)
}
fn style_for_hovered_bar(cx: &App) -> (Hsla, Hsla, Hsla, Pixels, Pixels) {
let (inset, radius) = (THUMB_INSET - px(1.), THUMB_RADIUS);
fn style_for_hovered_bar(cx: &App) -> (Hsla, Hsla, Hsla, Pixels, Pixels, Pixels) {
(
cx.theme().scrollbar_thumb_background,
cx.theme().scrollbar_thumb_border,
gpui::transparent_black(),
THUMB_ACTIVE_WIDTH,
THUMB_ACTIVE_INSET,
THUMB_ACTIVE_RADIUS,
)
}
fn style_for_idle(cx: &App) -> (Hsla, Hsla, Hsla, Pixels, Pixels, Pixels) {
let (width, inset, radius) = match cx.theme().scrollbar_mode {
ScrollBarMode::Scrolling => (THUMB_WIDTH, THUMB_INSET, THUMB_RADIUS),
_ => (THUMB_ACTIVE_WIDTH, THUMB_ACTIVE_INSET, THUMB_ACTIVE_RADIUS),
};
(
gpui::transparent_black(),
gpui::transparent_black(),
gpui::transparent_black(),
width,
inset,
radius,
)
}
fn style_for_idle(_: &App) -> (Hsla, Hsla, Hsla, Pixels, Pixels) {
(
gpui::transparent_black(),
gpui::transparent_black(),
gpui::transparent_black(),
THUMB_INSET,
THUMB_RADIUS - px(1.),
)
}
}
impl IntoElement for Scrollbar {
@@ -370,7 +384,7 @@ pub struct PrepaintState {
}
pub struct AxisPrepaintState {
axis: ScrollbarAxis,
axis: Axis,
bar_hitbox: Hitbox,
bounds: Bounds<Pixels>,
radius: Pixels,
@@ -400,11 +414,11 @@ impl Element for Scrollbar {
fn request_layout(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (gpui::LayoutId, Self::RequestLayoutState) {
) -> (LayoutId, Self::RequestLayoutState) {
let style = gpui::Style {
position: Position::Absolute,
flex_grow: 1.0,
@@ -421,8 +435,8 @@ impl Element for Scrollbar {
fn prepaint(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
bounds: Bounds<Pixels>,
_: &mut Self::RequestLayoutState,
window: &mut Window,
@@ -434,26 +448,30 @@ impl Element for Scrollbar {
let mut states = vec![];
let mut has_both = self.axis.is_both();
let scroll_size = self
.scroll_size
.unwrap_or(self.scroll_handle.content_size());
for axis in self.axis.all().into_iter() {
let is_vertical = axis.is_vertical();
let (scroll_area_size, container_size, scroll_position) = if is_vertical {
(
self.scroll_size.height,
scroll_size.height,
hitbox.size.height,
self.scroll_handle.offset().y,
)
} else {
(
self.scroll_size.width,
scroll_size.width,
hitbox.size.width,
self.scroll_handle.offset().x,
)
};
// The horizontal scrollbar is set avoid overlapping with the vertical scrollbar, if the vertical scrollbar is visible.
let margin_end = if has_both && !is_vertical {
WIDTH
THUMB_ACTIVE_WIDTH
} else {
px(0.)
};
@@ -494,12 +512,27 @@ impl Element for Scrollbar {
};
let state = self.state.clone();
let is_always_to_show = cx.theme().scrollbar_mode.is_always();
let is_hover_to_show = cx.theme().scrollbar_mode.is_hover();
let is_hovered_on_bar = state.get().hovered_axis == Some(axis);
let is_hovered_on_thumb = state.get().hovered_on_thumb == Some(axis);
let (thumb_bg, bar_bg, bar_border, inset, radius) =
let (thumb_bg, bar_bg, bar_border, thumb_width, inset, radius) =
if state.get().dragged_axis == Some(axis) {
Self::style_for_active(cx)
} else if is_hover_to_show && (is_hovered_on_bar || is_hovered_on_thumb) {
if is_hovered_on_thumb {
Self::style_for_hovered_thumb(cx)
} else {
Self::style_for_hovered_bar(cx)
}
} else if is_always_to_show {
#[allow(clippy::if_same_then_else)]
if is_hovered_on_thumb {
Self::style_for_hovered_thumb(cx)
} else {
Self::style_for_hovered_bar(cx)
}
} else {
let mut idle_state = Self::style_for_idle(cx);
// Delay 2s to fade out the scrollbar thumb (in 1s)
@@ -531,43 +564,39 @@ impl Element for Scrollbar {
idle_state
};
// The clickable area of the thumb
let thumb_length = thumb_end - thumb_start - inset * 2;
let thumb_bounds = if is_vertical {
Bounds::from_corners(
point(bounds.origin.x, bounds.origin.y + thumb_start),
point(bounds.origin.x + WIDTH, bounds.origin.y + thumb_end),
Bounds::from_corner_and_size(
Corner::TopRight,
bounds.top_right() + point(-inset, inset + thumb_start),
size(WIDTH, thumb_length),
)
} else {
Bounds::from_corners(
point(bounds.origin.x + thumb_start, bounds.origin.y),
point(bounds.origin.x + thumb_end, bounds.origin.y + WIDTH),
Bounds::from_corner_and_size(
Corner::BottomLeft,
bounds.bottom_left() + point(inset + thumb_start, -inset),
size(thumb_length, WIDTH),
)
};
// The actual render area of the thumb
let thumb_fill_bounds = if is_vertical {
Bounds::from_corners(
point(
bounds.origin.x + inset + BORDER_WIDTH,
bounds.origin.y + thumb_start + inset,
),
point(
bounds.origin.x + WIDTH - inset,
bounds.origin.y + thumb_end - inset,
),
Bounds::from_corner_and_size(
Corner::TopRight,
bounds.top_right() + point(-inset, inset + thumb_start),
size(thumb_width, thumb_length),
)
} else {
Bounds::from_corners(
point(
bounds.origin.x + thumb_start + inset,
bounds.origin.y + inset + BORDER_WIDTH,
),
point(
bounds.origin.x + thumb_end - inset,
bounds.origin.y + WIDTH - inset,
),
Bounds::from_corner_and_size(
Corner::BottomLeft,
bounds.bottom_left() + point(inset + thumb_start, -inset),
size(thumb_length, thumb_width),
)
};
let bar_hitbox = window.with_content_mask(Some(ContentMask { bounds }), |window| {
window.insert_hitbox(bounds, HitboxBehavior::Normal)
window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal)
});
states.push(AxisPrepaintState {
@@ -592,16 +621,19 @@ impl Element for Scrollbar {
fn paint(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: Bounds<Pixels>,
_: &mut Self::RequestLayoutState,
prepaint: &mut Self::PrepaintState,
window: &mut Window,
_cx: &mut App,
cx: &mut App,
) {
let view_id = window.current_view();
let hitbox_bounds = prepaint.hitbox.bounds;
let is_visible = self.state.get().is_scrollbar_visible();
let is_visible =
self.state.get().is_scrollbar_visible() || cx.theme().scrollbar_mode.is_always();
let is_hover_to_show = cx.theme().scrollbar_mode.is_hover();
// Update last_scroll_time when offset is changed.
if self.scroll_handle.offset() != self.state.get().last_scroll_offset {
@@ -637,23 +669,14 @@ impl Element for Scrollbar {
bounds,
corner_radii: (0.).into(),
background: gpui::transparent_black().into(),
border_widths: if is_vertical {
Edges {
top: px(0.),
right: px(0.),
bottom: px(0.),
left: BORDER_WIDTH,
}
} else {
Edges {
top: BORDER_WIDTH,
right: px(0.),
bottom: px(0.),
left: px(0.),
}
border_widths: Edges {
top: px(0.),
right: px(0.),
bottom: px(0.),
left: px(0.),
},
border_color: state.border,
border_style: BorderStyle::Solid,
border_style: BorderStyle::default(),
});
cx.paint_quad(
@@ -663,7 +686,6 @@ impl Element for Scrollbar {
window.on_mouse_event({
let state = self.state.clone();
let view_id = self.view_id;
let scroll_handle = self.scroll_handle.clone();
move |event: &ScrollWheelEvent, phase, _, cx| {
@@ -682,10 +704,9 @@ impl Element for Scrollbar {
let safe_range = (-scroll_area_size + container_size)..px(0.);
if is_visible {
if is_hover_to_show || is_visible {
window.on_mouse_event({
let state = self.state.clone();
let view_id = self.view_id;
let scroll_handle = self.scroll_handle.clone();
move |event: &MouseDownEvent, phase, _, cx| {
@@ -734,14 +755,13 @@ impl Element for Scrollbar {
window.on_mouse_event({
let scroll_handle = self.scroll_handle.clone();
let state = self.state.clone();
let view_id = self.view_id;
let max_fps_duration = Duration::from_millis((1000 / self.max_fps) as u64);
move |event: &MouseMoveEvent, _, _, cx| {
let mut notify = false;
// When is hover to show mode or it was visible,
// we need to update the hovered state and increase the last_scroll_time.
let need_hover_to_update = is_visible;
let need_hover_to_update = is_hover_to_show || is_visible;
// Update hovered state for scrollbar
if bounds.contains(&event.position) && need_hover_to_update {
state.set(state.get().with_hovered(Some(axis)));
@@ -815,7 +835,6 @@ impl Element for Scrollbar {
});
window.on_mouse_event({
let view_id = self.view_id;
let state = self.state.clone();
move |_event: &MouseUpEvent, phase, _, cx| {

View File

@@ -1,8 +1,7 @@
use std::fmt::{self, Display, Formatter};
use gpui::{
div, px, App, Axis, Div, Element, ElementId, EntityId, Pixels, Refineable, StyleRefinement,
Styled, Window,
div, px, App, Axis, Div, Element, ElementId, Pixels, Refineable, StyleRefinement, Styled,
};
use serde::{Deserialize, Serialize};
use theme::ActiveTheme;
@@ -48,19 +47,15 @@ pub trait StyledExt: Styled + Sized {
self.flex().flex_col()
}
/// Render a border with a width of 1px, color ring color
fn outline(self, _window: &Window, cx: &App) -> Self {
self.border_color(cx.theme().ring)
}
/// Wraps the element in a ScrollView.
///
/// Current this is only have a vertical scrollbar.
fn scrollable(self, view_id: EntityId, axis: ScrollbarAxis) -> Scrollable<Self>
#[inline]
fn scrollable(self, axis: impl Into<ScrollbarAxis>) -> Scrollable<Self>
where
Self: Element,
{
Scrollable::new(view_id, self, axis)
Scrollable::new(axis, self)
}
font_weight!(font_thin, THIN);
@@ -74,6 +69,7 @@ pub trait StyledExt: Styled + Sized {
font_weight!(font_black, BLACK);
/// Set as Popover style
#[inline]
fn popover_style(self, cx: &mut App) -> Self {
self.bg(cx.theme().background)
.border_1()