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

28
crates/app/Cargo.toml Normal file
View File

@@ -0,0 +1,28 @@
[package]
name = "coop"
version = "0.1.0"
edition = "2021"
publish = false
[[bin]]
name = "coop"
path = "src/main.rs"
[dependencies]
gpui.workspace = true
components.workspace = true
reqwest_client.workspace = true
tokio.workspace = true
nostr-sdk.workspace = true
keyring-search.workspace = true
keyring.workspace = true
anyhow.workspace = true
serde.workspace = true
serde_json.workspace = true
itertools.workspace = true
chrono.workspace = true
dirs.workspace = true
tracing-subscriber = { version = "0.3.18", features = ["fmt"] }
rust-embed = "8.5.0"

27
crates/app/src/asset.rs Normal file
View File

@@ -0,0 +1,27 @@
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

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

156
crates/app/src/main.rs Normal file
View File

@@ -0,0 +1,156 @@
use asset::Assets;
use components::Root;
use constants::{APP_NAME, FAKE_SIG};
use dirs::config_dir;
use gpui::*;
use nostr_sdk::prelude::*;
use std::{fs, str::FromStr, sync::Arc, time::Duration};
use tokio::sync::OnceCell;
use states::user::UserState;
use ui::app::AppView;
pub mod asset;
pub mod constants;
pub mod states;
pub mod ui;
pub mod utils;
actions!(main_menu, [Quit]);
pub static CLIENT: OnceCell<Client> = OnceCell::const_new();
pub async fn get_client() -> &'static Client {
CLIENT
.get_or_init(|| async {
// Setup app data folder
let config_dir = config_dir().expect("Config directory not found");
let _ = fs::create_dir_all(config_dir.join("Coop/"));
// Setup database
let lmdb = NostrLMDB::open(config_dir.join("Coop/nostr"))
.expect("Database is NOT initialized");
// Client options
let opts = Options::new()
.gossip(true)
.max_avg_latency(Duration::from_secs(2));
// Setup Nostr Client
let client = ClientBuilder::default().database(lmdb).opts(opts).build();
// Add some bootstrap relays
let _ = client.add_relay("wss://relay.damus.io").await;
let _ = client.add_relay("wss://relay.primal.net").await;
let _ = client.add_discovery_relay("wss://directory.yabu.me").await;
let _ = client.add_discovery_relay("wss://user.kindpag.es/").await;
// Connect to all relays
client.connect().await;
// Return client
client
})
.await
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
// Initialize nostr client
let _client = get_client().await;
App::new()
.with_assets(Assets)
.with_http_client(Arc::new(reqwest_client::ReqwestClient::new()))
.run(move |cx| {
// Initialize components
components::init(cx);
// Set quit action
cx.on_action(quit);
// Set app state
UserState::set_global(cx);
// Refresh
cx.refresh();
// Handle notifications
cx.foreground_executor()
.spawn(async move {
let client = get_client().await;
// Generate a fake signature for rumor event.
// TODO: Find better way to save unsigned event to database.
let fake_sig = Signature::from_str(FAKE_SIG).unwrap();
client
.handle_notifications(|notification| async {
#[allow(clippy::collapsible_match)]
if let RelayPoolNotification::Message { message, .. } = notification {
if let RelayMessage::Event { event, .. } = message {
if event.kind == Kind::GiftWrap {
if let Ok(UnwrappedGift { rumor, .. }) =
client.unwrap_gift_wrap(&event).await
{
println!("rumor: {}", rumor.as_json());
let mut rumor_clone = rumor.clone();
// Compute event id if not exist
rumor_clone.ensure_id();
let ev = Event::new(
rumor_clone.id.expect("System error"),
rumor_clone.pubkey,
rumor_clone.created_at,
rumor_clone.kind,
rumor_clone.tags,
rumor_clone.content,
fake_sig,
);
// Save rumor to database to further query
if let Err(e) = client.database().save_event(&ev).await
{
println!("Error: {}", e)
}
}
} else if event.kind == Kind::Metadata {
// TODO: handle metadata
}
}
}
Ok(false)
})
.await
})
.detach();
// Set window size
let bounds = Bounds::centered(None, size(px(900.0), px(680.0)), cx);
let opts = 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.open_window(opts, |cx| {
let app_view = cx.new_view(AppView::new);
cx.new_view(|cx| Root::new(app_view.into(), cx))
})
.unwrap();
});
}
fn quit(_: &Quit, cx: &mut AppContext) {
cx.quit();
}

View File

@@ -0,0 +1,2 @@
pub mod room;
pub mod user;

View File

@@ -0,0 +1,35 @@
use gpui::*;
use nostr_sdk::prelude::*;
#[derive(Clone)]
pub struct RoomLastMessage {
pub content: Option<String>,
pub time: Timestamp,
}
#[derive(Clone, IntoElement)]
pub struct Room {
members: Vec<PublicKey>,
last_message: Option<RoomLastMessage>,
}
impl Room {
pub fn new(members: Vec<PublicKey>, last_message: Option<RoomLastMessage>) -> Self {
Self {
members,
last_message,
}
}
}
impl RenderOnce for Room {
fn render(self, _cx: &mut WindowContext) -> impl IntoElement {
div().child("TODO")
}
}
pub struct Rooms {
pub rooms: Vec<Room>,
}
impl Global for Rooms {}

View File

@@ -0,0 +1,19 @@
use gpui::*;
use nostr_sdk::prelude::*;
#[derive(Clone)]
pub struct UserState {
pub current_user: Option<PublicKey>,
}
impl Global for UserState {}
impl UserState {
pub fn set_global(cx: &mut AppContext) {
cx.set_global(Self::new());
}
fn new() -> Self {
Self { current_user: None }
}
}

189
crates/app/src/ui/app.rs Normal file
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))
}
}

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

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

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

View File

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

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

View File

@@ -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
crates/app/src/ui/mod.rs Normal file
View File

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

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

29
crates/app/src/utils.rs Normal file
View File

@@ -0,0 +1,29 @@
use chrono::{Local, TimeZone};
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
}
pub fn ago(time: u64) -> String {
let now = Local::now();
let input_time = Local.timestamp_opt(time as i64, 0).unwrap();
let diff = (now - input_time).num_hours();
if diff < 24 {
let duration = now.signed_duration_since(input_time);
format!("{} ago", duration.num_hours())
} else {
input_time.format("%b %d").to_string()
}
}