chore: improve performance (#42)
* use uniform list for rooms list * move profile cache to outside gpui context * update comment * refactor * refactor * . * . * add avatar component * . * refactor * .
This commit is contained in:
@@ -36,5 +36,4 @@ futures.workspace = true
|
||||
oneshot.workspace = true
|
||||
|
||||
webbrowser = "1.0.4"
|
||||
rustls = "0.23.23"
|
||||
tracing-subscriber = { version = "0.3.18", features = ["fmt"] }
|
||||
|
||||
@@ -2,14 +2,14 @@ use std::sync::Arc;
|
||||
|
||||
use account::Account;
|
||||
use anyhow::Error;
|
||||
use chats::ChatRegistry;
|
||||
use global::{
|
||||
constants::{DEFAULT_MODAL_WIDTH, DEFAULT_SIDEBAR_WIDTH, IMAGE_CACHE_LIMIT},
|
||||
constants::{DEFAULT_MODAL_WIDTH, DEFAULT_SIDEBAR_WIDTH},
|
||||
get_client,
|
||||
};
|
||||
use gpui::{
|
||||
div, image_cache, impl_internal_actions, prelude::FluentBuilder, px, App, AppContext, Axis,
|
||||
Context, Entity, InteractiveElement, IntoElement, ParentElement, Render, Styled, Subscription,
|
||||
Task, Window,
|
||||
div, impl_internal_actions, prelude::FluentBuilder, px, App, AppContext, Axis, Context, Entity,
|
||||
InteractiveElement, IntoElement, ParentElement, Render, Styled, Subscription, Task, Window,
|
||||
};
|
||||
use nostr_sdk::prelude::*;
|
||||
use serde::Deserialize;
|
||||
@@ -21,14 +21,13 @@ use ui::{
|
||||
ContextModal, IconName, Root, Sizable, TitleBar,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
lru_cache::cache_provider,
|
||||
views::{
|
||||
chat::{self, Chat},
|
||||
compose, login, new_account, onboarding, profile, relays, sidebar, welcome,
|
||||
},
|
||||
use crate::views::{
|
||||
chat::{self, Chat},
|
||||
compose, login, new_account, onboarding, profile, relays, sidebar, welcome,
|
||||
};
|
||||
|
||||
impl_internal_actions!(dock, [ToggleModal]);
|
||||
|
||||
pub fn init(window: &mut Window, cx: &mut App) -> Entity<ChatSpace> {
|
||||
ChatSpace::new(window, cx)
|
||||
}
|
||||
@@ -63,25 +62,11 @@ pub struct ToggleModal {
|
||||
pub modal: ModalKind,
|
||||
}
|
||||
|
||||
impl_internal_actions!(dock, [AddPanel, ToggleModal]);
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Deserialize)]
|
||||
pub struct AddPanel {
|
||||
panel: PanelKind,
|
||||
position: DockPlacement,
|
||||
}
|
||||
|
||||
impl AddPanel {
|
||||
pub fn new(panel: PanelKind, position: DockPlacement) -> Self {
|
||||
Self { panel, position }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ChatSpace {
|
||||
titlebar: bool,
|
||||
dock: Entity<DockArea>,
|
||||
#[allow(unused)]
|
||||
subscriptions: SmallVec<[Subscription; 2]>,
|
||||
subscriptions: SmallVec<[Subscription; 3]>,
|
||||
}
|
||||
|
||||
impl ChatSpace {
|
||||
@@ -97,6 +82,7 @@ impl ChatSpace {
|
||||
|
||||
cx.new(|cx| {
|
||||
let account = Account::global(cx);
|
||||
let chats = ChatRegistry::global(cx);
|
||||
let mut subscriptions = smallvec![];
|
||||
|
||||
subscriptions.push(cx.observe_in(
|
||||
@@ -111,6 +97,21 @@ impl ChatSpace {
|
||||
},
|
||||
));
|
||||
|
||||
subscriptions.push(cx.subscribe_in(
|
||||
&chats,
|
||||
window,
|
||||
|this, _state, event, window, cx| {
|
||||
if let Some(room) = event.0.upgrade() {
|
||||
this.dock.update(cx, |this, cx| {
|
||||
let panel = chat::init(room, window, cx);
|
||||
this.add_panel(panel, DockPlacement::Center, window, cx);
|
||||
});
|
||||
} else {
|
||||
window.push_notification("Failed to open room. Please retry later.", cx);
|
||||
}
|
||||
},
|
||||
));
|
||||
|
||||
subscriptions.push(cx.observe_new::<Chat>(|this, window, cx| {
|
||||
if let Some(window) = window {
|
||||
this.load_messages(window, cx);
|
||||
@@ -204,22 +205,6 @@ impl ChatSpace {
|
||||
})
|
||||
}
|
||||
|
||||
fn on_panel_action(&mut self, action: &AddPanel, window: &mut Window, cx: &mut Context<Self>) {
|
||||
match &action.panel {
|
||||
PanelKind::Room(id) => {
|
||||
// User must be logged in to open a room
|
||||
match chat::init(id, window, cx) {
|
||||
Ok(panel) => {
|
||||
self.dock.update(cx, |dock_area, cx| {
|
||||
dock_area.add_panel(panel, action.position, window, cx);
|
||||
});
|
||||
}
|
||||
Err(e) => window.push_notification(e.to_string(), cx),
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn on_modal_action(
|
||||
&mut self,
|
||||
action: &ToggleModal,
|
||||
@@ -294,69 +279,62 @@ impl Render for ChatSpace {
|
||||
.relative()
|
||||
.size_full()
|
||||
.child(
|
||||
image_cache(cache_provider("image-cache", IMAGE_CACHE_LIMIT))
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.size_full()
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.size_full()
|
||||
// Title Bar
|
||||
.when(self.titlebar, |this| {
|
||||
this.child(
|
||||
TitleBar::new()
|
||||
// Left side
|
||||
.child(div())
|
||||
// Right side
|
||||
// Title Bar
|
||||
.when(self.titlebar, |this| {
|
||||
this.child(
|
||||
TitleBar::new()
|
||||
// Left side
|
||||
.child(div())
|
||||
// Right side
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_end()
|
||||
.gap_2()
|
||||
.px_2()
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_end()
|
||||
.gap_2()
|
||||
.px_2()
|
||||
.child(
|
||||
Button::new("appearance")
|
||||
.xsmall()
|
||||
.ghost()
|
||||
.map(|this| {
|
||||
if cx.theme().mode.is_dark() {
|
||||
this.icon(IconName::Sun)
|
||||
} else {
|
||||
this.icon(IconName::Moon)
|
||||
}
|
||||
})
|
||||
.on_click(cx.listener(
|
||||
|_, _, window, cx| {
|
||||
if cx.theme().mode.is_dark() {
|
||||
Theme::change(
|
||||
ThemeMode::Light,
|
||||
Some(window),
|
||||
cx,
|
||||
);
|
||||
} else {
|
||||
Theme::change(
|
||||
ThemeMode::Dark,
|
||||
Some(window),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
},
|
||||
)),
|
||||
),
|
||||
Button::new("appearance")
|
||||
.xsmall()
|
||||
.ghost()
|
||||
.map(|this| {
|
||||
if cx.theme().mode.is_dark() {
|
||||
this.icon(IconName::Sun)
|
||||
} else {
|
||||
this.icon(IconName::Moon)
|
||||
}
|
||||
})
|
||||
.on_click(cx.listener(|_, _, window, cx| {
|
||||
if cx.theme().mode.is_dark() {
|
||||
Theme::change(
|
||||
ThemeMode::Light,
|
||||
Some(window),
|
||||
cx,
|
||||
);
|
||||
} else {
|
||||
Theme::change(
|
||||
ThemeMode::Dark,
|
||||
Some(window),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
})),
|
||||
),
|
||||
)
|
||||
})
|
||||
// Dock
|
||||
.child(self.dock.clone()),
|
||||
),
|
||||
),
|
||||
)
|
||||
})
|
||||
// Dock
|
||||
.child(self.dock.clone()),
|
||||
)
|
||||
// Notifications
|
||||
.child(div().absolute().top_8().children(notification_layer))
|
||||
// Modals
|
||||
.children(modal_layer)
|
||||
// Actions
|
||||
.on_action(cx.listener(Self::on_panel_action))
|
||||
.on_action(cx.listener(Self::on_modal_action))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use futures::FutureExt;
|
||||
use gpui::{
|
||||
hash, AnyImageCache, App, AppContext, Asset, AssetLogger, Context, ElementId, Entity,
|
||||
ImageAssetLoader, ImageCache, ImageCacheProvider, Window,
|
||||
};
|
||||
|
||||
pub fn cache_provider(id: impl Into<ElementId>, max_items: usize) -> LruCacheProvider {
|
||||
LruCacheProvider {
|
||||
id: id.into(),
|
||||
max_items,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LruCacheProvider {
|
||||
id: ElementId,
|
||||
max_items: usize,
|
||||
}
|
||||
|
||||
impl ImageCacheProvider for LruCacheProvider {
|
||||
fn provide(&mut self, window: &mut Window, cx: &mut App) -> AnyImageCache {
|
||||
window
|
||||
.with_global_id(self.id.clone(), |global_id, window| {
|
||||
window.with_element_state::<Entity<LruCache>, _>(global_id, |lru_cache, _window| {
|
||||
let mut lru_cache =
|
||||
lru_cache.unwrap_or_else(|| cx.new(|cx| LruCache::new(self.max_items, cx)));
|
||||
if lru_cache.read(cx).max_items != self.max_items {
|
||||
lru_cache = cx.new(|cx| LruCache::new(self.max_items, cx));
|
||||
}
|
||||
(lru_cache.clone(), lru_cache)
|
||||
})
|
||||
})
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
struct LruCache {
|
||||
max_items: usize,
|
||||
usages: Vec<u64>,
|
||||
cache: HashMap<u64, gpui::ImageCacheItem>,
|
||||
}
|
||||
|
||||
impl LruCache {
|
||||
fn new(max_items: usize, cx: &mut Context<Self>) -> Self {
|
||||
cx.on_release(|simple_cache, cx| {
|
||||
for (_, mut item) in std::mem::take(&mut simple_cache.cache) {
|
||||
if let Some(Ok(image)) = item.get() {
|
||||
cx.drop_image(image, None);
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
Self {
|
||||
max_items,
|
||||
usages: Vec::with_capacity(max_items),
|
||||
cache: HashMap::with_capacity(max_items),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageCache for LruCache {
|
||||
fn load(
|
||||
&mut self,
|
||||
resource: &gpui::Resource,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<Result<Arc<gpui::RenderImage>, gpui::ImageCacheError>> {
|
||||
assert_eq!(self.usages.len(), self.cache.len());
|
||||
assert!(self.cache.len() <= self.max_items);
|
||||
|
||||
let hash = hash(resource);
|
||||
|
||||
if let Some(item) = self.cache.get_mut(&hash) {
|
||||
let current_ix = self
|
||||
.usages
|
||||
.iter()
|
||||
.position(|item| *item == hash)
|
||||
.expect("cache and usages must stay in sync");
|
||||
self.usages.remove(current_ix);
|
||||
self.usages.insert(0, hash);
|
||||
|
||||
return item.get();
|
||||
}
|
||||
|
||||
let fut = AssetLogger::<ImageAssetLoader>::load(resource.clone(), cx);
|
||||
let task = cx.background_executor().spawn(fut).shared();
|
||||
if self.usages.len() == self.max_items {
|
||||
let oldest = self.usages.pop().unwrap();
|
||||
let mut image = self
|
||||
.cache
|
||||
.remove(&oldest)
|
||||
.expect("cache and usages must be in sync");
|
||||
if let Some(Ok(image)) = image.get() {
|
||||
cx.drop_image(image, Some(window));
|
||||
}
|
||||
}
|
||||
self.cache
|
||||
.insert(hash, gpui::ImageCacheItem::Loading(task.clone()));
|
||||
self.usages.insert(0, hash);
|
||||
|
||||
let entity = window.current_view();
|
||||
window
|
||||
.spawn(cx, {
|
||||
async move |cx| {
|
||||
_ = task.await;
|
||||
cx.on_next_frame(move |_, cx| {
|
||||
cx.notify(entity);
|
||||
});
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use global::{
|
||||
ALL_MESSAGES_SUB_ID, APP_ID, APP_PUBKEY, BOOTSTRAP_RELAYS, METADATA_BATCH_LIMIT,
|
||||
METADATA_BATCH_TIMEOUT, NEW_MESSAGE_SUB_ID, SEARCH_RELAYS,
|
||||
},
|
||||
get_client,
|
||||
get_client, init_global_state, profiles,
|
||||
};
|
||||
use gpui::{
|
||||
actions, px, size, App, AppContext, Application, Bounds, KeyBinding, Menu, MenuItem,
|
||||
@@ -21,9 +21,9 @@ use gpui::{point, SharedString, TitlebarOptions};
|
||||
#[cfg(target_os = "linux")]
|
||||
use gpui::{WindowBackgroundAppearance, WindowDecorations};
|
||||
use nostr_sdk::{
|
||||
nips::nip01::Coordinate, pool::prelude::ReqExitPolicy, Client, Event, EventBuilder, EventId,
|
||||
Filter, JsonUtil, Keys, Kind, Metadata, PublicKey, RelayMessage, RelayPoolNotification,
|
||||
SubscribeAutoCloseOptions, SubscriptionId, Tag,
|
||||
async_utility::task::spawn, nips::nip01::Coordinate, pool::prelude::ReqExitPolicy, Client,
|
||||
Event, EventBuilder, EventId, Filter, JsonUtil, Keys, Kind, Metadata, PublicKey, RelayMessage,
|
||||
RelayPoolNotification, SubscribeAutoCloseOptions, SubscriptionId, Tag,
|
||||
};
|
||||
use smol::Timer;
|
||||
use std::{collections::HashSet, mem, sync::Arc, time::Duration};
|
||||
@@ -32,7 +32,6 @@ use ui::Root;
|
||||
|
||||
pub(crate) mod asset;
|
||||
pub(crate) mod chatspace;
|
||||
pub(crate) mod lru_cache;
|
||||
pub(crate) mod views;
|
||||
|
||||
actions!(coop, [Quit]);
|
||||
@@ -41,8 +40,6 @@ actions!(coop, [Quit]);
|
||||
enum Signal {
|
||||
/// Receive event
|
||||
Event(Event),
|
||||
/// Receive metadata
|
||||
Metadata(Box<(PublicKey, Option<Metadata>)>),
|
||||
/// Receive eose
|
||||
Eose,
|
||||
/// Receive app updates
|
||||
@@ -50,205 +47,207 @@ enum Signal {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Enable logging
|
||||
// Initialize logging
|
||||
tracing_subscriber::fmt::init();
|
||||
// Fix crash on startup
|
||||
_ = rustls::crypto::aws_lc_rs::default_provider().install_default();
|
||||
// Initialize global state
|
||||
init_global_state();
|
||||
|
||||
let (event_tx, event_rx) = smol::channel::bounded::<Signal>(2048);
|
||||
let (batch_tx, batch_rx) = smol::channel::bounded::<Vec<PublicKey>>(500);
|
||||
|
||||
// Initialize nostr client
|
||||
let client = get_client();
|
||||
let opts = SubscribeAutoCloseOptions::default().exit_policy(ReqExitPolicy::ExitOnEOSE);
|
||||
|
||||
// Spawn a task to establish relay connections
|
||||
// NOTE: Use `async_utility` instead of `smol-rs`
|
||||
spawn(async move {
|
||||
for relay in BOOTSTRAP_RELAYS.into_iter() {
|
||||
if let Err(e) = client.add_relay(relay).await {
|
||||
log::error!("Failed to add relay {}: {}", relay, e);
|
||||
}
|
||||
}
|
||||
|
||||
for relay in SEARCH_RELAYS.into_iter() {
|
||||
if let Err(e) = client.add_relay(relay).await {
|
||||
log::error!("Failed to add relay {}: {}", relay, e);
|
||||
}
|
||||
}
|
||||
|
||||
// Establish connection to bootstrap relays
|
||||
client.connect().await;
|
||||
|
||||
log::info!("Connected to bootstrap relays");
|
||||
log::info!("Subscribing to app updates...");
|
||||
|
||||
let coordinate = Coordinate {
|
||||
kind: Kind::Custom(32267),
|
||||
public_key: PublicKey::from_hex(APP_PUBKEY).expect("App Pubkey is invalid"),
|
||||
identifier: APP_ID.into(),
|
||||
};
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::ReleaseArtifactSet)
|
||||
.coordinate(&coordinate)
|
||||
.limit(1);
|
||||
|
||||
if let Err(e) = client
|
||||
.subscribe_to(BOOTSTRAP_RELAYS, filter, Some(opts))
|
||||
.await
|
||||
{
|
||||
log::error!("Failed to subscribe for app updates: {}", e);
|
||||
}
|
||||
});
|
||||
|
||||
// Spawn a task to handle metadata batching
|
||||
// NOTE: Use `async_utility` instead of `smol-rs`
|
||||
spawn(async move {
|
||||
let mut batch: HashSet<PublicKey> = HashSet::new();
|
||||
|
||||
loop {
|
||||
let mut timeout =
|
||||
Box::pin(Timer::after(Duration::from_millis(METADATA_BATCH_TIMEOUT)).fuse());
|
||||
|
||||
select! {
|
||||
pubkeys = batch_rx.recv().fuse() => {
|
||||
match pubkeys {
|
||||
Ok(keys) => {
|
||||
batch.extend(keys);
|
||||
if batch.len() >= METADATA_BATCH_LIMIT {
|
||||
sync_metadata(mem::take(&mut batch), client, opts).await;
|
||||
}
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
_ = timeout => {
|
||||
if !batch.is_empty() {
|
||||
sync_metadata(mem::take(&mut batch), client, opts).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Spawn a task to handle relay pool notification
|
||||
// NOTE: Use `async_utility` instead of `smol-rs`
|
||||
spawn(async move {
|
||||
let keys = Keys::generate();
|
||||
let all_id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
|
||||
let new_id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
|
||||
let mut notifications = client.notifications();
|
||||
|
||||
let mut processed_events: HashSet<EventId> = HashSet::new();
|
||||
|
||||
while let Ok(notification) = notifications.recv().await {
|
||||
if let RelayPoolNotification::Message { message, .. } = notification {
|
||||
match message {
|
||||
RelayMessage::Event {
|
||||
event,
|
||||
subscription_id,
|
||||
} => {
|
||||
if processed_events.contains(&event.id) {
|
||||
continue;
|
||||
}
|
||||
processed_events.insert(event.id);
|
||||
|
||||
match event.kind {
|
||||
Kind::GiftWrap => {
|
||||
let event = match get_unwrapped(event.id).await {
|
||||
Ok(event) => event,
|
||||
Err(_) => match client.unwrap_gift_wrap(&event).await {
|
||||
Ok(unwrap) => match unwrap.rumor.sign_with_keys(&keys) {
|
||||
Ok(unwrapped) => {
|
||||
set_unwrapped(event.id, &unwrapped, &keys)
|
||||
.await
|
||||
.ok();
|
||||
unwrapped
|
||||
}
|
||||
Err(_) => continue,
|
||||
},
|
||||
Err(_) => continue,
|
||||
},
|
||||
};
|
||||
|
||||
let mut pubkeys = vec![];
|
||||
pubkeys.extend(event.tags.public_keys());
|
||||
pubkeys.push(event.pubkey);
|
||||
|
||||
// Send all pubkeys to the batch to sync metadata
|
||||
batch_tx.send(pubkeys).await.ok();
|
||||
|
||||
// Save the event to the database, use for query directly.
|
||||
client.database().save_event(&event).await.ok();
|
||||
|
||||
// Send this event to the GPUI
|
||||
if new_id == *subscription_id {
|
||||
event_tx.send(Signal::Event(event)).await.ok();
|
||||
}
|
||||
}
|
||||
Kind::Metadata => {
|
||||
let metadata = Metadata::from_json(&event.content).ok();
|
||||
|
||||
profiles()
|
||||
.write()
|
||||
.await
|
||||
.entry(event.pubkey)
|
||||
.and_modify(|entry| {
|
||||
if entry.is_none() {
|
||||
*entry = metadata.clone();
|
||||
}
|
||||
})
|
||||
.or_insert_with(|| metadata);
|
||||
}
|
||||
Kind::ContactList => {
|
||||
if let Ok(signer) = client.signer().await {
|
||||
if let Ok(public_key) = signer.get_public_key().await {
|
||||
if public_key == event.pubkey {
|
||||
let pubkeys = event
|
||||
.tags
|
||||
.public_keys()
|
||||
.copied()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
batch_tx.send(pubkeys).await.ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::ReleaseArtifactSet => {
|
||||
let filter = Filter::new()
|
||||
.ids(event.tags.event_ids().copied())
|
||||
.kind(Kind::FileMetadata);
|
||||
|
||||
if let Err(e) = client
|
||||
.subscribe_to(BOOTSTRAP_RELAYS, filter, Some(opts))
|
||||
.await
|
||||
{
|
||||
log::error!("Failed to subscribe for file metadata: {}", e);
|
||||
} else {
|
||||
event_tx
|
||||
.send(Signal::AppUpdates(event.into_owned()))
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
RelayMessage::EndOfStoredEvents(subscription_id) => {
|
||||
if all_id == *subscription_id {
|
||||
event_tx.send(Signal::Eose).await.ok();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Initialize application
|
||||
let app = Application::new()
|
||||
.with_assets(Assets)
|
||||
.with_http_client(Arc::new(reqwest_client::ReqwestClient::new()));
|
||||
|
||||
// Connect to default relays
|
||||
app.background_executor()
|
||||
.spawn(async move {
|
||||
for relay in BOOTSTRAP_RELAYS.into_iter() {
|
||||
if let Err(e) = client.add_relay(relay).await {
|
||||
log::error!("Failed to add relay {}: {}", relay, e);
|
||||
}
|
||||
}
|
||||
|
||||
for relay in SEARCH_RELAYS.into_iter() {
|
||||
if let Err(e) = client.add_relay(relay).await {
|
||||
log::error!("Failed to add relay {}: {}", relay, e);
|
||||
}
|
||||
}
|
||||
|
||||
// Establish connection to bootstrap relays
|
||||
client.connect().await;
|
||||
|
||||
log::info!("Connected to bootstrap relays");
|
||||
log::info!("Subscribing to app updates...");
|
||||
|
||||
let coordinate = Coordinate {
|
||||
kind: Kind::Custom(32267),
|
||||
public_key: PublicKey::from_hex(APP_PUBKEY).expect("App Pubkey is invalid"),
|
||||
identifier: APP_ID.into(),
|
||||
};
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::ReleaseArtifactSet)
|
||||
.coordinate(&coordinate)
|
||||
.limit(1);
|
||||
|
||||
if let Err(e) = client
|
||||
.subscribe_to(BOOTSTRAP_RELAYS, filter, Some(opts))
|
||||
.await
|
||||
{
|
||||
log::error!("Failed to subscribe for app updates: {}", e);
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
// Handle batch metadata
|
||||
app.background_executor()
|
||||
.spawn(async move {
|
||||
let mut batch: HashSet<PublicKey> = HashSet::new();
|
||||
|
||||
loop {
|
||||
let mut timeout =
|
||||
Box::pin(Timer::after(Duration::from_millis(METADATA_BATCH_TIMEOUT)).fuse());
|
||||
|
||||
select! {
|
||||
pubkeys = batch_rx.recv().fuse() => {
|
||||
match pubkeys {
|
||||
Ok(keys) => {
|
||||
batch.extend(keys);
|
||||
if batch.len() >= METADATA_BATCH_LIMIT {
|
||||
sync_metadata(mem::take(&mut batch), client, opts).await;
|
||||
}
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
_ = timeout => {
|
||||
if !batch.is_empty() {
|
||||
sync_metadata(mem::take(&mut batch), client, opts).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
// Handle notifications
|
||||
app.background_executor()
|
||||
.spawn(async move {
|
||||
let keys = Keys::generate();
|
||||
let all_id = SubscriptionId::new(ALL_MESSAGES_SUB_ID);
|
||||
let new_id = SubscriptionId::new(NEW_MESSAGE_SUB_ID);
|
||||
let mut notifications = client.notifications();
|
||||
|
||||
let mut processed_events: HashSet<EventId> = HashSet::new();
|
||||
|
||||
while let Ok(notification) = notifications.recv().await {
|
||||
if let RelayPoolNotification::Message { message, .. } = notification {
|
||||
match message {
|
||||
RelayMessage::Event {
|
||||
event,
|
||||
subscription_id,
|
||||
} => {
|
||||
if processed_events.contains(&event.id) { continue }
|
||||
processed_events.insert(event.id);
|
||||
|
||||
match event.kind {
|
||||
Kind::GiftWrap => {
|
||||
let event = match get_unwrapped(event.id).await {
|
||||
Ok(event) => event,
|
||||
Err(_) => match client.unwrap_gift_wrap(&event).await {
|
||||
Ok(unwrap) => {
|
||||
match unwrap.rumor.sign_with_keys(&keys) {
|
||||
Ok(unwrapped) => {
|
||||
set_unwrapped(event.id, &unwrapped, &keys)
|
||||
.await
|
||||
.ok();
|
||||
unwrapped
|
||||
}
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
Err(_) => continue,
|
||||
},
|
||||
};
|
||||
|
||||
let mut pubkeys = vec![];
|
||||
pubkeys.extend(event.tags.public_keys());
|
||||
pubkeys.push(event.pubkey);
|
||||
|
||||
// Send all pubkeys to the batch to sync metadata
|
||||
batch_tx.send(pubkeys).await.ok();
|
||||
|
||||
// Save the event to the database, use for query directly.
|
||||
client.database().save_event(&event).await.ok();
|
||||
|
||||
// Send this event to the GPUI
|
||||
if new_id == *subscription_id {
|
||||
event_tx.send(Signal::Event(event)).await.ok();
|
||||
}
|
||||
}
|
||||
Kind::Metadata => {
|
||||
let metadata = Metadata::from_json(&event.content).ok();
|
||||
|
||||
event_tx
|
||||
.send(Signal::Metadata(Box::new((event.pubkey, metadata))))
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
Kind::ContactList => {
|
||||
if let Ok(signer) = client.signer().await {
|
||||
if let Ok(public_key) = signer.get_public_key().await {
|
||||
if public_key == event.pubkey {
|
||||
let pubkeys = event
|
||||
.tags
|
||||
.public_keys()
|
||||
.copied()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
batch_tx.send(pubkeys).await.ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::ReleaseArtifactSet => {
|
||||
let filter = Filter::new()
|
||||
.ids(event.tags.event_ids().copied())
|
||||
.kind(Kind::FileMetadata);
|
||||
|
||||
if let Err(e) = client
|
||||
.subscribe_to(BOOTSTRAP_RELAYS, filter, Some(opts))
|
||||
.await
|
||||
{
|
||||
log::error!("Failed to subscribe for file metadata: {}", e);
|
||||
} else {
|
||||
event_tx
|
||||
.send(Signal::AppUpdates(event.into_owned()))
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
RelayMessage::EndOfStoredEvents(subscription_id) => {
|
||||
if all_id == *subscription_id {
|
||||
event_tx.send(Signal::Eose).await.ok();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
app.run(move |cx| {
|
||||
// Bring the app to the foreground
|
||||
cx.activate(true);
|
||||
@@ -328,11 +327,6 @@ fn main() {
|
||||
this.event_to_message(event, window, cx);
|
||||
});
|
||||
}
|
||||
Signal::Metadata(data) => {
|
||||
chats.update(cx, |this, cx| {
|
||||
this.add_profile(data.0, data.1, cx);
|
||||
});
|
||||
}
|
||||
Signal::AppUpdates(event) => {
|
||||
auto_updater.update(cx, |this, cx| {
|
||||
this.update(event, cx);
|
||||
|
||||
@@ -1,20 +1,18 @@
|
||||
use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::Arc};
|
||||
|
||||
use anyhow::{anyhow, Error};
|
||||
use async_utility::task::spawn;
|
||||
use chats::{
|
||||
message::Message,
|
||||
room::{Room, SendError},
|
||||
ChatRegistry,
|
||||
};
|
||||
use common::{nip96_upload, profile::SharedProfile};
|
||||
use global::{constants::IMAGE_SERVICE, get_client};
|
||||
use common::{nip96_upload, profile::RenderProfile};
|
||||
use global::get_client;
|
||||
use gpui::{
|
||||
div, img, impl_internal_actions, list, prelude::FluentBuilder, px, red, relative, svg, white,
|
||||
AnyElement, App, AppContext, Context, Div, Element, Empty, Entity, EventEmitter, Flatten,
|
||||
FocusHandle, Focusable, InteractiveElement, IntoElement, ListAlignment, ListState, ObjectFit,
|
||||
ParentElement, PathPromptOptions, Render, SharedString, StatefulInteractiveElement, Styled,
|
||||
StyledImage, Subscription, Window,
|
||||
div, img, impl_internal_actions, list, prelude::FluentBuilder, px, red, relative, rems, svg,
|
||||
white, AnyElement, App, AppContext, Context, Div, Element, Empty, Entity, EventEmitter,
|
||||
Flatten, FocusHandle, Focusable, InteractiveElement, IntoElement, ListAlignment, ListState,
|
||||
ObjectFit, ParentElement, PathPromptOptions, Render, RetainAllImageCache, SharedString,
|
||||
StatefulInteractiveElement, Styled, StyledImage, Subscription, Window,
|
||||
};
|
||||
use itertools::Itertools;
|
||||
use nostr_sdk::prelude::*;
|
||||
@@ -23,6 +21,7 @@ use smallvec::{smallvec, SmallVec};
|
||||
use smol::fs;
|
||||
use theme::ActiveTheme;
|
||||
use ui::{
|
||||
avatar::Avatar,
|
||||
button::{Button, ButtonVariants},
|
||||
dock_area::panel::{Panel, PanelEvent},
|
||||
emoji_picker::EmojiPicker,
|
||||
@@ -40,12 +39,8 @@ pub struct ChangeSubject(pub String);
|
||||
|
||||
impl_internal_actions!(chat, [ChangeSubject]);
|
||||
|
||||
pub fn init(id: &u64, window: &mut Window, cx: &mut App) -> Result<Arc<Entity<Chat>>, Error> {
|
||||
if let Some(room) = ChatRegistry::global(cx).read(cx).room(id, cx) {
|
||||
Ok(Arc::new(Chat::new(id, room, window, cx)))
|
||||
} else {
|
||||
Err(anyhow!("Chat Room not found."))
|
||||
}
|
||||
pub fn init(room: Entity<Room>, window: &mut Window, cx: &mut App) -> Arc<Entity<Chat>> {
|
||||
Arc::new(Chat::new(room, window, cx))
|
||||
}
|
||||
|
||||
pub struct Chat {
|
||||
@@ -63,12 +58,13 @@ pub struct Chat {
|
||||
// Media Attachment
|
||||
attaches: Entity<Option<Vec<Url>>>,
|
||||
uploading: bool,
|
||||
image_cache: Entity<RetainAllImageCache>,
|
||||
#[allow(dead_code)]
|
||||
subscriptions: SmallVec<[Subscription; 2]>,
|
||||
}
|
||||
|
||||
impl Chat {
|
||||
pub fn new(id: &u64, room: Entity<Room>, window: &mut Window, cx: &mut App) -> Entity<Self> {
|
||||
pub fn new(room: Entity<Room>, window: &mut Window, cx: &mut App) -> Entity<Self> {
|
||||
let attaches = cx.new(|_| None);
|
||||
let replies_to = cx.new(|_| None);
|
||||
|
||||
@@ -144,9 +140,10 @@ impl Chat {
|
||||
});
|
||||
|
||||
Self {
|
||||
image_cache: RetainAllImageCache::new(cx),
|
||||
focus_handle: cx.focus_handle(),
|
||||
uploading: false,
|
||||
id: id.to_string().into(),
|
||||
id: room.read(cx).id.to_string().into(),
|
||||
text_data: HashMap::new(),
|
||||
room,
|
||||
messages,
|
||||
@@ -428,18 +425,15 @@ impl Chat {
|
||||
let path: SharedString = url.to_string().into();
|
||||
|
||||
div()
|
||||
.id(path.clone())
|
||||
.id("")
|
||||
.relative()
|
||||
.w_16()
|
||||
.child(
|
||||
img(format!(
|
||||
"{}/?url={}&w=128&h=128&fit=cover&n=-1",
|
||||
IMAGE_SERVICE, path
|
||||
))
|
||||
.size_16()
|
||||
.shadow_lg()
|
||||
.rounded(cx.theme().radius)
|
||||
.object_fit(ObjectFit::ScaleDown),
|
||||
img(path.clone())
|
||||
.size_16()
|
||||
.shadow_lg()
|
||||
.rounded(cx.theme().radius)
|
||||
.object_fit(ObjectFit::ScaleDown),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
@@ -481,7 +475,7 @@ impl Chat {
|
||||
.child(
|
||||
div()
|
||||
.text_color(cx.theme().text_accent)
|
||||
.child(message.author.as_ref().unwrap().shared_name()),
|
||||
.child(message.author.as_ref().unwrap().render_name()),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
@@ -565,7 +559,7 @@ impl Chat {
|
||||
div()
|
||||
.flex()
|
||||
.gap_3()
|
||||
.child(img(author.shared_avatar()).size_8().flex_shrink_0())
|
||||
.child(Avatar::new(author.render_avatar()).size(rems(2.)))
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
@@ -583,7 +577,7 @@ impl Chat {
|
||||
div()
|
||||
.font_semibold()
|
||||
.text_color(cx.theme().text)
|
||||
.child(author.shared_name()),
|
||||
.child(author.render_name()),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
@@ -621,7 +615,7 @@ impl Chat {
|
||||
.author
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.shared_name(),
|
||||
.render_name(),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
@@ -707,7 +701,7 @@ impl Panel for Chat {
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_1p5()
|
||||
.child(img(url).size_5().flex_shrink_0())
|
||||
.child(Avatar::new(url).size(rems(1.25)))
|
||||
.child(label)
|
||||
.into_any()
|
||||
})
|
||||
@@ -753,6 +747,7 @@ impl Focusable for Chat {
|
||||
impl Render for Chat {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
v_flex()
|
||||
.image_cache(self.image_cache.clone())
|
||||
.size_full()
|
||||
.child(list(self.list_state.clone()).flex_1())
|
||||
.child(
|
||||
@@ -845,7 +840,7 @@ fn message_errors(errors: Vec<SendError>, cx: &App) -> Div {
|
||||
.gap_1()
|
||||
.text_color(cx.theme().text_muted)
|
||||
.child("Send to:")
|
||||
.child(error.profile.shared_name()),
|
||||
.child(error.profile.render_name()),
|
||||
)
|
||||
.child(error.message)
|
||||
}))
|
||||
|
||||
@@ -4,8 +4,8 @@ use std::{
|
||||
};
|
||||
|
||||
use anyhow::Error;
|
||||
use chats::ChatRegistry;
|
||||
use common::profile::SharedProfile;
|
||||
use chats::{room::Room, ChatRegistry};
|
||||
use common::profile::RenderProfile;
|
||||
use global::get_client;
|
||||
use gpui::{
|
||||
div, img, impl_internal_actions, prelude::FluentBuilder, px, red, relative, uniform_list, App,
|
||||
@@ -20,13 +20,10 @@ use smol::Timer;
|
||||
use theme::ActiveTheme;
|
||||
use ui::{
|
||||
button::{Button, ButtonVariants},
|
||||
dock_area::dock::DockPlacement,
|
||||
input::{InputEvent, InputState, TextInput},
|
||||
ContextModal, Disableable, Icon, IconName, Sizable, StyledExt,
|
||||
};
|
||||
|
||||
use crate::chatspace::{AddPanel, PanelKind};
|
||||
|
||||
pub fn init(window: &mut Window, cx: &mut App) -> Entity<Compose> {
|
||||
cx.new(|cx| Compose::new(window, cx))
|
||||
}
|
||||
@@ -153,14 +150,13 @@ impl Compose {
|
||||
cx.spawn_in(window, async move |this, cx| match event.await {
|
||||
Ok(event) => {
|
||||
cx.update(|window, cx| {
|
||||
ChatRegistry::global(cx).update(cx, |chats, cx| {
|
||||
let id = chats.event_to_room(&event, window, cx);
|
||||
window.close_modal(cx);
|
||||
window.dispatch_action(
|
||||
Box::new(AddPanel::new(PanelKind::Room(id), DockPlacement::Center)),
|
||||
cx,
|
||||
);
|
||||
let room = cx.new(|_| Room::new(&event).kind(chats::room::RoomKind::Ongoing));
|
||||
|
||||
ChatRegistry::global(cx).update(cx, |this, cx| {
|
||||
this.push_room(room, cx);
|
||||
});
|
||||
|
||||
window.close_modal(cx);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
@@ -338,7 +334,7 @@ impl Render for Compose {
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_1()
|
||||
.child(div().pb_0p5().text_sm().font_semibold().child("Subject:"))
|
||||
.child(div().text_sm().font_semibold().child("Subject:"))
|
||||
.child(TextInput::new(&self.title_input).small().appearance(false)),
|
||||
),
|
||||
)
|
||||
@@ -415,11 +411,11 @@ impl Render for Compose {
|
||||
.gap_3()
|
||||
.text_sm()
|
||||
.child(
|
||||
img(item.shared_avatar())
|
||||
img(item.render_avatar())
|
||||
.size_7()
|
||||
.flex_shrink_0(),
|
||||
)
|
||||
.child(item.shared_name()),
|
||||
.child(item.render_name()),
|
||||
)
|
||||
.when(is_select, |this| {
|
||||
this.child(
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::str::FromStr;
|
||||
use account::Account;
|
||||
use async_utility::task::spawn;
|
||||
use common::nip96_upload;
|
||||
use global::{constants::IMAGE_SERVICE, get_client};
|
||||
use global::get_client;
|
||||
use gpui::{
|
||||
div, img, prelude::FluentBuilder, relative, AnyElement, App, AppContext, Context, Entity,
|
||||
EventEmitter, Flatten, FocusHandle, Focusable, IntoElement, ParentElement, PathPromptOptions,
|
||||
@@ -231,16 +231,18 @@ impl Render for NewAccount {
|
||||
.gap_2()
|
||||
.map(|this| {
|
||||
if self.avatar_input.read(cx).value().is_empty() {
|
||||
this.child(img("brand/avatar.png").size_10().flex_shrink_0())
|
||||
this.child(
|
||||
img("brand/avatar.png")
|
||||
.rounded_full()
|
||||
.size_10()
|
||||
.flex_shrink_0(),
|
||||
)
|
||||
} else {
|
||||
this.child(
|
||||
img(format!(
|
||||
"{}/?url={}&w=100&h=100&fit=cover&mask=circle&n=-1",
|
||||
IMAGE_SERVICE,
|
||||
self.avatar_input.read(cx).value()
|
||||
))
|
||||
.size_10()
|
||||
.flex_shrink_0(),
|
||||
img(self.avatar_input.read(cx).value().clone())
|
||||
.rounded_full()
|
||||
.size_10()
|
||||
.flex_shrink_0(),
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use async_utility::task::spawn;
|
||||
use common::nip96_upload;
|
||||
use global::{constants::IMAGE_SERVICE, get_client};
|
||||
use global::get_client;
|
||||
use gpui::{
|
||||
div, img, prelude::FluentBuilder, App, AppContext, Context, Entity, Flatten, IntoElement,
|
||||
ParentElement, PathPromptOptions, Render, Styled, Task, Window,
|
||||
@@ -243,15 +243,18 @@ impl Render for Profile {
|
||||
.map(|this| {
|
||||
let picture = self.avatar_input.read(cx).value();
|
||||
if picture.is_empty() {
|
||||
this.child(img("brand/avatar.png").size_10().flex_shrink_0())
|
||||
this.child(
|
||||
img("brand/avatar.png")
|
||||
.rounded_full()
|
||||
.size_10()
|
||||
.flex_shrink_0(),
|
||||
)
|
||||
} else {
|
||||
this.child(
|
||||
img(format!(
|
||||
"{}/?url={}&w=100&h=100&fit=cover&mask=circle&n=-1",
|
||||
IMAGE_SERVICE, picture
|
||||
))
|
||||
.size_10()
|
||||
.flex_shrink_0(),
|
||||
img(picture.clone())
|
||||
.rounded_full()
|
||||
.size_10()
|
||||
.flex_shrink_0(),
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
116
crates/coop/src/views/sidebar/element.rs
Normal file
116
crates/coop/src/views/sidebar/element.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::{
|
||||
div, img, prelude::FluentBuilder, rems, App, ClickEvent, Div, InteractiveElement, IntoElement,
|
||||
ParentElement as _, RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window,
|
||||
};
|
||||
use theme::ActiveTheme;
|
||||
use ui::{avatar::Avatar, StyledExt};
|
||||
|
||||
#[derive(IntoElement)]
|
||||
pub struct DisplayRoom {
|
||||
ix: usize,
|
||||
base: Div,
|
||||
img: Option<SharedString>,
|
||||
label: Option<SharedString>,
|
||||
description: Option<SharedString>,
|
||||
#[allow(clippy::type_complexity)]
|
||||
handler: Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>,
|
||||
}
|
||||
|
||||
impl DisplayRoom {
|
||||
pub fn new(ix: usize) -> Self {
|
||||
Self {
|
||||
ix,
|
||||
base: div().h_9().w_full().px_1p5(),
|
||||
img: None,
|
||||
label: None,
|
||||
description: None,
|
||||
handler: Rc::new(|_, _, _| {}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
|
||||
self.label = Some(label.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
|
||||
self.description = Some(description.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn img(mut self, img: impl Into<SharedString>) -> Self {
|
||||
self.img = Some(img.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn on_click(
|
||||
mut self,
|
||||
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
|
||||
) -> Self {
|
||||
self.handler = Rc::new(handler);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for DisplayRoom {
|
||||
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let handler = self.handler.clone();
|
||||
|
||||
self.base
|
||||
.id(self.ix)
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.text_sm()
|
||||
.rounded(cx.theme().radius)
|
||||
.child(
|
||||
div()
|
||||
.flex_shrink_0()
|
||||
.size_6()
|
||||
.rounded_full()
|
||||
.overflow_hidden()
|
||||
.map(|this| {
|
||||
if let Some(path) = self.img {
|
||||
this.child(Avatar::new(path).size(rems(1.5)))
|
||||
} else {
|
||||
this.child(
|
||||
img("brand/avatar.png")
|
||||
.rounded_full()
|
||||
.size_6()
|
||||
.into_any_element(),
|
||||
)
|
||||
}
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.when_some(self.label, |this, label| {
|
||||
this.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.line_clamp(1)
|
||||
.text_ellipsis()
|
||||
.font_medium()
|
||||
.child(label),
|
||||
)
|
||||
})
|
||||
.when_some(self.description, |this, description| {
|
||||
this.child(
|
||||
div()
|
||||
.flex_shrink_0()
|
||||
.text_xs()
|
||||
.text_color(cx.theme().text_placeholder)
|
||||
.child(description),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.hover(|this| this.bg(cx.theme().elevated_surface_background))
|
||||
.on_click(move |ev, window, cx| handler(ev, window, cx))
|
||||
}
|
||||
}
|
||||
@@ -1,329 +0,0 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::{
|
||||
div, percentage, prelude::FluentBuilder, App, ClickEvent, Div, Img, InteractiveElement,
|
||||
IntoElement, ParentElement as _, RenderOnce, SharedString, StatefulInteractiveElement, Styled,
|
||||
Window,
|
||||
};
|
||||
use theme::ActiveTheme;
|
||||
use ui::{tooltip::Tooltip, Collapsible, Icon, IconName, Sizable, StyledExt};
|
||||
|
||||
type Handler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
|
||||
|
||||
#[derive(IntoElement)]
|
||||
pub struct Parent {
|
||||
base: Div,
|
||||
icon: Option<Icon>,
|
||||
tooltip: Option<SharedString>,
|
||||
label: SharedString,
|
||||
items: Vec<Folder>,
|
||||
collapsed: bool,
|
||||
handler: Handler,
|
||||
}
|
||||
|
||||
impl Parent {
|
||||
pub fn new(label: impl Into<SharedString>) -> Self {
|
||||
Self {
|
||||
base: div().flex().flex_col().gap_2(),
|
||||
label: label.into(),
|
||||
icon: None,
|
||||
tooltip: None,
|
||||
items: Vec::new(),
|
||||
collapsed: false,
|
||||
handler: Rc::new(|_, _, _| {}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
|
||||
self.icon = Some(icon.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
|
||||
self.tooltip = Some(tooltip.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn collapsed(mut self, collapsed: bool) -> Self {
|
||||
self.collapsed = collapsed;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn child(mut self, child: impl Into<Folder>) -> Self {
|
||||
self.items.push(child.into());
|
||||
self
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Folder>>) -> Self {
|
||||
self.items = children.into_iter().map(Into::into).collect();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn on_click(
|
||||
mut self,
|
||||
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
|
||||
) -> Self {
|
||||
self.handler = Rc::new(handler);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Collapsible for Parent {
|
||||
fn is_collapsed(&self) -> bool {
|
||||
self.collapsed
|
||||
}
|
||||
|
||||
fn collapsed(mut self, collapsed: bool) -> Self {
|
||||
self.collapsed = collapsed;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for Parent {
|
||||
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let handler = self.handler.clone();
|
||||
|
||||
self.base
|
||||
.child(
|
||||
div()
|
||||
.id(self.label.clone())
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.px_2()
|
||||
.h_8()
|
||||
.rounded(cx.theme().radius)
|
||||
.text_sm()
|
||||
.text_color(cx.theme().text_muted)
|
||||
.font_medium()
|
||||
.child(
|
||||
Icon::new(IconName::CaretDown)
|
||||
.xsmall()
|
||||
.when(self.collapsed, |this| this.rotate(percentage(270. / 360.))),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.when_some(self.icon, |this, icon| this.child(icon.small()))
|
||||
.child(self.label.clone()),
|
||||
)
|
||||
.when_some(self.tooltip.clone(), |this, tooltip| {
|
||||
this.tooltip(move |window, cx| {
|
||||
Tooltip::new(tooltip.clone(), window, cx).into()
|
||||
})
|
||||
})
|
||||
.hover(|this| this.bg(cx.theme().elevated_surface_background))
|
||||
.on_click(move |ev, window, cx| handler(ev, window, cx)),
|
||||
)
|
||||
.when(!self.collapsed, |this| {
|
||||
this.child(div().flex().flex_col().gap_2().pl_3().children(self.items))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(IntoElement)]
|
||||
pub struct Folder {
|
||||
base: Div,
|
||||
icon: Option<Icon>,
|
||||
tooltip: Option<SharedString>,
|
||||
label: SharedString,
|
||||
items: Vec<FolderItem>,
|
||||
collapsed: bool,
|
||||
handler: Handler,
|
||||
}
|
||||
|
||||
impl Folder {
|
||||
pub fn new(label: impl Into<SharedString>) -> Self {
|
||||
Self {
|
||||
base: div().flex().flex_col().gap_2(),
|
||||
label: label.into(),
|
||||
icon: None,
|
||||
tooltip: None,
|
||||
items: Vec::new(),
|
||||
collapsed: false,
|
||||
handler: Rc::new(|_, _, _| {}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
|
||||
self.icon = Some(icon.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
|
||||
self.tooltip = Some(tooltip.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn collapsed(mut self, collapsed: bool) -> Self {
|
||||
self.collapsed = collapsed;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn children(mut self, children: impl IntoIterator<Item = impl Into<FolderItem>>) -> Self {
|
||||
self.items = children.into_iter().map(Into::into).collect();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn on_click(
|
||||
mut self,
|
||||
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
|
||||
) -> Self {
|
||||
self.handler = Rc::new(handler);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Collapsible for Folder {
|
||||
fn is_collapsed(&self) -> bool {
|
||||
self.collapsed
|
||||
}
|
||||
|
||||
fn collapsed(mut self, collapsed: bool) -> Self {
|
||||
self.collapsed = collapsed;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for Folder {
|
||||
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let handler = self.handler.clone();
|
||||
|
||||
self.base
|
||||
.child(
|
||||
div()
|
||||
.id(self.label.clone())
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.px_2()
|
||||
.h_8()
|
||||
.rounded(cx.theme().radius)
|
||||
.text_sm()
|
||||
.text_color(cx.theme().text_muted)
|
||||
.font_medium()
|
||||
.child(
|
||||
Icon::new(IconName::CaretDown)
|
||||
.xsmall()
|
||||
.when(self.collapsed, |this| this.rotate(percentage(270. / 360.))),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.when_some(self.icon, |this, icon| this.child(icon.small()))
|
||||
.child(self.label.clone()),
|
||||
)
|
||||
.when_some(self.tooltip.clone(), |this, tooltip| {
|
||||
this.tooltip(move |window, cx| {
|
||||
Tooltip::new(tooltip.clone(), window, cx).into()
|
||||
})
|
||||
})
|
||||
.hover(|this| this.bg(cx.theme().elevated_surface_background))
|
||||
.on_click(move |ev, window, cx| handler(ev, window, cx)),
|
||||
)
|
||||
.when(!self.collapsed, |this| {
|
||||
this.child(div().flex().flex_col().gap_1().pl_6().children(self.items))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(IntoElement)]
|
||||
pub struct FolderItem {
|
||||
ix: usize,
|
||||
base: Div,
|
||||
img: Option<Img>,
|
||||
label: Option<SharedString>,
|
||||
description: Option<SharedString>,
|
||||
handler: Handler,
|
||||
}
|
||||
|
||||
impl FolderItem {
|
||||
pub fn new(ix: usize) -> Self {
|
||||
Self {
|
||||
ix,
|
||||
base: div().h_8().w_full().px_2(),
|
||||
img: None,
|
||||
label: None,
|
||||
description: None,
|
||||
handler: Rc::new(|_, _, _| {}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
|
||||
self.label = Some(label.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
|
||||
self.description = Some(description.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn img(mut self, img: Img) -> Self {
|
||||
self.img = Some(img);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn on_click(
|
||||
mut self,
|
||||
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
|
||||
) -> Self {
|
||||
self.handler = Rc::new(handler);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for FolderItem {
|
||||
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let handler = self.handler.clone();
|
||||
|
||||
self.base
|
||||
.id(self.ix)
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.text_sm()
|
||||
.rounded(cx.theme().radius)
|
||||
.child(div().size_6().flex_none().map(|this| {
|
||||
if let Some(img) = self.img {
|
||||
this.child(img.size_6().flex_none())
|
||||
} else {
|
||||
this.child(
|
||||
div()
|
||||
.size_6()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.justify_center()
|
||||
.items_center()
|
||||
.rounded_full()
|
||||
.bg(cx.theme().element_background),
|
||||
)
|
||||
}
|
||||
}))
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.when_some(self.label, |this, label| {
|
||||
this.child(div().truncate().text_ellipsis().font_medium().child(label))
|
||||
})
|
||||
.when_some(self.description, |this, description| {
|
||||
this.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.text_color(cx.theme().text_placeholder)
|
||||
.child(description),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.hover(|this| this.bg(cx.theme().elevated_surface_background))
|
||||
.on_click(move |ev, window, cx| handler(ev, window, cx))
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
use std::{
|
||||
collections::{BTreeSet, HashSet},
|
||||
time::Duration,
|
||||
};
|
||||
use std::{collections::BTreeSet, ops::Range, time::Duration};
|
||||
|
||||
use account::Account;
|
||||
use async_utility::task::spawn;
|
||||
@@ -10,33 +7,30 @@ use chats::{
|
||||
ChatRegistry,
|
||||
};
|
||||
|
||||
use common::{debounced_delay::DebouncedDelay, profile::SharedProfile};
|
||||
use folder::{Folder, FolderItem, Parent};
|
||||
use common::{debounced_delay::DebouncedDelay, profile::RenderProfile};
|
||||
use element::DisplayRoom;
|
||||
use global::{constants::SEARCH_RELAYS, get_client};
|
||||
use gpui::{
|
||||
div, img, prelude::FluentBuilder, AnyElement, App, AppContext, Context, Entity, EventEmitter,
|
||||
FocusHandle, Focusable, InteractiveElement, IntoElement, ParentElement, Render, ScrollHandle,
|
||||
SharedString, StatefulInteractiveElement, Styled, Subscription, Task, Window,
|
||||
div, prelude::FluentBuilder, rems, uniform_list, AnyElement, App, AppContext, Context, Entity,
|
||||
EventEmitter, FocusHandle, Focusable, IntoElement, ParentElement, Render, RetainAllImageCache,
|
||||
SharedString, Styled, Subscription, Task, Window,
|
||||
};
|
||||
use itertools::Itertools;
|
||||
use nostr_sdk::prelude::*;
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use theme::ActiveTheme;
|
||||
use ui::{
|
||||
button::{Button, ButtonCustomVariant, ButtonRounded, ButtonVariants},
|
||||
dock_area::{
|
||||
dock::DockPlacement,
|
||||
panel::{Panel, PanelEvent},
|
||||
},
|
||||
avatar::Avatar,
|
||||
button::{Button, ButtonRounded, ButtonVariants},
|
||||
dock_area::panel::{Panel, PanelEvent},
|
||||
input::{InputEvent, InputState, TextInput},
|
||||
popup_menu::{PopupMenu, PopupMenuExt},
|
||||
skeleton::Skeleton,
|
||||
IconName, Sizable, StyledExt,
|
||||
ContextModal, IconName, Selectable, Sizable, StyledExt,
|
||||
};
|
||||
|
||||
use crate::chatspace::{AddPanel, ModalKind, PanelKind, ToggleModal};
|
||||
use crate::chatspace::{ModalKind, ToggleModal};
|
||||
|
||||
mod folder;
|
||||
mod element;
|
||||
|
||||
const FIND_DELAY: u64 = 600;
|
||||
const FIND_LIMIT: usize = 10;
|
||||
@@ -45,18 +39,6 @@ pub fn init(window: &mut Window, cx: &mut App) -> Entity<Sidebar> {
|
||||
Sidebar::new(window, cx)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Item {
|
||||
Ongoing,
|
||||
Incoming,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum SubItem {
|
||||
Trusted,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
pub struct Sidebar {
|
||||
name: SharedString,
|
||||
// Search
|
||||
@@ -65,13 +47,12 @@ pub struct Sidebar {
|
||||
finding: bool,
|
||||
local_result: Entity<Option<Vec<Entity<Room>>>>,
|
||||
global_result: Entity<Option<Vec<Entity<Room>>>>,
|
||||
// Layout
|
||||
folders: bool,
|
||||
active_items: HashSet<Item>,
|
||||
active_subitems: HashSet<SubItem>,
|
||||
// Rooms
|
||||
active_filter: Entity<RoomKind>,
|
||||
trusted_only: bool,
|
||||
// GPUI
|
||||
focus_handle: FocusHandle,
|
||||
scroll_handle: ScrollHandle,
|
||||
image_cache: Entity<RetainAllImageCache>,
|
||||
#[allow(dead_code)]
|
||||
subscriptions: SmallVec<[Subscription; 1]>,
|
||||
}
|
||||
@@ -82,16 +63,7 @@ impl Sidebar {
|
||||
}
|
||||
|
||||
fn view(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let focus_handle = cx.focus_handle();
|
||||
let scroll_handle = ScrollHandle::default();
|
||||
|
||||
let mut active_items = HashSet::with_capacity(2);
|
||||
active_items.insert(Item::Ongoing);
|
||||
|
||||
let mut active_subitems = HashSet::with_capacity(2);
|
||||
active_subitems.insert(SubItem::Trusted);
|
||||
active_subitems.insert(SubItem::Unknown);
|
||||
|
||||
let active_filter = cx.new(|_| RoomKind::Ongoing);
|
||||
let local_result = cx.new(|_| None);
|
||||
let global_result = cx.new(|_| None);
|
||||
|
||||
@@ -100,8 +72,10 @@ impl Sidebar {
|
||||
|
||||
let mut subscriptions = smallvec![];
|
||||
|
||||
subscriptions.push(
|
||||
cx.subscribe_in(&find_input, window, |this, _, event, _, cx| {
|
||||
subscriptions.push(cx.subscribe_in(
|
||||
&find_input,
|
||||
window,
|
||||
|this, _state, event, _window, cx| {
|
||||
match event {
|
||||
InputEvent::PressEnter { .. } => this.search(cx),
|
||||
InputEvent::Change(text) => {
|
||||
@@ -119,44 +93,24 @@ impl Sidebar {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}),
|
||||
);
|
||||
},
|
||||
));
|
||||
|
||||
Self {
|
||||
name: "Chat Sidebar".into(),
|
||||
folders: false,
|
||||
focus_handle: cx.focus_handle(),
|
||||
image_cache: RetainAllImageCache::new(cx),
|
||||
find_debouncer: DebouncedDelay::new(),
|
||||
finding: false,
|
||||
trusted_only: false,
|
||||
active_filter,
|
||||
find_input,
|
||||
local_result,
|
||||
global_result,
|
||||
active_items,
|
||||
active_subitems,
|
||||
focus_handle,
|
||||
scroll_handle,
|
||||
subscriptions,
|
||||
}
|
||||
}
|
||||
|
||||
fn toggle_item(&mut self, item: Item, cx: &mut Context<Self>) {
|
||||
if !self.active_items.remove(&item) {
|
||||
self.active_items.insert(item);
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn toggle_subitem(&mut self, subitem: SubItem, cx: &mut Context<Self>) {
|
||||
if !self.active_subitems.remove(&subitem) {
|
||||
self.active_subitems.insert(subitem);
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn toggle_folder(&mut self, cx: &mut Context<Self>) {
|
||||
self.folders = !self.folders;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn debounced_search(&self, cx: &mut Context<Self>) -> Task<()> {
|
||||
cx.spawn(async move |this, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
@@ -189,7 +143,7 @@ impl Sidebar {
|
||||
|
||||
spawn(async move {
|
||||
let client = get_client();
|
||||
let signer = client.signer().await.unwrap();
|
||||
let signer = client.signer().await.expect("signer is required");
|
||||
|
||||
for event in events.into_iter() {
|
||||
let metadata = Metadata::from_json(event.content).unwrap_or_default();
|
||||
@@ -227,6 +181,14 @@ impl Sidebar {
|
||||
return;
|
||||
}
|
||||
|
||||
if query.starts_with("nevent1")
|
||||
|| query.starts_with("naddr")
|
||||
|| query.starts_with("nsec1")
|
||||
|| query.starts_with("note1")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Return if search is in progress
|
||||
if self.finding {
|
||||
return;
|
||||
@@ -299,83 +261,151 @@ impl Sidebar {
|
||||
});
|
||||
}
|
||||
|
||||
fn push_room(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if let Some(result) = self.global_result.read(cx).as_ref() {
|
||||
if let Some(room) = result.iter().find(|this| this.read(cx).id == id).cloned() {
|
||||
ChatRegistry::global(cx).update(cx, |this, cx| {
|
||||
this.push_room(room, cx);
|
||||
});
|
||||
window.dispatch_action(
|
||||
Box::new(AddPanel::new(PanelKind::Room(id), DockPlacement::Center)),
|
||||
cx,
|
||||
);
|
||||
self.clear_search_results(cx);
|
||||
}
|
||||
}
|
||||
fn filter(&self, kind: &RoomKind, cx: &Context<Self>) -> bool {
|
||||
self.active_filter.read(cx) == kind
|
||||
}
|
||||
|
||||
fn set_filter(&mut self, kind: RoomKind, cx: &mut Context<Self>) {
|
||||
self.active_filter.update(cx, |this, cx| {
|
||||
*this = kind;
|
||||
cx.notify();
|
||||
})
|
||||
}
|
||||
|
||||
fn set_trusted_only(&mut self, cx: &mut Context<Self>) {
|
||||
self.trusted_only = !self.trusted_only;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn open_room(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let room = if let Some(room) = ChatRegistry::get_global(cx).room(&id, cx) {
|
||||
room
|
||||
} else {
|
||||
self.clear_search_results(cx);
|
||||
|
||||
let Some(result) = self.global_result.read(cx).as_ref() else {
|
||||
window.push_notification("Failed to open room. Please try again later.", cx);
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(room) = result.iter().find(|this| this.read(cx).id == id).cloned() else {
|
||||
window.push_notification("Failed to open room. Please try again later.", cx);
|
||||
return;
|
||||
};
|
||||
|
||||
room
|
||||
};
|
||||
|
||||
ChatRegistry::global(cx).update(cx, |this, cx| {
|
||||
this.push_room(room, cx);
|
||||
});
|
||||
}
|
||||
|
||||
fn render_account(&self, profile: &Profile, cx: &Context<Self>) -> impl IntoElement {
|
||||
div()
|
||||
.px_3()
|
||||
.h_8()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.justify_between()
|
||||
.items_center()
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.text_sm()
|
||||
.font_semibold()
|
||||
.child(Avatar::new(profile.render_avatar()).size(rems(1.75)))
|
||||
.child(profile.render_name()),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.child(
|
||||
Button::new("user")
|
||||
.icon(IconName::Ellipsis)
|
||||
.small()
|
||||
.ghost()
|
||||
.rounded(ButtonRounded::Full)
|
||||
.popup_menu(|this, _window, _cx| {
|
||||
this.menu(
|
||||
"Profile",
|
||||
Box::new(ToggleModal {
|
||||
modal: ModalKind::Profile,
|
||||
}),
|
||||
)
|
||||
.menu(
|
||||
"Relays",
|
||||
Box::new(ToggleModal {
|
||||
modal: ModalKind::Relay,
|
||||
}),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
Button::new("compose")
|
||||
.icon(IconName::PlusFill)
|
||||
.tooltip("Create DM or Group DM")
|
||||
.small()
|
||||
.primary()
|
||||
.rounded(ButtonRounded::Full)
|
||||
.on_click(cx.listener(|_, _, window, cx| {
|
||||
window.dispatch_action(
|
||||
Box::new(ToggleModal {
|
||||
modal: ModalKind::Compose,
|
||||
}),
|
||||
cx,
|
||||
);
|
||||
})),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_skeleton(&self, total: i32) -> impl IntoIterator<Item = impl IntoElement> {
|
||||
(0..total).map(|_| {
|
||||
div()
|
||||
.h_8()
|
||||
.h_9()
|
||||
.w_full()
|
||||
.px_2()
|
||||
.px_1p5()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.child(Skeleton::new().flex_shrink_0().size_6().rounded_full())
|
||||
.child(Skeleton::new().w_20().h_3().rounded_sm())
|
||||
.child(Skeleton::new().w_40().h_4().rounded_sm())
|
||||
})
|
||||
}
|
||||
|
||||
fn render_global_items(rooms: &[Entity<Room>], cx: &Context<Self>) -> Vec<FolderItem> {
|
||||
let mut items = Vec::with_capacity(rooms.len());
|
||||
fn render_uniform_item(
|
||||
&self,
|
||||
rooms: &[Entity<Room>],
|
||||
range: Range<usize>,
|
||||
cx: &Context<Self>,
|
||||
) -> Vec<impl IntoElement> {
|
||||
let mut items = Vec::with_capacity(range.end - range.start);
|
||||
|
||||
for room in rooms.iter() {
|
||||
let this = room.read(cx);
|
||||
let id = this.id;
|
||||
let label = this.display_name(cx);
|
||||
let img = this.display_image(cx).map(img);
|
||||
for ix in range {
|
||||
if let Some(room) = rooms.get(ix) {
|
||||
let this = room.read(cx);
|
||||
let id = this.id;
|
||||
let ago = this.ago();
|
||||
let label = this.display_name(cx);
|
||||
let img = this.display_image(cx);
|
||||
|
||||
let item = FolderItem::new(id as usize)
|
||||
.label(label)
|
||||
.img(img)
|
||||
.on_click({
|
||||
cx.listener(move |this, _, window, cx| {
|
||||
this.push_room(id, window, cx);
|
||||
})
|
||||
let handler = cx.listener(move |this, _, window, cx| {
|
||||
this.open_room(id, window, cx);
|
||||
});
|
||||
|
||||
items.push(item);
|
||||
}
|
||||
|
||||
items
|
||||
}
|
||||
|
||||
fn render_items(rooms: &[Entity<Room>], cx: &Context<Self>) -> Vec<FolderItem> {
|
||||
let mut items = Vec::with_capacity(rooms.len());
|
||||
|
||||
for room in rooms.iter() {
|
||||
let room = room.read(cx);
|
||||
let id = room.id;
|
||||
let ago = room.ago();
|
||||
let label = room.display_name(cx);
|
||||
let img = room.display_image(cx).map(img);
|
||||
|
||||
let item = FolderItem::new(id as usize)
|
||||
.label(label)
|
||||
.description(ago)
|
||||
.img(img)
|
||||
.on_click({
|
||||
cx.listener(move |_, _, window, cx| {
|
||||
window.dispatch_action(
|
||||
Box::new(AddPanel::new(PanelKind::Room(id), DockPlacement::Center)),
|
||||
cx,
|
||||
);
|
||||
})
|
||||
});
|
||||
|
||||
items.push(item);
|
||||
items.push(
|
||||
DisplayRoom::new(ix)
|
||||
.img(img)
|
||||
.label(label)
|
||||
.description(ago)
|
||||
.on_click(handler),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
items
|
||||
@@ -409,220 +439,145 @@ impl Focusable for Sidebar {
|
||||
}
|
||||
|
||||
impl Render for Sidebar {
|
||||
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let account = Account::get_global(cx).profile_ref();
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let chats = ChatRegistry::get_global(cx);
|
||||
|
||||
// Get search result
|
||||
let local_result = self.local_result.read(cx);
|
||||
let global_result = self.global_result.read(cx);
|
||||
let rooms = if let Some(results) = self.local_result.read(cx) {
|
||||
results.to_owned()
|
||||
} else {
|
||||
#[allow(clippy::collapsible_else_if)]
|
||||
if self.active_filter.read(cx) == &RoomKind::Ongoing {
|
||||
chats.ongoing_rooms(cx)
|
||||
} else {
|
||||
chats.request_rooms(self.trusted_only, cx)
|
||||
}
|
||||
};
|
||||
|
||||
div()
|
||||
.id("sidebar")
|
||||
.track_focus(&self.focus_handle)
|
||||
.track_scroll(&self.scroll_handle)
|
||||
.overflow_y_scroll()
|
||||
.image_cache(self.image_cache.clone())
|
||||
.size_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_3()
|
||||
.py_1()
|
||||
.when_some(account, |this, profile| {
|
||||
this.child(
|
||||
div()
|
||||
.px_3()
|
||||
.h_7()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.justify_between()
|
||||
.items_center()
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.text_sm()
|
||||
.font_semibold()
|
||||
.child(img(profile.shared_avatar()).size_7())
|
||||
.child(profile.shared_name()),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.child(
|
||||
Button::new("user")
|
||||
.icon(IconName::Ellipsis)
|
||||
.small()
|
||||
.ghost()
|
||||
.rounded(ButtonRounded::Full)
|
||||
.popup_menu(|this, _window, _cx| {
|
||||
this.menu(
|
||||
"Profile",
|
||||
Box::new(ToggleModal {
|
||||
modal: ModalKind::Profile,
|
||||
}),
|
||||
)
|
||||
.menu(
|
||||
"Relays",
|
||||
Box::new(ToggleModal {
|
||||
modal: ModalKind::Relay,
|
||||
}),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
Button::new("compose")
|
||||
.icon(IconName::PlusFill)
|
||||
.tooltip("Create DM or Group DM")
|
||||
.small()
|
||||
.primary()
|
||||
.rounded(ButtonRounded::Full)
|
||||
.on_click(cx.listener(|_, _, window, cx| {
|
||||
window.dispatch_action(
|
||||
Box::new(ToggleModal {
|
||||
modal: ModalKind::Compose,
|
||||
}),
|
||||
cx,
|
||||
);
|
||||
})),
|
||||
),
|
||||
),
|
||||
)
|
||||
// Account
|
||||
.when_some(Account::get_global(cx).profile_ref(), |this, profile| {
|
||||
this.child(self.render_account(profile, cx))
|
||||
})
|
||||
// Search Input
|
||||
.child(
|
||||
div().px_3().h_7().flex_none().child(
|
||||
div().px_3().w_full().h_7().flex_none().child(
|
||||
TextInput::new(&self.find_input).small().suffix(
|
||||
Button::new("find")
|
||||
.icon(IconName::Search)
|
||||
.tooltip("Press Enter to search")
|
||||
.small()
|
||||
.custom(
|
||||
ButtonCustomVariant::new(window, cx)
|
||||
.active(gpui::transparent_black())
|
||||
.color(gpui::transparent_black())
|
||||
.hover(gpui::transparent_black())
|
||||
.foreground(cx.theme().text_placeholder),
|
||||
),
|
||||
.transparent()
|
||||
.small(),
|
||||
),
|
||||
),
|
||||
)
|
||||
.when_some(global_result.as_ref(), |this, rooms| {
|
||||
// Global Search Results
|
||||
.when_some(self.global_result.read(cx).clone(), |this, rooms| {
|
||||
this.child(
|
||||
div()
|
||||
.px_1()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_1()
|
||||
.children(Self::render_global_items(rooms, cx)),
|
||||
div().px_1().w_full().flex_1().overflow_y_hidden().child(
|
||||
uniform_list(
|
||||
cx.entity(),
|
||||
"results",
|
||||
rooms.len(),
|
||||
move |this, range, _window, cx| {
|
||||
this.render_uniform_item(&rooms, range, cx)
|
||||
},
|
||||
)
|
||||
.h_full(),
|
||||
),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.px_1()
|
||||
.px_2()
|
||||
.w_full()
|
||||
.flex_1()
|
||||
.overflow_y_hidden()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_1()
|
||||
.child(
|
||||
div()
|
||||
.mb_1()
|
||||
.px_2()
|
||||
.flex_none()
|
||||
.px_1()
|
||||
.w_full()
|
||||
.h_9()
|
||||
.flex()
|
||||
.justify_between()
|
||||
.items_center()
|
||||
.text_sm()
|
||||
.font_semibold()
|
||||
.text_color(cx.theme().text_placeholder)
|
||||
.child("Messages")
|
||||
.justify_between()
|
||||
.child(
|
||||
Button::new("menu")
|
||||
.tooltip("Toggle chat folders")
|
||||
.map(|this| {
|
||||
if self.folders {
|
||||
this.icon(IconName::FilterFill)
|
||||
} else {
|
||||
this.icon(IconName::Filter)
|
||||
}
|
||||
})
|
||||
.small()
|
||||
.custom(
|
||||
ButtonCustomVariant::new(window, cx)
|
||||
.foreground(cx.theme().text_placeholder)
|
||||
.color(cx.theme().ghost_element_background)
|
||||
.hover(cx.theme().ghost_element_background)
|
||||
.active(cx.theme().ghost_element_background),
|
||||
)
|
||||
.on_click(cx.listener(move |this, _, _, cx| {
|
||||
this.toggle_folder(cx);
|
||||
})),
|
||||
),
|
||||
)
|
||||
.when(chats.wait_for_eose, |this| {
|
||||
this.children(self.render_skeleton(6))
|
||||
})
|
||||
.map(|this| {
|
||||
if let Some(rooms) = local_result {
|
||||
this.children(Self::render_items(rooms, cx))
|
||||
} else if !self.folders {
|
||||
this.children(Self::render_items(&chats.rooms, cx))
|
||||
} else {
|
||||
this.child(
|
||||
Folder::new("Ongoing")
|
||||
.icon(IconName::Folder)
|
||||
.tooltip("All ongoing conversations")
|
||||
.collapsed(!self.active_items.contains(&Item::Ongoing))
|
||||
.on_click(cx.listener(move |this, _, _, cx| {
|
||||
this.toggle_item(Item::Ongoing, cx);
|
||||
}))
|
||||
.children(Self::render_items(
|
||||
&chats.rooms_by_kind(RoomKind::Ongoing, cx),
|
||||
cx,
|
||||
)),
|
||||
)
|
||||
.child(
|
||||
Parent::new("Incoming")
|
||||
.icon(IconName::Folder)
|
||||
.tooltip("Incoming messages")
|
||||
.collapsed(!self.active_items.contains(&Item::Incoming))
|
||||
.on_click(cx.listener(move |this, _, _, cx| {
|
||||
this.toggle_item(Item::Incoming, cx);
|
||||
}))
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.child(
|
||||
Folder::new("Trusted")
|
||||
.icon(IconName::Folder)
|
||||
.tooltip("Incoming messages from trusted contacts")
|
||||
.collapsed(
|
||||
!self.active_subitems.contains(&SubItem::Trusted),
|
||||
)
|
||||
.on_click(cx.listener(move |this, _, _, cx| {
|
||||
this.toggle_subitem(SubItem::Trusted, cx);
|
||||
}))
|
||||
.children(Self::render_items(
|
||||
&chats.rooms_by_kind(RoomKind::Trusted, cx),
|
||||
cx,
|
||||
)),
|
||||
Button::new("all")
|
||||
.label("All")
|
||||
.small()
|
||||
.bold()
|
||||
.secondary()
|
||||
.rounded(ButtonRounded::Full)
|
||||
.selected(self.filter(&RoomKind::Ongoing, cx))
|
||||
.on_click(cx.listener(|this, _, _, cx| {
|
||||
this.set_filter(RoomKind::Ongoing, cx);
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
Folder::new("Unknown")
|
||||
.icon(IconName::Folder)
|
||||
.tooltip("Incoming messages from unknowns")
|
||||
.collapsed(
|
||||
!self.active_subitems.contains(&SubItem::Unknown),
|
||||
)
|
||||
.on_click(cx.listener(move |this, _, _, cx| {
|
||||
this.toggle_subitem(SubItem::Unknown, cx);
|
||||
}))
|
||||
.children(Self::render_items(
|
||||
&chats.rooms_by_kind(RoomKind::Unknown, cx),
|
||||
cx,
|
||||
)),
|
||||
Button::new("requests")
|
||||
.label("Requests")
|
||||
.small()
|
||||
.bold()
|
||||
.secondary()
|
||||
.rounded(ButtonRounded::Full)
|
||||
.selected(!self.filter(&RoomKind::Ongoing, cx))
|
||||
.on_click(cx.listener(|this, _, _, cx| {
|
||||
this.set_filter(RoomKind::Unknown, cx);
|
||||
})),
|
||||
),
|
||||
)
|
||||
}
|
||||
}),
|
||||
.when(!self.filter(&RoomKind::Ongoing, cx), |this| {
|
||||
this.child(
|
||||
Button::new("trusted")
|
||||
.tooltip("Only show rooms from trusted contacts")
|
||||
.map(|this| {
|
||||
if self.trusted_only {
|
||||
this.icon(IconName::FilterFill)
|
||||
} else {
|
||||
this.icon(IconName::Filter)
|
||||
}
|
||||
})
|
||||
.small()
|
||||
.transparent()
|
||||
.on_click(cx.listener(|this, _, _, cx| {
|
||||
this.set_trusted_only(cx);
|
||||
})),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.when(chats.wait_for_eose, |this| {
|
||||
this.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_1()
|
||||
.children(self.render_skeleton(10)),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
uniform_list(
|
||||
cx.entity(),
|
||||
"rooms",
|
||||
rooms.len(),
|
||||
move |this, range, _window, cx| {
|
||||
this.render_uniform_item(&rooms, range, cx)
|
||||
},
|
||||
)
|
||||
.h_full(),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user