wip: refactor

This commit is contained in:
2024-12-07 15:08:47 +07:00
parent c8315a2f93
commit 187d0078f9
20 changed files with 7609 additions and 330 deletions

143
crates/app/src/views/app.rs Normal file
View File

@@ -0,0 +1,143 @@
use components::{
dock::{DockArea, DockItem, DockPlacement, PanelStyle},
theme::{ActiveTheme, Theme},
Root, TitleBar,
};
use coop_ui::block::BlockContainer;
use gpui::*;
use nostr_sdk::prelude::*;
use serde::Deserialize;
use std::sync::Arc;
use super::{
dock::{left_dock::LeftDock, welcome::WelcomeBlock},
onboarding::Onboarding,
};
use crate::states::account::AccountState;
#[derive(Clone, PartialEq, Eq, Deserialize)]
pub struct AddPanel {
pub title: Option<String>,
pub receiver: PublicKey,
}
impl_actions!(dock, [AddPanel]);
pub struct DockAreaTab {
id: &'static str,
version: usize,
}
pub const DOCK_AREA: DockAreaTab = DockAreaTab {
id: "dock",
version: 1,
};
pub struct AppView {
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();
// 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).panel_style(PanelStyle::TabBar)
});
cx.observe_global::<AccountState>(|view, cx| {
// TODO: save dock state and load previous state on startup
if cx.global::<AccountState>().in_use.is_some() {
Self::init_layout(view.dock.downgrade(), cx);
}
})
.detach();
AppView { onboarding, dock }
}
fn init_layout(dock_area: WeakView<DockArea>, cx: &mut WindowContext) {
let left = DockItem::panel(Arc::new(BlockContainer::panel::<LeftDock>(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(260.)), 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(BlockContainer::panel::<WelcomeBlock>(cx)),
// TODO: add chat block
],
None,
dock_area,
cx,
)],
vec![None],
dock_area,
cx,
)
}
fn on_action_add_panel(&mut self, _action: &AddPanel, cx: &mut ViewContext<Self>) {
// TODO: add chat panel
let panel = Arc::new(BlockContainer::panel::<WelcomeBlock>(cx));
self.dock.update(cx, |dock_area, cx| {
dock_area.add_panel(panel, DockPlacement::Center, cx);
});
}
}
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::<AccountState>().in_use.is_none() {
content = content.size_full().child(self.onboarding.clone())
} else {
content = content
.on_action(cx.listener(Self::on_action_add_panel))
.size_full()
.flex()
.flex_col()
.child(TitleBar::new())
.child(self.dock.clone())
}
div()
.bg(cx.theme().background)
.text_color(cx.theme().foreground)
.size_full()
.child(content)
.child(div().absolute().top_8().children(notification_layer))
.children(modal_layer)
}
}

View File

@@ -0,0 +1,49 @@
use coop_ui::block::Block;
use gpui::*;
pub struct ChatBlock {
focus_handle: FocusHandle,
}
impl ChatBlock {
pub fn view(cx: &mut WindowContext) -> View<Self> {
cx.new_view(Self::new)
}
fn new(cx: &mut ViewContext<Self>) -> Self {
Self {
focus_handle: cx.focus_handle(),
}
}
}
impl Block for ChatBlock {
fn title() -> &'static str {
"Chat"
}
fn new_view(cx: &mut WindowContext) -> View<impl FocusableView> {
Self::view(cx)
}
fn zoomable() -> bool {
false
}
}
impl FocusableView for ChatBlock {
fn focus_handle(&self, _: &gpui::AppContext) -> gpui::FocusHandle {
self.focus_handle.clone()
}
}
impl Render for ChatBlock {
fn render(&mut self, _cx: &mut gpui::ViewContext<Self>) -> impl IntoElement {
div()
.size_full()
.flex()
.items_center()
.justify_center()
.child("Test")
}
}

View File

@@ -0,0 +1,164 @@
use components::{theme::ActiveTheme, Collapsible, Selectable, StyledExt};
use gpui::*;
use nostr_sdk::prelude::*;
use prelude::FluentBuilder;
use serde::Deserialize;
use crate::{
utils::{ago, show_npub},
views::app::AddPanel,
};
#[derive(Clone, PartialEq, Eq, Deserialize)]
pub struct ChatDelegate {
title: Option<String>,
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,
// 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();
Self {
id,
item,
base: div(),
selected: false,
is_collapsed: false,
}
}
}
impl Selectable for Chat {
fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
fn element_id(&self) -> &gpui::ElementId {
&self.id
}
}
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 {
fn interactivity(&mut self) -> &mut gpui::Interactivity {
self.base.interactivity()
}
}
impl RenderOnce for Chat {
fn render(self, cx: &mut WindowContext) -> impl IntoElement {
let ago = ago(self.item.last_seen.as_u64());
let mut content = div()
.font_medium()
.text_color(cx.theme().sidebar_accent_foreground);
if let Some(metadata) = self.item.metadata.clone() {
content = content
.flex()
.items_center()
.gap_2()
.map(|this| {
if let Some(picture) = metadata.picture {
this.flex_shrink_0().child(
img(picture)
.size_6()
.rounded_full()
.object_fit(ObjectFit::Cover),
)
} else {
this.flex_shrink_0()
.child(div().size_6().rounded_full().bg(cx.theme().muted))
}
})
.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")
}
})
} else {
content = content
.flex()
.items_center()
.gap_2()
.child(
div()
.flex_shrink_0()
.size_6()
.rounded_full()
.bg(cx.theme().muted),
)
.child("Anon")
}
self.base
.id(self.id)
.h_8()
.px_1()
.flex()
.items_center()
.justify_between()
.text_xs()
.rounded_md()
.hover(|this| {
this.bg(cx.theme().sidebar_accent)
.text_color(cx.theme().sidebar_accent_foreground)
})
.child(content)
.child(
div()
.child(ago)
.text_color(cx.theme().sidebar_accent_foreground.opacity(0.7)),
)
.on_click(move |_, cx| {
cx.dispatch_action(Box::new(AddPanel {
title: self.item.title.clone(),
receiver: self.item.public_key,
}))
})
}
}

