feat: render attachment after upload

This commit is contained in:
2025-01-16 08:02:25 +07:00
parent de20b4b219
commit 161e6a5342
3 changed files with 127 additions and 78 deletions

View File

@@ -35,7 +35,7 @@ impl RenderOnce for Message {
.border_l_2() .border_l_2()
.border_color(cx.theme().background) .border_color(cx.theme().background)
.hover(|this| { .hover(|this| {
this.bg(cx.theme().base.step(cx, ColorScaleStep::TWO)) this.bg(cx.theme().accent.step(cx, ColorScaleStep::TWO))
.border_color(cx.theme().accent.step(cx, ColorScaleStep::NINE)) .border_color(cx.theme().accent.step(cx, ColorScaleStep::NINE))
}) })
.child( .child(

View File

@@ -1,11 +1,12 @@
use crate::{ use crate::{
constants::IMAGE_SERVICE,
get_client, get_client,
states::chat::room::Room, states::chat::room::Room,
utils::{ago, compare, nip96_upload}, utils::{ago, compare, nip96_upload},
}; };
use async_utility::task::spawn; use async_utility::task::spawn;
use gpui::{ use gpui::{
div, img, list, px, AnyElement, AppContext, Context, EventEmitter, Flatten, FocusHandle, div, img, list, px, white, AnyElement, AppContext, Context, EventEmitter, Flatten, FocusHandle,
FocusableView, InteractiveElement, IntoElement, ListAlignment, ListState, Model, ObjectFit, FocusableView, InteractiveElement, IntoElement, ListAlignment, ListState, Model, ObjectFit,
ParentElement, PathPromptOptions, Pixels, Render, SharedString, StatefulInteractiveElement, ParentElement, PathPromptOptions, Pixels, Render, SharedString, StatefulInteractiveElement,
Styled, StyledImage, View, ViewContext, VisualContext, WeakModel, WeakView, WindowContext, Styled, StyledImage, View, ViewContext, VisualContext, WeakModel, WeakView, WindowContext,
@@ -14,7 +15,6 @@ use itertools::Itertools;
use message::Message; use message::Message;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use smol::fs; use smol::fs;
use std::sync::Arc;
use tokio::sync::oneshot; use tokio::sync::oneshot;
use ui::{ use ui::{
button::{Button, ButtonVariants}, button::{Button, ButtonVariants},
@@ -244,11 +244,21 @@ impl ChatPanel {
fn send_message(&mut self, view: WeakView<TextInput>, cx: &mut ViewContext<Self>) { fn send_message(&mut self, view: WeakView<TextInput>, cx: &mut ViewContext<Self>) {
let room = self.room.read(cx); let room = self.room.read(cx);
let content = Arc::new(self.input.read(cx).text().to_string());
let owner = room.owner.clone(); let owner = room.owner.clone();
let members = room.members.to_vec();
let mut members = room.members.to_vec(); // Get message
members.push(owner.clone()); let mut content = self.input.read(cx).text().to_string();
// Get all attaches and merge with message
if let Some(attaches) = self.attaches.read(cx).as_ref() {
let merged = attaches
.iter()
.map(|url| url.to_string())
.collect::<Vec<_>>()
.join("\n");
content = format!("{}\n{}", content, merged)
}
// Async // Async
let async_state = self.state.clone(); let async_state = self.state.clone();
@@ -261,7 +271,7 @@ impl ChatPanel {
.background_executor() .background_executor()
.spawn({ .spawn({
let client = get_client(); let client = get_client();
let content = Arc::clone(&content).to_string(); let content = content.clone().to_string();
let tags: Vec<Tag> = members let tags: Vec<Tag> = members
.iter() .iter()
.filter_map(|m| { .filter_map(|m| {
@@ -307,14 +317,18 @@ impl ChatPanel {
fn upload(&mut self, cx: &mut ViewContext<Self>) { fn upload(&mut self, cx: &mut ViewContext<Self>) {
let attaches = self.attaches.clone(); let attaches = self.attaches.clone();
let paths = cx.prompt_for_paths(PathPromptOptions { let paths = cx.prompt_for_paths(PathPromptOptions {
files: true, files: true,
directories: false, directories: false,
multiple: false, multiple: false,
}); });
cx.spawn(move |_, mut async_cx| async move { // Show loading spinner
self.is_uploading = true;
cx.notify();
// TODO: support multiple upload
cx.spawn(move |this, mut async_cx| async move {
match Flatten::flatten(paths.await.map_err(|e| e.into())) { match Flatten::flatten(paths.await.map_err(|e| e.into())) {
Ok(Some(mut paths)) => { Ok(Some(mut paths)) => {
let path = paths.pop().unwrap(); let path = paths.pop().unwrap();
@@ -329,6 +343,15 @@ impl ChatPanel {
}); });
if let Ok(url) = rx.await { if let Ok(url) = rx.await {
// Stop loading spinner
if let Some(view) = this.upgrade() {
_ = async_cx.update_view(&view, |this, cx| {
this.is_uploading = false;
cx.notify();
});
}
// Update attaches model
_ = async_cx.update_model(&attaches, |model, cx| { _ = async_cx.update_model(&attaches, |model, cx| {
if let Some(model) = model.as_mut() { if let Some(model) = model.as_mut() {
model.push(url); model.push(url);
@@ -347,8 +370,14 @@ impl ChatPanel {
.detach(); .detach();
} }
fn remove(&mut self, cx: &mut ViewContext<Self>) { fn remove(&mut self, url: &Url, cx: &mut ViewContext<Self>) {
// TODO self.attaches.update(cx, |model, cx| {
if let Some(urls) = model.as_mut() {
let ix = urls.iter().position(|x| x == url).unwrap();
urls.remove(ix);
cx.notify();
}
});
} }
} }
@@ -400,40 +429,58 @@ impl Render for ChatPanel {
.size_full() .size_full()
.child(list(self.list.clone()).flex_1()) .child(list(self.list.clone()).flex_1())
.child( .child(
div().flex_shrink_0().p_2().child(
div() div()
.flex_shrink_0()
.flex() .flex()
.flex_col() .flex_col()
.gap_1()
.when_some(self.attaches.read(cx).as_ref(), |this, attaches| { .when_some(self.attaches.read(cx).as_ref(), |this, attaches| {
this.flex() this.gap_1p5().children(attaches.iter().map(|url| {
.items_center() let url = url.clone();
.gap_1p5()
.px_2()
.children(attaches.iter().map(|url| {
let path: SharedString = url.to_string().into(); let path: SharedString = url.to_string().into();
div() div()
.id(path.clone()) .id(path.clone())
.relative()
.w_16()
.child( .child(
img(path) img(format!(
.h_16() "{}/?url={}&w=128&h=128&fit=cover&n=-1",
IMAGE_SERVICE, path
))
.size_16()
.shadow_lg()
.rounded(px(cx.theme().radius)) .rounded(px(cx.theme().radius))
.object_fit(ObjectFit::ScaleDown), .object_fit(ObjectFit::ScaleDown),
) )
.child(
div()
.absolute()
.top_neg_2()
.right_neg_2()
.size_4()
.flex()
.items_center()
.justify_center()
.rounded_full()
.bg(cx.theme().danger)
.child(
Icon::new(IconName::Close)
.size_2()
.text_color(white()),
),
)
.on_click(cx.listener(move |this, _, cx| { .on_click(cx.listener(move |this, _, cx| {
this.remove(cx); this.remove(&url, cx);
})) }))
})) }))
}) })
.child( .child(
div() div()
.w_full() .w_full()
.h_12() .h_9()
.flex() .flex()
.items_center() .items_center()
.gap_2() .gap_2()
.px_2()
.child( .child(
Button::new("upload") Button::new("upload")
.icon(Icon::new(IconName::Upload)) .icon(Icon::new(IconName::Upload))
@@ -453,6 +500,7 @@ impl Render for ChatPanel {
.child(self.input.clone()), .child(self.input.clone()),
), ),
), ),
),
) )
} }
} }

View File

@@ -18,6 +18,7 @@ pub struct ThemeColors {
pub scrollbar_thumb: Hsla, pub scrollbar_thumb: Hsla,
pub scrollbar_thumb_hover: Hsla, pub scrollbar_thumb_hover: Hsla,
pub window_border: Hsla, pub window_border: Hsla,
pub danger: Hsla,
} }
impl ThemeColors { impl ThemeColors {
@@ -29,6 +30,7 @@ impl ThemeColors {
scrollbar: hsl(0., 0., 97.).opacity(0.75), scrollbar: hsl(0., 0., 97.).opacity(0.75),
scrollbar_thumb: hsl(0., 0., 69.).opacity(0.9), scrollbar_thumb: hsl(0., 0., 69.).opacity(0.9),
scrollbar_thumb_hover: hsl(0., 0., 59.), scrollbar_thumb_hover: hsl(0., 0., 59.),
danger: hsl(0.0, 84.2, 60.2),
} }
} }
@@ -40,6 +42,7 @@ impl ThemeColors {
scrollbar: hsl(240., 1., 15.).opacity(0.75), scrollbar: hsl(240., 1., 15.).opacity(0.75),
scrollbar_thumb: hsl(0., 0., 48.).opacity(0.9), scrollbar_thumb: hsl(0., 0., 48.).opacity(0.9),
scrollbar_thumb_hover: hsl(0., 0., 68.), scrollbar_thumb_hover: hsl(0., 0., 68.),
danger: hsl(0.0, 62.8, 30.6),
} }
} }
} }
@@ -76,6 +79,19 @@ pub fn init(cx: &mut AppContext) {
Theme::sync_system_appearance(cx) Theme::sync_system_appearance(cx)
} }
#[derive(Debug, Clone, Copy, Default, PartialEq, PartialOrd, Eq)]
pub enum Appearance {
#[default]
Light,
Dark,
}
impl Appearance {
pub fn is_dark(&self) -> bool {
matches!(self, Self::Dark)
}
}
pub struct Theme { pub struct Theme {
colors: ThemeColors, colors: ThemeColors,
/// Base colors. /// Base colors.
@@ -132,27 +148,24 @@ impl Theme {
} }
pub fn change(mode: Appearance, cx: &mut AppContext) { pub fn change(mode: Appearance, cx: &mut AppContext) {
let colors = match mode { let theme = Theme::new(mode);
Appearance::Light => ThemeColors::light(),
Appearance::Dark => ThemeColors::dark(),
};
let mut theme = Theme::from(colors);
theme.appearance = mode;
cx.set_global(theme); cx.set_global(theme);
cx.refresh(); cx.refresh();
} }
} }
impl From<ThemeColors> for Theme { impl Theme {
fn from(colors: ThemeColors) -> Self { fn new(appearance: Appearance) -> Self {
let color_scales = default_color_scales(); let color_scales = default_color_scales();
let colors = match appearance {
Appearance::Light => ThemeColors::light(),
Appearance::Dark => ThemeColors::dark(),
};
Theme { Theme {
base: color_scales.gray, base: color_scales.gray,
accent: color_scales.yellow, accent: color_scales.yellow,
appearance: Appearance::default(),
font_size: 16.0, font_size: 16.0,
font_family: if cfg!(target_os = "macos") { font_family: if cfg!(target_os = "macos") {
".SystemUIFont".into() ".SystemUIFont".into()
@@ -164,20 +177,8 @@ impl From<ThemeColors> for Theme {
radius: 6.0, radius: 6.0,
shadow: false, shadow: false,
scrollbar_show: ScrollbarShow::default(), scrollbar_show: ScrollbarShow::default(),
appearance,
colors, colors,
} }
} }
} }
#[derive(Debug, Clone, Copy, Default, PartialEq, PartialOrd, Eq)]
pub enum Appearance {
#[default]
Light,
Dark,
}
impl Appearance {
pub fn is_dark(&self) -> bool {
matches!(self, Self::Dark)
}
}