wip: refactor

This commit is contained in:
2025-01-08 12:34:13 +07:00
parent fe24f84b02
commit 122ee4c8bb
13 changed files with 360 additions and 271 deletions

View File

@@ -3,5 +3,5 @@ pub const APP_NAME: &str = "Coop";
pub const FAKE_SIG: &str = "f9e79d141c004977192d05a86f81ec7c585179c371f7350a5412d33575a2a356433f58e405c2296ed273e2fe0aafa25b641e39cc4e1f3f261ebf55bce0cbac83"; pub const FAKE_SIG: &str = "f9e79d141c004977192d05a86f81ec7c585179c371f7350a5412d33575a2a356433f58e405c2296ed273e2fe0aafa25b641e39cc4e1f3f261ebf55bce0cbac83";
pub const NEW_MESSAGE_SUB_ID: &str = "listen_new_giftwrap"; pub const NEW_MESSAGE_SUB_ID: &str = "listen_new_giftwrap";
pub const ALL_MESSAGES_SUB_ID: &str = "listen_all_giftwraps"; pub const ALL_MESSAGES_SUB_ID: &str = "listen_all_giftwraps";
pub const METADATA_DELAY: u64 = 100; pub const METADATA_DELAY: u64 = 200;
pub const IMAGE_SERVICE: &str = "https://wsrv.nl"; pub const IMAGE_SERVICE: &str = "https://wsrv.nl";

View File

