wip: refactor

This commit is contained in:
reya
2024-12-01 08:56:53 +07:00
parent 018769b780
commit 03b8004304
25 changed files with 618 additions and 316 deletions
+189
View File
@@ -0,0 +1,189 @@
use components::{
dock::{DockArea, DockItem, PanelStyle},
theme::{ActiveTheme, Theme},
Root, TitleBar,
};
use gpui::*;
use itertools::Itertools;
use nostr_sdk::prelude::*;
use std::{cmp::Reverse, sync::Arc, time::Duration};
use crate::{
get_client,
states::{
room::{Room, RoomLastMessage, Rooms},
user::UserState,
},
};
use super::{
block::{welcome::WelcomeBlock, BlockContainer},
onboarding::Onboarding,
};
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_area: 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();
// 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)
});
// Set dock layout
Self::init_layout(dock_area.downgrade(), cx);
AppView {
onboarding,
dock_area,
}
}
fn init_layout(dock_area: WeakView<DockArea>, cx: &mut WindowContext) {
let dock_item = Self::init_dock_items(&dock_area, cx);
let left_panels = DockItem::split_with_sizes(
Axis::Vertical,
vec![DockItem::tabs(vec![], None, &dock_area, cx)],
vec![None, None],
&dock_area,
cx,
);
_ = 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_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,
)
}
}
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())
} else {
content = content
.size_full()
.flex()
.flex_col()
.child(TitleBar::new())
.child(self.dock_area.clone())
}
div()
.bg(cx.theme().background)
.text_color(cx.theme().foreground)
.size_full()
.child(content)
.children(modal_layer)
.child(div().absolute().top_8().children(notification_layer))
}
}
+190
View File
@@ -0,0 +1,190 @@
use components::{
button::Button,
dock::{DockItemState, Panel, PanelEvent, TitleStyle},
h_flex,
popup_menu::PopupMenu,
theme::ActiveTheme,
v_flex,
};
use gpui::*;
use prelude::FluentBuilder;
pub mod welcome;
actions!(block, [PanelInfo]);
pub fn section(title: impl IntoElement, cx: &WindowContext) -> Div {
h_flex()
.items_center()
.gap_4()
.p_4()
.w_full()
.rounded_lg()
.border_1()
.border_color(cx.theme().border)
.flex_wrap()
.justify_around()
.child(div().flex_none().w_full().child(title))
}
pub struct BlockContainer {
focus_handle: FocusHandle,
name: SharedString,
title_bg: Option<Hsla>,
description: SharedString,
width: Option<Pixels>,
height: Option<Pixels>,
block: Option<AnyView>,
closeable: bool,
zoomable: bool,
}
#[derive(Debug)]
pub enum ContainerEvent {
Close,
}
pub trait Block: FocusableView {
fn klass() -> &'static str {
std::any::type_name::<Self>().split("::").last().unwrap()
}
fn title() -> &'static str;
fn description() -> &'static str {
""
}
fn closeable() -> bool {
true
}
fn zoomable() -> bool {
true
}
fn title_bg() -> Option<Hsla> {
None
}
fn new_view(cx: &mut WindowContext) -> View<impl FocusableView>;
}
impl EventEmitter<ContainerEvent> for BlockContainer {}
impl BlockContainer {
pub fn new(cx: &mut WindowContext) -> Self {
let focus_handle = cx.focus_handle();
Self {
focus_handle,
name: "".into(),
title_bg: None,
description: "".into(),
width: None,
height: None,
block: None,
closeable: true,
zoomable: true,
}
}
pub fn panel<B: Block>(cx: &mut WindowContext) -> View<Self> {
let name = B::title();
let description = B::description();
let block = B::new_view(cx);
let focus_handle = block.focus_handle(cx);
cx.new_view(|cx| {
let mut story = Self::new(cx).block(block.into());
story.focus_handle = focus_handle;
story.closeable = B::closeable();
story.zoomable = B::zoomable();
story.name = name.into();
story.description = description.into();
story.title_bg = B::title_bg();
story
})
}
pub fn width(mut self, width: gpui::Pixels) -> Self {
self.width = Some(width);
self
}
pub fn height(mut self, height: gpui::Pixels) -> Self {
self.height = Some(height);
self
}
pub fn block(mut self, block: AnyView) -> Self {
self.block = Some(block);
self
}
fn on_action_panel_info(&mut self, _: &PanelInfo, _cx: &mut ViewContext<Self>) {
// struct Info;
// let note = Notification::new(format!("You have clicked panel info on: {}", self.name)).id::<Info>();
// cx.push_notification(note);
}
}
impl Panel for BlockContainer {
fn panel_name(&self) -> &'static str {
"BlockContainer"
}
fn title(&self, _cx: &WindowContext) -> AnyElement {
self.name.clone().into_any_element()
}
fn title_style(&self, cx: &WindowContext) -> Option<TitleStyle> {
self.title_bg.map(|bg| TitleStyle {
background: bg,
foreground: cx.theme().foreground,
})
}
fn closeable(&self, _cx: &WindowContext) -> bool {
self.closeable
}
fn zoomable(&self, _cx: &WindowContext) -> bool {
self.zoomable
}
fn popup_menu(&self, menu: PopupMenu, _cx: &WindowContext) -> PopupMenu {
menu.track_focus(&self.focus_handle)
.menu("Info", Box::new(PanelInfo))
}
fn toolbar_buttons(&self, _cx: &WindowContext) -> Vec<Button> {
vec![]
}
fn dump(&self, _cx: &AppContext) -> DockItemState {
DockItemState::new(self)
}
}
impl EventEmitter<PanelEvent> for BlockContainer {}
impl FocusableView for BlockContainer {
fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
self.focus_handle.clone()
}
}
impl Render for BlockContainer {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
v_flex()
.size_full()
.track_focus(&self.focus_handle)
.on_action(cx.listener(Self::on_action_panel_info))
.when_some(self.block.clone(), |this, story| {
this.child(v_flex().size_full().child(story))
})
}
}
+160
View File
@@ -0,0 +1,160 @@
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)
}
}
+57
View File
@@ -0,0 +1,57 @@
use components::{
theme::{ActiveTheme, Colorize},
StyledExt,
};
use gpui::*;
use super::Block;
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()
}
}
@@ -0,0 +1,96 @@
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
@@ -0,0 +1,49 @@
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())
}
}
@@ -0,0 +1,86 @@
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),
)),
),
)
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod app;
pub mod block;
pub mod onboarding;
+81
View File
@@ -0,0 +1,81 @@
use components::{
input::{InputEvent, TextInput},
label::Label,
};
use gpui::*;
use keyring::Entry;
use nostr_sdk::prelude::*;
use crate::{constants::KEYRING_SERVICE, get_client, states::user::UserState};
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| {
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();
}
}
})
.detach();
Self { input }
}
}
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()),
)
}
}