Skip to main content

cosmic_applet_avestruz/views/
compose.rs

1// SPDX-License-Identifier: MIT
2
3//! The composer view for Avestruz: a note, a reply or a quote being written.
4//!
5//! A reply shows what it answers above the text, in brief, and a quote what
6//! it quotes under the text, set apart as other clients will show it. The
7//! text is in
8//! an editor whose state is in the app model, so a popup that closes takes
9//! nothing with it. Ctrl+Enter publishes, as the button does; Cancel,
10//! beside it, leaves and keeps nothing of what was written.
11//!
12//! Above the text, a control chooses between writing it and looking at how
13//! it would show: the note as a row of a list would have it, whole, in a
14//! frame that stands where the text does and scrolls when it has more than
15//! there is room for (see [`crate::handlers::compose`]).
16//!
17//! The paperclip under the text attaches a file, which is sent to the
18//! account's media servers; while it is on its way it shows under the
19//! text with how far it has got, and when it is there its address goes
20//! into the text.
21
22use 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
42/// The editor the text is written in.
43pub static COMPOSE_EDITOR_ID: LazyLock<widget::Id> = LazyLock::new(widget::Id::unique);
44
45/// How tall the editor is with little in it, and how tall it grows before
46/// the text scrolls inside it.
47const EDITOR_MIN_HEIGHT: f32 = 120.0;
48const EDITOR_MAX_HEIGHT: f32 = 300.0;
49
50/// How wide each of the two choices above the text is at least: writing
51/// it, and looking at how it would show.
52const COMPOSE_TAB_WIDTH: u16 = 76;
53/// The room between the frame what is written shows in and what it shows,
54/// as the text has in its own.
55const PREVIEW_PADDING: f32 = 8.0;
56/// The room kept on the right of what the frame shows for the bar it
57/// scrolls by.
58const PREVIEW_SCROLLBAR: f32 = 8.0;
59/// How much of the popup's height is not the frame's: the line above the
60/// composer, the note written to, the files on their way, and the line
61/// with the way to publish, with the room between them.
62const AROUND_THE_PREVIEW: f32 = 280.0;
63
64/// How much of the note replied to or quoted is shown with the text, in
65/// characters, and how wide its author's picture is.
66const QUOTE_MAX_CHARS: usize = 140;
67const QUOTE_AVATAR_SIZE: f32 = 24.0;
68
69/// What a note says as one line of plain text: links by their label, people
70/// by name, and line breaks as spaces.
71fn 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
81/// How the editor looks: the theme's editor, with the thin rounded border
82/// its text inputs have rather than a heavy square one.
83fn 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
90/// How the note a quote quotes is set apart under the text: in a thin
91/// rounded border, as the editor is, in the colour of the lines between
92/// rows.
93fn 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
103/// What the keys do in the editor: Ctrl+Enter publishes; pasting asks
104/// what is on the clipboard, which may be a file to attach and not text
105/// (see [`crate::handlers::media`]); Backspace with nothing in the text
106/// (`empty`) for it to rub out leaves the composer (see
107/// [`crate::handlers::compose`]); and the rest is the editor's own.
108fn 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    // Ctrl+P is the composer's, wherever the keyboard is: nothing of the
113    // text's.
114    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
126/// `shown`, which is what is being written as it would show, in the frame
127/// that stands where the text does: as tall as what it holds, no shorter
128/// than the text is at its shortest and no taller than `room`, past which
129/// it scrolls.
130fn framed<'a>(shown: Element<'a, Message>, room: f32) -> Element<'a, Message> {
131    // Beside it, something as tall as the text is at its shortest and no
132    // wider than nothing: the frame is never shorter than that.
133    let shown = widget::Row::new()
134        .push(widget::Space::new().height(Length::Fixed(EDITOR_MIN_HEIGHT - 2.0 * PREVIEW_PADDING)))
135        .push(shown);
136    // Room on the right for the bar it scrolls by.
137    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
146/// Whether what was written is kept as a draft, asked of whoever pressed
147/// Backspace to leave the composer, and the three answers there are, each
148/// with the key that gives it.
149fn 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
163/// A file on its way to a media server: what it is called, how far it has
164/// got, and the way to call it off.
165fn 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        // A long name is cut rather than wrapped.
177        .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    /// The line above the composer: the way back, and what is being written.
187    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        // Two choices, one of them always made: writing it, and looking at
197        // how it would show.
198        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    /// The note a reply answers or a quote quotes, in brief: who wrote it,
217    /// when, and how it starts.
218    fn view_note_in_brief<'a>(&'a self, note: &'a Note) -> Element<'a, Message> {
219        let name = display_name(&self.profiles, &note.author);
220        let picture = self.profiles.get(&note.author).and_then(|profile| profile.picture.as_deref());
221        let author_picture = avatar(&self.images, picture, &note.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    /// What is being written as it would show once it is out, where the
240    /// text is while it is written: who writes it and all it says, as a
241    /// row of a list would have it, in a frame the size of what it holds,
242    /// no smaller than the text's and no taller than the popup has room
243    /// for, past which it scrolls. With nothing written, it says so.
244    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    /// Render the composer. With nothing being written there is nothing to
257    /// show but what is under it.
258    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        // Not a blank line or a space: those are something to rub out.
269        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            // The menu would be a popup of its own, over a popup.
281            .context_menu(false);
282        // Asked whether it is kept as a draft, the text is not written
283        // to: the keys are the answer's.
284        let editor = if composer.leaving { editor } else { editor.on_action(Message::ComposeEdited) };
285        // In its place, how it would show, while that is looked at.
286        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        // A quote needs nothing said: the note quoted is something to
293        // publish.
294        let quoting = matches!(composer.target, Target::Quote(_));
295        // Nor does anything go out while a file attached to it is still
296        // on its way.
297        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        // The way out that keeps nothing: what rubbing out all that was
304        // written and then leaving comes to. Not while it is on its way
305        // out: there is no calling that back.
306        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        // The question is asked where the way to publish was: nothing
338        // goes out while leaving is being thought about.
339        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        // How tall the frame is around something `tall`, with `room` to
364        // be at most.
365        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        // Never shorter than the text is with little in it: the way to
376        // publish does not come up under a short note.
377        assert_eq!(framing(10.0, 500.0), EDITOR_MIN_HEIGHT);
378        // As tall as what it holds, with the room around that.
379        assert_eq!(framing(200.0, 500.0), 216.0);
380        // And no taller than there is room for: the rest is scrolled to.
381        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(&note, &profiles), "gm @fiatjaf see example.com/a/page #nostr");
400    }
401}