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

View File

@@ -1,5 +1,5 @@
use coop_ui::{
dock::{DockArea, DockItem, DockPlacement, PanelStyle},
dock::{DockArea, DockItem, DockPlacement},
theme::{ActiveTheme, Theme},
Root, TitleBar,
};
@@ -12,7 +12,7 @@ use super::{
dock::{chat::ChatPanel, left_dock::LeftDock, welcome::WelcomePanel},
onboarding::Onboarding,
};
use crate::states::account::AccountState;
use crate::states::account::AccountRegistry;
#[derive(Clone, PartialEq, Eq, Deserialize)]
pub struct AddPanel {
@@ -49,13 +49,11 @@ impl AppView {
let onboarding = cx.new_view(Onboarding::new);
// Dock
let dock = cx.new_view(|cx| {
DockArea::new(DOCK_AREA.id, Some(DOCK_AREA.version), cx).panel_style(PanelStyle::TabBar)
});
let dock = cx.new_view(|cx| DockArea::new(DOCK_AREA.id, Some(DOCK_AREA.version), cx));
cx.observe_global::<AccountState>(|view, cx| {
cx.observe_global::<AccountRegistry>(|view, cx| {
// 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);
}
})
@@ -115,9 +113,7 @@ impl Render for AppView {
let mut content = div();
if cx.global::<AccountState>().in_use.is_none() {
content = content.size_full().child(self.onboarding.clone())
} else {
if cx.global::<AccountRegistry>().is_user_logged_in() {
content = content
.on_action(cx.listener(Self::on_action_add_panel))
.size_full()
@@ -125,6 +121,8 @@ impl Render for AppView {
.flex_col()
.child(TitleBar::new())
.child(self.dock.clone())
} else {
content = content.size_full().child(self.onboarding.clone())
}
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 nostr_sdk::prelude::*;
use prelude::FluentBuilder;
use serde::Deserialize;
use crate::{
get_client,
states::signal::SignalRegistry,
utils::{ago, show_npub},
views::app::AddPanel,
};
#[derive(Clone, PartialEq, Eq, Deserialize)]
pub struct ChatDelegate {
title: Option<String>,
#[derive(IntoElement)]
struct ChatItem {
id: ElementId,
public_key: PublicKey,
metadata: Option<Metadata>,
last_seen: Timestamp,
}
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,
title: Option<String>,
// Interactive
base: Div,
selected: bool,
is_collapsed: bool,
}
impl Chat {
pub fn new(item: ChatDelegate) -> Self {
let id = SharedString::from(item.public_key.to_hex()).into();
impl ChatItem {
pub fn new(
public_key: PublicKey,
metadata: Option<Metadata>,
last_seen: Timestamp,
title: Option<String>,
) -> Self {
let id = SharedString::from(public_key.to_hex()).into();
Self {
id,
item,
public_key,
metadata,
last_seen,
title,
base: div(),
selected: false,
is_collapsed: false,
}
}
}
impl Selectable for Chat {
impl Selectable for ChatItem {
fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
@@ -68,32 +54,22 @@ impl Selectable for Chat {
}
}
impl Collapsible for Chat {
fn is_collapsed(&self) -> bool {
self.is_collapsed
}
fn collapsed(mut self, collapsed: bool) -> Self {
self.is_collapsed = collapsed;
self
}
}
impl InteractiveElement for Chat {
impl InteractiveElement for ChatItem {
fn interactivity(&mut self) -> &mut gpui::Interactivity {
self.base.interactivity()
}
}
impl RenderOnce for Chat {
impl RenderOnce for ChatItem {
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()
.font_medium()
.text_color(cx.theme().sidebar_accent_foreground);
if let Some(metadata) = self.item.metadata.clone() {
if let Some(metadata) = self.metadata.clone() {
content = content
.flex()
.items_center()
@@ -108,16 +84,14 @@ impl RenderOnce for Chat {
)
} else {
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| {
if let Some(display_name) = metadata.display_name {
this.child(display_name)
} else if let Ok(npub) = show_npub(self.item.public_key, 16) {
this.child(npub)
} else {
this.child("Anon")
this.child(fallback_name)
}
})
} else {
@@ -126,13 +100,12 @@ impl RenderOnce for Chat {
.items_center()
.gap_2()
.child(
div()
img("brand/avatar.png")
.flex_shrink_0()
.size_6()
.rounded_full()
.bg(cx.theme().muted),
.rounded_full(),
)
.child("Anon")
.child(fallback_name)
}
self.base
@@ -156,9 +129,95 @@ impl RenderOnce for Chat {
)
.on_click(move |_, cx| {
cx.dispatch_action(Box::new(AddPanel {
title: self.item.title.clone(),
receiver: self.item.public_key,
title: self.title.clone(),
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 coop_ui::{theme::ActiveTheme, v_flex, StyledExt};
use chat::Chat;
use coop_ui::{theme::ActiveTheme, v_flex, Collapsible, Icon, IconName, StyledExt};
use gpui::*;
use itertools::Itertools;
use nostr_sdk::prelude::*;
use std::{cmp::Reverse, time::Duration};
use prelude::FluentBuilder;
use crate::{get_client, states::account::AccountState};
use crate::states::chat::ChatRegistry;
pub mod chat;
pub struct Inbox {
label: SharedString,
chats: Model<Option<Vec<ChatDelegate>>>,
chats: Model<Option<Vec<View<Chat>>>>,
is_collapsed: bool,
}
impl Inbox {
pub fn new(cx: &mut ViewContext<'_, Self>) -> Self {
let chats = cx.new_model(|_| None);
let async_chats = chats.clone();
if let Some(public_key) = cx.global::<AccountState>().in_use {
let client = get_client();
let filter = Filter::new()
.kind(Kind::PrivateDirectMessage)
.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();
}
cx.observe_global::<ChatRegistry>(|inbox, cx| {
inbox.add_chats(cx);
})
.detach();
Self {
label: "Inbox".into(),
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 {
@@ -104,25 +62,38 @@ impl Render for Inbox {
let mut content = div();
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()
.pt_3()
.gap_1()
.pt_2()
.px_2()
.gap_2()
.child(
div()
.id("inbox")
.h_7()
.px_1()
.flex()
.items_center()
.gap_2()
.rounded_md()
.text_xs()
.font_semibold()
.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(content)
.when(!self.is_collapsed, |this| this.child(content))
}
}

View File

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

View File

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

View File

@@ -7,7 +7,7 @@ use gpui::*;
use keyring::Entry;
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 {
input: View<TextInput>,
@@ -50,8 +50,8 @@ impl Onboarding {
});
// Update view
cx.update_global(|state: &mut AccountState, cx| {
state.in_use = Some(public_key);
cx.update_global(|state: &mut AccountRegistry, cx| {
state.set_user(Some(public_key));
cx.notify();
});