wip: refactor

This commit is contained in:
2025-01-25 08:11:34 +07:00
parent 29a8e2c8ac
commit 6a67a79c3f
21 changed files with 410 additions and 452 deletions

View File

@@ -1,102 +0,0 @@
use crate::{get_client, states::app::AppRegistry};
use common::constants::IMAGE_SERVICE;
use gpui::prelude::FluentBuilder;
use gpui::{
actions, img, Context, IntoElement, Model, ObjectFit, ParentElement, Render, Styled,
StyledImage, ViewContext,
};
use nostr_sdk::prelude::*;
use ui::{
button::{Button, ButtonVariants},
popup_menu::PopupMenuExt,
Icon, IconName, Sizable,
};
actions!(account, [ToDo]);
pub struct Account {
public_key: PublicKey,
metadata: Model<Option<Metadata>>,
}
impl Account {
pub fn new(public_key: PublicKey, cx: &mut ViewContext<'_, Self>) -> Self {
let metadata = cx.new_model(|_| None);
let refreshs = cx.global_mut::<AppRegistry>().refreshs();
if let Some(refreshs) = refreshs.upgrade() {
cx.observe(&refreshs, |this, _, cx| {
this.load_metadata(cx);
})
.detach();
}
Self {
public_key,
metadata,
}
}
pub fn load_metadata(&self, cx: &mut ViewContext<Self>) {
let mut async_cx = cx.to_async();
let async_metadata = self.metadata.clone();
cx.foreground_executor()
.spawn({
let client = get_client();
let public_key = self.public_key;
async move {
let metadata = async_cx
.background_executor()
.spawn(async move { client.database().metadata(public_key).await })
.await;
if let Ok(metadata) = metadata {
_ = async_cx.update_model(&async_metadata, |model, cx| {
*model = metadata;
cx.notify();
});
}
}
})
.detach();
}
}
impl Render for Account {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
Button::new("account")
.ghost()
.xsmall()
.reverse()
.icon(Icon::new(IconName::ChevronDownSmall))
.map(|this| {
if let Some(metadata) = self.metadata.read(cx).as_ref() {
this.map(|this| {
if let Some(picture) = metadata.picture.clone() {
this.flex_shrink_0().child(
img(format!("{}/?url={}&w=72&h=72&n=-1", IMAGE_SERVICE, picture))
.size_5()
.rounded_full()
.object_fit(ObjectFit::Cover),
)
} else {
this.flex_shrink_0()
.child(img("brand/avatar.png").size_5().rounded_full())
}
})
} else {
this.flex_shrink_0()
.child(img("brand/avatar.png").size_5().rounded_full())
}
})
.popup_menu(move |this, _cx| {
this.menu("Profile", Box::new(ToDo))
.menu("Contacts", Box::new(ToDo))
.menu("Settings", Box::new(ToDo))
.separator()
.menu("Change account", Box::new(ToDo))
})
}
}

View File