@@ -8,7 +8,7 @@ use gpui::{
VisualContext, WindowBounds, WindowDecorations, WindowKind, WindowOptions, VisualContext, WindowBounds, WindowDecorations, WindowKind, WindowOptions,
}; };
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use states::{account::AccountRegistry, chat::ChatRegistry}; use states::{app::AppRegistry, chat::ChatRegistry};
use std::{ use std::{
collections::HashSet, collections::HashSet,
fs, fs,
@@ -38,6 +38,8 @@ static CLIENT: OnceLock<Client> = OnceLock::new();
pub enum Signal { pub enum Signal {
/// Receive event /// Receive event
Event(Event), Event(Event),
/// Receive metadata
Metadata(PublicKey),
/// Receive EOSE /// Receive EOSE
Eose, Eose,
} }
@@ -99,7 +101,6 @@ async fn main() {
let all_messages = SubscriptionId::new(ALL_MESSAGES_SUB_ID); let all_messages = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
while let Ok(notification) = notifications.recv().await { while let Ok(notification) = notifications.recv().await {
#[allow(clippy::collapsible_match)]
if let RelayPoolNotification::Message { message, .. } = notification { if let RelayPoolNotification::Message { message, .. } = notification {
if let RelayMessage::Event { if let RelayMessage::Event {
event, event,
@@ -143,6 +144,10 @@ async fn main() {
} }
Err(e) => println!("Unwrap error: {}", e), Err(e) => println!("Unwrap error: {}", e),
} }
} else if event.kind == Kind::Metadata {
if let Err(e) = signal_tx.send(Signal::Metadata(event.pubkey)).await {
println!("Send error: {}", e)
}
} }
} else if let RelayMessage::EndOfStoredEvents(subscription_id) = message { } else if let RelayMessage::EndOfStoredEvents(subscription_id) = message {
if subscription_id == all_messages { if subscription_id == all_messages {
@@ -195,8 +200,8 @@ async fn main() {
.with_assets(Assets) .with_assets(Assets)
.with_http_client(Arc::new(reqwest_client::ReqwestClient::new())) .with_http_client(Arc::new(reqwest_client::ReqwestClient::new()))
.run(move |cx| { .run(move |cx| {
// Account state // App state
AccountRegistry::set_global(cx); AppRegistry::set_global(cx);
// Chat state // Chat state
ChatRegistry::set_global(cx); ChatRegistry::set_global(cx);
@@ -216,20 +221,23 @@ async fn main() {
let hex = String::from_utf8(secret).unwrap(); let hex = String::from_utf8(secret).unwrap();
let keys = Keys::parse(&hex).unwrap(); let keys = Keys::parse(&hex).unwrap();
_ = client.set_signer(keys).await; // Update signer
async_cx
.background_executor()
.spawn(async move { client.set_signer(keys).await })
.detach();
// Update global state // Update global state
_ = async_cx.update_global::<AccountRegistry, _>(|state, _cx| { _ = async_cx.update_global::<AppRegistry, _>(|state, cx| {
state.set_user(Some(public_key)); state.set_user(public_key, cx);
state.set_loading();
}); });
} else { } else {
_ = async_cx.update_global::<AccountRegistry, _>(|state, _| { _ = async_cx.update_global::<AppRegistry, _>(|state, _| {
state.set_loading(); state.set_loading();
}); });
} }
} else { } else {
_ = async_cx.update_global::<AccountRegistry, _>(|state, _| { _ = async_cx.update_global::<AppRegistry, _>(|state, _| {
state.set_loading(); state.set_loading();
}); });
} }
@@ -258,6 +266,11 @@ async fn main() {
state.init(cx); state.init(cx);
}); });
} }
Signal::Metadata(public_key) => {
_ = async_cx.update_global::<AppRegistry, _>(|state, cx| {
state.set_refresh(public_key, cx);
});
}
Signal::Event(event) => { Signal::Event(event) => {
let metadata = async_cx let metadata = async_cx
.background_executor() .background_executor()

View File

@@ -1,85 +0,0 @@
use gpui::*;
use nostr_sdk::prelude::*;
use std::time::Duration;
use crate::{
constants::{ALL_MESSAGES_SUB_ID, NEW_MESSAGE_SUB_ID},
get_client,
};
pub struct AccountRegistry {
public_key: Option<PublicKey>,
pub(crate) is_loading: bool,
}
impl Global for AccountRegistry {}
impl AccountRegistry {
pub fn set_global(cx: &mut AppContext) {
cx.set_global(Self::new());
cx.observe_global::<Self>(|cx| {
let state = cx.global::<Self>();
if let Some(public_key) = state.public_key {
let client = get_client();
let all_messages_sub_id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
let new_message_sub_id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
// Create a filter for getting all gift wrapped events send to current user
let all_messages = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
// Subscription options
let opts = SubscribeAutoCloseOptions::default()
.exit_policy(ReqExitPolicy::WaitDurationAfterEOSE(Duration::from_secs(5)));
// Create a filter for getting new message
let new_message = Filter::new()
.kind(Kind::GiftWrap)
.pubkey(public_key)
.limit(0);
cx.background_executor()
.spawn(async move {
// Subscribe for all messages
if client
.subscribe_with_id(all_messages_sub_id, vec![all_messages], Some(opts))
.await
.is_ok()
{
// Subscribe for new message
_ = client
.subscribe_with_id(new_message_sub_id, vec![new_message], None)
.await
}
})
.detach();
}
})
.detach();
}
pub fn set_loading(&mut self) {
self.is_loading = false
}
pub fn get(&self) -> Option<PublicKey> {
self.public_key
}
pub fn set_user(&mut self, public_key: Option<PublicKey>) {
self.public_key = public_key
}
pub fn is_user_logged_in(&self) -> bool {
self.public_key.is_some()
}
fn new() -> Self {
Self {
public_key: None,
is_loading: true,
}
}
}

View File

@@ -0,0 +1,111 @@
use crate::{
constants::{ALL_MESSAGES_SUB_ID, NEW_MESSAGE_SUB_ID},
get_client,
};
use gpui::*;
use nostr_sdk::prelude::*;
use std::time::Duration;
pub struct AppRegistry {
user: Model<Option<PublicKey>>,
refreshs: Model<Vec<PublicKey>>,
pub(crate) is_loading: bool,
}
impl Global for AppRegistry {}
impl AppRegistry {
pub fn set_global(cx: &mut AppContext) {
let refreshs = cx.new_model(|_| Vec::new());
let user = cx.new_model(|_| None);
let async_user = user.clone();
cx.set_global(Self {
user,
refreshs,
is_loading: true,
});
cx.observe(&async_user, |model, cx| {
if let Some(public_key) = model.read(cx).clone().as_ref() {
let client = get_client();
let public_key = *public_key;
let all_messages_sub_id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
let new_message_sub_id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
// Create a filter for getting all gift wrapped events send to current user
let all_messages = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
// Subscription options
let opts = SubscribeAutoCloseOptions::default()
.exit_policy(ReqExitPolicy::WaitDurationAfterEOSE(Duration::from_secs(5)));
// Create a filter for getting new message
let new_message = Filter::new()
.kind(Kind::GiftWrap)
.pubkey(public_key)
.limit(0);
cx.background_executor()
.spawn(async move {
// Subscribe for all messages
_ = client
.subscribe_with_id(all_messages_sub_id, vec![all_messages], Some(opts))
.await;
// Subscribe for new message
_ = client
.subscribe_with_id(new_message_sub_id, vec![new_message], None)
.await;
let subscription = Filter::new()
.kind(Kind::Metadata)
.author(public_key)
.limit(1);
// Get metadata
_ = client.sync(subscription, &SyncOptions::default()).await;
let subscription = Filter::new()
.kind(Kind::ContactList)
.author(public_key)
.limit(1);
// Get contact list
_ = client.sync(subscription, &SyncOptions::default()).await;
})
.detach();
}
})
.detach();
}
pub fn set_loading(&mut self) {
self.is_loading = false
}
pub fn set_user(&mut self, public_key: PublicKey, cx: &mut AppContext) {
self.user.update(cx, |model, cx| {
*model = Some(public_key);
cx.notify();
});
self.is_loading = false;
}
pub fn set_refresh(&mut self, public_key: PublicKey, cx: &mut AppContext) {
self.refreshs.update(cx, |this, cx| {
this.push(public_key);
cx.notify();
})
}
pub fn current_user(&self) -> WeakModel<Option<PublicKey>> {
self.user.downgrade()
}
pub fn refreshs(&self) -> WeakModel<Vec<PublicKey>> {
self.refreshs.downgrade()
}
}

View File

@@ -97,11 +97,8 @@ impl ChatRegistry {
} }
pub fn init(&mut self, cx: &mut AppContext) { pub fn init(&mut self, cx: &mut AppContext) {
if self.is_initialized {
return;
}
let async_cx = cx.to_async(); let async_cx = cx.to_async();
// Get all current room's ids // Get all current room's ids
let ids: Vec<String> = self let ids: Vec<String> = self
.rooms .rooms
@@ -113,42 +110,43 @@ impl ChatRegistry {
cx.foreground_executor() cx.foreground_executor()
.spawn(async move { .spawn(async move {
let client = get_client(); let client = get_client();
let signer = client.signer().await.unwrap(); let query: anyhow::Result<Vec<Event>, anyhow::Error> = async_cx
let public_key = signer.get_public_key().await.unwrap();
let filter = Filter::new()
.kind(Kind::PrivateDirectMessage)
.pubkey(public_key);
let events = async_cx
.background_executor() .background_executor()
.spawn(async move { .spawn(async move {
if let Ok(events) = client.database().query(vec![filter]).await { let signer = client.signer().await?;
events let public_key = signer.get_public_key().await?;
.into_iter()
.filter(|ev| ev.pubkey != public_key) let filter = Filter::new()
.filter(|ev| { .kind(Kind::PrivateDirectMessage)
let new_id = get_room_id(&ev.pubkey, &ev.tags); .pubkey(public_key);
// Get new events only
!ids.iter().any(|id| id == &new_id) let events = client.database().query(vec![filter]).await?;
}) // Filter all messages from current user let result = events
.unique_by(|ev| ev.pubkey) .into_iter()
.sorted_by_key(|ev| Reverse(ev.created_at)) .filter(|ev| ev.pubkey != public_key)
.collect::<Vec<_>>() .filter(|ev| {
} else { let new_id = get_room_id(&ev.pubkey, &ev.tags);
Vec::new() // Get new events only
} !ids.iter().any(|id| id == &new_id)
}) // Filter all messages from current user
.unique_by(|ev| ev.pubkey)
.sorted_by_key(|ev| Reverse(ev.created_at))
.collect::<Vec<_>>();
Ok(result)
}) })
.await; .await;
_ = async_cx.update_global::<Self, _>(|state, cx| { if let Ok(events) = query {
state.rooms.update(cx, |model, cx| { _ = async_cx.update_global::<Self, _>(|state, cx| {
model.extend(events); state.rooms.update(cx, |model, cx| {
cx.notify(); model.extend(events);
}); cx.notify();
});
state.is_initialized = true; state.is_initialized = true;
}); });
}
}) })
.detach(); .detach();
} }

View File

@@ -1,2 +1,2 @@
pub mod account; pub mod app;
pub mod chat; pub mod chat;

View File

@@ -10,12 +10,12 @@ use ui::{
Icon, IconName, Sizable, Icon, IconName, Sizable,
}; };
use crate::states::app::AppRegistry;
use crate::{constants::IMAGE_SERVICE, get_client}; use crate::{constants::IMAGE_SERVICE, get_client};
actions!(account, [ToDo]); actions!(account, [ToDo]);
pub struct Account { pub struct Account {
#[allow(dead_code)]
public_key: PublicKey, public_key: PublicKey,
metadata: Model<Option<Metadata>>, metadata: Model<Option<Metadata>>,
} }
@@ -23,32 +23,46 @@ pub struct Account {
impl Account { impl Account {
pub fn new(public_key: PublicKey, cx: &mut ViewContext<'_, Self>) -> Self { pub fn new(public_key: PublicKey, cx: &mut ViewContext<'_, Self>) -> Self {
let metadata = cx.new_model(|_| None); let metadata = cx.new_model(|_| None);
let async_metadata = metadata.clone(); let refreshs = cx.global_mut::<AppRegistry>().refreshs();
let mut async_cx = cx.to_async(); if let Some(refreshs) = refreshs.upgrade() {
cx.observe(&refreshs, |this, _, cx| {
cx.foreground_executor() this.load_metadata(cx);
.spawn(async move {
let client = get_client();
let query = async_cx
.background_executor()
.spawn(async move { client.database().metadata(public_key).await })
.await;
if let Ok(metadata) = query {
_ = async_cx.update_model(&async_metadata, |a, b| {
*a = metadata;
b.notify();
});
};
}) })
.detach(); .detach();
}
Self { Self {
public_key, public_key,
metadata, metadata,
} }
} }
pub fn load_metadata(&self, cx: &mut ViewContext<Self>) {
let mut async_cx = cx.to_async();
let async_metadata = self.metadata.clone();
cx.foreground_executor()
.spawn({
let client = get_client();
let public_key = self.public_key;
async move {
let metadata = async_cx
.background_executor()
.spawn(async move { client.database().metadata(public_key).await })
.await;
if let Ok(metadata) = metadata {
_ = async_cx.update_model(&async_metadata, |model, cx| {
*model = metadata;
cx.notify();
});
}
}
})
.detach();
}
} }
impl Render for Account { impl Render for Account {
@@ -59,20 +73,25 @@ impl Render for Account {
.reverse() .reverse()
.ghost() .ghost()
.icon(Icon::new(IconName::ChevronDownSmall)) .icon(Icon::new(IconName::ChevronDownSmall))
.when_some(self.metadata.read(cx).as_ref(), |this, metadata| { .map(|this| {
this.map(|this| { if let Some(metadata) = self.metadata.read(cx).as_ref() {
if let Some(picture) = metadata.picture.clone() { this.map(|this| {
this.flex_shrink_0().child( if let Some(picture) = metadata.picture.clone() {
img(format!("{}/?url={}&w=72&h=72&n=-1", IMAGE_SERVICE, picture)) this.flex_shrink_0().child(
.size_5() img(format!("{}/?url={}&w=72&h=72&n=-1", IMAGE_SERVICE, picture))
.rounded_full() .size_5()
.object_fit(ObjectFit::Cover), .rounded_full()
) .object_fit(ObjectFit::Cover),
} else { )
this.flex_shrink_0() } else {
.child(img("brand/avatar.png").size_6().rounded_full()) this.flex_shrink_0()
} .child(img("brand/avatar.png").size_5().rounded_full())
}) }
})
} else {
this.flex_shrink_0()
.child(img("brand/avatar.png").size_5().rounded_full())
}
}) })
.popup_menu(move |this, _cx| { .popup_menu(move |this, _cx| {
this.menu("Profile", Box::new(ToDo)) this.menu("Profile", Box::new(ToDo))

View File

@@ -2,8 +2,7 @@ use super::{
account::Account, chat::ChatPanel, onboarding::Onboarding, sidebar::Sidebar, account::Account, chat::ChatPanel, onboarding::Onboarding, sidebar::Sidebar,
welcome::WelcomePanel, welcome::WelcomePanel,
}; };
use crate::states::{account::AccountRegistry, chat::Room}; use crate::states::{app::AppRegistry, chat::Room};
use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
div, impl_actions, px, Axis, Context, Edges, InteractiveElement, IntoElement, Model, div, impl_actions, px, Axis, Context, Edges, InteractiveElement, IntoElement, Model,
ParentElement, Render, Styled, View, ViewContext, VisualContext, WeakView, WindowContext, ParentElement, Render, Styled, View, ViewContext, VisualContext, WeakView, WindowContext,
@@ -64,20 +63,31 @@ impl AppView {
// Dock // Dock
let dock = cx.new_view(|cx| DockArea::new(DOCK_AREA.id, Some(DOCK_AREA.version), cx)); let dock = cx.new_view(|cx| DockArea::new(DOCK_AREA.id, Some(DOCK_AREA.version), cx));
cx.observe_global::<AccountRegistry>(move |view, cx| { // Get current user from app state
if let Some(public_key) = cx.global::<AccountRegistry>().get() { let current_user = cx.global::<AppRegistry>().current_user();
Self::init_layout(view.dock.downgrade(), cx);
// TODO: save dock state and load previous state on startup
let view = cx.new_view(|cx| Account::new(public_key, cx)); if let Some(current_user) = current_user.upgrade() {
cx.observe(&current_user, move |view, model, cx| {
if let Some(public_key) = model.read(cx).clone().as_ref() {
Self::init_layout(view.dock.downgrade(), cx);
// TODO: save dock state and load previous state on startup
cx.update_model(&async_account, |model, cx| { let view = cx.new_view(|cx| {
*model = Some(view); let view = Account::new(*public_key, cx);
cx.notify(); // Initial load metadata
}); view.load_metadata(cx);
}
}) view
.detach(); });
cx.update_model(&async_account, |model, cx| {
*model = Some(view);
cx.notify();
});
}
})
.detach();
}
AppView { AppView {
account, account,
@@ -138,11 +148,10 @@ impl Render for AppView {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement { fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
let modal_layer = Root::render_modal_layer(cx); let modal_layer = Root::render_modal_layer(cx);
let notification_layer = Root::render_notification_layer(cx); let notification_layer = Root::render_notification_layer(cx);
let state = cx.global::<AccountRegistry>();
let mut content = div().size_full().flex().flex_col(); let mut content = div().size_full().flex().flex_col();
if state.is_loading { if cx.global::<AppRegistry>().is_loading {
content = content.child(div()).child( content = content.child(div()).child(
div() div()
.flex_1() .flex_1()
@@ -151,7 +160,7 @@ impl Render for AppView {
.justify_center() .justify_center()
.child(Indicator::new().small()), .child(Indicator::new().small()),
) )
} else if state.is_user_logged_in() { } else if let Some(account) = self.account.read(cx).as_ref() {
content = content content = content
.child( .child(
TitleBar::new() TitleBar::new()
@@ -165,9 +174,7 @@ impl Render for AppView {
.justify_end() .justify_end()
.gap_1() .gap_1()
.px_2() .px_2()
.when_some(self.account.read(cx).as_ref(), |this, account| { .child(account.clone()),
this.child(account.clone())
}),
), ),
) )
.child(self.dock.clone()) .child(self.dock.clone())

View File

@@ -15,10 +15,7 @@ use ui::{
use super::message::RoomMessage; use super::message::RoomMessage;
use crate::{ use crate::{
get_client, get_client,
states::{ states::chat::{ChatRegistry, Room},
account::AccountRegistry,
chat::{ChatRegistry, Room},
},
}; };
#[derive(Clone)] #[derive(Clone)]
@@ -202,7 +199,6 @@ impl RoomPanel {
fn send_message(&mut self, cx: &mut ViewContext<Self>) { fn send_message(&mut self, cx: &mut ViewContext<Self>) {
let owner = self.owner; let owner = self.owner;
let current_user = cx.global::<AccountRegistry>().get().unwrap();
let content = self.input.read(cx).text().to_string(); let content = self.input.read(cx).text().to_string();
let content2 = content.clone(); let content2 = content.clone();
let content3 = content2.clone(); let content3 = content2.clone();
@@ -216,6 +212,14 @@ impl RoomPanel {
let client = get_client(); let client = get_client();
async move { async move {
let current_user = async_cx
.background_executor()
.spawn(async move {
let signer = client.signer().await.unwrap();
signer.get_public_key().await.unwrap()
})
.await;
// Send message to all members // Send message to all members
async_cx async_cx
.background_executor() .background_executor()

View File

@@ -1,15 +1,11 @@
use gpui::{ use crate::{constants::KEYRING_SERVICE, get_client, states::app::AppRegistry};
div, IntoElement, use gpui::{div, IntoElement, ParentElement, Render, Styled, View, ViewContext, VisualContext};
ParentElement, Render, Styled, View, ViewContext, VisualContext,
};
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use ui::{ use ui::{
input::{InputEvent, TextInput}, input::{InputEvent, TextInput},
label::Label, label::Label,
}; };
use crate::{constants::KEYRING_SERVICE, get_client, states::account::AccountRegistry};
pub struct Onboarding { pub struct Onboarding {
input: View<TextInput>, input: View<TextInput>,
} }
@@ -40,7 +36,6 @@ impl Onboarding {
let secret = keys.secret_key().to_secret_hex(); let secret = keys.secret_key().to_secret_hex();
let mut async_cx = cx.to_async(); let mut async_cx = cx.to_async();
let view_id = cx.entity_id();
cx.foreground_executor() cx.foreground_executor()
.spawn({ .spawn({
@@ -50,10 +45,8 @@ impl Onboarding {
async move { async move {
if task.await.is_ok() { if task.await.is_ok() {
_ = client.set_signer(keys).await; _ = client.set_signer(keys).await;
// Update global state _ = async_cx.update_global::<AppRegistry, _>(|state, cx| {
_ = async_cx.update_global::<AccountRegistry, _>(|state, cx| { state.set_user(public_key, cx);
state.set_user(Some(public_key));
cx.notify(Some(view_id));
}); });
} }
} }

View File

@@ -1,6 +1,4 @@
use crate::{ use crate::{constants::IMAGE_SERVICE, get_client, utils::show_npub};
constants::IMAGE_SERVICE, get_client, states::account::AccountRegistry, utils::show_npub,
};
use gpui::{ use gpui::{
div, img, impl_actions, list, px, Context, ElementId, FocusHandle, InteractiveElement, div, img, impl_actions, list, px, Context, ElementId, FocusHandle, InteractiveElement,
IntoElement, ListAlignment, ListState, Model, ParentElement, Pixels, Render, RenderOnce, IntoElement, ListAlignment, ListState, Model, ParentElement, Pixels, Render, RenderOnce,
@@ -24,12 +22,12 @@ impl_actions!(contacts, [SelectContact]);
struct ContactListItem { struct ContactListItem {
id: ElementId, id: ElementId,
public_key: PublicKey, public_key: PublicKey,
metadata: Option<Metadata>, metadata: Metadata,
selected: bool, selected: bool,
} }
impl ContactListItem { impl ContactListItem {
pub fn new(public_key: PublicKey, metadata: Option<Metadata>) -> Self { pub fn new(public_key: PublicKey, metadata: Metadata) -> Self {
let id = SharedString::from(public_key.to_hex()).into(); let id = SharedString::from(public_key.to_hex()).into();
Self { Self {
@@ -55,36 +53,6 @@ impl Selectable for ContactListItem {
impl RenderOnce for ContactListItem { impl RenderOnce for ContactListItem {
fn render(self, cx: &mut WindowContext) -> impl IntoElement { fn render(self, cx: &mut WindowContext) -> impl IntoElement {
let fallback = show_npub(self.public_key, 16); let fallback = show_npub(self.public_key, 16);
let mut content = div().flex().items_center().gap_2().text_sm();
if let Some(metadata) = self.metadata {
content = content
.map(|this| {
if let Some(picture) = metadata.picture {
this.flex_shrink_0().child(
img(format!(
"{}/?url={}&w=72&h=72&fit=cover&mask=circle&n=-1",
IMAGE_SERVICE, picture
))
.size_6(),
)
} else {
this.flex_shrink_0()
.child(img("brand/avatar.png").size_6().rounded_full())
}
})
.map(|this| {
if let Some(display_name) = metadata.display_name {
this.flex_1().child(display_name)
} else {
this.flex_1().child(fallback)
}
})
} else {
content = content
.child(img("brand/avatar.png").size_6().rounded_full())
.child(fallback)
}
div() div()
.id(self.id) .id(self.id)
@@ -95,7 +63,34 @@ impl RenderOnce for ContactListItem {
.flex() .flex()
.items_center() .items_center()
.justify_between() .justify_between()
.child(content) .child(
div()
.flex()
.items_center()
.gap_2()
.text_sm()
.map(|this| {
if let Some(picture) = self.metadata.picture {
this.flex_shrink_0().child(
img(format!(
"{}/?url={}&w=72&h=72&fit=cover&mask=circle&n=-1",
IMAGE_SERVICE, picture
))
.size_6(),
)
} else {
this.flex_shrink_0()
.child(img("brand/avatar.png").size_6().rounded_full())
}
})
.map(|this| {
if let Some(display_name) = self.metadata.display_name {
this.flex_1().child(display_name)
} else {
this.flex_1().child(fallback)
}
}),
)
.when(self.selected, |this| { .when(self.selected, |this| {
this.child( this.child(
Icon::new(IconName::CircleCheck) Icon::new(IconName::CircleCheck)
@@ -141,20 +136,24 @@ impl ContactList {
cx.foreground_executor() cx.foreground_executor()
.spawn({ .spawn({
let client = get_client(); let client = get_client();
let current_user = cx.global::<AccountRegistry>().get();
async move { async move {
if let Some(public_key) = current_user { let query: anyhow::Result<BTreeSet<Profile>, anyhow::Error> = async_cx
if let Ok(profiles) = async_cx .background_executor()
.background_executor() .spawn(async move {
.spawn(async move { client.database().contacts(public_key).await }) let signer = client.signer().await?;
.await let public_key = signer.get_public_key().await?;
{ let profiles = client.database().contacts(public_key).await?;
_ = async_cx.update_model(&async_contacts, |model, cx| {
*model = profiles; Ok(profiles)
cx.notify(); })
}); .await;
}
if let Ok(profiles) = query {
_ = async_cx.update_model(&async_contacts, |model, cx| {
*model = profiles;
cx.notify();
});
} }
} }
}) })
@@ -166,9 +165,7 @@ impl ContactList {
count: profiles.len(), count: profiles.len(),
items: profiles items: profiles
.into_iter() .into_iter()
.map(|contact| { .map(|contact| ContactListItem::new(contact.public_key(), contact.metadata()))
ContactListItem::new(contact.public_key(), Some(contact.metadata()))
})
.collect(), .collect(),
}; };
@@ -194,7 +191,7 @@ impl ContactList {
} }
} }
pub fn selected(&self) -> Vec<PublicKey> { pub fn _selected(&self) -> Vec<PublicKey> {
self.selected.clone().into_iter().collect() self.selected.clone().into_iter().collect()
} }
@@ -210,7 +207,7 @@ impl ContactList {
let public_key = contact.public_key(); let public_key = contact.public_key();
let metadata = contact.metadata(); let metadata = contact.metadata();
ContactListItem::new(public_key, Some(metadata)) ContactListItem::new(contact.public_key(), metadata)
.selected(self.selected.contains(&public_key)) .selected(self.selected.contains(&public_key))
}) })
.collect(), .collect(),
@@ -238,7 +235,7 @@ impl Render for ContactList {
.flex() .flex()
.flex_col() .flex_col()
.gap_1() .gap_1()
.child(div().font_semibold().child("Contacts")) .child(div().font_semibold().text_sm().child("Contacts"))
.child( .child(
div() div()
.p_1() .p_1()

View File

@@ -1,10 +1,11 @@
use crate::{ use crate::{
constants::IMAGE_SERVICE, constants::IMAGE_SERVICE,
get_client, get_client,
states::chat::ChatRegistry, states::{
states::chat::Room, app::AppRegistry,
utils::get_room_id, chat::{ChatRegistry, Room},
utils::{ago, show_npub}, },
utils::{ago, get_room_id, show_npub},
views::app::{AddPanel, PanelKind}, views::app::{AddPanel, PanelKind},
}; };
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
@@ -20,12 +21,21 @@ use ui::{skeleton::Skeleton, theme::ActiveTheme, v_flex, Collapsible, Icon, Icon
struct InboxListItem { struct InboxListItem {
id: SharedString, id: SharedString,
event: Event, event: Event,
metadata: Option<Metadata>, metadata: Model<Option<Metadata>>,
} }
impl InboxListItem { impl InboxListItem {
pub fn new(event: Event, metadata: Option<Metadata>, _cx: &mut ViewContext<'_, Self>) -> Self { pub fn new(event: Event, metadata: Option<Metadata>, cx: &mut ViewContext<'_, Self>) -> Self {
let id = SharedString::from(get_room_id(&event.pubkey, &event.tags)); let id = SharedString::from(get_room_id(&event.pubkey, &event.tags));
let metadata = cx.new_model(|_| metadata);
let refreshs = cx.global_mut::<AppRegistry>().refreshs();
if let Some(refreshs) = refreshs.upgrade() {
cx.observe(&refreshs, |this, _, cx| {
this.load_metadata(cx);
})
.detach();
}
Self { Self {
id, id,
@@ -34,8 +44,35 @@ impl InboxListItem {
} }
} }
pub fn load_metadata(&self, cx: &mut ViewContext<Self>) {
let mut async_cx = cx.to_async();
let async_metadata = self.metadata.clone();
cx.foreground_executor()
.spawn({
let client = get_client();
let public_key = self.event.pubkey;
async move {
let metadata = async_cx
.background_executor()
.spawn(async move { client.database().metadata(public_key).await })
.await;
if let Ok(metadata) = metadata {
_ = async_cx.update_model(&async_metadata, |model, cx| {
*model = metadata;
cx.notify();
});
}
}
})
.detach();
}
pub fn action(&self, cx: &mut WindowContext<'_>) { pub fn action(&self, cx: &mut WindowContext<'_>) {
let room = Arc::new(Room::parse(&self.event, self.metadata.clone())); let metadata = self.metadata.read(cx).clone();
let room = Arc::new(Room::parse(&self.event, metadata));
cx.dispatch_action(Box::new(AddPanel { cx.dispatch_action(Box::new(AddPanel {
panel: PanelKind::Room(room), panel: PanelKind::Room(room),
@@ -53,7 +90,7 @@ impl Render for InboxListItem {
.font_medium() .font_medium()
.text_color(cx.theme().sidebar_accent_foreground); .text_color(cx.theme().sidebar_accent_foreground);
if let Some(metadata) = self.metadata.clone() { if let Some(metadata) = self.metadata.read(cx).as_ref() {
content = content content = content
.flex() .flex()
.items_center() .items_center()
@@ -145,9 +182,6 @@ impl Inbox {
} }
pub fn load(&mut self, cx: &mut ViewContext<Self>) { pub fn load(&mut self, cx: &mut ViewContext<Self>) {
// Hide loading indicator
self.set_loading(cx);
// Get all room's events // Get all room's events
let events: Vec<Event> = cx.global::<ChatRegistry>().rooms.read(cx).clone(); let events: Vec<Event> = cx.global::<ChatRegistry>().rooms.read(cx).clone();
@@ -179,15 +213,13 @@ impl Inbox {
*model = Some(views); *model = Some(views);
cx.notify() cx.notify()
}); });
this.is_loading = false;
cx.notify();
}); });
}) })
.detach(); .detach();
} }
fn set_loading(&mut self, cx: &mut ViewContext<Self>) {
self.is_loading = false;
cx.notify();
}
} }
impl Collapsible for Inbox { impl Collapsible for Inbox {

View File

@@ -57,8 +57,8 @@ impl Sidebar {
.rounded(ButtonRounded::Large) .rounded(ButtonRounded::Large)
.w_full() .w_full()
.on_click({ .on_click({
let contact_list = contact_list.clone(); let _contact_list = contact_list.clone();
move |_, cx| { move |_, _cx| {
// TODO: open room // TODO: open room
} }
}), }),