wip: refactor

This commit is contained in:
2024-12-13 10:11:12 +07:00
parent 10f042acab
commit f82eaa4ac3
20 changed files with 431 additions and 231 deletions

BIN
assets/brand/avatar.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path fill="currentColor" d="M9.8 10.25c-1.052 0-1.633 1.221-.97 2.038l2.2 2.707c.5.616 1.44.616 1.94 0l2.2-2.707c.664-.817.082-2.038-.97-2.038H9.8Z"/>
</svg>

After

Width:  |  Height:  |  Size: 257 B

View File

@@ -1,4 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path fill="#000" d="M12 13a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm8.25 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm-16.5 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"/> <path fill="currentColor" d="M12 13a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm8.25 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm-16.5 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"/>
<path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 13a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm8.25 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm-16.5 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"/> <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 13a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm8.25 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm-16.5 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 441 B

After

Width:  |  Height:  |  Size: 457 B

View File

@@ -1,3 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M13.75 3.75v6.5m0 0h6.5m-6.5 0 6.5-6.5m-10 16.5v-6.5m0 0h-6.5m6.5 0-6.5 6.5"/> <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M13.75 3.75v6.5m0 0h6.5m-6.5 0 6.5-6.5m-10 16.5v-6.5m0 0h-6.5m6.5 0-6.5 6.5"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 273 B

After

Width:  |  Height:  |  Size: 281 B

View File

@@ -1,4 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path fill="#000" fill-rule="evenodd" d="M4.75 4A2.75 2.75 0 0 0 2 6.75v10.5A2.75 2.75 0 0 0 4.75 20h14.5A2.75 2.75 0 0 0 22 17.25V6.75A2.75 2.75 0 0 0 19.25 4H4.75ZM3.5 6.75c0-.69.56-1.25 1.25-1.25h5.75v13H4.75c-.69 0-1.25-.56-1.25-1.25V6.75Z" clip-rule="evenodd"/> <path fill="currentColor" fill-rule="evenodd" d="M4.75 4A2.75 2.75 0 0 0 2 6.75v10.5A2.75 2.75 0 0 0 4.75 20h14.5A2.75 2.75 0 0 0 22 17.25V6.75A2.75 2.75 0 0 0 19.25 4H4.75ZM3.5 6.75c0-.69.56-1.25 1.25-1.25h5.75v13H4.75c-.69 0-1.25-.56-1.25-1.25V6.75Z" clip-rule="evenodd"/>
<path fill="#000" fill-rule="evenodd" d="M7 9.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2ZM7 13a1 1 0 1 1 0-2 1 1 0 0 1 0 2Zm0 3.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z" clip-rule="evenodd"/> <path fill="currentColor" fill-rule="evenodd" d="M7 9.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2ZM7 13a1 1 0 1 1 0-2 1 1 0 0 1 0 2Zm0 3.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z" clip-rule="evenodd"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 543 B

After

Width:  |  Height:  |  Size: 559 B

View File

@@ -1,4 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path fill="#000" fill-rule="evenodd" d="M4.75 4A2.75 2.75 0 0 0 2 6.75v10.5A2.75 2.75 0 0 0 4.75 20h14.5A2.75 2.75 0 0 0 22 17.25V6.75A2.75 2.75 0 0 0 19.25 4H4.75ZM3.5 6.75c0-.69.56-1.25 1.25-1.25h5.75v13H4.75c-.69 0-1.25-.56-1.25-1.25V6.75Z" clip-rule="evenodd"/> <path fill="currentColor" fill-rule="evenodd" d="M4.75 4A2.75 2.75 0 0 0 2 6.75v10.5A2.75 2.75 0 0 0 4.75 20h14.5A2.75 2.75 0 0 0 22 17.25V6.75A2.75 2.75 0 0 0 19.25 4H4.75ZM3.5 6.75c0-.69.56-1.25 1.25-1.25h5.75v13H4.75c-.69 0-1.25-.56-1.25-1.25V6.75Z" clip-rule="evenodd"/>
<path fill="#000" fill-rule="evenodd" d="M7 9.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2ZM7 13a1 1 0 1 1 0-2 1 1 0 0 1 0 2Zm0 3.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z" clip-rule="evenodd"/> <path fill="currentColor" fill-rule="evenodd" d="M7 9.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2ZM7 13a1 1 0 1 1 0-2 1 1 0 0 1 0 2Zm0 3.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z" clip-rule="evenodd"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 543 B