@@ -1,20 +1,20 @@
use super::{
account::Account, chat::ChatPanel, onboarding::Onboarding, sidebar::Sidebar,
welcome::WelcomePanel,
};
use crate::states::{app::AppRegistry, chat::ChatRegistry};
use super::{chat::ChatPanel, onboarding::Onboarding, sidebar::Sidebar, welcome::WelcomePanel};
use gpui::{
div, impl_internal_actions, px, svg, Axis, Context, Edges, InteractiveElement, IntoElement,
Model, ParentElement, Render, Styled, View, ViewContext, VisualContext, WeakView,
WindowContext,
actions, div, img, impl_internal_actions, px, svg, Axis, Edges, InteractiveElement,
IntoElement, ObjectFit, ParentElement, Render, Styled, StyledImage, View, ViewContext,
VisualContext, WeakView, WindowContext,
};
use registry::{app::AppRegistry, chat::ChatRegistry, contact::Contact};
use serde::Deserialize;
use std::sync::Arc;
use ui::{
button::{Button, ButtonVariants},
dock_area::{dock::DockPlacement, DockArea, DockItem},
notification::NotificationType,
theme::{scale::ColorScaleStep, ActiveTheme, Theme},
ContextModal, Root, TitleBar,
popup_menu::PopupMenuExt,
prelude::FluentBuilder,
theme::{scale::ColorScaleStep, ActiveTheme},
ContextModal, Icon, IconName, Root, Sizable, TitleBar,
};
#[derive(Clone, PartialEq, Eq, Deserialize)]
@@ -28,7 +28,10 @@ pub struct AddPanel {
pub position: DockPlacement,
}
// Dock actions
impl_internal_actions!(dock, [AddPanel]);
// Account actions
actions!(account, [OpenProfile, OpenContacts, OpenSettings, Logout]);
pub struct DockAreaTab {
id: &'static str,
@@ -41,98 +44,31 @@ pub const DOCK_AREA: DockAreaTab = DockAreaTab {
};
pub struct AppView {
account: Model<Option<View<Account>>>,
onboarding: View<Onboarding>,
dock: View<DockArea>,
}
impl AppView {
pub fn new(cx: &mut ViewContext<'_, Self>) -> AppView {
// Sync theme with system
cx.observe_window_appearance(|_, cx| {
Theme::sync_system_appearance(cx);
})
.detach();
// Account
let account = cx.new_model(|_| None);
let async_account = account.clone();
// Onboarding
let onboarding = cx.new_view(Onboarding::new);
// Dock
let dock = cx.new_view(|cx| DockArea::new(DOCK_AREA.id, Some(DOCK_AREA.version), cx));
// Get current user from app state
let current_user = cx.global::<AppRegistry>().current_user();
let weak_user = cx.global::<AppRegistry>().user();
if let Some(current_user) = current_user.upgrade() {
cx.observe(&current_user, move |view, model, cx| {
if let Some(public_key) = model.read(cx).clone().as_ref() {
Self::init_layout(view.dock.downgrade(), cx);
// TODO: save dock state and load previous state on startup
let view = cx.new_view(|cx| {
let view = Account::new(*public_key, cx);
// Initial load metadata
view.load_metadata(cx);
view
});
cx.update_model(&async_account, |model, cx| {
*model = Some(view);
cx.notify();
});
if let Some(user) = weak_user.upgrade() {
cx.observe(&user, move |view, this, cx| {
if this.read(cx).is_some() {
Self::render_dock(view.dock.downgrade(), cx);
}
})
.detach();
}
AppView {
account,
onboarding,
dock,
}
AppView { onboarding, dock }
}
fn init_layout(dock_area: WeakView<DockArea>, cx: &mut WindowContext) {
let left = DockItem::panel(Arc::new(Sidebar::new(cx)));
let center = Self::init_dock_items(&dock_area, cx);
_ = dock_area.update(cx, |view, cx| {
view.set_version(DOCK_AREA.version, cx);
view.set_left_dock(left, Some(px(240.)), true, cx);
view.set_center(center, cx);
view.set_dock_collapsible(
Edges {
left: false,
..Default::default()
},
cx,
);
// TODO: support right dock?
// TODO: support bottom dock?
});
}
fn init_dock_items(dock_area: &WeakView<DockArea>, cx: &mut WindowContext) -> DockItem {
DockItem::split_with_sizes(
Axis::Vertical,
vec![DockItem::tabs(
vec![Arc::new(WelcomePanel::new(cx))],
None,
dock_area,
cx,
)],
vec![None],
dock_area,
cx,
)
}
fn on_action_add_panel(&mut self, action: &AddPanel, cx: &mut ViewContext<Self>) {
fn on_panel_action(&mut self, action: &AddPanel, cx: &mut ViewContext<Self>) {
match &action.panel {
PanelKind::Room(id) => {
if let Some(weak_room) = cx.global::<ChatRegistry>().room(id, cx) {
@@ -152,53 +88,109 @@ impl AppView {
}
};
}
fn render_account(&self, account: Contact) -> impl IntoElement {
Button::new("account")
.ghost()
.xsmall()
.reverse()
.icon(Icon::new(IconName::ChevronDownSmall))
.child(
img(account.avatar())
.size_5()
.rounded_full()
.object_fit(ObjectFit::Cover),
)
.popup_menu(move |this, _cx| {
this.menu("Profile", Box::new(OpenProfile))
.menu("Contacts", Box::new(OpenContacts))
.menu("Settings", Box::new(OpenSettings))
.separator()
.menu("Change account", Box::new(Logout))
})
}
fn render_dock(dock_area: WeakView<DockArea>, cx: &mut WindowContext) {
let left = DockItem::panel(Arc::new(Sidebar::new(cx)));
let center = DockItem::split_with_sizes(
Axis::Vertical,
vec![DockItem::tabs(
vec![Arc::new(WelcomePanel::new(cx))],
None,
&dock_area,
cx,
)],
vec![None],
&dock_area,
cx,
);
_ = dock_area.update(cx, |view, cx| {
view.set_version(DOCK_AREA.version, cx);
view.set_left_dock(left, Some(px(240.)), true, cx);
view.set_center(center, cx);
view.set_dock_collapsible(
Edges {
left: false,
..Default::default()
},
cx,
);
// TODO: support right dock?
// TODO: support bottom dock?
});
}
}
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().size_full().flex().flex_col();
if cx.global::<AppRegistry>().is_loading {
content = content.child(div()).child(
div().flex_1().flex().items_center().justify_center().child(
svg()
.path("brand/coop.svg")
.size_12()
.text_color(cx.theme().base.step(cx, ColorScaleStep::THREE)),
),
)
} else if let Some(account) = self.account.read(cx).as_ref() {
content = content
.child(
TitleBar::new()
// Left side
.child(div())
// Right side
.child(
div()
.flex()
.items_center()
.justify_end()
.gap_1()
.px_2()
.child(account.clone()),
),
)
.child(self.dock.clone())
.on_action(cx.listener(Self::on_action_add_panel))
} else {
content = content
.child(TitleBar::new())
.child(self.onboarding.clone())
}
let state = cx.global::<AppRegistry>();
div()
.size_full()
.child(content)
.flex()
.flex_col()
// Main
.map(|this| {
if state.is_loading {
this
// Placeholder
.child(div())
.child(
div().flex_1().flex().items_center().justify_center().child(
svg()
.path("brand/coop.svg")
.size_12()
.text_color(cx.theme().base.step(cx, ColorScaleStep::THREE)),
),
)
} else if let Some(contact) = state.current_user(cx) {
this.child(
TitleBar::new()
// Left side
.child(div())
// Right side
.child(
div()
.flex()
.items_center()
.justify_end()
.gap_1()
.px_2()
.child(self.render_account(contact)),
),
)
.child(self.dock.clone())
.on_action(cx.listener(Self::on_panel_action))
} else {
this.child(TitleBar::new()).child(self.onboarding.clone())
}
})
// Notification
.child(div().absolute().top_8().children(notification_layer))
// Modal
.children(modal_layer)
}
}

View File

@@ -1,8 +1,8 @@
use crate::states::chat::room::Member;
use gpui::{
div, img, px, InteractiveElement, IntoElement, ParentElement, RenderOnce, SharedString, Styled,
WindowContext,
};
use registry::contact::Contact;
use ui::{
theme::{scale::ColorScaleStep, ActiveTheme},
StyledExt,
@@ -10,7 +10,7 @@ use ui::{
#[derive(Clone, Debug, IntoElement)]
pub struct Message {
member: Member,
member: Contact,
content: SharedString,
ago: SharedString,
}
@@ -26,7 +26,7 @@ impl PartialEq for Message {
}
impl Message {
pub fn new(member: Member, content: SharedString, ago: SharedString) -> Self {
pub fn new(member: Contact, content: SharedString, ago: SharedString) -> Self {
Self {
member,
content,

View File

@@ -12,7 +12,9 @@ use gpui::{
use itertools::Itertools;
use message::Message;
use nostr_sdk::prelude::*;
use registry::room::Room;
use smol::fs;
use state::get_client;
use tokio::sync::oneshot;
use ui::{
button::{Button, ButtonRounded, ButtonVariants},
@@ -27,8 +29,6 @@ use ui::{
v_flex, ContextModal, Icon, IconName, Sizable,
};
use crate::{get_client, states::chat::room::Room};
mod message;
#[derive(Clone)]

View File

@@ -1,4 +1,3 @@
mod account;
mod chat;
mod onboarding;
mod sidebar;

View File

@@ -1,10 +1,10 @@
use common::constants::KEYRING_SERVICE;
use gpui::{div, IntoElement, ParentElement, Render, Styled, View, ViewContext, VisualContext};
use nostr_sdk::prelude::*;
use registry::{app::AppRegistry, contact::Contact};
use state::get_client;
use ui::input::{InputEvent, TextInput};
use crate::{get_client, states::app::AppRegistry};
pub struct Onboarding {
input: View<TextInput>,
}
@@ -43,10 +43,28 @@ impl Onboarding {
async move {
if task.await.is_ok() {
_ = client.set_signer(keys).await;
_ = async_cx.update_global::<AppRegistry, _>(|state, cx| {
state.set_user(public_key, cx);
});
let query: anyhow::Result<Metadata, anyhow::Error> = async_cx
.background_executor()
.spawn(async move {
// Update signer
_ = client.set_signer(keys).await;
// Get metadata
if let Some(metadata) =
client.database().metadata(public_key).await?
{
Ok(metadata)
} else {
Ok(Metadata::new())
}
})
.await;
if let Ok(metadata) = query {
_ = async_cx.update_global::<AppRegistry, _>(|state, cx| {
state.set_user(Contact::new(public_key, metadata), cx);
});
}
}
}
})

View File

@@ -1,10 +1,3 @@
use crate::{
get_client,
states::{
app::AppRegistry,
chat::room::{Member, Room},
},
};
use common::utils::{random_name, room_hash};
use gpui::{
div, img, impl_internal_actions, px, uniform_list, Context, FocusHandle, InteractiveElement,
@@ -12,7 +5,9 @@ use gpui::{
View, ViewContext, VisualContext, WindowContext,
};
use nostr_sdk::prelude::*;
use registry::{app::AppRegistry, contact::Contact, room::Room};
use serde::Deserialize;
use state::get_client;
use std::{collections::HashSet, time::Duration};
use ui::{
button::{Button, ButtonRounded},
@@ -32,7 +27,7 @@ pub struct Compose {
title_input: View<TextInput>,
message_input: View<TextInput>,
user_input: View<TextInput>,
contacts: Model<Option<Vec<Member>>>,
contacts: Model<Option<Vec<Contact>>>,
selected: Model<HashSet<PublicKey>>,
focus_handle: FocusHandle,
is_loading: bool,
@@ -77,15 +72,15 @@ impl Compose {
let client = get_client();
async move {
let query: anyhow::Result<Vec<Member>, anyhow::Error> = async_cx
let query: anyhow::Result<Vec<Contact>, anyhow::Error> = async_cx
.background_executor()
.spawn(async move {
let signer = client.signer().await?;
let public_key = signer.get_public_key().await?;
let profiles = client.database().contacts(public_key).await?;
let members: Vec<Member> = profiles
let members: Vec<Contact> = profiles
.into_iter()
.map(|profile| Member::new(profile.public_key(), profile.metadata()))
.map(|profile| Contact::new(profile.public_key(), profile.metadata()))
.collect();
Ok(members)
@@ -120,11 +115,9 @@ impl Compose {
}
pub fn room(&self, cx: &WindowContext) -> Option<Room> {
let weak_user = cx.global::<AppRegistry>().current_user();
if let Some(user) = weak_user.upgrade() {
let public_key = user.read(cx).unwrap();
let current_user = cx.global::<AppRegistry>().current_user(cx);
if let Some(current_user) = current_user {
// Convert selected pubkeys into nostr tags
let tags: Vec<Tag> = self
.selected
@@ -135,19 +128,19 @@ impl Compose {
let tags = Tags::new(tags);
// Convert selected pubkeys into members
let members: Vec<Member> = self
let members: Vec<Contact> = self
.selected
.read(cx)
.clone()
.into_iter()
.map(|pk| Member::new(pk, Metadata::new()))
.map(|pk| Contact::new(pk, Metadata::new()))
.collect();
// Get room's id
let id = room_hash(&tags);
// Get room's owner (current user)
let owner = Member::new(public_key, Metadata::new());
let owner = Contact::new(current_user.public_key(), Metadata::new());
// Get room's title
let title = self.title_input.read(cx).text().to_string().into();
@@ -193,7 +186,7 @@ impl Compose {
_ = async_cx.update_view(&view, |this, cx| {
this.contacts.update(cx, |this, cx| {
if let Some(members) = this {
members.insert(0, Member::new(public_key, metadata));
members.insert(0, Contact::new(public_key, metadata));
}
cx.notify();
});

View File

@@ -1,12 +1,10 @@
use crate::{
states::chat::ChatRegistry,
views::app::{AddPanel, PanelKind},
};
use crate::views::app::{AddPanel, PanelKind};
use common::utils::message_ago;
use gpui::{
div, img, percentage, prelude::FluentBuilder, px, InteractiveElement, IntoElement,
ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, ViewContext,
};
use registry::chat::ChatRegistry;
use ui::{
dock_area::dock::DockPlacement,
skeleton::Skeleton,

View File

@@ -1,10 +1,11 @@
use crate::{states::chat::ChatRegistry, views::sidebar::inbox::Inbox};
use crate::views::sidebar::inbox::Inbox;
use compose::Compose;
use gpui::{
div, px, AnyElement, AppContext, BorrowAppContext, Entity, EntityId, EventEmitter, FocusHandle,
FocusableView, InteractiveElement, IntoElement, ParentElement, Render, SharedString,
StatefulInteractiveElement, Styled, View, ViewContext, VisualContext, WindowContext,
};
use registry::chat::ChatRegistry;
use ui::{
button::{Button, ButtonRounded, ButtonVariants},
dock_area::{