feat: Out-of-Box Experience (#12)

* refactor app view

* feat: onboarding

* add back buttons in onboarding
This commit is contained in:
reya
2025-03-25 12:34:39 +07:00
committed by GitHub
parent e15cbcc22c
commit 00cf7792e5
34 changed files with 1680 additions and 1920 deletions

View File

@@ -1,2 +1,168 @@
pub mod registry;
use std::cmp::Reverse;
use anyhow::anyhow;
use common::{last_seen::LastSeen, utils::room_hash};
use global::get_client;
use gpui::{App, AppContext, Context, Entity, Global, Task, WeakEntity};
use itertools::Itertools;
use nostr_sdk::prelude::*;
use crate::room::{IncomingEvent, Room};
pub mod room;
pub fn init(cx: &mut App) {
ChatRegistry::set_global(cx.new(|_| ChatRegistry::new()), cx);
}
struct GlobalChatRegistry(Entity<ChatRegistry>);
impl Global for GlobalChatRegistry {}
pub struct ChatRegistry {
rooms: Vec<Entity<Room>>,
is_loading: bool,
}
impl ChatRegistry {
pub fn global(cx: &mut App) -> Entity<Self> {
cx.global::<GlobalChatRegistry>().0.clone()
}
pub fn set_global(state: Entity<Self>, cx: &mut App) {
cx.set_global(GlobalChatRegistry(state));
}
fn new() -> Self {
Self {
rooms: 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()
}
pub fn load_chat_rooms(&mut self, cx: &mut Context<Self>) {
let client = get_client();
let task: Task<Result<Vec<Event>, Error>> = cx.background_spawn(async move {
let signer = client.signer().await?;
let public_key = signer.get_public_key().await?;
let send = Filter::new()
.kind(Kind::PrivateDirectMessage)
.author(public_key);
let recv = Filter::new()
.kind(Kind::PrivateDirectMessage)
.pubkey(public_key);
let send_events = client.database().query(send).await?;
let recv_events = client.database().query(recv).await?;
let events = send_events.merge(recv_events);
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();
Ok(result)
});
cx.spawn(|this, cx| async move {
if let Ok(events) = task.await {
_ = cx.update(|cx| {
_ = this.update(cx, |this, cx| {
if !events.is_empty() {
let current_ids = this.current_rooms_ids(cx);
let items: Vec<Entity<Room>> = events
.into_iter()
.filter_map(|ev| {
let new = room_hash(&ev);
// Filter all seen rooms
if !current_ids.iter().any(|this| this == &new) {
Some(Room::new(&ev, cx))
} else {
None
}
})
.collect();
this.is_loading = false;
this.rooms.extend(items);
this.rooms
.sort_by_key(|room| Reverse(room.read(cx).last_seen()));
} else {
this.is_loading = false;
}
cx.notify();
});
});
}
})
.detach();
}
pub fn rooms(&self) -> &[Entity<Room>] {
&self.rooms
}
pub fn is_loading(&self) -> bool {
self.is_loading
}
pub fn get(&self, id: &u64, cx: &App) -> Option<WeakEntity<Room>> {
self.rooms
.iter()
.find(|model| model.read(cx).id == *id)
.map(|room| room.downgrade())
}
pub fn push_room(
&mut self,
room: Entity<Room>,
cx: &mut Context<Self>,
) -> Result<(), anyhow::Error> {
if !self
.rooms
.iter()
.any(|current| current.read(cx) == room.read(cx))
{
self.rooms.insert(0, room);
cx.notify();
Ok(())
} else {
Err(anyhow!("Room already exists"))
}
}
pub fn push_message(&mut self, event: Event, cx: &mut Context<Self>) {
let id = room_hash(&event);
if let Some(room) = self.rooms.iter().find(|room| room.read(cx).id == id) {
room.update(cx, |this, cx| {
this.last_seen = LastSeen(event.created_at);
cx.emit(IncomingEvent { event });
cx.notify();
});
// Re-sort rooms by last seen
self.rooms
.sort_by_key(|room| Reverse(room.read(cx).last_seen()));
} else {
let new_room = Room::new(&event, cx);
// Push the new room to the front of the list
self.rooms.insert(0, new_room);
}
cx.notify();
}
}

View File

@@ -1,174 +0,0 @@
use std::cmp::Reverse;
use anyhow::anyhow;
use common::{last_seen::LastSeen, utils::room_hash};
use global::get_client;
use gpui::{App, AppContext, Context, Entity, Global, Task, WeakEntity};
use itertools::Itertools;
use nostr_sdk::prelude::*;
use crate::room::{IncomingEvent, Room};
pub fn init(cx: &mut App) {
ChatRegistry::register(cx);
}
struct GlobalChatRegistry(Entity<ChatRegistry>);
impl Global for GlobalChatRegistry {}
pub struct ChatRegistry {
rooms: Vec<Entity<Room>>,
is_loading: bool,
}
impl ChatRegistry {
pub fn global(cx: &mut App) -> Option<Entity<Self>> {
cx.try_global::<GlobalChatRegistry>()
.map(|global| global.0.clone())
}
pub fn register(cx: &mut App) -> Entity<Self> {
Self::global(cx).unwrap_or_else(|| {
let entity = cx.new(Self::new);
// Set global state
cx.set_global(GlobalChatRegistry(entity.clone()));
entity
})
}
fn new(_cx: &mut Context<Self>) -> Self {
Self {
rooms: 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()
}
pub fn load_chat_rooms(&mut self, cx: &mut Context<Self>) {
let client = get_client();
let task: Task<Result<Vec<Event>, Error>> = cx.background_spawn(async move {
let signer = client.signer().await?;
let public_key = signer.get_public_key().await?;
let send = Filter::new()
.kind(Kind::PrivateDirectMessage)
.author(public_key);
let recv = Filter::new()
.kind(Kind::PrivateDirectMessage)
.pubkey(public_key);
let send_events = client.database().query(send).await?;
let recv_events = client.database().query(recv).await?;
let events = send_events.merge(recv_events);
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();
Ok(result)
});
cx.spawn(|this, cx| async move {
if let Ok(events) = task.await {
_ = cx.update(|cx| {
_ = this.update(cx, |this, cx| {
if !events.is_empty() {
let current_ids = this.current_rooms_ids(cx);
let items: Vec<Entity<Room>> = events
.into_iter()
.filter_map(|ev| {
let new = room_hash(&ev);
// Filter all seen rooms
if !current_ids.iter().any(|this| this == &new) {
Some(Room::new(&ev, cx))
} else {
None
}
})
.collect();
this.is_loading = false;
this.rooms.extend(items);
this.rooms
.sort_by_key(|room| Reverse(room.read(cx).last_seen()));
} else {
this.is_loading = false;
}
cx.notify();
});
});
}
})
.detach();
}
pub fn rooms(&self) -> &[Entity<Room>] {
&self.rooms
}
pub fn is_loading(&self) -> bool {
self.is_loading
}
pub fn get(&self, id: &u64, cx: &App) -> Option<WeakEntity<Room>> {
self.rooms
.iter()
.find(|model| model.read(cx).id == *id)
.map(|room| room.downgrade())
}
pub fn push_room(
&mut self,
room: Entity<Room>,
cx: &mut Context<Self>,
) -> Result<(), anyhow::Error> {
if !self
.rooms
.iter()
.any(|current| current.read(cx) == room.read(cx))
{
self.rooms.insert(0, room);
cx.notify();
Ok(())
} else {
Err(anyhow!("Room already exists"))
}
}
pub fn push_message(&mut self, event: Event, cx: &mut Context<Self>) {
let id = room_hash(&event);
if let Some(room) = self.rooms.iter().find(|room| room.read(cx).id == id) {
room.update(cx, |this, cx| {
this.last_seen = LastSeen(event.created_at);
cx.emit(IncomingEvent { event });
cx.notify();
});
// Re-sort rooms by last seen
self.rooms
.sort_by_key(|room| Reverse(room.read(cx).last_seen()));
} else {
let new_room = Room::new(&event, cx);
// Push the new room to the front of the list
self.rooms.insert(0, new_room);
}
cx.notify();
}
}

View File

@@ -1,12 +1,8 @@
use std::collections::HashSet;
use anyhow::{anyhow, Error};
use common::{
last_seen::LastSeen,
profile::NostrProfile,
utils::{device_pubkey, room_hash},
};
use global::{constants::DEVICE_ANNOUNCEMENT_KIND, get_client, get_device_keys};
use anyhow::Error;
use common::{last_seen::LastSeen, profile::NostrProfile, utils::room_hash};
use global::get_client;
use gpui::{App, AppContext, Entity, EventEmitter, SharedString, Task};
use nostr_sdk::prelude::*;
use smallvec::{smallvec, SmallVec};
@@ -170,19 +166,14 @@ impl Room {
let pubkeys = self.public_keys();
cx.background_spawn(async move {
let Some(device) = get_device_keys().await else {
return Err(anyhow!("Device not found. Please restart the application."));
};
let user_signer = client.signer().await?;
let user_pubkey = user_signer.get_public_key().await?;
let mut report = Vec::with_capacity(pubkeys.len());
let signer = client.signer().await?;
let public_key = signer.get_public_key().await?;
let mut report = vec![];
let tags: Vec<Tag> = pubkeys
.iter()
.filter_map(|pubkey| {
if pubkey != &user_pubkey {
if pubkey != &public_key {
Some(Tag::public_key(*pubkey))
} else {
None
@@ -191,41 +182,10 @@ impl Room {
.collect();
for pubkey in pubkeys.iter() {
let filter = Filter::new()
.kind(Kind::Custom(DEVICE_ANNOUNCEMENT_KIND))
.author(*pubkey)
.limit(1);
// Check if the pubkey has a device announcement,
// then choose the appropriate signer based on device presence
let event = match client.database().query(filter).await?.first() {
Some(event) => {
log::info!("Use device signer to send message");
let signer = &device;
// Get the device's public key of other user
let device_pubkey = device_pubkey(event)?;
let rumor = EventBuilder::private_msg_rumor(*pubkey, &content)
.tags(tags.clone())
.build(user_pubkey);
EventBuilder::gift_wrap(
signer,
&device_pubkey,
rumor,
vec![Tag::public_key(*pubkey)],
)
.await?
}
None => {
log::info!("Use user signer to send message");
let signer = client.signer().await?;
EventBuilder::private_msg(&signer, *pubkey, &content, tags.clone()).await?
}
};
if let Err(e) = client.send_event(&event).await {
if let Err(e) = client
.send_private_msg(*pubkey, &content, tags.clone())
.await
{
report.push(e.to_string());
}
}