View File

@@ -0,0 +1,128 @@
use chat::{Chat, ChatDelegate};
use components::{theme::ActiveTheme, v_flex, StyledExt};
use gpui::*;
use itertools::Itertools;
use nostr_sdk::prelude::*;
use std::{cmp::Reverse, time::Duration};
use crate::{get_client, states::account::AccountState};
pub mod chat;
pub struct Inbox {
label: SharedString,
chats: Model<Option<Vec<ChatDelegate>>>,
}
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()
.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 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();
}
Self {
label: "Inbox".into(),
chats,
}
}
}
impl Render for Inbox {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
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())))
}
v_flex()
.pt_3()
.px_2()
.gap_2()
.child(
div()
.id("inbox")
.h_7()
.flex()
.items_center()
.gap_2()
.text_xs()
.font_semibold()
.text_color(cx.theme().sidebar_foreground.opacity(0.7))
.child(self.label.clone()),
)
.child(content)
}
}

View File

@@ -0,0 +1,55 @@
use components::{scroll::ScrollbarAxis, StyledExt};
use coop_ui::block::Block;
use gpui::*;
use super::inbox::Inbox;
pub struct LeftDock {
inbox: View<Inbox>,
focus_handle: FocusHandle,
view_id: EntityId,
}
impl LeftDock {
pub fn view(cx: &mut WindowContext) -> View<Self> {
cx.new_view(Self::new)
}
fn new(cx: &mut ViewContext<Self>) -> Self {
let inbox = cx.new_view(Inbox::new);
Self {
inbox,
focus_handle: cx.focus_handle(),
view_id: cx.view().entity_id(),
}
}
}
impl Block for LeftDock {
fn title() -> &'static str {
"Left Dock"
}
fn new_view(cx: &mut WindowContext) -> View<impl FocusableView> {
Self::view(cx)
}
fn zoomable() -> bool {
false
}
}
impl FocusableView for LeftDock {
fn focus_handle(&self, _: &gpui::AppContext) -> gpui::FocusHandle {
self.focus_handle.clone()
}
}
impl Render for LeftDock {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
div()
.child(self.inbox.clone())
.scrollable(self.view_id, ScrollbarAxis::Vertical)
}
}

View File

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

View File

@@ -0,0 +1,56 @@
use components::{
theme::{ActiveTheme, Colorize},
StyledExt,
};
use coop_ui::block::Block;
use gpui::*;
pub struct WelcomeBlock {
focus_handle: FocusHandle,
}
impl WelcomeBlock {
pub fn view(cx: &mut WindowContext) -> View<Self> {
cx.new_view(Self::new)
}
fn new(cx: &mut ViewContext<Self>) -> Self {
Self {
focus_handle: cx.focus_handle(),
}
}
}
impl Block for WelcomeBlock {
fn title() -> &'static str {
"Welcome"
}
fn new_view(cx: &mut WindowContext) -> View<impl FocusableView> {
Self::view(cx)
}
fn zoomable() -> bool {
false
}
}
impl FocusableView for WelcomeBlock {
fn focus_handle(&self, _: &gpui::AppContext) -> gpui::FocusHandle {
self.focus_handle.clone()
}
}
impl Render for WelcomeBlock {
fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> impl IntoElement {
div()
.size_full()
.flex()
.items_center()
.justify_center()
.child("coop on nostr.")
.text_color(cx.theme().muted.darken(0.1))
.font_black()
.text_sm()
}
}

View File

@@ -0,0 +1,3 @@
pub mod app;
pub mod dock;
pub mod onboarding;

View File

@@ -0,0 +1,79 @@
use async_utility::task::spawn;
use components::{
input::{InputEvent, TextInput},
label::Label,
};
use gpui::*;
use keyring::Entry;
use nostr_sdk::prelude::*;
use crate::{constants::KEYRING_SERVICE, get_client, states::account::AccountState};
pub struct Onboarding {
input: View<TextInput>,
}
impl Onboarding {
pub fn new(cx: &mut ViewContext<'_, Self>) -> Self {
let input = cx.new_view(|cx| {
let mut input = TextInput::new(cx);
input.set_size(components::Size::Medium, cx);
input
});
cx.subscribe(&input, move |_, text_input, input_event, cx| {
if let InputEvent::PressEnter = input_event {
let content = text_input.read(cx).text().to_string();
_ = 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 {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
div()
.size_full()
.flex()
.items_center()
.justify_center()
.child(
div()
.size_1_3()
.flex()
.flex_col()
.gap_1()
.child(Label::new("Private Key").text_sm())
.child(self.input.clone()),
)
}
}