cosmic_applet_avestruz/views/
compose.rs1use std::collections::HashMap;
23use std::sync::LazyLock;
24
25use cosmic::Element;
26use cosmic::iced::keyboard::Key;
27use cosmic::iced::keyboard::key::Named;
28use cosmic::iced::widget::text::Wrapping;
29use cosmic::iced::{Alignment, Border, Length};
30use cosmic::widget::text_editor::{Binding, Catalog, KeyPress, Status, Style, text_editor};
31use cosmic::widget::{self, button, container, text};
32use nostr_sdk::prelude::PublicKey;
33
34use crate::fl;
35use crate::helpers::{relative_time, truncate_chars, unix_now};
36use crate::messages::Message;
37use crate::nostr::compose::Target;
38use crate::nostr::models::{Note, Profile, display_name};
39use crate::state::{AppModel, Composer, Preview, Upload};
40use crate::views::components::{avatar, note_being_written};
41
42pub static COMPOSE_EDITOR_ID: LazyLock<widget::Id> = LazyLock::new(widget::Id::unique);
44
45const EDITOR_MIN_HEIGHT: f32 = 120.0;
48const EDITOR_MAX_HEIGHT: f32 = 300.0;
49
50const COMPOSE_TAB_WIDTH: u16 = 76;
53const PREVIEW_PADDING: f32 = 8.0;
56const PREVIEW_SCROLLBAR: f32 = 8.0;
59const AROUND_THE_PREVIEW: f32 = 280.0;
63
64const QUOTE_MAX_CHARS: usize = 140;
67const QUOTE_AVATAR_SIZE: f32 = 24.0;
68
69fn plain_text(note: &Note, profiles: &HashMap<PublicKey, Profile>) -> String {
72 let text: String = note
73 .content
74 .segments
75 .iter()
76 .map(|segment| segment.words(&|person| format!("@{}", display_name(profiles, person))))
77 .collect();
78 text.split_whitespace().collect::<Vec<_>>().join(" ")
79}
80
81fn editor_style(theme: &cosmic::Theme, status: Status) -> Style {
84 let mut style = theme.style(&<cosmic::Theme as Catalog>::default(), status);
85 style.border.width = 1.0;
86 style.border.radius = theme.cosmic().corner_radii.radius_s.into();
87 style
88}
89
90fn quoted_style() -> cosmic::theme::Container<'static> {
94 cosmic::theme::Container::custom(|theme| {
95 let cosmic = theme.cosmic();
96 container::Style {
97 border: Border { color: cosmic.bg_divider().into(), width: 1.0, radius: cosmic.corner_radii.radius_s.into() },
98 ..container::Style::default()
99 }
100 })
101}
102
103fn key_binding(press: KeyPress, empty: bool) -> Option<Binding<Message>> {
109 if press.key == Key::Named(Named::Enter) && press.modifiers.command() {
110 return Some(Binding::Custom(Message::Publish));
111 }
112 if press.modifiers.command() && matches!(press.key.as_ref(), Key::Character("p" | "P")) {
115 return None;
116 }
117 if empty && press.key == Key::Named(Named::Backspace) && matches!(press.status, Status::Focused { .. }) {
118 return Some(Binding::Custom(Message::ComposerRubbedOut));
119 }
120 match Binding::from_key_press(press) {
121 Some(Binding::Paste) => Some(Binding::Custom(Message::ComposePaste)),
122 binding => binding,
123 }
124}
125
126fn framed<'a>(shown: Element<'a, Message>, room: f32) -> Element<'a, Message> {
131 let shown = widget::Row::new()
134 .push(widget::Space::new().height(Length::Fixed(EDITOR_MIN_HEIGHT - 2.0 * PREVIEW_PADDING)))
135 .push(shown);
136 let shown =
138 container(shown).padding([PREVIEW_PADDING, PREVIEW_PADDING + PREVIEW_SCROLLBAR, PREVIEW_PADDING, PREVIEW_PADDING]);
139 container(widget::scrollable(shown.width(Length::Fill)).height(Length::Shrink))
140 .width(Length::Fill)
141 .max_height(room)
142 .class(quoted_style())
143 .into()
144}
145
146fn view_leaving<'a>() -> Element<'a, Message> {
150 let answers = widget::Row::new()
151 .push(button::suggested(fl!("compose-leaving-keep")).on_press(Message::CloseComposer))
152 .push(button::destructive(fl!("compose-leaving-discard")).on_press(Message::DiscardDraft))
153 .push(button::text(fl!("compose-leaving-stay")).on_press(Message::ResumeComposer))
154 .spacing(8)
155 .align_y(Alignment::Center);
156 widget::Column::new()
157 .push(text(fl!("compose-leaving")).size(13).wrapping(Wrapping::WordOrGlyph))
158 .push(answers)
159 .spacing(8)
160 .into()
161}
162
163fn view_upload(upload: &Upload) -> Element<'_, Message> {
166 let how_far = match upload.percent() {
167 Some(percent) => fl!("compose-upload-sent", percent = percent),
168 None => fl!("compose-upload-preparing"),
169 };
170 let cancel = button::icon(widget::icon::from_name("window-close-symbolic"))
171 .extra_small()
172 .tooltip(fl!("compose-upload-cancel"))
173 .on_press(Message::CancelUpload(upload.id));
174 widget::Row::new()
175 .push(widget::icon::from_name("mail-attachment-symbolic").size(14))
176 .push(container(text(upload.name.as_str()).size(12).wrapping(Wrapping::None)).width(Length::Fill).clip(true))
178 .push(text(how_far).size(11).wrapping(Wrapping::None))
179 .push(cancel)
180 .spacing(8)
181 .align_y(Alignment::Center)
182 .into()
183}
184
185impl AppModel {
186 fn view_compose_header(&self, composer: &Composer) -> Element<'_, Message> {
188 let back = button::icon(widget::icon::from_name("go-previous-symbolic"))
189 .tooltip(fl!("compose-back"))
190 .on_press(Message::CloseComposer);
191 let title = match composer.target {
192 Target::Note => fl!("compose-title-note"),
193 Target::Reply(_) => fl!("compose-title-reply"),
194 Target::Quote(_) => fl!("compose-title-quote"),
195 };
196 let tabs = widget::segmented_control::horizontal(&self.compose_tabs)
199 .on_activate(Message::SelectComposeTab)
200 .minimum_button_width(COMPOSE_TAB_WIDTH)
201 .width(Length::Shrink);
202 widget::Row::new()
203 .push(back)
204 .push(
205 container(text(title).size(16).font(cosmic::font::bold()).wrapping(Wrapping::None))
206 .width(Length::Fill)
207 .clip(true),
208 )
209 .push(tabs)
210 .spacing(8)
211 .align_y(Alignment::Center)
212 .padding([4, 12])
213 .into()
214 }
215
216 fn view_note_in_brief<'a>(&'a self, note: &'a Note) -> Element<'a, Message> {
219 let name = display_name(&self.profiles, ¬e.author);
220 let picture = self.profiles.get(¬e.author).and_then(|profile| profile.picture.as_deref());
221 let author_picture = avatar(&self.images, picture, ¬e.author, &name, QUOTE_AVATAR_SIZE);
222 let said = plain_text(note, &self.profiles);
223
224 let who = widget::Row::new()
225 .push(
226 container(text(name).size(12).font(cosmic::font::bold()).wrapping(Wrapping::None)).width(Length::Fill).clip(true),
227 )
228 .push(text(relative_time(unix_now(), note.created_at)).size(11).wrapping(Wrapping::None))
229 .spacing(8)
230 .align_y(Alignment::Center);
231 let body = widget::Column::new()
232 .push(who)
233 .push(text(truncate_chars(&said, QUOTE_MAX_CHARS).into_owned()).size(12).wrapping(Wrapping::WordOrGlyph))
234 .spacing(2)
235 .width(Length::Fill);
236 widget::Row::new().push(author_picture).push(body).spacing(8).into()
237 }
238
239 fn view_preview<'a>(&'a self, preview: &'a Preview) -> Element<'a, Message> {
245 let context = self.row_context(&preview.expanded, None);
246 let said = &preview.note.content;
247 let nothing = said.segments.is_empty() && said.images.is_empty() && said.videos.is_empty() && said.quotes.is_empty();
248 let shown: Element<'a, Message> = if nothing {
249 text(fl!("compose-preview-empty")).size(13).into()
250 } else {
251 note_being_written(&preview.note, &context)
252 };
253 framed(shown, (self.popup_max_height() - AROUND_THE_PREVIEW).max(EDITOR_MIN_HEIGHT))
254 }
255
256 pub fn view_compose(&self) -> Element<'_, Message> {
259 let Some(composer) = &self.composer else {
260 return self.view_feed();
261 };
262 let (placeholder, publish) = match composer.target {
263 Target::Note => (fl!("compose-placeholder-note"), fl!("compose-publish")),
264 Target::Reply(_) => (fl!("compose-placeholder-reply"), fl!("compose-reply")),
265 Target::Quote(_) => (fl!("compose-placeholder-quote"), fl!("compose-publish")),
266 };
267
268 let empty = composer.content.text().is_empty();
270 let editor = text_editor(&composer.content)
271 .id(COMPOSE_EDITOR_ID.clone())
272 .placeholder(placeholder)
273 .key_binding(move |press| key_binding(press, empty))
274 .style(editor_style)
275 .size(14)
276 .padding(8)
277 .wrapping(Wrapping::WordOrGlyph)
278 .min_height(EDITOR_MIN_HEIGHT)
279 .max_height(EDITOR_MAX_HEIGHT)
280 .context_menu(false);
282 let editor = if composer.leaving { editor } else { editor.on_action(Message::ComposeEdited) };
285 let editor: Element<'_, Message> = match &composer.preview {
287 Some(preview) => self.view_preview(preview),
288 None => editor.into(),
289 };
290
291 let written = composer.content.text().trim().chars().count();
292 let quoting = matches!(composer.target, Target::Quote(_));
295 let uploads: Vec<&Upload> = self.uploads_for(composer.target).collect();
298 let can_publish = (written > 0 || quoting) && !composer.publishing && self.nostr.is_some() && uploads.is_empty();
299 let publish_label = if composer.publishing { fl!("compose-publishing") } else { publish };
300 let attach = button::icon(widget::icon::from_name("mail-attachment-symbolic"))
301 .tooltip(fl!("compose-attach"))
302 .on_press_maybe((!composer.publishing && !self.media.picking).then_some(Message::AttachMedia));
303 let cancel = button::standard(fl!("compose-cancel"))
307 .tooltip(fl!("compose-cancel-tip"))
308 .on_press_maybe((!composer.publishing).then_some(Message::DiscardDraft));
309 let footer = widget::Row::new()
310 .push(attach)
311 .push(
312 container(text(fl!("compose-count", count = written)).size(11).wrapping(Wrapping::None))
313 .width(Length::Fill)
314 .clip(true),
315 )
316 .push(cancel)
317 .push(text(fl!("compose-shortcut")).size(11).wrapping(Wrapping::None))
318 .push(button::suggested(publish_label).on_press_maybe(can_publish.then_some(Message::Publish)))
319 .spacing(8)
320 .align_y(Alignment::Center);
321
322 let mut body = widget::Column::new().spacing(8).padding([8, 12]).width(Length::Fill);
323 match &composer.about {
324 Some(quoted) if quoting => {
325 let quoted = container(self.view_note_in_brief(quoted)).padding(8).width(Length::Fill).class(quoted_style());
326 body = body.push(editor).push(quoted);
327 }
328 Some(answered) => body = body.push(self.view_note_in_brief(answered)).push(editor),
329 None => body = body.push(editor),
330 }
331 for upload in uploads {
332 body = body.push(view_upload(upload));
333 }
334 if let Some(error) = &composer.error {
335 body = body.push(text(error.as_str()).size(12).class(cosmic::theme::Text::Accent).wrapping(Wrapping::WordOrGlyph));
336 }
337 body = body.push(if composer.leaving { view_leaving() } else { footer.into() });
340
341 widget::Column::new()
342 .push(self.view_compose_header(composer))
343 .push(widget::divider::horizontal::default())
344 .push(body)
345 .into()
346 }
347}
348
349#[cfg(test)]
350mod tests {
351 use super::{EDITOR_MIN_HEIGHT, framed, plain_text};
352 use crate::messages::Message;
353 use crate::nostr::content::{self, FEED_NOTE_MAX_CHARS};
354 use crate::nostr::models::{Note, Profile};
355 use cosmic::iced::core::widget::Tree;
356 use cosmic::iced::core::{Length, Size, layout};
357 use nostr_sdk::prelude::{EventId, Keys, Kind, ToBech32};
358 use std::collections::HashMap;
359
360 #[test]
361 fn the_frame_of_what_is_written_is_as_tall_as_what_it_holds_within_its_bounds() {
362 let renderer = crate::views::components::testing::renderer();
363 let framing = |tall: f32, room: f32| {
366 let held: cosmic::Element<'_, Message> = cosmic::widget::Space::new().width(Length::Fill).height(tall).into();
367 let mut frame = framed(held, room);
368 let mut tree = Tree::new(frame.as_widget());
369 let limits = layout::Limits::new(Size::ZERO, Size::new(600.0, 2_000.0));
370 let laid_out = frame.as_widget_mut().layout(&mut tree, &renderer, &limits).size();
371 assert_eq!(laid_out.width, 600.0, "as wide as the composer");
372 laid_out.height
373 };
374
375 assert_eq!(framing(10.0, 500.0), EDITOR_MIN_HEIGHT);
378 assert_eq!(framing(200.0, 500.0), 216.0);
380 assert_eq!(framing(900.0, 500.0), 500.0);
382 }
383
384 #[test]
385 fn a_note_in_brief_is_one_line_with_names_and_labels() {
386 let friend = Keys::generate().public_key();
387 let said = format!("gm nostr:{}\n\nsee https://www.example.com/a/page?x=1 #nostr", friend.to_bech32().unwrap());
388 let note = Note {
389 id: EventId::from_byte_array([7; 32]),
390 kind: Kind::TextNote,
391 author: Keys::generate().public_key(),
392 created_at: 0,
393 content: content::parse(&said, FEED_NOTE_MAX_CHARS),
394 reply_to: None,
395 quoted: Vec::new(),
396 };
397 let profiles = HashMap::from([(friend, Profile { name: Some("fiatjaf".into()), ..Profile::default() })]);
398
399 assert_eq!(plain_text(¬e, &profiles), "gm @fiatjaf see example.com/a/page #nostr");
400 }
401}