wip: refactor

This commit is contained in:
reya
2024-12-04 14:52:40 +07:00
parent 03b8004304
commit c8315a2f93
16 changed files with 463 additions and 615 deletions
+56 -88
View File
@@ -1,23 +1,16 @@
use components::{
dock::{DockArea, DockItem, PanelStyle},
dock::{DockArea, DockItem},
indicator::Indicator,
theme::{ActiveTheme, Theme},
Root, TitleBar,
Root, Sizable, TitleBar,
};
use gpui::*;
use itertools::Itertools;
use nostr_sdk::prelude::*;
use std::{cmp::Reverse, sync::Arc, time::Duration};
use std::sync::Arc;
use crate::{
get_client,
states::{
room::{Room, RoomLastMessage, Rooms},
user::UserState,
},
};
use crate::states::account::AccountState;
use super::{
block::{welcome::WelcomeBlock, BlockContainer},
block::{rooms::Rooms, welcome::WelcomeBlock, BlockContainer},
onboarding::Onboarding,
};
@@ -33,7 +26,7 @@ pub const DOCK_AREA: DockAreaTab = DockAreaTab {
pub struct AppView {
onboarding: View<Onboarding>,
dock_area: View<DockArea>,
dock: Model<Option<View<DockArea>>>,
}
impl AppView {
@@ -44,75 +37,34 @@ impl AppView {
})
.detach();
// Observe UserState
// If current user is present, fetching all gift wrap events
cx.observe_global::<UserState>(|_v, cx| {
let app_state = cx.global::<UserState>();
let view_id = cx.parent_view_id();
let mut async_cx = cx.to_async();
if let Some(public_key) = app_state.current_user {
cx.foreground_executor()
.spawn(async move {
let client = get_client().await;
let filter = Filter::new().pubkey(public_key).kind(Kind::GiftWrap);
let mut rumors: Vec<UnsignedEvent> = Vec::new();
if let Ok(mut rx) = client
.stream_events(vec![filter], Some(Duration::from_secs(30)))
.await
{
while let Some(event) = rx.next().await {
if let Ok(UnwrappedGift { rumor, .. }) =
client.unwrap_gift_wrap(&event).await
{
rumors.push(rumor);
};
}
let items = rumors
.into_iter()
.sorted_by_key(|ev| Reverse(ev.created_at))
.filter(|ev| ev.pubkey != public_key)
.unique_by(|ev| ev.pubkey)
.map(|item| {
Room::new(
vec![item.pubkey, public_key],
Some(RoomLastMessage {
content: Some(item.content),
time: item.created_at,
}),
)
})
.collect::<Vec<_>>();
_ = async_cx.update_global::<Rooms, _>(|state, cx| {
state.rooms = items;
cx.notify(view_id);
});
}
})
.detach();
}
})
.detach();
// Onboarding
let onboarding = cx.new_view(Onboarding::new);
// Dock
let dock_area = cx.new_view(|cx| {
DockArea::new(DOCK_AREA.id, Some(DOCK_AREA.version), cx).panel_style(PanelStyle::TabBar)
});
let dock = cx.new_model(|_| None);
let async_dock = dock.clone();
// Set dock layout
Self::init_layout(dock_area.downgrade(), cx);
// Observe UserState
// If current user is present, fetching all gift wrap events
cx.observe_global::<AccountState>(move |_, cx| {
if cx.global::<AccountState>().in_use.is_some() {
// Setup dock area
let dock_area =
cx.new_view(|cx| DockArea::new(DOCK_AREA.id, Some(DOCK_AREA.version), cx));
AppView {
onboarding,
dock_area,
}
// Setup dock layout
Self::init_layout(dock_area.downgrade(), cx);
// Update dock model
cx.update_model(&async_dock, |a, b| {
*a = Some(dock_area);
b.notify();
});
}
})
.detach();
AppView { onboarding, dock }
}
fn init_layout(dock_area: WeakView<DockArea>, cx: &mut WindowContext) {
@@ -120,7 +72,12 @@ impl AppView {
let left_panels = DockItem::split_with_sizes(
Axis::Vertical,
vec![DockItem::tabs(vec![], None, &dock_area, cx)],
vec![DockItem::tabs(
vec![Arc::new(BlockContainer::panel::<Rooms>(cx))],
None,
&dock_area,
cx,
)],
vec![None, None],
&dock_area,
cx,
@@ -129,7 +86,7 @@ impl AppView {
_ = dock_area.update(cx, |view, cx| {
view.set_version(DOCK_AREA.version, cx);
view.set_left_dock(left_panels, Some(px(260.)), true, cx);
view.set_root(dock_item, cx);
view.set_center(dock_item, cx);
view.set_dock_collapsible(
Edges {
left: false,
@@ -165,17 +122,28 @@ impl Render for AppView {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
let modal_layer = Root::render_modal_layer(cx);
let notification_layer = Root::render_notification_layer(cx);
let mut content = div();
if cx.global::<UserState>().current_user.is_none() {
content = content.child(self.onboarding.clone())
if cx.global::<AccountState>().in_use.is_none() {
content = content.size_full().child(self.onboarding.clone())
} else {
content = content
.size_full()
.flex()
.flex_col()
.child(TitleBar::new())
.child(self.dock_area.clone())
#[allow(clippy::collapsible_else_if)]
if let Some(dock) = self.dock.read(cx).as_ref() {
content = content
.size_full()
.flex()
.flex_col()
.child(TitleBar::new())
.child(dock.clone())
} else {
content = content
.size_full()
.flex()
.items_center()
.justify_center()
.child(Indicator::new().small())
}
}
div()
@@ -183,7 +151,7 @@ impl Render for AppView {
.text_color(cx.theme().foreground)
.size_full()
.child(content)
.children(modal_layer)
.child(div().absolute().top_8().children(notification_layer))
.children(modal_layer)
}
}
+1
View File
@@ -9,6 +9,7 @@ use components::{
use gpui::*;
use prelude::FluentBuilder;
pub mod rooms;
pub mod welcome;
actions!(block, [PanelInfo]);
+157
View File
@@ -0,0 +1,157 @@
use components::{indicator::Indicator, Sizable};
use gpui::*;
use itertools::Itertools;
use nostr_sdk::prelude::*;
use std::{cmp::Reverse, time::Duration};
use super::Block;
use crate::{
get_client,
states::{account::AccountState, room::Room},
};
struct RoomList {
rooms: Vec<Room>,
}
impl RoomList {
pub fn new(raw_events: Vec<Event>, cx: &mut ViewContext<'_, Self>) -> Self {
let rooms: Vec<Room> = raw_events
.into_iter()
.map(|event| Room::new(event, cx))
.collect();
Self { rooms }
}
}
impl Render for RoomList {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
div().flex().flex_col().gap_1().children(self.rooms.clone())
}
}
pub struct Rooms {
rooms: Model<Option<View<RoomList>>>,
focus_handle: FocusHandle,
}
impl Rooms {
pub fn view(cx: &mut WindowContext) -> View<Self> {
cx.new_view(Self::new)
}
fn new(cx: &mut ViewContext<Self>) -> Self {
let rooms = cx.new_model(|_| None);
let async_rooms = rooms.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()
.sorted_by_key(|ev| Reverse(ev.created_at))
.filter(|ev| ev.pubkey != public_key)
.unique_by(|ev| ev.pubkey)
.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 opts = SubscribeAutoCloseOptions::default()
.filter(FilterOptions::WaitDurationAfterEOSE(Duration::from_secs(2)));
async_cx
.background_executor()
.spawn(async move {
if let Err(e) = client.subscribe(vec![filter], Some(opts)).await {
println!("Error: {}", e);
}
})
.await;
let view = async_cx.new_view(|cx| RoomList::new(events, cx)).unwrap();
_ = async_cx.update_model(&async_rooms, |a, b| {
*a = Some(view);
b.notify();
});
})
.detach();
}
Self {
rooms,
focus_handle: cx.focus_handle(),
}
}
}
impl Block for Rooms {
fn title() -> &'static str {
"Rooms"
}
fn new_view(cx: &mut WindowContext) -> View<impl FocusableView> {
Self::view(cx)
}
fn zoomable() -> bool {
false
}
}
impl FocusableView for Rooms {
fn focus_handle(&self, _: &gpui::AppContext) -> gpui::FocusHandle {
self.focus_handle.clone()
}
}
impl Render for Rooms {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
let mut content = div();
if let Some(room_list) = self.rooms.read(cx).as_ref() {
content = content
.flex()
.flex_col()
.gap_1()
.px_2()
.child(room_list.clone());
} else {
content = content
.w_full()
.flex()
.justify_center()
.child(Indicator::new().small())
}
div().child(content)
}
}
-160
View File
@@ -1,160 +0,0 @@
use components::{theme::ActiveTheme, StyledExt};
use gpui::*;
use nostr_sdk::prelude::*;
use prelude::FluentBuilder;
use std::time::Duration;
use super::Block;
use crate::{state::get_client, utils::ago};
#[derive(Clone, IntoElement)]
struct Room {
#[allow(dead_code)]
public_key: PublicKey,
message_at: Timestamp,
metadata: Model<Option<Metadata>>,
}
impl Room {
pub fn new(public_key: PublicKey, created_at: Timestamp, cx: &mut WindowContext) -> Self {
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().await;
let metadata = client
.fetch_metadata(public_key, Some(Duration::from_secs(2)))
.await
.unwrap();
async_metadata
.update(&mut async_cx, |a, b| {
*a = Some(metadata);
b.notify()
})
.unwrap();
})
.detach();
Self {
public_key,
metadata,
message_at: created_at,
}
}
}
impl RenderOnce for Room {
fn render(self, cx: &mut WindowContext) -> impl IntoElement {
let ago = ago(self.message_at.as_u64());
let metadata = match self.metadata.read(cx) {
Some(metadata) => div()
.flex()
.gap_2()
.when_some(metadata.picture.clone(), |parent, picture| {
parent.child(
img(picture)
.size_6()
.rounded_full()
.object_fit(ObjectFit::Cover),
)
})
.when_some(metadata.display_name.clone(), |parent, display_name| {
parent.child(display_name).font_medium()
}),
None => div()
.flex()
.gap_2()
.child(div().size_6().rounded_full().bg(cx.theme().muted))
.child("Unnamed"),
};
div()
.flex()
.justify_between()
.items_center()
.px_2()
.text_sm()
.child(metadata)
.child(ago)
}
}
struct Rooms {
rooms: Vec<Room>,
}
impl Rooms {
pub fn new(items: Vec<UnsignedEvent>, cx: &mut ViewContext<'_, Self>) -> Self {
let rooms: Vec<Room> = items
.iter()
.map(|item| Room::new(item.pubkey, item.created_at, cx))
.collect();
Self { rooms }
}
}
impl Render for Rooms {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
div().flex().flex_col().gap_2().children(self.rooms.clone())
}
}
pub struct Sidebar {
rooms: Model<Option<View<Rooms>>>,
focus_handle: FocusHandle,
}
impl Sidebar {
pub fn view(cx: &mut WindowContext) -> View<Self> {
cx.new_view(Self::new)
}
fn new(cx: &mut ViewContext<Self>) -> Self {
let rooms = cx.new_model(|_| None);
let async_rooms = rooms.clone();
let mut async_cx = cx.to_async();
Self {
rooms,
focus_handle: cx.focus_handle(),
}
}
}
impl Block for Sidebar {
fn title() -> &'static str {
"Sidebar"
}
fn new_view(cx: &mut WindowContext) -> View<impl FocusableView> {
Self::view(cx)
}
fn zoomable() -> bool {
false
}
}
impl FocusableView for Sidebar {
fn focus_handle(&self, _: &gpui::AppContext) -> gpui::FocusHandle {
self.focus_handle.clone()
}
}
impl Render for Sidebar {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
let mut content = div();
if let Some(rooms) = self.rooms.read(cx).as_ref() {
content = content.child(rooms.clone());
}
div().pt_4().child(content)
}
}
@@ -1,96 +0,0 @@
use client::NostrClient;
use components::theme::ActiveTheme;
use gpui::*;
use nostr_sdk::prelude::*;
use prelude::FluentBuilder;
use std::time::Duration;
use crate::state::AppState;
#[derive(Clone, IntoElement)]
struct Account {
#[allow(dead_code)] // TODO: remove this
public_key: PublicKey,
metadata: Model<Option<Metadata>>,
}
impl Account {
pub fn new(public_key: PublicKey, cx: &mut WindowContext) -> Self {
let client = cx.global::<NostrClient>().client;
let metadata = cx.new_model(|_| None);
let async_metadata = metadata.clone();
let mut async_cx = cx.to_async();
cx.foreground_executor()
.spawn(async move {
match client
.fetch_metadata(public_key, Some(Duration::from_secs(2)))
.await
{
Ok(metadata) => {
async_metadata
.update(&mut async_cx, |a, b| {
*a = Some(metadata);
b.notify()
})
.unwrap();
}
Err(_) => todo!(),
}
})
.detach();
Self {
public_key,
metadata,
}
}
}
impl RenderOnce for Account {
fn render(self, cx: &mut WindowContext) -> impl IntoElement {
match self.metadata.read(cx) {
Some(metadata) => div()
.w_8()
.h_12()
.px_1()
.flex()
.items_center()
.justify_center()
.border_b_2()
.border_color(cx.theme().primary_active)
.when_some(metadata.picture.clone(), |parent, picture| {
parent.child(
img(picture)
.size_6()
.rounded_full()
.object_fit(ObjectFit::Cover),
)
}),
None => div(), // TODO: add fallback image
}
}
}
pub struct BottomBar {}
impl BottomBar {
pub fn new(cx: &mut ViewContext<'_, Self>) -> BottomBar {
BottomBar {}
}
}
impl Render for BottomBar {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
div()
.h_12()
.px_3()
.flex_shrink_0()
.flex()
.items_center()
.justify_center()
.gap_1()
}
}
-49
View File
@@ -1,49 +0,0 @@
use bottom_bar::BottomBar;
use components::{
resizable::{h_resizable, resizable_panel, ResizablePanelGroup},
theme::ActiveTheme,
};
use gpui::*;
use navigation::Navigation;
pub mod bottom_bar;
pub mod navigation;
pub struct ChatSpace {
layout: View<ResizablePanelGroup>,
}
impl ChatSpace {
pub fn new(cx: &mut ViewContext<'_, Self>) -> Self {
let navigation = cx.new_view(Navigation::new);
let layout = cx.new_view(|cx| {
h_resizable(cx)
.child(
resizable_panel().size(px(260.)).content(move |cx| {
div()
.size_full()
.bg(cx.theme().side_bar_background)
.text_color(cx.theme().side_bar_foreground)
.flex()
.flex_col()
.child(navigation.clone())
.into_any_element()
}),
cx,
)
.child(
resizable_panel().content(|_| div().child("Content").into_any_element()),
cx,
)
});
Self { layout }
}
}
impl Render for ChatSpace {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
div().relative().size_full().child(self.layout.clone())
}
}
@@ -1,86 +0,0 @@
use components::{theme::ActiveTheme, Icon, IconName};
use gpui::*;
#[derive(IntoElement)]
struct NavItem {
text: SharedString,
icon: Icon,
}
impl NavItem {
pub fn new(text: SharedString, icon: Icon) -> Self {
Self { text, icon }
}
}
impl RenderOnce for NavItem {
fn render(self, cx: &mut WindowContext) -> impl IntoElement {
div()
.hover(|this| {
this.bg(cx.theme().side_bar_accent)
.text_color(cx.theme().side_bar_accent_foreground)
})
.rounded_md()
.flex()
.items_center()
.h_7()
.px_2()
.gap_2()
.child(self.icon)
.child(div().pt(px(2.)).child(self.text))
}
}
pub struct Navigation {}
impl Navigation {
pub fn new(cx: &mut ViewContext<'_, Self>) -> Self {
Self {}
}
}
impl Render for Navigation {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
div().flex_1().w_full().px_2().child(div().h_11()).child(
div().flex().flex_col().gap_4().child(
div()
.flex()
.flex_col()
.gap_1()
.text_sm()
.child(NavItem::new(
"Find".into(),
Icon::new(IconName::Search)
.path("icons/search.svg")
.size_4()
.flex_shrink_0()
.text_color(cx.theme().foreground),
))
.child(NavItem::new(
"Messages".into(),
Icon::new(IconName::Search)
.path("icons/messages.svg")
.size_4()
.flex_shrink_0()
.text_color(cx.theme().foreground),
))
.child(NavItem::new(
"Notifications".into(),
Icon::new(IconName::Search)
.path("icons/notifications.svg")
.size_4()
.flex_shrink_0()
.text_color(cx.theme().foreground),
))
.child(NavItem::new(
"explore".into(),
Icon::new(IconName::Search)
.path("icons/explore.svg")
.size_4()
.flex_shrink_0()
.text_color(cx.theme().foreground),
)),
),
)
}
}
+29 -31
View File
@@ -1,3 +1,4 @@
use async_utility::task::spawn;
use components::{
input::{InputEvent, TextInput},
label::Label,
@@ -6,7 +7,7 @@ use gpui::*;
use keyring::Entry;
use nostr_sdk::prelude::*;
use crate::{constants::KEYRING_SERVICE, get_client, states::user::UserState};
use crate::{constants::KEYRING_SERVICE, get_client, states::account::AccountState};
pub struct Onboarding {
input: View<TextInput>,
@@ -21,44 +22,41 @@ impl Onboarding {
});
cx.subscribe(&input, move |_, text_input, input_event, cx| {
let mut async_cx = cx.to_async();
let view_id = cx.parent_view_id();
if let InputEvent::PressEnter = input_event {
let content = text_input.read(cx).text().to_string();
if let Ok(keys) = Keys::parse(content) {
cx.foreground_executor()
.spawn(async move {
let client = get_client().await;
let public_key = keys.public_key();
let secret = keys.secret_key().to_secret_hex();
let entry =
Entry::new(KEYRING_SERVICE, &public_key.to_bech32().unwrap())
.unwrap();
// Store private key to OS Keyring
let _ = entry.set_password(&secret);
// Update signer
client.set_signer(keys).await;
// Update view
async_cx.update_global(|state: &mut UserState, cx| {
state.current_user = Some(public_key);
cx.notify(view_id);
})
})
.detach();
}
_ = Self::save_keys(&content, cx);
}
})
.detach();
Self { input }
}
fn save_keys(content: &str, cx: &mut ViewContext<Self>) -> anyhow::Result<(), anyhow::Error> {
let keys = Keys::parse(content)?;
let public_key = keys.public_key();
let bech32 = public_key.to_bech32().unwrap();
let secret = keys.secret_key().to_secret_hex();
let entry = Entry::new(KEYRING_SERVICE, &bech32).unwrap();
// Save secret key to keyring
entry.set_password(&secret)?;
// Update signer
spawn(async move {
get_client().set_signer(keys).await;
});
// Update view
cx.update_global(|state: &mut AccountState, cx| {
state.in_use = Some(public_key);
cx.notify();
});
Ok(())
}
}
impl Render for Onboarding {