feat: sharpen chat experiences (#9)

* feat: add global account and refactor chat registry

* chore: improve last seen

* chore: reduce string alloc

* wip: refactor room

* chore: fix edit profile panel

* chore: refactor open window in main

* chore: refactor sidebar

* chore: refactor room
This commit is contained in:
reya
2025-02-23 08:29:05 +07:00
committed by GitHub
parent cfa628a8a6
commit bbc778d5ca
23 changed files with 1167 additions and 1150 deletions

View File

@@ -13,5 +13,6 @@ nostr-sdk.workspace = true
anyhow.workspace = true
itertools.workspace = true
chrono.workspace = true
smallvec.workspace = true
smol.workspace = true
oneshot.workspace = true

View File

@@ -1,12 +1,11 @@
use crate::room::Room;
use anyhow::anyhow;
use common::utils::{compare, room_hash, signer_public_key};
use common::{last_seen::LastSeen, utils::room_hash};
use gpui::{App, AppContext, Context, Entity, Global, WeakEntity};
use itertools::Itertools;
use nostr_sdk::prelude::*;
use state::get_client;
use std::cmp::Reverse;
use crate::room::Room;
use std::{cmp::Reverse, rc::Rc, sync::RwLock};
pub fn init(cx: &mut App) {
ChatRegistry::register(cx);
@@ -17,7 +16,7 @@ struct GlobalChatRegistry(Entity<ChatRegistry>);
impl Global for GlobalChatRegistry {}
pub struct ChatRegistry {
rooms: Vec<Entity<Room>>,
rooms: Rc<RwLock<Vec<Entity<Room>>>>,
is_loading: bool,
}
@@ -40,83 +39,67 @@ impl ChatRegistry {
// Set global state
cx.set_global(GlobalChatRegistry(entity.clone()));
// Observe and load metadata for any new rooms
cx.observe_new::<Room>(|this, _window, cx| {
let client = get_client();
let pubkeys = this.pubkeys();
let (tx, rx) = oneshot::channel::<Vec<(PublicKey, Metadata)>>();
cx.background_spawn(async move {
let mut profiles = Vec::new();
for public_key in pubkeys.into_iter() {
if let Ok(metadata) = client.database().metadata(public_key).await {
profiles.push((public_key, metadata.unwrap_or_default()));
}
}
_ = tx.send(profiles);
})
.detach();
cx.spawn(|this, mut cx| async move {
if let Ok(profiles) = rx.await {
if let Some(room) = this.upgrade() {
_ = cx.update_entity(&room, |this, cx| {
for profile in profiles.into_iter() {
this.set_metadata(profile.0, profile.1);
}
cx.notify();
});
}
}
})
.detach();
})
.detach();
entity
})
}
fn new(_cx: &mut Context<Self>) -> Self {
Self {
rooms: vec![],
rooms: Rc::new(RwLock::new(vec![])),
is_loading: true,
}
}
pub fn current_rooms_ids(&self, cx: &mut Context<Self>) -> Vec<u64> {
self.rooms.iter().map(|room| room.read(cx).id).collect()
self.rooms
.read()
.unwrap()
.iter()
.map(|room| room.read(cx).id)
.collect()
}
pub fn load_chat_rooms(&mut self, cx: &mut Context<Self>) {
let client = get_client();
let (tx, rx) = oneshot::channel::<Vec<Event>>();
let (tx, rx) = oneshot::channel::<Option<Vec<Event>>>();
cx.background_spawn(async move {
if let Ok(public_key) = signer_public_key(client).await {
let filter = Filter::new()
let result = async {
let signer = client.signer().await?;
let public_key = signer.get_public_key().await?;
let send = Filter::new()
.kind(Kind::PrivateDirectMessage)
.author(public_key);
// Get all DM events from database
if let Ok(events) = client.database().query(filter).await {
let result: Vec<Event> = events
.into_iter()
.filter(|ev| ev.tags.public_keys().peekable().peek().is_some())
.unique_by(room_hash)
.sorted_by_key(|ev| Reverse(ev.created_at))
.collect();
let recv = Filter::new()
.kind(Kind::PrivateDirectMessage)
.pubkey(public_key);
_ = tx.send(result);
}
let send_events = client.database().query(send).await?;
let recv_events = client.database().query(recv).await?;
Ok::<_, anyhow::Error>(send_events.merge(recv_events))
}
.await;
if let Ok(events) = result {
let result: Vec<Event> = events
.into_iter()
.filter(|ev| ev.tags.public_keys().peekable().peek().is_some())
.unique_by(room_hash)
.sorted_by_key(|ev| Reverse(ev.created_at))
.collect();
_ = tx.send(Some(result));
} else {
_ = tx.send(None);
}
})
.detach();
cx.spawn(|this, cx| async move {
if let Ok(events) = rx.await {
if let Ok(Some(events)) = rx.await {
if !events.is_empty() {
_ = cx.update(|cx| {
_ = this.update(cx, |this, cx| {
@@ -127,14 +110,14 @@ impl ChatRegistry {
let new = room_hash(&ev);
// Filter all seen events
if !current_rooms.iter().any(|this| this == &new) {
Some(cx.new(|cx| Room::parse(&ev, cx)))
Some(Room::new(&ev, cx))
} else {
None
}
})
.collect();
this.rooms.extend(items);
this.rooms.write().unwrap().extend(items);
this.is_loading = false;
cx.notify();
@@ -146,8 +129,8 @@ impl ChatRegistry {
.detach();
}
pub fn rooms(&self) -> &Vec<Entity<Room>> {
&self.rooms
pub fn rooms(&self) -> Vec<Entity<Room>> {
self.rooms.read().unwrap().clone()
}
pub fn is_loading(&self) -> bool {
@@ -156,18 +139,25 @@ impl ChatRegistry {
pub fn get(&self, id: &u64, cx: &App) -> Option<WeakEntity<Room>> {
self.rooms
.read()
.unwrap()
.iter()
.find(|model| model.read(cx).id == *id)
.map(|room| room.downgrade())
}
pub fn new_room(&mut self, room: Room, cx: &mut Context<Self>) -> Result<(), anyhow::Error> {
if !self
.rooms
pub fn push_room(
&mut self,
room: Entity<Room>,
cx: &mut Context<Self>,
) -> Result<(), anyhow::Error> {
let mut rooms = self.rooms.write().unwrap();
if !rooms
.iter()
.any(|current| compare(&current.read(cx).pubkeys(), &room.pubkeys()))
.any(|current| current.read(cx) == room.read(cx))
{
self.rooms.insert(0, cx.new(|_| room));
rooms.insert(0, room);
cx.notify();
Ok(())
@@ -177,32 +167,27 @@ impl ChatRegistry {
}
pub fn push_message(&mut self, event: Event, cx: &mut Context<Self>) {
// Get all pubkeys from event's tags for comparision
let mut pubkeys: Vec<_> = event.tags.public_keys().copied().collect();
pubkeys.push(event.pubkey);
let id = room_hash(&event);
let mut rooms = self.rooms.write().unwrap();
if let Some(room) = self
.rooms
.iter()
.find(|room| compare(&room.read(cx).pubkeys(), &pubkeys))
{
if let Some(room) = rooms.iter().find(|room| room.read(cx).id == id) {
room.update(cx, |this, cx| {
this.last_seen.set(event.created_at);
this.new_messages.update(cx, |this, cx| {
this.push(event);
cx.notify();
});
if let Some(last_seen) = Rc::get_mut(&mut this.last_seen) {
*last_seen = LastSeen(event.created_at);
}
this.new_messages.push(event);
cx.notify();
});
// Re sort rooms by last seen
self.rooms
.sort_by_key(|room| Reverse(room.read(cx).last_seen()));
rooms.sort_by_key(|room| Reverse(room.read(cx).last_seen()));
cx.notify();
} else {
let room = cx.new(|cx| Room::parse(&event, cx));
self.rooms.insert(0, room);
let mut rooms = self.rooms.write().unwrap();
let new_room = Room::new(&event, cx);
rooms.insert(0, new_room);
cx.notify();
}
}

View File

@@ -1,138 +1,161 @@
use common::{
last_seen::LastSeen,
profile::NostrProfile,
utils::{compare, random_name, room_hash},
utils::{random_name, room_hash},
};
use gpui::{App, AppContext, Entity, SharedString};
use nostr_sdk::prelude::*;
use std::collections::HashSet;
use smallvec::{smallvec, SmallVec};
use state::get_client;
use std::{collections::HashSet, rc::Rc};
pub struct Room {
pub id: u64,
pub title: Option<SharedString>,
pub owner: NostrProfile, // Owner always match current user
pub members: Vec<NostrProfile>, // Extract from event's tags
pub last_seen: LastSeen,
pub is_group: bool,
pub new_messages: Entity<Vec<Event>>, // Hold all new messages
pub last_seen: Rc<LastSeen>,
/// Subject of the room (Nostr)
pub title: String,
/// Display name of the room (used for display purposes in Coop)
pub display_name: Option<SharedString>,
/// All members of the room
pub members: SmallVec<[NostrProfile; 2]>,
/// Store all new messages
pub new_messages: Vec<Event>,
}
impl PartialEq for Room {
fn eq(&self, other: &Self) -> bool {
compare(&self.pubkeys(), &other.pubkeys())
self.id == other.id
}
}
impl Room {
pub fn new(
id: u64,
owner: NostrProfile,
members: Vec<NostrProfile>,
title: Option<SharedString>,
last_seen: LastSeen,
cx: &mut App,
) -> Self {
let new_messages = cx.new(|_| Vec::new());
let is_group = members.len() > 1;
let title = if title.is_none() {
Some(random_name(2).into())
} else {
title
};
Self {
id,
owner,
members,
title,
last_seen,
is_group,
new_messages,
}
}
/// Convert nostr event to room
pub fn parse(event: &Event, cx: &mut App) -> Room {
pub fn new(event: &Event, cx: &mut App) -> Entity<Self> {
let id = room_hash(event);
let last_seen = LastSeen(event.created_at);
// Always equal to current user
let owner = NostrProfile::new(event.pubkey, Metadata::default());
// Get all pubkeys that invole in this group
let members: Vec<NostrProfile> = event
.tags
.public_keys()
.collect::<HashSet<_>>()
.into_iter()
.map(|public_key| NostrProfile::new(*public_key, Metadata::default()))
.collect();
// Get title from event's tags
let last_seen = Rc::new(LastSeen(event.created_at));
// Get the subject from the event's tags, or create a random subject if none is found
let title = if let Some(tag) = event.tags.find(TagKind::Subject) {
tag.content().map(|s| s.to_owned().into())
tag.content()
.map(|s| s.to_owned())
.unwrap_or(random_name(2))
} else {
None
random_name(2)
};
Self::new(id, owner, members, title, last_seen, cx)
let room = cx.new(|cx| {
let this = Self {
id,
last_seen,
title,
display_name: None,
members: smallvec![],
new_messages: vec![],
};
let mut pubkeys = vec![];
// Get all pubkeys from event's tags
pubkeys.extend(event.tags.public_keys().collect::<HashSet<_>>());
pubkeys.push(event.pubkey);
let client = get_client();
let (tx, rx) = oneshot::channel::<Vec<NostrProfile>>();
cx.background_spawn(async move {
let signer = client.signer().await.unwrap();
let signer_pubkey = signer.get_public_key().await.unwrap();
let mut profiles = vec![];
for public_key in pubkeys.into_iter() {
if let Ok(result) = client.database().metadata(public_key).await {
let metadata = result.unwrap_or_default();
let profile = NostrProfile::new(public_key, metadata);
if public_key == signer_pubkey {
profiles.push(profile);
} else {
profiles.insert(0, profile);
}
}
}
_ = tx.send(profiles);
})
.detach();
cx.spawn(|this, cx| async move {
if let Ok(profiles) = rx.await {
_ = cx.update(|cx| {
let display_name = if profiles.len() > 2 {
let merged = profiles
.iter()
.take(2)
.map(|profile| profile.name().to_string())
.collect::<Vec<_>>()
.join(", ");
let name: SharedString =
format!("{}, +{}", merged, profiles.len() - 2).into();
Some(name)
} else {
None
};
_ = this.update(cx, |this: &mut Room, cx| {
this.members.extend(profiles);
this.display_name = display_name;
cx.notify();
});
});
}
})
.detach();
this
});
room
}
/// Set contact's metadata by public key
pub fn set_metadata(&mut self, public_key: PublicKey, metadata: Metadata) {
if self.owner.public_key() == public_key {
self.owner.set_metadata(&metadata);
}
for member in self.members.iter_mut() {
if member.public_key() == public_key {
member.set_metadata(&metadata);
}
}
pub fn id(&self) -> u64 {
self.id
}
/// Get room's member by public key
pub fn member(&self, public_key: &PublicKey) -> Option<NostrProfile> {
if &self.owner.public_key() == public_key {
Some(self.owner.clone())
} else {
self.members
.iter()
.find(|m| &m.public_key() == public_key)
.cloned()
}
self.members
.iter()
.find(|m| &m.public_key() == public_key)
.cloned()
}
/// Get room's first member's public key
pub fn first_member(&self) -> Option<&NostrProfile> {
self.members.first()
}
/// Collect room's member's public keys
pub fn public_keys(&self) -> Vec<PublicKey> {
self.members.iter().map(|m| m.public_key()).collect()
}
/// Get room's display name
pub fn name(&self) -> String {
if self.members.len() <= 2 {
self.members
.iter()
.map(|profile| profile.name())
.collect::<Vec<_>>()
.join(", ")
} else {
let name = self
.members
.iter()
.take(2)
.map(|profile| profile.name())
.collect::<Vec<_>>()
.join(", ");
format!("{}, +{}", name, self.members.len() - 2)
}
pub fn name(&self) -> Option<SharedString> {
self.display_name.clone()
}
pub fn last_seen(&self) -> &LastSeen {
&self.last_seen
/// Determine if room is a group
pub fn is_group(&self) -> bool {
self.members.len() > 2
}
/// Get all public keys from current room
pub fn pubkeys(&self) -> Vec<PublicKey> {
let mut pubkeys: Vec<_> = self.members.iter().map(|m| m.public_key()).collect();
pubkeys.push(self.owner.public_key());
/// Get room's last seen
pub fn last_seen(&self) -> Rc<LastSeen> {
self.last_seen.clone()
}
pubkeys
/// Get room's last seen as ago format
pub fn ago(&self) -> SharedString {
self.last_seen.ago()
}
}