Skip to main content

cosmic_applet_avestruz/handlers/
compose.rs

1// SPDX-License-Identifier: MIT
2
3//! Composer message handlers for Avestruz.
4//!
5//! A note, a reply or a quote is written in a view of its own. What is
6//! written belongs to what it is written to: leaving the composer keeps the
7//! text as that target's draft, and coming back finds it. The draft of a
8//! new note is also written to a file whenever the composer or the popup is
9//! left, so it is there after a restart.
10//!
11//! Cancel, beside the way to publish, leaves and keeps nothing, without
12//! asking: it is what rubbing out all that was written and then leaving
13//! comes to, so there is no draft after it, and the files on their way to
14//! be attached are called off.
15//!
16//! Backspace leaves the composer as well, and may keep nothing too (see
17//! [`Leaving`]). With nothing written there is
18//! nothing to keep, and it leaves. With something written it asks first:
19//! keep it as a draft, discard it, or go on writing.
20//!
21//! ```mermaid
22//! flowchart TD
23//!     key["Backspace, with nothing in the text for it to rub out, or with the keyboard out of the text"] --> held{"Was it held down, rubbing the text out until a moment ago?"}
24//!     held -->|"yes"| nothing["Nothing: rubbing out what was written is not leaving"]
25//!     held -->|"no"| written{"Is anything written, or a file on its way to be attached?"}
26//!     written -->|"no"| leave["The composer is left, and there is no draft"]
27//!     written -->|"yes"| ask["It asks: keep it as a draft?"]
28//!     ask -->|"Enter"| keep["Left, and what was written is kept as the draft"]
29//!     ask -->|"Backspace"| discard["Left, and nothing is kept: the draft is gone, and the files are called off"]
30//!     ask -->|"Escape"| stay["Not left: the keyboard is back in the text"]
31//! ```
32//!
33//! A quote is written as a note is, with the note it quotes on show under
34//! the text. That note's address is put under what was written when it goes
35//! out, and may be all that goes out: a quote needs nothing said.
36//!
37//! What is written can be looked at as it would show once it is out, in
38//! place of the text: the control above the text chooses, and Ctrl+P is
39//! the other of the two. It is what publishing would send, read as a row
40//! reads a note and shown whole: Markdown, pictures, videos, the page it
41//! links to, the people it names and the notes it quotes, which are looked
42//! for as a list would look for them. The text is not written to
43//! meanwhile, so what shows is what would go out; a file that gets where
44//! it was going meanwhile shows too. Pressing somebody it names, or a note
45//! it quotes, leaves the composer as the way back does: what was written
46//! is kept.
47//!
48//! ```mermaid
49//! flowchart LR
50//!     text["The text"] -->|"Preview, Ctrl+P"| note["As a note that is not one yet"]
51//!     note --> shown["Shown as a row would show it, whole"]
52//!     note -->|"it quotes notes"| sought["Looked for: the store, then the relays"]
53//!     sought -->|"it says the same still"| shown
54//!     shown -->|"Write, Ctrl+P"| text
55//!     shown -->|"Publish, Ctrl+Enter"| out["Signed and sent"]
56//! ```
57//!
58//! A file is attached by sending it to the account's media servers and
59//! putting its address in the text (see [`crate::handlers::media`]). What
60//! the note says of that file goes out with it, as long as the address is
61//! still in the text.
62//!
63//! Publishing has the account's signer sign (its key from the keyring, or
64//! its remote signer) and sends to the connected relays. Until a relay has
65//! taken it the text stays where it is; once one has, the note or the quote
66//! shows at the top of the feed, or the reply in its place in the thread.
67
68use std::collections::HashMap;
69use std::time::{Duration, Instant};
70
71use cosmic::iced::widget::operation::focus;
72use cosmic::prelude::*;
73use cosmic::widget::segmented_button;
74use cosmic::widget::text_editor::{Action, Content, Motion};
75use nostr_sdk::prelude::{EventId, PublicKey, Tag};
76
77use crate::drafts;
78use crate::fl;
79use crate::handlers::auth::sign_error_text;
80use crate::helpers::unix_now;
81use crate::messages::{Message, PublishFailure};
82use crate::nostr::account::Signer;
83use crate::nostr::blossom;
84use crate::nostr::client::{NostrService, PublishError};
85use crate::nostr::compose::{self, Target};
86use crate::nostr::models::Note;
87use crate::state::{AppModel, Composer, Preview, ViewState};
88use crate::views::compose::COMPOSE_EDITOR_ID;
89
90/// How long after the text was last rubbed out a Backspace is still taken
91/// for the one that did it, held down: longer than the gap between the
92/// repeats of a held key, which come some thirty to a second, and
93/// shorter than the gap between two presses made on purpose.
94const RUBBING_OUT: Duration = Duration::from_millis(150);
95
96/// What Backspace does to the composer, pressed to leave it.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub(crate) enum Leaving {
99    /// Leave: there is nothing to keep.
100    Leave,
101    /// Ask whether what was written is kept as a draft.
102    Ask,
103    /// Leave, and keep nothing: it was asked, and this is the answer.
104    Discard,
105}
106
107impl Leaving {
108    /// What Backspace does to a composer with something `written` in it
109    /// or not, a file on its way to be attached to it (`attaching`) or
110    /// not, and the question already `asked` or not.
111    pub(crate) fn on_backspace(written: bool, attaching: bool, asked: bool) -> Self {
112        match (asked, written || attaching) {
113            (true, _) => Self::Discard,
114            (false, true) => Self::Ask,
115            (false, false) => Self::Leave,
116        }
117    }
118}
119
120/// Whether a Backspace pressed at `now` is one held down that has been
121/// rubbing the text out, which was last changed at `rubbed`.
122fn held_from_rubbing_out(rubbed: Option<Instant>, now: Instant) -> bool {
123    rubbed.is_some_and(|rubbed| now.saturating_duration_since(rubbed) < RUBBING_OUT)
124}
125
126/// Have `signer` sign `text` as `author`'s note, or reply to what `target`
127/// names, which `answered` wrote, and send it to the relays, with `said`
128/// for what it says of the files it links to. The text of a quote names
129/// what it quotes already. Returns it as a row shows it.
130async fn publish(
131    service: NostrService,
132    signer: Signer,
133    author: PublicKey,
134    target: Target,
135    answered: Option<PublicKey>,
136    text: String,
137    said: Vec<Tag>,
138) -> Result<Note, PublishFailure> {
139    let parent = match target {
140        // What a quote quotes is in its text.
141        Target::Note | Target::Quote(_) => None,
142        Target::Reply(id) => {
143            let answered = answered.ok_or(PublishFailure::NoteGone)?;
144            Some(service.event(id, answered).await.ok_or(PublishFailure::NoteGone)?)
145        }
146    };
147    let unsigned = compose::build(&text, parent.as_ref(), author).tags(said);
148    let event = service.sign_and_publish(&signer, author, unsigned).await.map_err(PublishFailure::Failed)?;
149    Ok(service.note(event).await)
150}
151
152/// What is in `composer` as it would go out: the text, without the space
153/// around it, and under the text of a quote the address of the note it
154/// quotes.
155fn outgoing(composer: &Composer) -> String {
156    let text = composer.content.text().trim().to_string();
157    match (composer.target, &composer.about) {
158        (Target::Quote(_), Some(quoted)) => compose::quote(&text, quoted),
159        _ => text,
160    }
161}
162
163/// Where writing is in the control that chooses between it and the look
164/// at how what is written would show, and where the look is.
165const WRITE_TAB: u16 = 0;
166const PREVIEW_TAB: u16 = 1;
167
168/// Whether `found` is `shown`, which is being written and looked at, with
169/// no fewer of the notes it quotes: what was looked for when it said
170/// something else is not what it says now.
171fn is_the_same_with_more(shown: &Note, found: &Note) -> bool {
172    shown.content == found.content && shown.quoted_count() <= found.quoted_count()
173}
174
175/// Why an event did not go out, in the user's language.
176pub(crate) fn publish_error_text(error: PublishError) -> String {
177    match error {
178        PublishError::Sign(error) => sign_error_text(error),
179        PublishError::NoRelayReachable => fl!("error-no-relay"),
180        PublishError::Refused(reason) => fl!("compose-error-refused", reason = reason),
181        PublishError::Failed(error) => fl!("compose-error-failed", error = error),
182    }
183}
184
185/// Why what was written did not go out, in the user's language.
186fn publish_failure_text(failure: PublishFailure) -> String {
187    match failure {
188        PublishFailure::NoteGone => fl!("compose-error-parent-gone"),
189        PublishFailure::Failed(error) => publish_error_text(error),
190    }
191}
192
193impl AppModel {
194    /// Whether the account can publish: someone is signed in with a key.
195    pub(crate) fn can_publish(&self) -> bool {
196        self.account.as_ref().is_some_and(|account| account.can_sign)
197    }
198
199    /// Open the composer on `target`, which is about `about` if it is about
200    /// a note, with what was written to it before, the cursor after it, and
201    /// the keyboard in the text.
202    fn open_composer(&mut self, target: Target, about: Option<Note>) -> Task<cosmic::Action<Message>> {
203        if !self.can_publish() {
204            return Task::none();
205        }
206        let mut content = Content::with_text(self.drafts.get(target));
207        content.perform(Action::Move(Motion::DocumentEnd));
208        self.composer = Some(Composer {
209            target,
210            about,
211            content,
212            publishing: false,
213            error: None,
214            leaving: false,
215            rubbed: None,
216            preview: None,
217        });
218        self.compose_tabs.activate_position(WRITE_TAB);
219        self.view_state = ViewState::Compose;
220        focus(COMPOSE_EDITOR_ID.clone())
221    }
222
223    /// Writing, or looking at how what is written would show, was chosen
224    /// in the control above the text: `chosen` is that choice in it.
225    pub fn handle_select_compose_tab(&mut self, chosen: segmented_button::Entity) -> Task<cosmic::Action<Message>> {
226        match self.compose_tabs.data::<bool>(chosen).copied() {
227            Some(preview) => self.show_compose_preview(preview),
228            None => Task::none(),
229        }
230    }
231
232    /// Ctrl+P: the other of the two. Nothing, where nothing is being
233    /// written.
234    pub fn handle_toggle_compose_preview(&mut self) -> Task<cosmic::Action<Message>> {
235        match &self.composer {
236            Some(composer) if self.view_state == ViewState::Compose => self.show_compose_preview(composer.preview.is_none()),
237            _ => Task::none(),
238        }
239    }
240
241    /// Show what is written as it would show once out (`preview`), or the
242    /// text again, with the keyboard back in it. A video that played in
243    /// what is not looked at any more is held.
244    fn show_compose_preview(&mut self, preview: bool) -> Task<cosmic::Action<Message>> {
245        let Some(composer) = self.composer.as_mut() else {
246            return Task::none();
247        };
248        if preview {
249            self.compose_tabs.activate_position(PREVIEW_TAB);
250            return self.preview_composed();
251        }
252        composer.preview = None;
253        self.compose_tabs.activate_position(WRITE_TAB);
254        self.videos.pause();
255        focus(COMPOSE_EDITOR_ID.clone())
256    }
257
258    /// Put together how what is in the composer would show, as it is now:
259    /// what [`Self::handle_publish`] would send, read as a row reads a
260    /// note, with what it says of the files attached to it. The note a
261    /// quote is about is at hand; any other that the text names is looked
262    /// for, and so is everyone it mentions.
263    fn preview_composed(&mut self) -> Task<cosmic::Action<Message>> {
264        let Some(author) = self.account.as_ref().map(|account| account.public_key) else {
265            return Task::none();
266        };
267        let Some(composer) = self.composer.as_mut() else {
268            return Task::none();
269        };
270        let text = outgoing(composer);
271        let at_hand: HashMap<EventId, Note> = composer.about.iter().map(|note| (note.id, note.clone())).collect();
272        let note = Note::being_written(&text, &self.media.said_in(&text), author, unix_now()).with_quoted(&at_hand);
273        composer.preview = Some(Preview::of(note.clone()));
274
275        let people = self.look_up_people(note.people().collect());
276        let quoted = match self.nostr.clone() {
277            Some(service) if note.quotes_shown().next().is_some() => {
278                Task::perform(async move { service.quoting(note).await }, |note| {
279                    cosmic::Action::App(Message::ComposePreviewed(note))
280                })
281            }
282            _ => Task::none(),
283        };
284        Task::batch([people, quoted])
285    }
286
287    /// What is in the composer changed while how it would show is looked
288    /// at, and not by being written to: a file attached to it got where it
289    /// was going. It shows as it is now.
290    pub(crate) fn preview_composed_anew(&mut self) -> Task<cosmic::Action<Message>> {
291        match &self.composer {
292            Some(composer) if composer.preview.is_some() => self.preview_composed(),
293            _ => Task::none(),
294        }
295    }
296
297    /// The notes that what is being written quotes were looked for: `note`
298    /// is it with those that were found. Nothing, if it says something
299    /// else by now, or is not looked at any more.
300    pub fn handle_compose_previewed(&mut self, note: Note) -> Task<cosmic::Action<Message>> {
301        let Some(preview) = self.composer.as_mut().and_then(|composer| composer.preview.as_mut()) else {
302            return Task::none();
303        };
304        if !is_the_same_with_more(&preview.note, &note) {
305            return Task::none();
306        }
307        let people = note.people().collect();
308        preview.note = note;
309        self.look_up_people(people)
310    }
311
312    /// Write a new note.
313    pub fn handle_compose_note(&mut self) -> Task<cosmic::Action<Message>> {
314        self.open_composer(Target::Note, None)
315    }
316
317    /// Write a reply to the note `id`, which is one on show.
318    pub fn handle_compose_reply(&mut self, id: EventId) -> Task<cosmic::Action<Message>> {
319        match self.note_at_hand(id) {
320            Some(note) => self.open_composer(Target::Reply(id), Some(note)),
321            None => Task::none(),
322        }
323    }
324
325    /// Write a note that quotes the note `id`, which is one on show.
326    pub fn handle_compose_quote(&mut self, id: EventId) -> Task<cosmic::Action<Message>> {
327        self.repost_menu = None;
328        match self.note_at_hand(id) {
329            Some(note) => self.open_composer(Target::Quote(id), Some(note)),
330            None => Task::none(),
331        }
332    }
333
334    /// Something was typed, selected or moved in the composer. Nothing is,
335    /// while what is there is on its way out.
336    pub fn handle_compose_edited(&mut self, action: Action) {
337        if let Some(composer) = self.composer.as_mut().filter(|composer| !composer.publishing) {
338            if action.is_edit() {
339                composer.error = None;
340                composer.rubbed = Some(Instant::now());
341            }
342            composer.content.perform(action);
343        }
344    }
345
346    /// Backspace was pressed in the composer's text with nothing left in
347    /// it to rub out: leave the composer (see [`Self::handle_abandon_composer`]).
348    /// Not if it is the Backspace that rubbed out the last of the text,
349    /// still held down: that one was rubbing out, and goes on doing
350    /// nothing until it is let go.
351    pub fn handle_composer_rubbed_out(&mut self) -> Task<cosmic::Action<Message>> {
352        let now = Instant::now();
353        match self.composer.as_mut() {
354            Some(composer) if held_from_rubbing_out(composer.rubbed, now) => {
355                composer.rubbed = Some(now);
356                Task::none()
357            }
358            _ => self.handle_abandon_composer(),
359        }
360    }
361
362    /// Backspace was pressed to leave the composer: with nothing in the
363    /// text, or with the keyboard out of the text. With nothing written
364    /// it is left, and there is no draft. With something written, it is
365    /// asked whether that is kept as a draft; and pressed again once that
366    /// is asked, the answer is no (see [`Leaving`]). Nothing, while what
367    /// was written is on its way out.
368    pub fn handle_abandon_composer(&mut self) -> Task<cosmic::Action<Message>> {
369        let Some((target, written, asked)) = self
370            .composer
371            .as_ref()
372            .filter(|composer| !composer.publishing)
373            .map(|composer| (composer.target, !composer.content.text().trim().is_empty(), composer.leaving))
374        else {
375            return Task::none();
376        };
377        let attaching = self.uploads_for(target).next().is_some();
378        match Leaving::on_backspace(written, attaching, asked) {
379            Leaving::Leave => self.handle_close_composer(),
380            Leaving::Discard => self.handle_discard_draft(),
381            Leaving::Ask => {
382                if let Some(composer) = self.composer.as_mut() {
383                    composer.leaving = true;
384                }
385                Task::none()
386            }
387        }
388    }
389
390    /// Leave the composer and keep nothing of what was written: its
391    /// target has no draft any more, here or on the relay of this
392    /// machine, and the files that were on their way to be attached to
393    /// it are called off.
394    pub fn handle_discard_draft(&mut self) -> Task<cosmic::Action<Message>> {
395        let Some(composer) = self.composer.as_mut() else {
396            return Task::none();
397        };
398        composer.content = Content::new();
399        let target = composer.target;
400        let attaching: Vec<u64> = self.uploads_for(target).map(|upload| upload.id).collect();
401        for upload in attaching {
402            self.handle_cancel_upload(upload);
403        }
404        self.handle_close_composer()
405    }
406
407    /// Not leaving the composer after all: the question is put away, and
408    /// the keyboard is back in the text.
409    pub fn handle_resume_composer(&mut self) -> Task<cosmic::Action<Message>> {
410        match self.composer.as_mut() {
411            Some(composer) => {
412                composer.leaving = false;
413                focus(COMPOSE_EDITOR_ID.clone())
414            }
415            None => Task::none(),
416        }
417    }
418
419    /// Keep what is in the composer as its target's draft, and have the
420    /// relay of this machine keep it.
421    pub(crate) fn keep_draft(&mut self) -> Task<cosmic::Action<Message>> {
422        let Some(composer) = &self.composer else {
423            return Task::none();
424        };
425        let (target, text) = (composer.target, composer.content.text());
426        self.drafts.set(target, text);
427        self.send_draft(target)
428    }
429
430    /// Have the relay of this machine keep the draft for `target` as it
431    /// is now, with what it says of the files it links to, unless that is
432    /// how it has it. It takes the account's key: the draft is encrypted
433    /// to the account and signed. Where that can't
434    /// be asked for, the draft of a new note goes to its file.
435    pub(crate) fn send_draft(&mut self, target: Target) -> Task<cosmic::Action<Message>> {
436        let text = self.drafts.get(target).to_string();
437        if self.drafts_kept.get(&target).map_or("", String::as_str) == text {
438            return Task::none();
439        }
440        let account = self.account.as_ref().filter(|account| account.can_sign).map(|account| account.public_key);
441        let (Some(service), Some(account)) = (self.nostr.clone(), account) else {
442            return self.save_note_draft(target);
443        };
444        let (signer, said) = (self.signer.clone(), self.media.said_in(&text));
445        Task::perform(
446            async move {
447                let result = service.keep_draft(&signer, account, target, &text, &said).await;
448                (text, result)
449            },
450            move |(text, result)| cosmic::Action::App(Message::DraftKept { account, target, text, result }),
451        )
452    }
453
454    /// The relay of this machine took `text` as the draft of `account`
455    /// for `target`, or didn't. Taken, the file a new note's draft used
456    /// to be kept in is not needed; not taken, that file is where the
457    /// draft of a new note goes, so that it is there after a restart.
458    pub fn handle_draft_kept(
459        &mut self,
460        account: PublicKey,
461        target: Target,
462        text: String,
463        result: Result<(), String>,
464    ) -> Task<cosmic::Action<Message>> {
465        if self.account.as_ref().map(|account| account.public_key) != Some(account) {
466            return Task::none();
467        }
468        match result {
469            Ok(()) => {
470                if text.trim().is_empty() {
471                    self.drafts_kept.remove(&target);
472                } else {
473                    self.drafts_kept.insert(target, text);
474                }
475                if target == Target::Note {
476                    Task::future(drafts::save(self.draft_path.clone(), String::new())).discard()
477                } else {
478                    Task::none()
479                }
480            }
481            Err(e) => {
482                tracing::warn!("a draft could not be kept on the relay of this machine: {e}");
483                self.save_note_draft(target)
484            }
485        }
486    }
487
488    /// Ask the relay of this machine for the account's drafts, once for
489    /// an account, while the popup is open: reading them takes the key.
490    pub(crate) fn load_drafts(&mut self) -> Task<cosmic::Action<Message>> {
491        if self.popup.is_none() || self.drafts_asked {
492            return Task::none();
493        }
494        let account = self.account.as_ref().filter(|account| account.can_sign).map(|account| account.public_key);
495        let (Some(service), Some(account)) = (self.nostr.clone(), account) else {
496            return Task::none();
497        };
498        self.drafts_asked = true;
499        let signer = self.signer.clone();
500        Task::perform(async move { service.kept_drafts(&signer, account).await }, move |result| {
501            cosmic::Action::App(Message::KeptDraftsLoaded { account, result })
502        })
503    }
504
505    /// The relay of this machine said which drafts of `account` it keeps.
506    /// Whatever has been written since is newer.
507    pub fn handle_kept_drafts_loaded(&mut self, account: PublicKey, result: Result<Vec<(Target, String, Vec<Tag>)>, String>) {
508        if self.account.as_ref().map(|account| account.public_key) != Some(account) {
509            return;
510        }
511        match result {
512            Ok(kept) => {
513                tracing::debug!("{} draft(s) kept on the relay of this machine", kept.len());
514                for (target, text, said) in kept {
515                    // What it says of the files it links to is said
516                    // again when it goes out.
517                    for tag in said {
518                        if let Some(url) = blossom::imeta_url(&tag).map(str::to_string) {
519                            self.media.said.entry(url).or_insert(tag);
520                        }
521                    }
522                    if self.drafts.get(target).is_empty() {
523                        self.drafts.set(target, text.clone());
524                    }
525                    self.drafts_kept.insert(target, text);
526                }
527            }
528            Err(e) => tracing::warn!("the drafts could not be asked of the relay of this machine: {e}"),
529        }
530    }
531
532    /// Forget which drafts the relay of this machine has: the account
533    /// changed, and they were its own.
534    pub(crate) fn reset_kept_drafts(&mut self) {
535        self.drafts_kept.clear();
536        self.drafts_asked = false;
537    }
538
539    /// Write the draft of a new note to its file, if `target` is that: where
540    /// it is kept when the relay of this machine can't be given it.
541    fn save_note_draft(&self, target: Target) -> Task<cosmic::Action<Message>> {
542        if target != Target::Note {
543            return Task::none();
544        }
545        let (path, text) = (self.draft_path.clone(), self.drafts.get(Target::Note).to_string());
546        Task::future(drafts::save(path, text)).discard()
547    }
548
549    /// The draft of a new note was read at startup. Whatever has been
550    /// written since is newer.
551    pub fn handle_draft_loaded(&mut self, text: String) {
552        if self.drafts.get(Target::Note).is_empty() {
553            self.drafts.set(Target::Note, text);
554        }
555    }
556
557    /// Leave the composer for the view it was opened from, keeping what was
558    /// written.
559    pub fn handle_close_composer(&mut self) -> Task<cosmic::Action<Message>> {
560        let kept = self.keep_draft();
561        // A video that played in how it would show has nobody watching.
562        if self.composer.as_ref().is_some_and(|composer| composer.preview.is_some()) {
563            self.videos.pause();
564        }
565        self.composer = None;
566        Task::batch([kept, self.show_list_view()])
567    }
568
569    /// Sign what is in the composer and send it to the relays.
570    pub fn handle_publish(&mut self) -> Task<cosmic::Action<Message>> {
571        let (Some(service), Some(author)) =
572            (self.nostr.clone(), self.account.as_ref().filter(|account| account.can_sign).map(|account| account.public_key))
573        else {
574            return Task::none();
575        };
576        let Some(composer) = self.composer.as_mut().filter(|composer| !composer.publishing) else {
577            return Task::none();
578        };
579        let text = outgoing(composer);
580        let target = composer.target;
581        // Not while something attached to it is still on its way.
582        if text.is_empty() || self.media.uploads.iter().any(|upload| upload.target == target) {
583            return Task::none();
584        }
585        composer.publishing = true;
586        composer.error = None;
587        let answered = composer.about.as_ref().map(|note| note.author);
588        let (signer, said) = (self.signer.clone(), self.media.said_in(&text));
589        Task::perform(publish(service, signer, author, target, answered, text, said), move |result| {
590            cosmic::Action::App(Message::Published { target, result })
591        })
592    }
593
594    /// What was written to `target` went out, or didn't.
595    pub fn handle_published(&mut self, target: Target, result: Result<Note, PublishFailure>) -> Task<cosmic::Action<Message>> {
596        // The composer may have been left, or opened on something else,
597        // while this was on its way.
598        let open = self.composer.as_ref().is_some_and(|composer| composer.target == target);
599        match result {
600            Ok(note) => {
601                // Done with, on the relay of this machine and in the file.
602                self.drafts.set(target, String::new());
603                let saved = Task::batch([self.send_draft(target), self.save_note_draft(target)]);
604                let shown = if open {
605                    self.composer = None;
606                    self.show_list_view()
607                } else {
608                    Task::none()
609                };
610                Task::batch([saved, shown, self.show_published(target, note)])
611            }
612            Err(failure) => {
613                tracing::error!("publishing failed: {failure:?}");
614                let text = publish_failure_text(failure);
615                match self.composer.as_mut().filter(|_| open) {
616                    Some(composer) => {
617                        composer.publishing = false;
618                        composer.error = Some(text);
619                    }
620                    // The text is its target's draft still: say where
621                    // something can be read.
622                    None => self.error_message = Some(text),
623                }
624                Task::none()
625            }
626        }
627    }
628
629    /// Put a note that just went out where it belongs: a new note or a
630    /// quote at the top of the feed, brought into view, with the notes that
631    /// waited; a reply in every open thread that has the note it answers;
632    /// and any of them among its author's notes, wherever their profile is
633    /// open.
634    fn show_published(&mut self, target: Target, note: Note) -> Task<cosmic::Action<Message>> {
635        let mut people = Vec::new();
636        for state in self.profiles_mut().filter(|state| state.public_key == note.author) {
637            people.extend(state.notes.feed.merge([note.clone()]));
638        }
639        match target {
640            // With whatever waited to be shown, at the top of the feed:
641            // nothing that waits is older than what the feed shows.
642            Target::Note | Target::Quote(_) => {
643                self.following.pending.add(note);
644                let shown = self.show_new_notes(self.following.id);
645                Task::batch([shown, self.look_up_people(people)])
646            }
647            Target::Reply(parent) => {
648                for state in self.threads_mut().filter(|state| state.thread.contains(parent)) {
649                    people.extend(state.thread.merge([note.clone()]));
650                }
651                // The note answered has one more answer, wherever it shows.
652                if let Some(engagement) = self.engagement.get_mut(&parent) {
653                    engagement.replies += 1;
654                }
655                Task::batch([self.look_up_people(people), self.look_up_engagement([note.id])])
656            }
657        }
658    }
659}
660
661#[cfg(test)]
662mod tests {
663    use super::{Leaving, RUBBING_OUT, held_from_rubbing_out, is_the_same_with_more, outgoing};
664    use crate::nostr::compose::Target;
665    use crate::nostr::models::Note;
666    use crate::state::Composer;
667    use cosmic::widget::text_editor::Content;
668    use nostr_sdk::prelude::{EventId, Keys};
669    use std::collections::HashMap;
670    use std::time::{Duration, Instant};
671
672    /// A composer on `target`, about `about`, with `text` in it.
673    fn composer(target: Target, about: Option<Note>, text: &str) -> Composer {
674        Composer {
675            target,
676            about,
677            content: Content::with_text(text),
678            publishing: false,
679            error: None,
680            leaving: false,
681            rubbed: None,
682            preview: None,
683        }
684    }
685
686    #[test]
687    fn what_goes_out_is_the_text_without_the_space_around_it_and_a_quote_names_its_note() {
688        let me = Keys::generate().public_key();
689        assert_eq!(outgoing(&composer(Target::Note, None, "\n  gm\n\n")), "gm");
690
691        let quoted = Note { id: EventId::from_byte_array([3; 32]), ..Note::being_written("gn", &[], me, 0) };
692        let said = outgoing(&composer(Target::Quote(quoted.id), Some(quoted.clone()), "this "));
693        let (text, address) = said.split_once('\n').expect("the address is on a line of its own");
694        assert_eq!(text, "this");
695        assert!(address.starts_with("nostr:nevent1"), "{address}");
696        // With nothing said about it, the address is all there is.
697        assert!(outgoing(&composer(Target::Quote(quoted.id), Some(quoted.clone()), "")).starts_with("nostr:nevent1"));
698        // What a reply answers is in its tags, not in what it says.
699        assert_eq!(outgoing(&composer(Target::Reply(quoted.id), Some(quoted), "gn to you")), "gn to you");
700    }
701
702    #[test]
703    fn what_is_looked_at_takes_the_notes_found_for_it_only_while_it_says_the_same() {
704        let me = Keys::generate().public_key();
705        let quoted = Note { id: EventId::from_byte_array([3; 32]), ..Note::being_written("gn", &[], me, 0) };
706        let said = outgoing(&composer(Target::Quote(quoted.id), Some(quoted.clone()), "this"));
707        let shown = Note::being_written(&said, &[], me, 0);
708        let found = shown.clone().with_quoted(&HashMap::from([(quoted.id, quoted)]));
709        assert_eq!(found.quoted_count(), 1);
710
711        assert!(is_the_same_with_more(&shown, &found), "the note it quotes was found");
712        assert!(is_the_same_with_more(&found, &found), "found again, the same");
713        assert!(!is_the_same_with_more(&found, &shown), "what is at hand is not given up for less");
714        // It was written to meanwhile: what was found is of what it said.
715        let changed = Note::being_written(&format!("{said} too"), &[], me, 0);
716        assert!(!is_the_same_with_more(&changed, &found));
717    }
718
719    #[test]
720    fn backspace_leaves_an_empty_composer_and_asks_before_leaving_one_with_something_in_it() {
721        // Nothing written, nothing on its way: there is nothing to keep.
722        assert_eq!(Leaving::on_backspace(false, false, false), Leaving::Leave);
723        // Something written, or a file on its way to be attached: asked.
724        assert_eq!(Leaving::on_backspace(true, false, false), Leaving::Ask);
725        assert_eq!(Leaving::on_backspace(false, true, false), Leaving::Ask);
726        assert_eq!(Leaving::on_backspace(true, true, false), Leaving::Ask);
727        // Once asked, Backspace is the answer that keeps nothing.
728        assert_eq!(Leaving::on_backspace(true, false, true), Leaving::Discard);
729        assert_eq!(Leaving::on_backspace(false, true, true), Leaving::Discard);
730    }
731
732    #[test]
733    fn a_backspace_held_down_to_rub_the_text_out_is_not_one_that_leaves() {
734        let now = Instant::now() + Duration::from_secs(60);
735        // Nothing was rubbed out: the composer was only just opened.
736        assert!(!held_from_rubbing_out(None, now));
737        // The text was changed a repeat of a held key ago: still held.
738        assert!(held_from_rubbing_out(Some(now - Duration::from_millis(40)), now));
739        assert!(held_from_rubbing_out(Some(now), now));
740        // Changed a while ago: this press is one made on purpose.
741        assert!(!held_from_rubbing_out(Some(now - RUBBING_OUT), now));
742        assert!(!held_from_rubbing_out(Some(now - Duration::from_secs(5)), now));
743        // A clock that reads earlier than it did costs nothing.
744        assert!(held_from_rubbing_out(Some(now + Duration::from_millis(10)), now));
745    }
746}