After

Width:  |  Height:  |  Size: 559 B

View File

@@ -1,5 +1,6 @@
pub const KEYRING_SERVICE: &str = "Coop Safe Storage"; pub const KEYRING_SERVICE: &str = "Coop Safe Storage";
pub const APP_NAME: &str = "coop"; pub const APP_NAME: &str = "coop";
pub const FAKE_SIG: &str = "f9e79d141c004977192d05a86f81ec7c585179c371f7350a5412d33575a2a356433f58e405c2296ed273e2fe0aafa25b641e39cc4e1f3f261ebf55bce0cbac83"; pub const FAKE_SIG: &str = "f9e79d141c004977192d05a86f81ec7c585179c371f7350a5412d33575a2a356433f58e405c2296ed273e2fe0aafa25b641e39cc4e1f3f261ebf55bce0cbac83";
pub const SUBSCRIPTION_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 METADATA_DELAY: u64 = 150; pub const METADATA_DELAY: u64 = 150;

View File

@@ -9,9 +9,10 @@ use std::{
sync::{Arc, OnceLock}, sync::{Arc, OnceLock},
time::Duration, time::Duration,
}; };
use tokio::sync::mpsc;
use constants::{APP_NAME, FAKE_SIG}; use constants::{ALL_MESSAGES_SUB_ID, APP_NAME, FAKE_SIG, NEW_MESSAGE_SUB_ID};
use states::account::AccountState; use states::{account::AccountRegistry, chat::ChatRegistry, signal::SignalRegistry};
use views::app::AppView; use views::app::AppView;
pub mod asset; pub mod asset;
@@ -69,11 +70,76 @@ async fn main() {
// Connect to all relays // Connect to all relays
_ = client.connect().await; _ = client.connect().await;
// Channel for metadata signal
let (signal_tx, mut signal_rx) = mpsc::channel::<PublicKey>(1000); // TODO: adjust?
// Channel for new chat
let (new_chat_tx, mut new_chat_rx) = mpsc::channel::<Event>(1000); // TODO: adjust?
// Channel for all chats
let (all_chats_tx, mut all_chats_rx) = mpsc::channel::<i32>(1);
tokio::spawn(async move {
let sig = Signature::from_str(FAKE_SIG).unwrap();
let all_messages_sub_id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
let new_message_sub_id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
while let Ok(notification) = notifications.recv().await {
#[allow(clippy::collapsible_match)]
if let RelayPoolNotification::Message { message, .. } = notification {
if let RelayMessage::Event {
event,
subscription_id,
} = message
{
if event.kind == Kind::GiftWrap {
if let Ok(UnwrappedGift { rumor, .. }) =
client.unwrap_gift_wrap(&event).await
{
let mut rumor_clone = rumor.clone();
// Compute event id if not exist
rumor_clone.ensure_id();
if let Some(id) = rumor_clone.id {
let ev = Event::new(
id,
rumor_clone.pubkey,
rumor_clone.created_at,
rumor_clone.kind,
rumor_clone.tags,
rumor_clone.content,
sig,
);
// Save rumor to database to further query
_ = client.database().save_event(&ev).await;
// Send event to channel
if subscription_id == new_message_sub_id {
_ = new_chat_tx.send(ev).await;
}
}
}
} else if event.kind == Kind::Metadata {
_ = signal_tx.send(event.pubkey).await;
}
} else if let RelayMessage::EndOfStoredEvents(subscription_id) = message {
if all_messages_sub_id == subscription_id {
_ = all_chats_tx.send(1).await;
}
}
}
}
});
App::new() App::new()
.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| {
AccountState::set_global(cx); AccountRegistry::set_global(cx);
ChatRegistry::set_global(cx);
SignalRegistry::set_global(cx);
// Initialize components // Initialize components
coop_ui::init(cx); coop_ui::init(cx);
@@ -81,46 +147,32 @@ async fn main() {
// Set quit action // Set quit action
cx.on_action(quit); cx.on_action(quit);
// Handle notifications cx.spawn(|async_cx| async move {
cx.background_executor() while let Some(public_key) = signal_rx.recv().await {
.spawn({ _ = async_cx.update_global::<SignalRegistry, _>(|state, _cx| {
let sig = Signature::from_str(FAKE_SIG).unwrap(); state.push(public_key);
async move { });
while let Ok(notification) = notifications.recv().await { }
#[allow(clippy::collapsible_match)] })
if let RelayPoolNotification::Message { message, .. } = notification { .detach();
if let RelayMessage::Event { event, .. } = message {
if event.kind == Kind::GiftWrap {
if let Ok(UnwrappedGift { rumor, .. }) =
client.unwrap_gift_wrap(&event).await
{
let mut rumor_clone = rumor.clone();
// Compute event id if not exist cx.spawn(|async_cx| async move {
rumor_clone.ensure_id(); while let Some(event) = new_chat_rx.recv().await {
_ = async_cx.update_global::<ChatRegistry, _>(|state, cx| {
state.push(event, cx);
});
}
})
.detach();
if let Some(id) = rumor_clone.id { cx.spawn(|async_cx| async move {
let ev = Event::new( while let Some(_n) = all_chats_rx.recv().await {
id, _ = async_cx.update_global::<ChatRegistry, _>(|state, cx| {
rumor_clone.pubkey, state.load(cx);
rumor_clone.created_at, });
rumor_clone.kind, }
rumor_clone.tags, })
rumor_clone.content, .detach();
sig,
);
// Save rumor to database to further query
_ = client.database().save_event(&ev).await
}
}
}
}
}
}
}
})
.detach();
// Set window size // Set window size
let bounds = Bounds::centered(None, size(px(900.0), px(680.0)), cx); let bounds = Bounds::centered(None, size(px(900.0), px(680.0)), cx);

View File

@@ -3,33 +3,36 @@ use gpui::*;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use std::time::Duration; use std::time::Duration;
use crate::{constants::SUBSCRIPTION_ID, get_client}; use crate::{
constants::{ALL_MESSAGES_SUB_ID, NEW_MESSAGE_SUB_ID},
get_client,
};
pub struct AccountState { pub struct AccountRegistry {
pub in_use: Option<PublicKey>, public_key: Option<PublicKey>,
} }
impl Global for AccountState {} impl Global for AccountRegistry {}
impl AccountState { impl AccountRegistry {
pub fn set_global(cx: &mut AppContext) { pub fn set_global(cx: &mut AppContext) {
cx.set_global(Self::new()); cx.set_global(Self::new());
cx.observe_global::<Self>(|cx| { cx.observe_global::<Self>(|cx| {
let state = cx.global::<Self>(); let state = cx.global::<Self>();
if let Some(public_key) = state.in_use { if let Some(public_key) = state.public_key {
let client = get_client(); 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 // Create a filter for getting all gift wrapped events send to current user
let all_messages = Filter::new().kind(Kind::GiftWrap).pubkey(public_key); let all_messages = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
// Subscription options // Subscription options
let opts = SubscribeAutoCloseOptions::default().filter( let opts = SubscribeAutoCloseOptions::default()
FilterOptions::WaitDurationAfterEOSE(Duration::from_secs(10)), .filter(FilterOptions::WaitDurationAfterEOSE(Duration::from_secs(5)));
);
let subscription_id = SubscriptionId::new(SUBSCRIPTION_ID);
// Create a filter for getting new message // Create a filter for getting new message
let new_message = Filter::new() let new_message = Filter::new()
@@ -38,14 +41,15 @@ impl AccountState {
.limit(0); .limit(0);
spawn(async move { spawn(async move {
// Subscribe for all messages
if client if client
.subscribe(vec![all_messages], Some(opts)) .subscribe_with_id(all_messages_sub_id, vec![all_messages], Some(opts))
.await .await
.is_ok() .is_ok()
{ {
// Subscribe for new message // Subscribe for new message
_ = client _ = client
.subscribe_with_id(subscription_id, vec![new_message], None) .subscribe_with_id(new_message_sub_id, vec![new_message], None)
.await .await
} }
}); });
@@ -54,7 +58,15 @@ impl AccountState {
.detach(); .detach();
} }
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 { fn new() -> Self {
Self { in_use: None } Self { public_key: None }
} }
} }

View File

@@ -0,0 +1,75 @@
use gpui::*;
use itertools::Itertools;
use nostr_sdk::prelude::*;
use std::cmp::Reverse;
use crate::get_client;
pub struct ChatRegistry {
events: Model<Option<Vec<Event>>>,
}
impl Global for ChatRegistry {}
impl ChatRegistry {
pub fn set_global(cx: &mut AppContext) {
let events = cx.new_model(|_| None);
cx.set_global(Self::new(events));
}
pub fn load(&self, cx: &mut AppContext) {
let mut async_cx = cx.to_async();
let async_events = self.events.clone();
cx.foreground_executor()
.spawn(async move {
let client = get_client();
let signer = client.signer().await.unwrap();
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()
.spawn(async move {
if let Ok(events) = client.database().query(vec![filter]).await {
events
.into_iter()
.filter(|ev| ev.pubkey != public_key) // Filter messages from current user
.unique_by(|ev| ev.pubkey) // Get unique list
.sorted_by_key(|ev| Reverse(ev.created_at)) // Sort by created at
.collect::<Vec<_>>()
} else {
Vec::new()
}
})
.await;
async_cx.update_model(&async_events, |a, b| {
*a = Some(events);
b.notify();
})
})
.detach();
}
pub fn push(&self, event: Event, cx: &mut AppContext) {
cx.update_model(&self.events, |a, b| {
if let Some(events) = a {
events.push(event);
b.notify();
}
})
}
pub fn get(&self, cx: &WindowContext) -> Option<Vec<Event>> {
self.events.read(cx).clone()
}
fn new(events: Model<Option<Vec<Event>>>) -> Self {
Self { events }
}
}

View File

@@ -1 +1,3 @@
pub mod account; pub mod account;
pub mod chat;
pub mod signal;

View File

@@ -0,0 +1,28 @@
use gpui::*;
use nostr_sdk::prelude::*;
pub struct SignalRegistry {
public_keys: Vec<PublicKey>,
}
impl Global for SignalRegistry {}
impl SignalRegistry {
pub fn set_global(cx: &mut AppContext) {
cx.set_global(Self::new());
}
pub fn contains(&self, public_key: PublicKey) -> bool {
self.public_keys.contains(&public_key)
}
pub fn push(&mut self, public_key: PublicKey) {
self.public_keys.push(public_key);
}
fn new() -> Self {
Self {
public_keys: Vec::new(),
}
}
}

View File

@@ -15,8 +15,8 @@ pub fn get_all_accounts_from_keyring() -> Vec<PublicKey> {
accounts accounts
} }
pub fn show_npub(public_key: PublicKey, len: usize) -> anyhow::Result<String, anyhow::Error> { pub fn show_npub(public_key: PublicKey, len: usize) -> String {
let bech32 = public_key.to_bech32()?; let bech32 = public_key.to_bech32().unwrap_or_default();
let separator = " ... "; let separator = " ... ";
let sep_len = separator.len(); let sep_len = separator.len();
@@ -24,12 +24,12 @@ pub fn show_npub(public_key: PublicKey, len: usize) -> anyhow::Result<String, an
let front_chars = (chars_to_show + 1) / 2; // ceil let front_chars = (chars_to_show + 1) / 2; // ceil
let back_chars = chars_to_show / 2; // floor let back_chars = chars_to_show / 2; // floor
Ok(format!( format!(
"{}{}{}", "{}{}{}",
&bech32[..front_chars], &bech32[..front_chars],
separator, separator,
&bech32[bech32.len() - back_chars..] &bech32[bech32.len() - back_chars..]
)) )
} }
pub fn ago(time: u64) -> String { pub fn ago(time: u64) -> String {

View File

@@ -1,5 +1,5 @@
use coop_ui::{ use coop_ui::{
dock::{DockArea, DockItem, DockPlacement, PanelStyle}, dock::{DockArea, DockItem, DockPlacement},
theme::{ActiveTheme, Theme}, theme::{ActiveTheme, Theme},
Root, TitleBar, Root, TitleBar,
}; };
@@ -12,7 +12,7 @@ use super::{
dock::{chat::ChatPanel, left_dock::LeftDock, welcome::WelcomePanel}, dock::{chat::ChatPanel, left_dock::LeftDock, welcome::WelcomePanel},
onboarding::Onboarding, onboarding::Onboarding,
}; };
use crate::states::account::AccountState; use crate::states::account::AccountRegistry;
#[derive(Clone, PartialEq, Eq, Deserialize)] #[derive(Clone, PartialEq, Eq, Deserialize)]
pub struct AddPanel { pub struct AddPanel {
@@ -49,13 +49,11 @@ impl AppView {
let onboarding = cx.new_view(Onboarding::new); let onboarding = cx.new_view(Onboarding::new);
// Dock // Dock
let dock = cx.new_view(|cx| { let dock = cx.new_view(|cx| DockArea::new(DOCK_AREA.id, Some(DOCK_AREA.version), cx));
DockArea::new(DOCK_AREA.id, Some(DOCK_AREA.version), cx).panel_style(PanelStyle::TabBar)
});
cx.observe_global::<AccountState>(|view, cx| { cx.observe_global::<AccountRegistry>(|view, cx| {
// TODO: save dock state and load previous state on startup // TODO: save dock state and load previous state on startup
if cx.global::<AccountState>().in_use.is_some() { if cx.global::<AccountRegistry>().is_user_logged_in() {
Self::init_layout(view.dock.downgrade(), cx); Self::init_layout(view.dock.downgrade(), cx);
} }
}) })
@@ -115,9 +113,7 @@ impl Render for AppView {
let mut content = div(); let mut content = div();
if cx.global::<AccountState>().in_use.is_none() { if cx.global::<AccountRegistry>().is_user_logged_in() {
content = content.size_full().child(self.onboarding.clone())
} else {
content = content content = content
.on_action(cx.listener(Self::on_action_add_panel)) .on_action(cx.listener(Self::on_action_add_panel))
.size_full() .size_full()
@@ -125,6 +121,8 @@ impl Render for AppView {
.flex_col() .flex_col()
.child(TitleBar::new()) .child(TitleBar::new())
.child(self.dock.clone()) .child(self.dock.clone())
} else {
content = content.size_full().child(self.onboarding.clone())
} }
div() div()

View File

@@ -1,63 +1,49 @@
use coop_ui::{theme::ActiveTheme, Collapsible, Selectable, StyledExt}; use coop_ui::{theme::ActiveTheme, Selectable, StyledExt};
use gpui::*; use gpui::*;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use prelude::FluentBuilder; use prelude::FluentBuilder;
use serde::Deserialize;
use crate::{ use crate::{
get_client,
states::signal::SignalRegistry,
utils::{ago, show_npub}, utils::{ago, show_npub},
views::app::AddPanel, views::app::AddPanel,
}; };
#[derive(Clone, PartialEq, Eq, Deserialize)] #[derive(IntoElement)]
pub struct ChatDelegate { struct ChatItem {
title: Option<String>, id: ElementId,
public_key: PublicKey, public_key: PublicKey,
metadata: Option<Metadata>, metadata: Option<Metadata>,
last_seen: Timestamp, last_seen: Timestamp,
} title: Option<String>,
impl ChatDelegate {
pub fn new(
title: Option<String>,
public_key: PublicKey,
metadata: Option<Metadata>,
last_seen: Timestamp,
) -> Self {
Self {
title,
public_key,
metadata,
last_seen,
}
}
}
#[derive(IntoElement)]
pub struct Chat {
id: ElementId,
pub item: ChatDelegate,
// Interactive // Interactive
base: Div, base: Div,
selected: bool, selected: bool,
is_collapsed: bool,
} }
impl Chat { impl ChatItem {
pub fn new(item: ChatDelegate) -> Self { pub fn new(
let id = SharedString::from(item.public_key.to_hex()).into(); public_key: PublicKey,
metadata: Option<Metadata>,
last_seen: Timestamp,
title: Option<String>,
) -> Self {
let id = SharedString::from(public_key.to_hex()).into();
Self { Self {
id, id,
item, public_key,
metadata,
last_seen,
title,
base: div(), base: div(),
selected: false, selected: false,
is_collapsed: false,
} }
} }
} }
impl Selectable for Chat { impl Selectable for ChatItem {
fn selected(mut self, selected: bool) -> Self { fn selected(mut self, selected: bool) -> Self {
self.selected = selected; self.selected = selected;
self self
@@ -68,32 +54,22 @@ impl Selectable for Chat {
} }
} }
impl Collapsible for Chat { impl InteractiveElement for ChatItem {
fn is_collapsed(&self) -> bool {
self.is_collapsed
}
fn collapsed(mut self, collapsed: bool) -> Self {
self.is_collapsed = collapsed;
self
}
}
impl InteractiveElement for Chat {
fn interactivity(&mut self) -> &mut gpui::Interactivity { fn interactivity(&mut self) -> &mut gpui::Interactivity {
self.base.interactivity() self.base.interactivity()
} }
} }
impl RenderOnce for Chat { impl RenderOnce for ChatItem {
fn render(self, cx: &mut WindowContext) -> impl IntoElement { fn render(self, cx: &mut WindowContext) -> impl IntoElement {
let ago = ago(self.item.last_seen.as_u64()); let ago = ago(self.last_seen.as_u64());
let fallback_name = show_npub(self.public_key, 16);
let mut content = div() let mut content = div()
.font_medium() .font_medium()
.text_color(cx.theme().sidebar_accent_foreground); .text_color(cx.theme().sidebar_accent_foreground);
if let Some(metadata) = self.item.metadata.clone() { if let Some(metadata) = self.metadata.clone() {
content = content content = content
.flex() .flex()
.items_center() .items_center()
@@ -108,16 +84,14 @@ impl RenderOnce for Chat {
) )
} else { } else {
this.flex_shrink_0() this.flex_shrink_0()
.child(div().size_6().rounded_full().bg(cx.theme().muted)) .child(img("brand/avatar.png").size_6().rounded_full())
} }
}) })
.map(|this| { .map(|this| {
if let Some(display_name) = metadata.display_name { if let Some(display_name) = metadata.display_name {
this.child(display_name) this.child(display_name)
} else if let Ok(npub) = show_npub(self.item.public_key, 16) {
this.child(npub)
} else { } else {
this.child("Anon") this.child(fallback_name)
} }
}) })
} else { } else {
@@ -126,13 +100,12 @@ impl RenderOnce for Chat {
.items_center() .items_center()
.gap_2() .gap_2()
.child( .child(
div() img("brand/avatar.png")
.flex_shrink_0() .flex_shrink_0()
.size_6() .size_6()
.rounded_full() .rounded_full(),
.bg(cx.theme().muted),
) )
.child("Anon") .child(fallback_name)
} }
self.base self.base
@@ -156,9 +129,95 @@ impl RenderOnce for Chat {
) )
.on_click(move |_, cx| { .on_click(move |_, cx| {
cx.dispatch_action(Box::new(AddPanel { cx.dispatch_action(Box::new(AddPanel {
title: self.item.title.clone(), title: self.title.clone(),
receiver: self.item.public_key, receiver: self.public_key,
})) }))
}) })
} }
} }
pub struct Chat {
title: Option<String>,
public_key: PublicKey,
metadata: Model<Option<Metadata>>,
last_seen: Timestamp,
}
impl Chat {
pub fn new(event: Event, cx: &mut ViewContext<'_, Self>) -> Self {
let public_key = event.pubkey;
let last_seen = event.created_at;
let metadata = cx.new_model(|_| None);
let async_metadata = metadata.clone();
let mut async_cx = cx.to_async();
cx.foreground_executor()
.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();
cx.observe_global::<SignalRegistry>(|chat, cx| {
chat.load_profile(cx);
})
.detach();
Self {
public_key,
last_seen,
metadata,
title: None,
}
}
fn load_profile(&self, cx: &mut ViewContext<Self>) {
let public_key = self.public_key;
let async_metadata = self.metadata.clone();
let mut async_cx = cx.to_async();
if cx.global::<SignalRegistry>().contains(self.public_key) {
cx.foreground_executor()
.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();
}
}
}
impl Render for Chat {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
let metadata = self.metadata.read(cx).clone();
div().child(ChatItem::new(
self.public_key,
metadata,
self.last_seen,
self.title.clone(),
))
}
}

View File

@@ -1,102 +1,60 @@
use chat::{Chat, ChatDelegate}; use chat::Chat;
use coop_ui::{theme::ActiveTheme, v_flex, StyledExt}; use coop_ui::{theme::ActiveTheme, v_flex, Collapsible, Icon, IconName, StyledExt};
use gpui::*; use gpui::*;
use itertools::Itertools; use prelude::FluentBuilder;
use nostr_sdk::prelude::*;
use std::{cmp::Reverse, time::Duration};
use crate::{get_client, states::account::AccountState}; use crate::states::chat::ChatRegistry;
pub mod chat; pub mod chat;
pub struct Inbox { pub struct Inbox {
label: SharedString, label: SharedString,
chats: Model<Option<Vec<ChatDelegate>>>, chats: Model<Option<Vec<View<Chat>>>>,
is_collapsed: bool,
} }
impl Inbox { impl Inbox {
pub fn new(cx: &mut ViewContext<'_, Self>) -> Self { pub fn new(cx: &mut ViewContext<'_, Self>) -> Self {
let chats = cx.new_model(|_| None); let chats = cx.new_model(|_| None);
let async_chats = chats.clone();
if let Some(public_key) = cx.global::<AccountState>().in_use { cx.observe_global::<ChatRegistry>(|inbox, cx| {
let client = get_client(); inbox.add_chats(cx);
let filter = Filter::new() })
.kind(Kind::PrivateDirectMessage) .detach();
.pubkey(public_key);
let mut async_cx = cx.to_async();
cx.foreground_executor()
.spawn(async move {
let events = async_cx
.background_executor()
.spawn(async move {
if let Ok(events) = client.database().query(vec![filter]).await {
events
.into_iter()
.filter(|ev| ev.pubkey != public_key) // Filter messages from current user
.unique_by(|ev| ev.pubkey) // Get unique list
.sorted_by_key(|ev| Reverse(ev.created_at)) // Sort by created at
.collect::<Vec<_>>()
} else {
Vec::new()
}
})
.await;
// Get all public keys
let public_keys: Vec<PublicKey> =
events.iter().map(|event| event.pubkey).collect();
// Calculate total public keys
let total = public_keys.len();
// Create subscription for metadata events
let filter = Filter::new()
.kind(Kind::Metadata)
.authors(public_keys)
.limit(total);
let mut chats = Vec::new();
let mut stream = async_cx
.background_executor()
.spawn(async move {
client
.stream_events(vec![filter], Some(Duration::from_secs(15)))
.await
.unwrap()
})
.await;
while let Some(event) = stream.next().await {
// TODO: generate some random name?
let title = if let Some(tag) = event.tags.find(TagKind::Title) {
tag.content().map(|s| s.to_string())
} else {
None
};
let metadata = Metadata::from_json(event.content).ok();
let chat =
ChatDelegate::new(title, event.pubkey, metadata, event.created_at);
chats.push(chat);
}
_ = async_cx.update_model(&async_chats, |a, b| {
*a = Some(chats);
b.notify();
});
})
.detach();
}
Self { Self {
label: "Inbox".into(),
chats, chats,
label: "Inbox".into(),
is_collapsed: false,
} }
} }
fn add_chats(&self, cx: &mut ViewContext<Self>) {
let events = cx.global::<ChatRegistry>().get(cx);
if let Some(events) = events {
let chats: Vec<View<Chat>> = events
.into_iter()
.map(|event| cx.new_view(|cx| Chat::new(event, cx)))
.collect();
cx.update_model(&self.chats, |a, b| {
*a = Some(chats);
b.notify();
});
}
}
}
impl Collapsible for Inbox {
fn is_collapsed(&self) -> bool {
self.is_collapsed
}
fn collapsed(mut self, collapsed: bool) -> Self {
self.is_collapsed = collapsed;
self
}
} }
impl Render for Inbox { impl Render for Inbox {
@@ -104,25 +62,38 @@ impl Render for Inbox {
let mut content = div(); let mut content = div();
if let Some(chats) = self.chats.read(cx).as_ref() { if let Some(chats) = self.chats.read(cx).as_ref() {
content = content.children(chats.iter().map(move |item| Chat::new(item.clone()))) content = content.children(chats.clone())
} }
v_flex() v_flex()
.pt_3() .gap_1()
.pt_2()
.px_2() .px_2()
.gap_2()
.child( .child(
div() div()
.id("inbox") .id("inbox")
.h_7() .h_7()
.px_1()
.flex() .flex()
.items_center() .items_center()
.gap_2() .rounded_md()
.text_xs() .text_xs()
.font_semibold() .font_semibold()
.text_color(cx.theme().sidebar_foreground.opacity(0.7)) .text_color(cx.theme().sidebar_foreground.opacity(0.7))
.hover(|this| this.bg(cx.theme().sidebar_accent.opacity(0.7)))
.on_click(cx.listener(move |view, _event, cx| {
view.is_collapsed = !view.is_collapsed;
cx.notify();
}))
.child(
Icon::new(IconName::ChevronDown)
.size_6()
.when(self.is_collapsed, |this| {
this.rotate(percentage(270. / 360.))
}),
)
.child(self.label.clone()), .child(self.label.clone()),
) )
.child(content) .when(!self.is_collapsed, |this| this.child(content))
} }
} }

View File

@@ -29,12 +29,12 @@ impl LeftDock {
let inbox = cx.new_view(Inbox::new); let inbox = cx.new_view(Inbox::new);
Self { Self {
inbox,
name: "Left Dock".into(), name: "Left Dock".into(),
closeable: true, closeable: true,
zoomable: true, zoomable: true,
focus_handle: cx.focus_handle(), focus_handle: cx.focus_handle(),
view_id: cx.view().entity_id(), view_id: cx.view().entity_id(),
inbox,
} }
} }
} }

View File

@@ -1,5 +1,4 @@
pub mod chat; pub mod chat;
pub mod inbox;
pub mod left_dock; pub mod left_dock;
pub mod welcome; pub mod welcome;
pub mod inbox;

View File

@@ -7,7 +7,7 @@ use gpui::*;
use keyring::Entry; use keyring::Entry;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use crate::{constants::KEYRING_SERVICE, get_client, states::account::AccountState}; use crate::{constants::KEYRING_SERVICE, get_client, states::account::AccountRegistry};
pub struct Onboarding { pub struct Onboarding {
input: View<TextInput>, input: View<TextInput>,
@@ -50,8 +50,8 @@ impl Onboarding {
}); });
// Update view // Update view
cx.update_global(|state: &mut AccountState, cx| { cx.update_global(|state: &mut AccountRegistry, cx| {
state.in_use = Some(public_key); state.set_user(Some(public_key));
cx.notify(); cx.notify();
}); });

View File

@@ -283,8 +283,8 @@ impl ThemeColor {
table_head_foreground: hsl(240.0, 10., 3.9).opacity(0.7), table_head_foreground: hsl(240.0, 10., 3.9).opacity(0.7),
table_hover: hsl(240.0, 4.8, 95.0), table_hover: hsl(240.0, 4.8, 95.0),
table_row_border: hsl(240.0, 7.7, 94.5), table_row_border: hsl(240.0, 7.7, 94.5),
title_bar: hsl(0.0, 0.0, 100.), title_bar: hsl(0.0, 0.0, 98.0),
title_bar_border: hsl(240.0, 5.9, 90.0), title_bar_border: hsl(220.0, 13.0, 91.0),
sidebar: hsl(0.0, 0.0, 98.0), sidebar: hsl(0.0, 0.0, 98.0),
sidebar_accent: hsl(240.0, 4.8, 92.), sidebar_accent: hsl(240.0, 4.8, 92.),
sidebar_accent_foreground: hsl(240.0, 5.9, 10.0), sidebar_accent_foreground: hsl(240.0, 5.9, 10.0),
@@ -358,7 +358,7 @@ impl ThemeColor {
table_head_foreground: hsl(0., 0., 78.).opacity(0.7), table_head_foreground: hsl(0., 0., 78.).opacity(0.7),
table_hover: hsl(240.0, 3.7, 15.9).opacity(0.5), table_hover: hsl(240.0, 3.7, 15.9).opacity(0.5),
table_row_border: hsl(240.0, 3.7, 16.9).opacity(0.5), table_row_border: hsl(240.0, 3.7, 16.9).opacity(0.5),
title_bar: hsl(0., 0., 9.7), title_bar: hsl(240.0, 0.0, 10.0),
title_bar_border: hsl(240.0, 3.7, 15.9), title_bar_border: hsl(240.0, 3.7, 15.9),
sidebar: hsl(240.0, 0.0, 10.0), sidebar: hsl(240.0, 0.0, 10.0),
sidebar_accent: hsl(240.0, 3.7, 15.9), sidebar_accent: hsl(240.0, 3.7, 15.9),