wip: refactor

This commit is contained in:
2024-12-01 08:56:53 +07:00
parent 018769b780
commit 03b8004304
25 changed files with 618 additions and 316 deletions

View File

@@ -1,27 +0,0 @@
use anyhow::anyhow;
use gpui::*;
use rust_embed::RustEmbed;
#[derive(RustEmbed)]
#[folder = "../../assets"]
pub struct Assets;
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<std::borrow::Cow<'static, [u8]>>> {
Self::get(path)
.map(|f| Some(f.data))
.ok_or_else(|| anyhow!("could not find asset at path \"{}\"", path))
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
Ok(Self::iter()
.filter_map(|p| {
if p.starts_with(path) {
Some(p.into())
} else {
None
}
})
.collect())
}
}

View File

@@ -1,2 +0,0 @@
pub const KEYRING_SERVICE: &str = "Coop Safe Storage";
pub const APP_NAME: &str = "coop";

View File

@@ -1,95 +0,0 @@
use asset::Assets;
use client::NostrClient;
use constants::{APP_NAME, KEYRING_SERVICE};
use gpui::*;
use keyring::Entry;
use nostr_sdk::prelude::*;
use state::AppState;
use std::sync::Arc;
use utils::get_all_accounts_from_keyring;
use views::app::AppView;
pub mod asset;
pub mod constants;
pub mod state;
pub mod utils;
pub mod views;
actions!(main_menu, [Quit]);
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
// Initialize nostr client
let nostr = NostrClient::init().await;
// Initialize app state
let app_state = AppState::new();
App::new()
.with_assets(Assets)
.with_http_client(Arc::new(reqwest_client::ReqwestClient::new()))
.run(move |cx| {
// Initialize components
components::init(cx);
// Set global state
cx.set_global(nostr);
cx.set_global(app_state);
// Set quit action
cx.on_action(quit);
// Refresh
cx.refresh();
// Login
let async_cx = cx.to_async();
cx.foreground_executor()
.spawn(async move {
let accounts = get_all_accounts_from_keyring();
if let Some(account) = accounts.first() {
let client = async_cx
.read_global(|nostr: &NostrClient, _cx| nostr.client)
.unwrap();
let entry =
Entry::new(KEYRING_SERVICE, account.to_bech32().unwrap().as_ref())
.unwrap();
let password = entry.get_password().unwrap();
let keys = Keys::parse(password).unwrap();
client.set_signer(keys).await;
async_cx
.update_global(|app_state: &mut AppState, _cx| {
app_state.signer = Some(*account);
})
.unwrap();
}
})
.detach();
// Set window size
let bounds = Bounds::centered(None, size(px(900.0), px(680.0)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
window_decorations: Some(WindowDecorations::Client),
titlebar: Some(TitlebarOptions {
title: Some(SharedString::new_static(APP_NAME)),
appears_transparent: true,
traffic_light_position: Some(point(px(9.0), px(9.0))),
}),
..Default::default()
},
|cx| cx.new_view(AppView::new),
)
.unwrap();
});
}
fn quit(_: &Quit, cx: &mut AppContext) {
cx.quit();
}

View File

@@ -1,21 +0,0 @@
use gpui::Global;
use nostr_sdk::prelude::*;
pub struct AppState {
pub signer: Option<PublicKey>,
// TODO: add more app state
}
impl Global for AppState {}
impl AppState {
pub fn new() -> Self {
Self { signer: None }
}
}
impl Default for AppState {
fn default() -> Self {
Self::new()
}
}

View File

@@ -1,15 +0,0 @@
use keyring_search::{Limit, List, Search};
use nostr_sdk::prelude::*;
pub fn get_all_accounts_from_keyring() -> Vec<PublicKey> {
let search = Search::new().expect("Keyring not working.");
let results = search.by_service("Coop Safe Storage");
let list = List::list_credentials(&results, Limit::All);
let accounts: Vec<PublicKey> = list
.split_whitespace()
.filter(|v| v.starts_with("npub1") && !v.ends_with("coop"))
.filter_map(|i| PublicKey::from_bech32(i).ok())
.collect();
accounts
}

View File

@@ -1,110 +0,0 @@
use std::sync::Arc;
use components::{
dock::{DockArea, DockItem},
theme::{ActiveTheme, Theme},
TitleBar,
};
use gpui::*;
use super::{
block::{welcome::WelcomeBlock, BlockContainer},
onboarding::Onboarding,
};
use crate::state::AppState;
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();
// 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));
let weak_dock_area = dock_area.downgrade();
// Set dock layout
Self::init_layout(weak_dock_area, 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![], 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);
// 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)),
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 mut content = div();
if cx.global::<AppState>().signer.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)
}
}

View File

@@ -1,190 +0,0 @@
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))
})
}
}

View File

@@ -1,45 +0,0 @@
use gpui::*;
use super::Block;
pub struct WelcomeBlock {
focus_handle: FocusHandle,
}
impl WelcomeBlock {
fn new(cx: &mut ViewContext<Self>) -> Self {
Self {
focus_handle: cx.focus_handle(),
}
}
pub fn view(cx: &mut WindowContext) -> View<Self> {
cx.new_view(Self::new)
}
}
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().child("Welcome")
}
}

View File

@@ -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()
}
}

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())
}
}

View File

@@ -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),
)),
),
)
}
}

View File

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

View File

@@ -1,74 +0,0 @@
use ::client::NostrClient;
use components::{
input::{InputEvent, TextInput},
label::Label,
};
use gpui::*;
use keyring::Entry;
use nostr_sdk::prelude::*;
use crate::{constants::KEYRING_SERVICE, state::AppState};
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 client = cx.global::<NostrClient>().client;
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 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(|app_state: &mut AppState, cx| {
app_state.signer = 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_1_3()
.flex()
.flex_col()
.gap_1()
.child(Label::new("Private Key").text_sm())
.child(self.input.clone())
}
}