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

102
Cargo.lock generated
View File

@@ -208,7 +208,7 @@ dependencies = [
"serde", "serde",
"serde_repr", "serde_repr",
"url", "url",
"zbus 5.3.0", "zbus 5.3.1",
] ]
[[package]] [[package]]
@@ -380,7 +380,7 @@ dependencies = [
[[package]] [[package]]
name = "async-wsocket" name = "async-wsocket"
version = "0.12.0" version = "0.12.0"
source = "git+https://github.com/yukibtc/async-wsocket?rev=da5da94574f73da1b4d638fd9736298a67139c59#da5da94574f73da1b4d638fd9736298a67139c59" source = "git+https://github.com/yukibtc/async-wsocket?rev=5fba7927576064ac0698a4ee3df0d26e5cf726dd#5fba7927576064ac0698a4ee3df0d26e5cf726dd"
dependencies = [ dependencies = [
"async-utility", "async-utility",
"futures", "futures",
@@ -1014,7 +1014,7 @@ dependencies = [
[[package]] [[package]]
name = "collections" name = "collections"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#aacd80ee4a65d490cefee4b6413ece78c5611945" source = "git+https://github.com/zed-industries/zed#b7c6ffa6c2598dceb4bb4804538e636ed8e85700"
dependencies = [ dependencies = [
"indexmap", "indexmap",
"rustc-hash 2.1.0", "rustc-hash 2.1.0",
@@ -1090,6 +1090,7 @@ dependencies = [
"gpui", "gpui",
"itertools 0.13.0", "itertools 0.13.0",
"nostr-sdk", "nostr-sdk",
"registry",
"reqwest_client", "reqwest_client",
"rust-embed", "rust-embed",
"serde", "serde",
@@ -1263,9 +1264,9 @@ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
[[package]] [[package]]
name = "crunchy" name = "crunchy"
version = "0.2.2" version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" checksum = "43da5946c66ffcc7745f48db692ffbb10a83bfe0afd96235c5c2a4fb23994929"
[[package]] [[package]]
name = "crypto-common" name = "crypto-common"
@@ -1316,7 +1317,7 @@ dependencies = [
[[package]] [[package]]
name = "derive_refineable" name = "derive_refineable"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#aacd80ee4a65d490cefee4b6413ece78c5611945" source = "git+https://github.com/zed-industries/zed#b7c6ffa6c2598dceb4bb4804538e636ed8e85700"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -1518,9 +1519,9 @@ dependencies = [
[[package]] [[package]]
name = "etagere" name = "etagere"
version = "0.2.14" version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c732752b4ea11b36052d417d444d1474e948639fb02ff970efd7f18c180ca7f7" checksum = "fc89bf99e5dc15954a60f707c1e09d7540e5cd9af85fa75caa0b510bc08c5342"
dependencies = [ dependencies = [
"euclid", "euclid",
"svg_fmt", "svg_fmt",
@@ -2011,7 +2012,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui" name = "gpui"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#aacd80ee4a65d490cefee4b6413ece78c5611945" source = "git+https://github.com/zed-industries/zed#b7c6ffa6c2598dceb4bb4804538e636ed8e85700"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"as-raw-xcb-connection", "as-raw-xcb-connection",
@@ -2096,7 +2097,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui_macros" name = "gpui_macros"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#aacd80ee4a65d490cefee4b6413ece78c5611945" source = "git+https://github.com/zed-industries/zed#b7c6ffa6c2598dceb4bb4804538e636ed8e85700"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -2301,7 +2302,7 @@ dependencies = [
[[package]] [[package]]
name = "http_client" name = "http_client"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#aacd80ee4a65d490cefee4b6413ece78c5611945" source = "git+https://github.com/zed-industries/zed#b7c6ffa6c2598dceb4bb4804538e636ed8e85700"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bytes", "bytes",
@@ -2911,7 +2912,7 @@ dependencies = [
[[package]] [[package]]
name = "media" name = "media"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#aacd80ee4a65d490cefee4b6413ece78c5611945" source = "git+https://github.com/zed-industries/zed#b7c6ffa6c2598dceb4bb4804538e636ed8e85700"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bindgen", "bindgen",
@@ -2948,9 +2949,9 @@ dependencies = [
[[package]] [[package]]
name = "metal" name = "metal"
version = "0.30.0" version = "0.31.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3572083504c43e14aec05447f8a3d57cce0f66d7a3c1b9058572eca4d70ab9" checksum = "f569fb946490b5743ad69813cb19629130ce9374034abe31614a36402d18f99e"
dependencies = [ dependencies = [
"bitflags 2.8.0", "bitflags 2.8.0",
"block", "block",
@@ -3090,7 +3091,7 @@ checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
[[package]] [[package]]
name = "nostr" name = "nostr"
version = "0.38.0" version = "0.38.0"
source = "git+https://github.com/rust-nostr/nostr#d030b776f521fc2bb032f9490bab89e3bfbb5108" source = "git+https://github.com/rust-nostr/nostr#1470b8b00437e586fb86035484f942d6202db83a"
dependencies = [ dependencies = [
"aes", "aes",
"base64", "base64",
@@ -3118,7 +3119,7 @@ dependencies = [
[[package]] [[package]]
name = "nostr-database" name = "nostr-database"
version = "0.38.0" version = "0.38.0"
source = "git+https://github.com/rust-nostr/nostr#d030b776f521fc2bb032f9490bab89e3bfbb5108" source = "git+https://github.com/rust-nostr/nostr#1470b8b00437e586fb86035484f942d6202db83a"
dependencies = [ dependencies = [
"flatbuffers", "flatbuffers",
"nostr", "nostr",
@@ -3128,19 +3129,18 @@ dependencies = [
[[package]] [[package]]
name = "nostr-lmdb" name = "nostr-lmdb"
version = "0.38.0" version = "0.38.0"
source = "git+https://github.com/rust-nostr/nostr#d030b776f521fc2bb032f9490bab89e3bfbb5108" source = "git+https://github.com/rust-nostr/nostr#1470b8b00437e586fb86035484f942d6202db83a"
dependencies = [ dependencies = [
"async-utility", "async-utility",
"heed", "heed",
"nostr", "nostr",
"nostr-database", "nostr-database",
"tokio",
] ]
[[package]] [[package]]
name = "nostr-relay-pool" name = "nostr-relay-pool"
version = "0.38.0" version = "0.38.0"
source = "git+https://github.com/rust-nostr/nostr#d030b776f521fc2bb032f9490bab89e3bfbb5108" source = "git+https://github.com/rust-nostr/nostr#1470b8b00437e586fb86035484f942d6202db83a"
dependencies = [ dependencies = [
"async-utility", "async-utility",
"async-wsocket", "async-wsocket",
@@ -3156,7 +3156,7 @@ dependencies = [
[[package]] [[package]]
name = "nostr-sdk" name = "nostr-sdk"
version = "0.38.0" version = "0.38.0"
source = "git+https://github.com/rust-nostr/nostr#d030b776f521fc2bb032f9490bab89e3bfbb5108" source = "git+https://github.com/rust-nostr/nostr#1470b8b00437e586fb86035484f942d6202db83a"
dependencies = [ dependencies = [
"async-utility", "async-utility",
"nostr", "nostr",
@@ -3392,9 +3392,9 @@ dependencies = [
[[package]] [[package]]
name = "objc2-encode" name = "objc2-encode"
version = "4.0.3" version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7891e71393cd1f227313c9379a26a584ff3d7e6e7159e988851f0934c993f0f8" checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]] [[package]]
name = "objc2-foundation" name = "objc2-foundation"
@@ -3566,9 +3566,9 @@ dependencies = [
[[package]] [[package]]
name = "openssl-probe" name = "openssl-probe"
version = "0.1.5" version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e"
[[package]] [[package]]
name = "option-ext" name = "option-ext"
@@ -4163,7 +4163,7 @@ dependencies = [
[[package]] [[package]]
name = "refineable" name = "refineable"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#aacd80ee4a65d490cefee4b6413ece78c5611945" source = "git+https://github.com/zed-industries/zed#b7c6ffa6c2598dceb4bb4804538e636ed8e85700"
dependencies = [ dependencies = [
"derive_refineable", "derive_refineable",
] ]
@@ -4197,6 +4197,18 @@ version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
[[package]]
name = "registry"
version = "0.1.0"
dependencies = [
"anyhow",
"common",
"gpui",
"itertools 0.13.0",
"nostr-sdk",
"state",
]
[[package]] [[package]]
name = "reqwest" name = "reqwest"
version = "0.12.8" version = "0.12.8"
@@ -4292,7 +4304,7 @@ dependencies = [
[[package]] [[package]]
name = "reqwest_client" name = "reqwest_client"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#aacd80ee4a65d490cefee4b6413ece78c5611945" source = "git+https://github.com/zed-industries/zed#b7c6ffa6c2598dceb4bb4804538e636ed8e85700"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bytes", "bytes",
@@ -4413,9 +4425,9 @@ dependencies = [
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "0.38.43" version = "0.38.44"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a78891ee6bf2340288408954ac787aa063d8e8817e9f53abb37c695c6d834ef6" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
dependencies = [ dependencies = [
"bitflags 2.8.0", "bitflags 2.8.0",
"errno", "errno",
@@ -4642,7 +4654,7 @@ checksum = "c2fdfc24bc566f839a2da4c4295b82db7d25a24253867d5c64355abb5799bdbe"
[[package]] [[package]]
name = "semantic_version" name = "semantic_version"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#aacd80ee4a65d490cefee4b6413ece78c5611945" source = "git+https://github.com/zed-industries/zed#b7c6ffa6c2598dceb4bb4804538e636ed8e85700"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"serde", "serde",
@@ -4967,7 +4979,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]] [[package]]
name = "sum_tree" name = "sum_tree"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#aacd80ee4a65d490cefee4b6413ece78c5611945" source = "git+https://github.com/zed-industries/zed#b7c6ffa6c2598dceb4bb4804538e636ed8e85700"
dependencies = [ dependencies = [
"arrayvec", "arrayvec",
"log", "log",
@@ -5417,9 +5429,9 @@ dependencies = [
[[package]] [[package]]
name = "tokio-tungstenite" name = "tokio-tungstenite"
version = "0.24.0" version = "0.26.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9" checksum = "be4bf6fecd69fcdede0ec680aaf474cdab988f9de6bc73d3758f0160e3b7025a"
dependencies = [ dependencies = [
"futures-util", "futures-util",
"log", "log",
@@ -5576,9 +5588,9 @@ checksum = "2c591d83f69777866b9126b24c6dd9a18351f177e49d625920d19f989fd31cf8"
[[package]] [[package]]
name = "tungstenite" name = "tungstenite"
version = "0.24.0" version = "0.26.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a" checksum = "413083a99c579593656008130e29255e54dcaae495be556cc26888f211648c24"
dependencies = [ dependencies = [
"byteorder", "byteorder",
"bytes", "bytes",
@@ -5590,7 +5602,7 @@ dependencies = [
"rustls", "rustls",
"rustls-pki-types", "rustls-pki-types",
"sha1", "sha1",
"thiserror 1.0.69", "thiserror 2.0.11",
"utf-8", "utf-8",
] ]
@@ -5663,9 +5675,9 @@ checksum = "1df77b101bcc4ea3d78dafc5ad7e4f58ceffe0b2b16bf446aeb50b6cb4157656"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.14" version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" checksum = "11cd88e12b17c6494200a9c1b683a04fcac9573ed74cd1b62aeb2727c5592243"
[[package]] [[package]]
name = "unicode-linebreak" name = "unicode-linebreak"
@@ -5789,7 +5801,7 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]] [[package]]
name = "util" name = "util"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#aacd80ee4a65d490cefee4b6413ece78c5611945" source = "git+https://github.com/zed-industries/zed#b7c6ffa6c2598dceb4bb4804538e636ed8e85700"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-fs", "async-fs",
@@ -5814,9 +5826,9 @@ dependencies = [
[[package]] [[package]]
name = "uuid" name = "uuid"
version = "1.12.0" version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "744018581f9a3454a9e15beb8a33b017183f1e7c0cd170232a2d1453b23a51c4" checksum = "b3758f5e68192bb96cc8f9b7e2c2cfdabb435499a28499a42f8f984092adad4b"
dependencies = [ dependencies = [
"getrandom", "getrandom",
"serde", "serde",
@@ -6624,9 +6636,9 @@ dependencies = [
[[package]] [[package]]
name = "zbus" name = "zbus"
version = "5.3.0" version = "5.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "192a0d989036cd60a1e91a54c9851fb9ad5bd96125d41803eed79d2e2ef74bd7" checksum = "2494e4b3f44d8363eef79a8a75fc0649efb710eef65a66b5e688a5eb4afe678a"
dependencies = [ dependencies = [
"async-broadcast", "async-broadcast",
"async-executor", "async-executor",
@@ -6653,7 +6665,7 @@ dependencies = [
"windows-sys 0.59.0", "windows-sys 0.59.0",
"winnow", "winnow",
"xdg-home", "xdg-home",
"zbus_macros 5.3.0", "zbus_macros 5.3.1",
"zbus_names 4.1.1", "zbus_names 4.1.1",
"zvariant 5.2.0", "zvariant 5.2.0",
] ]
@@ -6673,9 +6685,9 @@ dependencies = [
[[package]] [[package]]
name = "zbus_macros" name = "zbus_macros"
version = "5.3.0" version = "5.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3685b5c81fce630efc3e143a4ded235b107f1b1cdf186c3f115529e5e5ae4265" checksum = "445efc01929302aee95e2b25bbb62a301ea8a6369466e4278e58e7d1dfb23631"
dependencies = [ dependencies = [
"proc-macro-crate", "proc-macro-crate",
"proc-macro2", "proc-macro2",

View File

@@ -12,6 +12,7 @@ path = "src/main.rs"
ui = { path = "../ui" } ui = { path = "../ui" }
common = { path = "../common" } common = { path = "../common" }
state = { path = "../state" } state = { path = "../state" }
registry = { path = "../registry" }
gpui.workspace = true gpui.workspace = true
reqwest_client.workspace = true reqwest_client.workspace = true

View File

@@ -10,8 +10,8 @@ use gpui::{
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
use gpui::{WindowBackgroundAppearance, WindowDecorations}; use gpui::{WindowBackgroundAppearance, WindowDecorations};
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use registry::{app::AppRegistry, chat::ChatRegistry, contact::Contact};
use state::{get_client, initialize_client}; use state::{get_client, initialize_client};
use states::{app::AppRegistry, chat::ChatRegistry};
use std::{collections::HashSet, str::FromStr, sync::Arc, time::Duration}; use std::{collections::HashSet, str::FromStr, sync::Arc, time::Duration};
use tokio::{ use tokio::{
sync::{mpsc, Mutex}, sync::{mpsc, Mutex},
@@ -21,7 +21,6 @@ use ui::Root;
use views::app::AppView; use views::app::AppView;
mod asset; mod asset;
mod states;
mod views; mod views;
actions!(main_menu, [Quit]); actions!(main_menu, [Quit]);
@@ -188,6 +187,7 @@ async fn main() {
// Set quit action // Set quit action
cx.on_action(quit); cx.on_action(quit);
// Spawn a thread to handle Nostr events
cx.spawn(|async_cx| async move { cx.spawn(|async_cx| async move {
let (tx, rx) = smol::channel::unbounded::<Signal>(); let (tx, rx) = smol::channel::unbounded::<Signal>();
@@ -219,25 +219,40 @@ async fn main() {
}) })
.detach(); .detach();
// Spawn a thread to update Nostr signer
cx.spawn(|async_cx| { cx.spawn(|async_cx| {
let task = cx.read_credentials(KEYRING_SERVICE); let task = cx.read_credentials(KEYRING_SERVICE);
async move { async move {
if let Ok(Some((npub, secret))) = task.await { if let Ok(Some((npub, secret))) = task.await {
let public_key = PublicKey::from_bech32(&npub).expect("Something wrong."); let public_key =
let hex = String::from_utf8(secret).expect("Something wrong."); PublicKey::from_bech32(&npub).expect("Public Key isn't valid.");
let keys = Keys::parse(&hex).expect("Something wrong.");
let query: anyhow::Result<Metadata, anyhow::Error> = async_cx
.background_executor()
.spawn(async move {
let hex = String::from_utf8(secret)?;
let keys = Keys::parse(&hex)?;
// Update signer // Update signer
async_cx _ = client.set_signer(keys).await;
.background_executor()
.spawn(async move { client.set_signer(keys).await })
.detach();
// Update global state // 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| { _ = async_cx.update_global::<AppRegistry, _>(|state, cx| {
state.set_user(public_key, cx); state.set_user(Contact::new(public_key, metadata), cx);
}); });
}
} else { } else {
_ = async_cx.update_global::<AppRegistry, _>(|state, _| { _ = async_cx.update_global::<AppRegistry, _>(|state, _| {
state.is_loading = false; state.is_loading = false;

View File

@@ -1,2 +0,0 @@
pub mod app;
pub mod chat;

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::{ use super::{chat::ChatPanel, onboarding::Onboarding, sidebar::Sidebar, welcome::WelcomePanel};
account::Account, chat::ChatPanel, onboarding::Onboarding, sidebar::Sidebar,
welcome::WelcomePanel,
};
use crate::states::{app::AppRegistry, chat::ChatRegistry};
use gpui::{ use gpui::{
div, impl_internal_actions, px, svg, Axis, Context, Edges, InteractiveElement, IntoElement, actions, div, img, impl_internal_actions, px, svg, Axis, Edges, InteractiveElement,
Model, ParentElement, Render, Styled, View, ViewContext, VisualContext, WeakView, IntoElement, ObjectFit, ParentElement, Render, Styled, StyledImage, View, ViewContext,
WindowContext, VisualContext, WeakView, WindowContext,
}; };
use registry::{app::AppRegistry, chat::ChatRegistry, contact::Contact};
use serde::Deserialize; use serde::Deserialize;
use std::sync::Arc; use std::sync::Arc;
use ui::{ use ui::{
button::{Button, ButtonVariants},
dock_area::{dock::DockPlacement, DockArea, DockItem}, dock_area::{dock::DockPlacement, DockArea, DockItem},
notification::NotificationType, notification::NotificationType,
theme::{scale::ColorScaleStep, ActiveTheme, Theme}, popup_menu::PopupMenuExt,
ContextModal, Root, TitleBar, prelude::FluentBuilder,
theme::{scale::ColorScaleStep, ActiveTheme},
ContextModal, Icon, IconName, Root, Sizable, TitleBar,
}; };
#[derive(Clone, PartialEq, Eq, Deserialize)] #[derive(Clone, PartialEq, Eq, Deserialize)]
@@ -28,7 +28,10 @@ pub struct AddPanel {
pub position: DockPlacement, pub position: DockPlacement,
} }
// Dock actions
impl_internal_actions!(dock, [AddPanel]); impl_internal_actions!(dock, [AddPanel]);
// Account actions
actions!(account, [OpenProfile, OpenContacts, OpenSettings, Logout]);
pub struct DockAreaTab { pub struct DockAreaTab {
id: &'static str, id: &'static str,
@@ -41,98 +44,31 @@ pub const DOCK_AREA: DockAreaTab = DockAreaTab {
}; };
pub struct AppView { pub struct AppView {
account: Model<Option<View<Account>>>,
onboarding: View<Onboarding>, onboarding: View<Onboarding>,
dock: View<DockArea>, dock: View<DockArea>,
} }
impl AppView { impl AppView {
pub fn new(cx: &mut ViewContext<'_, Self>) -> 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); let onboarding = cx.new_view(Onboarding::new);
// Dock
let dock = cx.new_view(|cx| DockArea::new(DOCK_AREA.id, Some(DOCK_AREA.version), cx)); let dock = cx.new_view(|cx| DockArea::new(DOCK_AREA.id, Some(DOCK_AREA.version), cx));
// Get current user from app state // 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() { if let Some(user) = weak_user.upgrade() {
cx.observe(&current_user, move |view, model, cx| { cx.observe(&user, move |view, this, cx| {
if let Some(public_key) = model.read(cx).clone().as_ref() { if this.read(cx).is_some() {
Self::init_layout(view.dock.downgrade(), cx); Self::render_dock(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();
});
} }
}) })
.detach(); .detach();
} }
AppView { AppView { onboarding, dock }
account,
onboarding,
dock,
}
} }
fn init_layout(dock_area: WeakView<DockArea>, cx: &mut WindowContext) { fn on_panel_action(&mut self, action: &AddPanel, cx: &mut ViewContext<Self>) {
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>) {
match &action.panel { match &action.panel {
PanelKind::Room(id) => { PanelKind::Room(id) => {
if let Some(weak_room) = cx.global::<ChatRegistry>().room(id, cx) { if let Some(weak_room) = cx.global::<ChatRegistry>().room(id, cx) {
@@ -152,17 +88,77 @@ 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 { impl Render for AppView {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement { fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
let modal_layer = Root::render_modal_layer(cx); let modal_layer = Root::render_modal_layer(cx);
let notification_layer = Root::render_notification_layer(cx); let notification_layer = Root::render_notification_layer(cx);
let state = cx.global::<AppRegistry>();
let mut content = div().size_full().flex().flex_col(); div()
.size_full()
if cx.global::<AppRegistry>().is_loading { .flex()
content = content.child(div()).child( .flex_col()
// Main
.map(|this| {
if state.is_loading {
this
// Placeholder
.child(div())
.child(
div().flex_1().flex().items_center().justify_center().child( div().flex_1().flex().items_center().justify_center().child(
svg() svg()
.path("brand/coop.svg") .path("brand/coop.svg")
@@ -170,9 +166,8 @@ impl Render for AppView {
.text_color(cx.theme().base.step(cx, ColorScaleStep::THREE)), .text_color(cx.theme().base.step(cx, ColorScaleStep::THREE)),
), ),
) )
} else if let Some(account) = self.account.read(cx).as_ref() { } else if let Some(contact) = state.current_user(cx) {
content = content this.child(
.child(
TitleBar::new() TitleBar::new()
// Left side // Left side
.child(div()) .child(div())
@@ -184,21 +179,18 @@ impl Render for AppView {
.justify_end() .justify_end()
.gap_1() .gap_1()
.px_2() .px_2()
.child(account.clone()), .child(self.render_account(contact)),
), ),
) )
.child(self.dock.clone()) .child(self.dock.clone())
.on_action(cx.listener(Self::on_action_add_panel)) .on_action(cx.listener(Self::on_panel_action))
} else { } else {
content = content this.child(TitleBar::new()).child(self.onboarding.clone())
.child(TitleBar::new())
.child(self.onboarding.clone())
} }
})
div() // Notification
.size_full()
.child(content)
.child(div().absolute().top_8().children(notification_layer)) .child(div().absolute().top_8().children(notification_layer))
// Modal
.children(modal_layer) .children(modal_layer)
} }
} }

View File

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

View File

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

View File

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

View File

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

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

View File

@@ -1,12 +1,10 @@
use crate::{ use crate::views::app::{AddPanel, PanelKind};
states::chat::ChatRegistry,
views::app::{AddPanel, PanelKind},
};
use common::utils::message_ago; use common::utils::message_ago;
use gpui::{ use gpui::{
div, img, percentage, prelude::FluentBuilder, px, InteractiveElement, IntoElement, div, img, percentage, prelude::FluentBuilder, px, InteractiveElement, IntoElement,
ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, ViewContext, ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, ViewContext,
}; };
use registry::chat::ChatRegistry;
use ui::{ use ui::{
dock_area::dock::DockPlacement, dock_area::dock::DockPlacement,
skeleton::Skeleton, 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 compose::Compose;
use gpui::{ use gpui::{
div, px, AnyElement, AppContext, BorrowAppContext, Entity, EntityId, EventEmitter, FocusHandle, div, px, AnyElement, AppContext, BorrowAppContext, Entity, EntityId, EventEmitter, FocusHandle,
FocusableView, InteractiveElement, IntoElement, ParentElement, Render, SharedString, FocusableView, InteractiveElement, IntoElement, ParentElement, Render, SharedString,
StatefulInteractiveElement, Styled, View, ViewContext, VisualContext, WindowContext, StatefulInteractiveElement, Styled, View, ViewContext, VisualContext, WindowContext,
}; };
use registry::chat::ChatRegistry;
use ui::{ use ui::{
button::{Button, ButtonRounded, ButtonVariants}, button::{Button, ButtonRounded, ButtonVariants},
dock_area::{ dock_area::{

View File

@@ -0,0 +1,14 @@
[package]
name = "registry"
version = "0.1.0"
edition = "2021"
publish = false
[dependencies]
common = { path = "../common" }
state = { path = "../state" }
gpui.workspace = true
nostr-sdk.workspace = true
anyhow.workspace = true
itertools.workspace = true

View File

@@ -1,62 +1,30 @@
use crate::get_client;
use common::constants::{ALL_MESSAGES_SUB_ID, NEW_MESSAGE_SUB_ID}; use common::constants::{ALL_MESSAGES_SUB_ID, NEW_MESSAGE_SUB_ID};
use gpui::*; use gpui::{AppContext, Context, Global, Model, WeakModel, WindowContext};
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use state::get_client;
use std::time::Duration; use std::time::Duration;
use crate::contact::Contact;
pub struct AppRegistry { pub struct AppRegistry {
user: Model<Option<PublicKey>>, user: Model<Option<Contact>>,
refreshs: Model<Vec<PublicKey>>, pub is_loading: bool,
pub(crate) is_loading: bool,
} }
impl Global for AppRegistry {} impl Global for AppRegistry {}
impl AppRegistry { impl AppRegistry {
pub fn set_global(cx: &mut AppContext) { pub fn set_global(cx: &mut AppContext) {
let refreshs = cx.new_model(|_| Vec::new()); let is_loading = true;
let user = cx.new_model(|_| None); let user: Model<Option<Contact>> = cx.new_model(|_| None);
let async_user = user.clone();
cx.set_global(Self { cx.observe(&user, |this, cx| {
user, if let Some(contact) = this.read(cx).as_ref() {
refreshs,
is_loading: true,
});
cx.observe(&async_user, |model, cx| {
if let Some(public_key) = model.read(cx).clone().as_ref() {
let client = get_client(); let client = get_client();
let public_key = *public_key; let public_key = contact.public_key();
let all_messages_sub_id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
let new_message_sub_id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
// Create a filter for getting all gift wrapped events send to current user
let all_messages = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
// Subscription options
let opts = SubscribeAutoCloseOptions::default()
.exit_policy(ReqExitPolicy::WaitDurationAfterEOSE(Duration::from_secs(5)));
// Create a filter for getting new message
let new_message = Filter::new()
.kind(Kind::GiftWrap)
.pubkey(public_key)
.limit(0);
cx.background_executor() cx.background_executor()
.spawn(async move { .spawn(async move {
// Subscribe for all messages
_ = client
.subscribe_with_id(all_messages_sub_id, vec![all_messages], Some(opts))
.await;
// Subscribe for new message
_ = client
.subscribe_with_id(new_message_sub_id, vec![new_message], None)
.await;
let subscription = Filter::new() let subscription = Filter::new()
.kind(Kind::Metadata) .kind(Kind::Metadata)
.author(public_key) .author(public_key)
@@ -72,27 +40,56 @@ impl AppRegistry {
// Get contact list // Get contact list
_ = client.sync(subscription, &SyncOptions::default()).await; _ = client.sync(subscription, &SyncOptions::default()).await;
let all_messages_sub_id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
let new_message_sub_id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
// Create a filter for getting all gift wrapped events send to current user
let all_messages = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
// Subscription options
let opts = SubscribeAutoCloseOptions::default().exit_policy(
ReqExitPolicy::WaitDurationAfterEOSE(Duration::from_secs(5)),
);
// Create a filter for getting new message
let new_message = Filter::new()
.kind(Kind::GiftWrap)
.pubkey(public_key)
.limit(0);
// Subscribe for all messages
_ = client
.subscribe_with_id(all_messages_sub_id, vec![all_messages], Some(opts))
.await;
// Subscribe for new message
_ = client
.subscribe_with_id(new_message_sub_id, vec![new_message], None)
.await;
}) })
.detach(); .detach();
} }
}) })
.detach(); .detach();
cx.set_global(Self { user, is_loading });
} }
pub fn set_user(&mut self, public_key: PublicKey, cx: &mut AppContext) { pub fn user(&self) -> WeakModel<Option<Contact>> {
self.user.update(cx, |model, cx| { self.user.downgrade()
*model = Some(public_key); }
pub fn set_user(&mut self, contact: Contact, cx: &mut AppContext) {
self.user.update(cx, |this, cx| {
*this = Some(contact);
cx.notify(); cx.notify();
}); });
self.is_loading = false; self.is_loading = false;
} }
pub fn current_user(&self) -> WeakModel<Option<PublicKey>> { pub fn current_user(&self, cx: &WindowContext) -> Option<Contact> {
self.user.downgrade() self.user.read(cx).clone()
}
pub fn refreshs(&self) -> WeakModel<Vec<PublicKey>> {
self.refreshs.downgrade()
} }
} }

View File

@@ -2,16 +2,14 @@ use common::utils::{compare, room_hash};
use gpui::{AppContext, Context, Global, Model, WeakModel}; use gpui::{AppContext, Context, Global, Model, WeakModel};
use itertools::Itertools; use itertools::Itertools;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use room::Room; use state::get_client;
use std::cmp::Reverse; use std::cmp::Reverse;
use crate::get_client; use crate::room::Room;
pub mod room;
pub struct Inbox { pub struct Inbox {
pub(crate) rooms: Vec<Model<Room>>, pub rooms: Vec<Model<Room>>,
pub(crate) is_loading: bool, pub is_loading: bool,
} }
impl Inbox { impl Inbox {
@@ -23,6 +21,12 @@ impl Inbox {
} }
} }
impl Default for Inbox {
fn default() -> Self {
Self::new()
}
}
pub struct ChatRegistry { pub struct ChatRegistry {
inbox: Model<Inbox>, inbox: Model<Inbox>,
} }
@@ -31,12 +35,11 @@ impl Global for ChatRegistry {}
impl ChatRegistry { impl ChatRegistry {
pub fn set_global(cx: &mut AppContext) { pub fn set_global(cx: &mut AppContext) {
let inbox = cx.new_model(|_| Inbox::new()); let inbox = cx.new_model(|_| Inbox::default());
cx.observe_new_models::<Room>(|this, cx| { cx.observe_new_models::<Room>(|this, cx| {
// Get all pubkeys to load metadata // Get all pubkeys to load metadata
let mut pubkeys: Vec<PublicKey> = this.members.iter().map(|m| m.public_key()).collect(); let pubkeys = this.get_all_keys();
pubkeys.push(this.owner.public_key());
cx.spawn(|weak_model, mut async_cx| async move { cx.spawn(|weak_model, mut async_cx| async move {
let query: Result<Vec<(PublicKey, Metadata)>, Error> = async_cx let query: Result<Vec<(PublicKey, Metadata)>, Error> = async_cx

View File

@@ -0,0 +1,63 @@
use common::{constants::IMAGE_SERVICE, utils::shorted_public_key};
use nostr_sdk::prelude::*;
#[derive(Debug, Clone)]
pub struct Contact {
public_key: PublicKey,
metadata: Metadata,
}
impl PartialEq for Contact {
fn eq(&self, other: &Self) -> bool {
self.public_key() == other.public_key()
}
}
impl Contact {
pub fn new(public_key: PublicKey, metadata: Metadata) -> Self {
Self {
public_key,
metadata,
}
}
/// Get contact's public key
pub fn public_key(&self) -> PublicKey {
self.public_key
}
/// Set contact's metadata
pub fn metadata(&mut self, metadata: &Metadata) {
self.metadata = metadata.clone()
}
/// Get contact's avatar
pub fn avatar(&self) -> String {
if let Some(picture) = &self.metadata.picture {
format!(
"{}/?url={}&w=100&h=100&fit=cover&mask=circle&n=-1",
IMAGE_SERVICE, picture
)
} else {
"brand/avatar.png".into()
}
}
/// Get contact's name
/// Fallback to public key as shorted format
pub fn name(&self) -> String {
if let Some(display_name) = &self.metadata.display_name {
if !display_name.is_empty() {
return display_name.clone();
}
}
if let Some(name) = &self.metadata.name {
if !name.is_empty() {
return name.clone();
}
}
shorted_public_key(self.public_key)
}
}

View File

@@ -0,0 +1,4 @@
pub mod app;
pub mod chat;
pub mod contact;
pub mod room;

View File

@@ -1,72 +1,15 @@
use common::{ use common::utils::{compare, random_name, room_hash};
constants::IMAGE_SERVICE,
utils::{compare, random_name, room_hash, shorted_public_key},
};
use gpui::SharedString; use gpui::SharedString;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
#[derive(Debug, Clone)] use crate::contact::Contact;
pub struct Member {
public_key: PublicKey,
metadata: Metadata,
}
impl PartialEq for Member {
fn eq(&self, other: &Self) -> bool {
self.public_key() == other.public_key()
}
}
impl Member {
pub fn new(public_key: PublicKey, metadata: Metadata) -> Self {
Self {
public_key,
metadata,
}
}
pub fn public_key(&self) -> PublicKey {
self.public_key
}
pub fn avatar(&self) -> String {
if let Some(picture) = &self.metadata.picture {
format!(
"{}/?url={}&w=100&h=100&fit=cover&mask=circle&n=-1",
IMAGE_SERVICE, picture
)
} else {
"brand/avatar.png".into()
}
}
pub fn name(&self) -> String {
if let Some(display_name) = &self.metadata.display_name {
if !display_name.is_empty() {
return display_name.clone();
}
}
if let Some(name) = &self.metadata.name {
if !name.is_empty() {
return name.clone();
}
}
shorted_public_key(self.public_key)
}
pub fn update(&mut self, metadata: &Metadata) {
self.metadata = metadata.clone()
}
}
#[derive(Debug)] #[derive(Debug)]
pub struct Room { pub struct Room {
pub id: u64, pub id: u64,
pub title: Option<SharedString>, pub title: Option<SharedString>,
pub owner: Member, // Owner always match current user pub owner: Contact, // Owner always match current user
pub members: Vec<Member>, // Extract from event's tags pub members: Vec<Contact>, // Extract from event's tags
pub last_seen: Timestamp, pub last_seen: Timestamp,
pub is_group: bool, pub is_group: bool,
pub new_messages: Vec<Event>, // Hold all new messages pub new_messages: Vec<Event>, // Hold all new messages
@@ -87,8 +30,8 @@ impl PartialEq for Room {
impl Room { impl Room {
pub fn new( pub fn new(
id: u64, id: u64,
owner: Member, owner: Contact,
members: Vec<Member>, members: Vec<Contact>,
title: Option<SharedString>, title: Option<SharedString>,
last_seen: Timestamp, last_seen: Timestamp,
) -> Self { ) -> Self {
@@ -110,16 +53,17 @@ impl Room {
} }
} }
/// Convert nostr event to room
pub fn parse(event: &Event) -> Room { pub fn parse(event: &Event) -> Room {
let id = room_hash(&event.tags); let id = room_hash(&event.tags);
let last_seen = event.created_at; let last_seen = event.created_at;
let owner = Member::new(event.pubkey, Metadata::default()); let owner = Contact::new(event.pubkey, Metadata::default());
let members: Vec<Member> = event let members: Vec<Contact> = event
.tags .tags
.public_keys() .public_keys()
.copied() .copied()
.map(|public_key| Member::new(public_key, Metadata::default())) .map(|public_key| Contact::new(public_key, Metadata::default()))
.collect(); .collect();
let title = if let Some(tag) = event.tags.find(TagKind::Title) { let title = if let Some(tag) = event.tags.find(TagKind::Title) {
@@ -131,19 +75,21 @@ impl Room {
Self::new(id, owner, members, title, last_seen) Self::new(id, owner, members, title, last_seen)
} }
/// Set contact's metadata by public key
pub fn set_metadata(&mut self, public_key: PublicKey, metadata: Metadata) { pub fn set_metadata(&mut self, public_key: PublicKey, metadata: Metadata) {
if self.owner.public_key() == public_key { if self.owner.public_key() == public_key {
self.owner.update(&metadata); self.owner.metadata(&metadata);
} }
for member in self.members.iter_mut() { for member in self.members.iter_mut() {
if member.public_key() == public_key { if member.public_key() == public_key {
member.update(&metadata); member.metadata(&metadata);
} }
} }
} }
pub fn member(&self, public_key: &PublicKey) -> Option<Member> { /// Get room's member by public key
pub fn member(&self, public_key: &PublicKey) -> Option<Contact> {
if &self.owner.public_key() == public_key { if &self.owner.public_key() == public_key {
Some(self.owner.clone()) Some(self.owner.clone())
} else { } else {
@@ -154,6 +100,7 @@ impl Room {
} }
} }
/// Get room's display name
pub fn name(&self) -> String { pub fn name(&self) -> String {
if self.members.len() <= 2 { if self.members.len() <= 2 {
self.members self.members
@@ -174,6 +121,7 @@ impl Room {
} }
} }
/// Get all public keys from room's contacts
pub fn get_all_keys(&self) -> Vec<PublicKey> { pub fn get_all_keys(&self) -> Vec<PublicKey> {
let mut pubkeys: Vec<_> = self.members.iter().map(|m| m.public_key()).collect(); let mut pubkeys: Vec<_> = self.members.iter().map(|m| m.public_key()).collect();
pubkeys.push(self.owner.public_key()); pubkeys.push(self.owner.public_key());

View File

@@ -669,9 +669,8 @@ impl TabPanel {
self.active_panel() self.active_panel()
.map(|panel| { .map(|panel| {
div() v_flex()
.id("tab-content") .id("tab-content")
.group("")
.overflow_hidden() .overflow_hidden()
.flex_1() .flex_1()
.p_1() .p_1()

View File

@@ -1,7 +1,7 @@
use crate::{ use crate::{
modal::Modal, modal::Modal,
notification::{Notification, NotificationList}, notification::{Notification, NotificationList},
theme::{scale::ColorScaleStep, ActiveTheme}, theme::{scale::ColorScaleStep, ActiveTheme, Theme},
window_border, window_border,
}; };
use gpui::{ use gpui::{
@@ -162,6 +162,11 @@ struct ActiveModal {
impl Root { impl Root {
pub fn new(view: AnyView, cx: &mut ViewContext<Self>) -> Self { pub fn new(view: AnyView, cx: &mut ViewContext<Self>) -> Self {
cx.observe_window_appearance(|_, cx| {
Theme::sync_system_appearance(cx);
})
.detach();
Self { Self {
previous_focus_handle: None, previous_focus_handle: None,
active_modals: Vec::new(), active_modals: Vec::new(),