Skip to main content

cosmic_applet_avestruz/handlers/
keys.rs

1// SPDX-License-Identifier: MIT
2
3//! The keyboard, on a list: stepping through its rows, opening the one
4//! the keyboard is at, showing the notes that wait, and going back.
5//!
6//! | Key | What it does |
7//! |---|---|
8//! | `j` | The next row: marked, and put at the top of what is in view |
9//! | `k` | The one before |
10//! | Home | The very top, and no row marked |
11//! | `l`, Enter | Open the marked row: a note's thread; for something told of with no note to it, whose it is |
12//! | `y` | Copy a link to the marked note that anyone can open, as the chain link under it does |
13//! | Space | The first thing the marked note links to, pictures apart: a video is played, or held if it plays; any other link is opened in the browser |
14//! | `h`, Backspace | Back: what the arrow at the top left of the view does |
15//! | Backspace | Out of the composer too, where `h` is a letter: with something written, it asks first whether to keep it as a draft (see [`crate::handlers::compose`]) |
16//! | `r` | Reply to the marked note, as the arrow under it does |
17//! | `R` | Offer the ways to pass the marked note on, as its repost action does: see below |
18//! | `z` | Zap the marked note, as the bolt under it does |
19//! | `b` | Bookmark the marked note, or take its bookmark off, as the ribbon under it does |
20//! | `B` | Show the bookmarks, over the list on show |
21//! | `s` | Show a page to search on, with the keyboard where the search is typed; on one already, only that |
22//! | `.` | Show the notes that wait, as the button over the list does |
23//! | `?` | Show what the keys do: a view of its own, which the menu above the feed opens too |
24//!
25//! The keys are a list's where no widget had a use for them: a text being
26//! typed takes them for itself (see [`crate::app`]). They work on
27//! whichever list is on show: the feed, a thread, the notes of a
28//! profile, the bookmarks, the notes a search found, what the account is
29//! told of.
30//!
31//! A row can be put at the top of what is in view only while there is
32//! enough under it: the last rows of a list can't be, and in a thread
33//! that fits the popup none can. So where the keyboard is does not go by
34//! where the list is scrolled to alone. The row it is at is **marked**,
35//! with a line around it, and each list keeps its own mark: coming back
36//! from a thread, the note it was opened from is marked still, and `j`
37//! goes on from there.
38//!
39//! ```mermaid
40//! flowchart TD
41//!     key["j or k"] --> live{"Is a row marked, and about where the view is?"}
42//!     live -->|"yes"| beside["The row after it, or before"]
43//!     live -->|"no: nothing marked, or the list was scrolled away from it"| place["The first row below the top of the view, or the last above it"]
44//!     beside --> mark["That row is marked, and the list scrolled to put it at the top, as far as it goes"]
45//!     place --> mark
46//!     open["l, Enter, y, Space or b"] --> which{"Is a row marked, and about where the view is?"}
47//!     which -->|"yes"| opened["It is that row: opened, its link copied, its video played or its link followed, bookmarked"]
48//!     which -->|"no"| top["The row at the top of the view is marked, and it is that one"]
49//! ```
50//!
51//! While the menu `R` opens is open, the keys are the menu's, and the
52//! keyboard is at one of the ways it offers, which is shown as one the
53//! pointer is over: the first that can be taken, to begin with.
54//!
55//! ```mermaid
56//! flowchart TD
57//!     r["R, on a list"] --> menu["The marked note's repost menu opens, the keyboard at the first way that can be taken"]
58//!     menu --> arrows["Arrow down or j, arrow up or k: the next way, or the one before"]
59//!     arrows --> menu
60//!     menu --> enter["Enter or l: that way is taken, and the menu is put away"]
61//!     menu --> away["R again, or Escape: the menu is put away, and nothing done"]
62//! ```
63//!
64//! A mark the list was scrolled away from is not gone back to: a key
65//! then goes by what is in view, as it does with nothing marked.
66
67use cosmic::prelude::*;
68use nostr_sdk::prelude::{EventId, PublicKey};
69
70use crate::handlers::navigation::scroll_list_to;
71use crate::messages::Message;
72use crate::nostr::engagement::Mark;
73use crate::nostr::models::Note;
74use crate::nostr::outbox::Whereabouts;
75use crate::nostr::search::SearchFor;
76use crate::nostr::thread::ThreadRow;
77use crate::previews::PreviewState;
78use crate::state::{AppModel, Expanded, FeedState, Page, Passing, RepostMenu, Step, ViewState};
79use crate::views::components::{RowHeights, RowSizes, estimated_note_height, estimated_notification_height};
80use crate::views::search::search_input_id;
81use crate::views::thread::estimated_row_height;
82
83/// How near, in points, the top of a row may be to the top of what is in
84/// view and be the row that is there: where a list is scrolled to is not
85/// kept to the last fraction.
86const AT_THE_TOP: f32 = 1.0;
87
88/// How much of a row has to show at the top of what is in view, in
89/// points, for it to be the row that is there, when none is marked: a
90/// row of which only the last line is left is on its way out, and the one
91/// under it is what is being looked at.
92const SHOWING: f32 = 40.0;
93
94/// What opening a row leads to.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96enum Leads {
97    /// The thread of this note.
98    Thread(EventId),
99    /// The profile of this person.
100    Profile(PublicKey),
101}
102
103/// A row of the list on show, or something above its rows that is a
104/// place to step to as a row is.
105#[derive(Debug, Clone, Copy, PartialEq)]
106struct Row {
107    /// What the row is told apart by, and marked by. `None` for what is
108    /// no row of the list.
109    key: Option<EventId>,
110    /// How far down what the scroller holds it starts.
111    start: f32,
112    /// What opening it leads to, if anything.
113    leads: Option<Leads>,
114    /// The note it shows, with its actions under it, if it shows one.
115    note: Option<EventId>,
116}
117
118impl Row {
119    /// The row of a note that starts at `start`, which opens its thread.
120    fn of_note(note: EventId, start: f32) -> Self {
121        Self { key: Some(note), start, leads: Some(Leads::Thread(note)), note: Some(note) }
122    }
123}
124
125/// The list on show, as the keyboard goes by it.
126struct Rows {
127    /// Its rows, from the top.
128    rows: Vec<Row>,
129    /// How far it is scrolled.
130    here: f32,
131    /// The row the keyboard was last at, if it was at any.
132    marked: Option<EventId>,
133}
134
135/// Where the keyboard is among `rows`: the row `marked`, if it is one of
136/// them and about where the list, scrolled to `here`, shows `view` points
137/// of itself. `None` with nothing marked, and with a mark the list was
138/// scrolled away from: one whose row starts above what is in view, or
139/// below it.
140fn marked_row(rows: &[Row], marked: Option<EventId>, here: f32, view: f32) -> Option<usize> {
141    let marked = marked?;
142    let at = rows.iter().position(|row| row.key == Some(marked))?;
143    let start = rows.get(at)?.start;
144    (start >= here - AT_THE_TOP && start <= here + view).then_some(at)
145}
146
147/// The row at the top of what is in view, in a list scrolled to `here`:
148/// the last that starts above where [`SHOWING`] of it would still show.
149fn row_at_top(rows: &[Row], here: f32) -> Option<usize> {
150    rows.iter().rposition(|row| row.start <= here + SHOWING)
151}
152
153/// Which of `rows` a step lands on, and where the list is scrolled to to
154/// have it at the top of what is in view. `None` if there is nowhere to
155/// go: the keyboard is at the first row, or the last.
156///
157/// From the row the keyboard is `at`, it is the one after it or before.
158/// With no such row it goes by where the list is scrolled to, `here`: the
159/// first row below the top of what is in view, or the last one above it.
160/// To the top is to where the list starts, with nothing marked.
161fn stepped(rows: &[Row], here: f32, at: Option<usize>, step: Step) -> Option<(Option<usize>, f32)> {
162    let to = match (step, at) {
163        (Step::Top, _) => return (here > AT_THE_TOP || at.is_some()).then_some((None, 0.0)),
164        (Step::Next, Some(at)) => at + 1,
165        (Step::Next, None) => rows.iter().position(|row| row.start > here + AT_THE_TOP)?,
166        (Step::Previous, Some(at)) => at.checked_sub(1)?,
167        (Step::Previous, None) => rows.iter().rposition(|row| row.start < here - AT_THE_TOP)?,
168    };
169    rows.get(to).map(|row| (Some(to), row.start))
170}
171
172/// Which of `ways`, the ways a menu offers that can be taken, the
173/// keyboard is at after a step from `at`: the next, or the one before,
174/// and no further than the first or the last. From none of them, the
175/// first, or the last if the step is back.
176fn stepped_way(ways: &[Passing], at: Option<Passing>, step: Step) -> Option<Passing> {
177    let place = at.and_then(|at| ways.iter().position(|way| *way == at));
178    let to = match (place, step) {
179        (_, Step::Top) | (None, Step::Next) => 0,
180        (None, Step::Previous) => ways.len().saturating_sub(1),
181        (Some(place), Step::Next) => (place + 1).min(ways.len().saturating_sub(1)),
182        (Some(place), Step::Previous) => place.saturating_sub(1),
183    };
184    ways.get(to).copied()
185}
186
187/// What Space does to a note.
188#[derive(Debug, PartialEq, Eq)]
189enum Pressed {
190    /// Play the video at this address, or hold it if it plays.
191    Play(String),
192    /// Open this address in the browser.
193    Open(String),
194}
195
196/// What Space does to `note`. It is for the first thing the note links
197/// to that is not a picture, which is shown where it is and has no use
198/// for a key. A video is played, and so is a page that `is_video` says
199/// turned out to be one; anything else is opened in the browser, as a
200/// click on the link does. Nothing, of a note that links to nothing.
201fn pressed(note: &Note, is_video: impl Fn(&str) -> bool) -> Option<Pressed> {
202    let first = note.content.first_link.as_ref()?;
203    let video = note.content.videos.iter().any(|video| video.url == *first) || is_video(first);
204    Some(if video { Pressed::Play(first.clone()) } else { Pressed::Open(first.clone()) })
205}
206
207/// The rows of a page whose list is `top` down the page, under something
208/// else: that, at the very top, is a place to step to as a row is, though
209/// it is none to mark or open, and the rows of the list follow it.
210fn under(top: f32, rows: Vec<Row>) -> Vec<Row> {
211    let above = Row { key: None, start: 0.0, leads: None, note: None };
212    std::iter::once(above).chain(rows.into_iter().map(|row| Row { start: top + row.start, ..row })).collect()
213}
214
215impl AppModel {
216    /// Whether the keys are a list's now: the popup is open, and no menu
217    /// is open over what it shows.
218    fn keys_are_the_lists(&self) -> bool {
219        let over_the_list =
220            self.menu_open || self.repost_menu.is_some() || self.reaction_menu.is_some() || self.who_menu.is_some();
221        self.popup.is_some() && !over_the_list
222    }
223
224    /// The list on show, as the keyboard goes by it: where its rows
225    /// start, from the top of what its scroller holds, what each leads
226    /// to, how far it is scrolled, and which row is marked. `None` where
227    /// what is on show is no list.
228    ///
229    /// A row is as tall as it measured, or as its estimate until it has
230    /// been in view: the same heights, by the same estimate, as the list
231    /// is laid out with (see [`RowHeights::starts`]).
232    fn rows_at_the_keys(&self) -> Option<Rows> {
233        let sizes = RowSizes::new(self.config.note_text_size());
234        let notes = |notes: &[Note], heights: &RowHeights<EventId>, expanded: &Expanded| -> Vec<Row> {
235            let starts = heights.starts(
236                notes,
237                |note: &Note| note.id,
238                |note, width| estimated_note_height(note, sizes, width, expanded.has(&note.id)),
239            );
240            notes.iter().zip(starts).map(|(note, start)| Row::of_note(note.id, start)).collect()
241        };
242        let feed = |state: &FeedState| notes(state.feed.notes(self.config.feed_mode), &state.heights, &state.expanded);
243        match self.view_state {
244            ViewState::Feed => {
245                let state = &self.following;
246                Some(Rows { rows: feed(state), here: state.position.get(), marked: state.marked })
247            }
248            ViewState::Page => Some(match self.pages.last()? {
249                Page::Thread(state) => {
250                    let listed = state.thread.rows();
251                    let starts = state.heights.starts(
252                        listed,
253                        |row: &ThreadRow| row.note.id,
254                        |row, width| estimated_row_height(row, sizes, width, &state.expanded),
255                    );
256                    // The note the thread is for leads nowhere: it is here.
257                    let focused = state.thread.focused();
258                    let leads = |note: EventId| (note != focused).then_some(Leads::Thread(note));
259                    let rows = listed.iter().zip(starts);
260                    let rows = rows.map(|(row, start)| Row { leads: leads(row.note.id), ..Row::of_note(row.note.id, start) });
261                    Rows { rows: rows.collect(), here: state.position.get(), marked: state.marked }
262                }
263                // Who they are is above their notes, in the same scroller.
264                Page::Profile(state) => Rows {
265                    rows: under(state.notes_top.get(), feed(&state.notes)),
266                    here: state.notes.position.get(),
267                    marked: state.notes.marked,
268                },
269                Page::Bookmarks(page) => {
270                    let listed = &page.notes;
271                    Rows {
272                        rows: notes(&listed.notes, &listed.heights, &listed.expanded),
273                        here: listed.position.get(),
274                        marked: listed.marked,
275                    }
276                }
277                Page::Search(page) => match page.what {
278                    SearchFor::Notes => Rows {
279                        rows: notes(&page.notes, &page.heights, &page.expanded),
280                        here: page.notes_position.get(),
281                        marked: page.marked,
282                    },
283                    // The people found are not rows that were measured:
284                    // there is the top to go to, and no more.
285                    SearchFor::People => Rows { rows: Vec::new(), here: page.people_position.get(), marked: None },
286                },
287                Page::Notifications(page) => {
288                    let told = &self.notifications.list;
289                    let listed = told.listed(self.notifications_tab());
290                    let starts = page.heights.starts(
291                        listed,
292                        // A place that holds nothing has no row, as in the view.
293                        |place: &usize| {
294                            told.get(*place).map_or(EventId::from_byte_array([0; 32]), |notification| notification.id)
295                        },
296                        |place, width| {
297                            told.get(*place).map_or(0.0, |notification| {
298                                estimated_notification_height(notification, sizes, width, page.expanded.has(&notification.id))
299                            })
300                        },
301                    );
302                    let rows = listed.iter().zip(starts).map(|(place, start)| match told.get(*place) {
303                        // As a click on it leads: to the note it is
304                        // about, or to whose doing it is.
305                        Some(notification) => Row {
306                            key: Some(notification.id),
307                            start,
308                            leads: Some(notification.about.map_or(Leads::Profile(notification.who), Leads::Thread)),
309                            note: notification.note.as_ref().map(|note| note.id),
310                        },
311                        None => Row { key: None, start, leads: None, note: None },
312                    });
313                    Rows { rows: rows.collect(), here: page.position.get(), marked: page.marked }
314                }
315            }),
316            _ => None,
317        }
318    }
319
320    /// Where the list on show keeps which of its rows is marked. `None`
321    /// where what is on show is no list.
322    fn mark_on_show(&mut self) -> Option<&mut Option<EventId>> {
323        match self.view_state {
324            ViewState::Feed => Some(&mut self.following.marked),
325            ViewState::Page => Some(match self.pages.last_mut()? {
326                Page::Thread(state) => &mut state.marked,
327                Page::Profile(state) => &mut state.notes.marked,
328                Page::Bookmarks(page) => &mut page.notes.marked,
329                Page::Search(page) => &mut page.marked,
330                Page::Notifications(page) => &mut page.marked,
331            }),
332            _ => None,
333        }
334    }
335
336    /// `j`, `k` or Home was pressed: with a list on show, and nothing
337    /// over it, the next row, the one before, or the very top goes to the
338    /// top of what is in view, as far as the list scrolls, and the row is
339    /// marked (see the [module](self)). Anywhere else the keys mean
340    /// nothing.
341    ///
342    /// On a profile, who they are is the first place: `k` from their
343    /// first note goes there, and `j` from there to their first note.
344    ///
345    /// A row below is where the heights of those above it put it, and
346    /// those have all been in view, coming down from the top: it lands
347    /// exactly. After a jump over rows never shown, a row above may be
348    /// off by what its estimate was, as scrolling up to it would be.
349    pub fn handle_step_note(&mut self, step: Step) -> Task<cosmic::Action<Message>> {
350        // With the repost menu open, the keys are the menu's.
351        if self.repost_menu.is_some() {
352            return self.handle_step_choice(step);
353        }
354        if !self.keys_are_the_lists() {
355            return Task::none();
356        }
357        let Some(Rows { rows, here, marked }) = self.rows_at_the_keys() else {
358            return Task::none();
359        };
360        let at = marked_row(&rows, marked, here, self.popup_max_height());
361        let Some((to, start)) = stepped(&rows, here, at, step) else {
362            return Task::none();
363        };
364        if let Some(mark) = self.mark_on_show() {
365            *mark = to.and_then(|to| rows.get(to)).and_then(|row| row.key);
366        }
367        scroll_list_to(start)
368    }
369
370    /// The row the keyboard is at, for a key that does something to it.
371    /// With no row marked where the view is, that is the row at the top
372    /// of what is in view, which is marked: it is where the keyboard is
373    /// from then on, and when the list is come back to. `None` where the
374    /// keys are not a list's, or the list has no row there.
375    fn row_at_the_keys(&mut self) -> Option<Row> {
376        if !self.keys_are_the_lists() {
377            return None;
378        }
379        let Rows { rows, here, marked } = self.rows_at_the_keys()?;
380        let at = marked_row(&rows, marked, here, self.popup_max_height()).or_else(|| row_at_top(&rows, here))?;
381        let row = *rows.get(at)?;
382        if let (Some(mark), Some(key)) = (self.mark_on_show(), row.key) {
383            *mark = Some(key);
384        }
385        Some(row)
386    }
387
388    /// `l` or Enter was pressed: open the row the keyboard is at (see
389    /// [`Self::row_at_the_keys`]), as a click on it does.
390    pub fn handle_open_marked(&mut self) -> Task<cosmic::Action<Message>> {
391        // With the repost menu open, the key takes what the keyboard is
392        // at in it.
393        if let Some(menu) = self.repost_menu.filter(|_| self.popup.is_some()) {
394            return match menu.at {
395                Some(Passing::Repost) => self.handle_mark(menu.note, Mark::Repost),
396                Some(Passing::Quote) => self.handle_compose_quote(menu.note),
397                None => Task::none(),
398            };
399        }
400        // Asked whether what was written is kept as a draft, the key
401        // says yes: the composer is left as its arrow leaves it.
402        let asked = self.view_state == ViewState::Compose && self.composer.as_ref().is_some_and(|composer| composer.leaving);
403        if asked && self.popup.is_some() {
404            return self.handle_close_composer();
405        }
406        match self.row_at_the_keys().and_then(|row| row.leads) {
407            Some(Leads::Thread(note)) => self.handle_open_thread(note, Whereabouts::default()),
408            Some(Leads::Profile(person)) => self.handle_open_profile(person),
409            None => Task::none(),
410        }
411    }
412
413    /// `y` was pressed: copy a link to the note the keyboard is at that
414    /// anyone can open, as the chain link under it does.
415    pub fn handle_share_marked(&mut self) -> Task<cosmic::Action<Message>> {
416        match self.row_at_the_keys().and_then(|row| row.note) {
417            Some(note) => self.handle_copy_share_link(note),
418            None => Task::none(),
419        }
420    }
421
422    /// Space was pressed: it is for the first thing the note the keyboard
423    /// is at links to, pictures apart (see [`pressed`]). A video is
424    /// played, or held if it plays, as a press of its play button does;
425    /// any other link is opened in the browser, as a click on it does.
426    pub fn handle_play_marked(&mut self) -> Task<cosmic::Action<Message>> {
427        let note = self.row_at_the_keys().and_then(|row| row.note).and_then(|note| self.note_at_hand(note));
428        let pressed = note.as_ref().and_then(|note| {
429            pressed(note, |page| self.videos.opened.contains(page) || matches!(self.previews.get(page), PreviewState::Video))
430        });
431        match pressed {
432            Some(Pressed::Play(url)) => self.handle_video_press(url),
433            Some(Pressed::Open(url)) => {
434                self.handle_open_url(&url);
435                Task::none()
436            }
437            None => Task::none(),
438        }
439    }
440
441    /// `r` was pressed: reply to the note the keyboard is at, as the
442    /// arrow under it does. Not by an account that can't publish.
443    pub fn handle_reply_marked(&mut self) -> Task<cosmic::Action<Message>> {
444        match self.row_at_the_keys().and_then(|row| row.note) {
445            Some(note) => self.handle_compose_reply(note),
446            None => Task::none(),
447        }
448    }
449
450    /// `z` was pressed: zap the note the keyboard is at, as the bolt
451    /// under it does. Nothing, if its author has nowhere to be zapped.
452    pub fn handle_zap_marked(&mut self) -> Task<cosmic::Action<Message>> {
453        match self.row_at_the_keys().and_then(|row| row.note) {
454            Some(note) => self.handle_zap_note(note),
455            None => Task::none(),
456        }
457    }
458
459    /// `R` was pressed: offer the ways to pass on the note the keyboard
460    /// is at, as its repost action does, with the keyboard at the first
461    /// that can be taken; or put the offer away, if it is showing. Not
462    /// to an account that can't publish.
463    pub fn handle_repost_marked(&mut self) -> Task<cosmic::Action<Message>> {
464        if self.repost_menu.take().is_some() || !self.can_publish() {
465            return Task::none();
466        }
467        if let Some(note) = self.row_at_the_keys().and_then(|row| row.note) {
468            let reposted = self.engagement.get(&note).is_some_and(|engagement| engagement.reposted);
469            self.reaction_menu = None;
470            self.repost_menu = Some(RepostMenu { note, at: Passing::open_to(reposted).first().copied() });
471        }
472        Task::none()
473    }
474
475    /// An arrow up or down was pressed, or `j` or `k` with the repost
476    /// menu open: the keyboard goes to the next of the ways the menu
477    /// offers, or the one before. Nothing, with no such menu open.
478    pub fn handle_step_choice(&mut self, step: Step) -> Task<cosmic::Action<Message>> {
479        if let Some(menu) = self.repost_menu.filter(|_| self.popup.is_some()) {
480            let reposted = self.engagement.get(&menu.note).is_some_and(|engagement| engagement.reposted);
481            self.repost_menu = Some(RepostMenu { at: stepped_way(Passing::open_to(reposted), menu.at, step), ..menu });
482        }
483        Task::none()
484    }
485
486    /// `b` was pressed: bookmark the note the keyboard is at, or take its
487    /// bookmark off if it has one, as the ribbon under it does.
488    pub fn handle_bookmark_marked(&mut self) -> Task<cosmic::Action<Message>> {
489        match self.row_at_the_keys().and_then(|row| row.note) {
490            Some(note) => self.handle_bookmark(note),
491            None => Task::none(),
492        }
493    }
494
495    /// Whether a list is on show for the keys that go elsewhere from one:
496    /// the feed, or a page opened over it. Not the composer or a zap,
497    /// which a stray key would put away, nor where nobody is signed in.
498    fn keys_go_elsewhere(&self) -> bool {
499        self.keys_are_the_lists() && matches!(self.view_state, ViewState::Feed | ViewState::Page)
500    }
501
502    /// `B` was pressed: show the bookmarks, as the menu does. Not over
503    /// the bookmarks themselves: one way back is enough.
504    pub fn handle_go_to_bookmarks(&mut self) -> Task<cosmic::Action<Message>> {
505        let there = self.view_state == ViewState::Page && matches!(self.pages.last(), Some(Page::Bookmarks(_)));
506        if !self.keys_go_elsewhere() || there {
507            return Task::none();
508        }
509        self.handle_open_bookmarks()
510    }
511
512    /// `s` was pressed: show a page to search on, as the magnifying glass
513    /// above the feed does, with the keyboard in the place to type in.
514    /// Over one already, the keyboard is put there and no other is
515    /// opened.
516    pub fn handle_go_to_search(&mut self) -> Task<cosmic::Action<Message>> {
517        if !self.keys_go_elsewhere() {
518            return Task::none();
519        }
520        match self.pages.last() {
521            Some(Page::Search(_)) if self.view_state == ViewState::Page => cosmic::widget::text_input::focus(search_input_id()),
522            _ => self.handle_open_search(),
523        }
524    }
525
526    /// `?` was pressed: show what the keys do, in the view that says so.
527    pub fn handle_show_keys(&mut self) -> Task<cosmic::Action<Message>> {
528        if self.keys_go_elsewhere() {
529            self.handle_open_keys();
530        }
531        Task::none()
532    }
533
534    /// `.` was pressed: show the notes that wait for the list on show, as
535    /// the button over it does. They are at its top, which is where it
536    /// goes, and no row is marked.
537    pub fn handle_show_waiting(&mut self) -> Task<cosmic::Action<Message>> {
538        if !self.keys_are_the_lists() {
539            return Task::none();
540        }
541        let state = match self.view_state {
542            ViewState::Feed => Some(&mut self.following),
543            ViewState::Page => match self.pages.last_mut() {
544                Some(Page::Profile(state)) => Some(&mut state.notes),
545                _ => None,
546            },
547            _ => None,
548        };
549        let Some(state) = state.filter(|state| !state.pending.is_empty()) else {
550            return Task::none();
551        };
552        state.marked = None;
553        let id = state.id;
554        self.show_new_notes(id)
555    }
556
557    /// Backspace was pressed, or is `held` down: go back, as `h` does;
558    /// and out of the composer too, which `h` is not, since Backspace
559    /// asks before anything written is lost (see
560    /// [`Self::handle_abandon_composer`]). Not out of the composer while
561    /// it is held: one press, one answer.
562    pub fn handle_backspace(&mut self, held: bool) -> Task<cosmic::Action<Message>> {
563        match self.view_state {
564            ViewState::Compose if !self.keys_are_the_lists() || held => Task::none(),
565            ViewState::Compose => self.handle_abandon_composer(),
566            _ => self.handle_go_back(),
567        }
568    }
569
570    /// `h` was pressed, or Backspace: go back, as the arrow at the top
571    /// left of the view on show does. Not out of the composer: an `h`
572    /// that was meant for its text, pressed when the keyboard was not in
573    /// it, would put it away. Backspace leaves it, in a way of its own
574    /// (see [`Self::handle_backspace`]).
575    pub fn handle_go_back(&mut self) -> Task<cosmic::Action<Message>> {
576        if !self.keys_are_the_lists() {
577            return Task::none();
578        }
579        match self.view_state {
580            ViewState::Page => self.handle_close_page(),
581            ViewState::Settings | ViewState::Relays | ViewState::Keys => self.show_list_view(),
582            ViewState::Media => self.handle_close_media(),
583            ViewState::Zap => self.handle_close_zap(),
584            ViewState::Feed | ViewState::Login | ViewState::Compose => Task::none(),
585        }
586    }
587}
588
589#[cfg(test)]
590mod tests {
591    use super::{Leads, Pressed, Row, marked_row, pressed, row_at_top, stepped, stepped_way, under};
592    use crate::nostr::content::{self, FEED_NOTE_MAX_CHARS};
593    use crate::nostr::models::Note;
594    use crate::state::{Passing, Step};
595    use nostr_sdk::prelude::{EventId, Keys, Kind};
596
597    /// A note that says `said`.
598    fn note(said: &str) -> Note {
599        Note {
600            id: id(7),
601            kind: Kind::TextNote,
602            author: Keys::generate().public_key(),
603            created_at: 0,
604            content: content::parse(said, FEED_NOTE_MAX_CHARS),
605            reply_to: None,
606            quoted: Vec::new(),
607        }
608    }
609
610    #[test]
611    fn the_keyboard_goes_through_the_ways_a_repost_menu_offers_and_no_further() {
612        use Passing::{Quote, Repost};
613        let both = Passing::open_to(false);
614        assert_eq!(both, [Repost, Quote]);
615        // It opens at the first; down and up go between them, and stop
616        // at either end.
617        assert_eq!(stepped_way(both, Some(Repost), Step::Next), Some(Quote));
618        assert_eq!(stepped_way(both, Some(Quote), Step::Next), Some(Quote));
619        assert_eq!(stepped_way(both, Some(Quote), Step::Previous), Some(Repost));
620        assert_eq!(stepped_way(both, Some(Repost), Step::Previous), Some(Repost));
621        assert_eq!(stepped_way(both, Some(Quote), Step::Top), Some(Repost));
622        // A menu a click opened has the keyboard at nothing: down comes
623        // to the first, and up to the last.
624        assert_eq!(stepped_way(both, None, Step::Next), Some(Repost));
625        assert_eq!(stepped_way(both, None, Step::Previous), Some(Quote));
626
627        // A note that was reposted can only be quoted: the keyboard is
628        // never at what can't be taken.
629        let quote_only = Passing::open_to(true);
630        assert_eq!(quote_only, [Quote]);
631        assert_eq!(stepped_way(quote_only, Some(Quote), Step::Previous), Some(Quote));
632        assert_eq!(stepped_way(quote_only, Some(Repost), Step::Next), Some(Quote));
633        assert_eq!(stepped_way(&[], None, Step::Next), None);
634    }
635
636    #[test]
637    fn space_plays_a_note_whose_first_link_is_a_video_and_opens_any_other_first_link() {
638        let (video, other) = ("https://cdn.example.com/one.mp4", "https://cdn.example.com/two.mp4");
639        let (page, picture) = ("https://example.com/watch/this", "https://example.com/a/picture.jpg");
640        let play = |url: &str| Some(Pressed::Play(url.to_string()));
641        let open = |url: &str| Some(Pressed::Open(url.to_string()));
642
643        // The first of its videos, whatever comes after it.
644        assert_eq!(pressed(&note(&format!("watch {video} and {other} and {page}")), |_| false), play(video));
645        // A link first: it is followed, though a video comes after.
646        assert_eq!(pressed(&note(&format!("read {page} then watch {video}")), |_| false), open(page));
647        // A picture is not what the key is for, wherever it stands.
648        assert_eq!(pressed(&note(&format!("{picture} then watch {video}")), |_| false), play(video));
649        assert_eq!(pressed(&note(&format!("{picture} and read {page}")), |_| false), open(page));
650
651        // A link that does not say what it is: played, if it turned out
652        // to be a video, and followed if not.
653        assert_eq!(pressed(&note(&format!("see {page}")), |_| true), play(page));
654        assert_eq!(pressed(&note(&format!("see {page}")), |_| false), open(page));
655        // A YouTube link is a video from the start.
656        let youtube = "https://youtu.be/aqz-KE-bpKQ";
657        assert_eq!(pressed(&note(&format!("{youtube} and {page}")), |_| false), play(youtube));
658
659        // Nothing linked to but pictures, or nothing at all: nothing done.
660        assert_eq!(pressed(&note(&format!("only words, and {picture}")), |_| true), None);
661        assert_eq!(pressed(&note("only words"), |_| true), None);
662    }
663
664    fn id(byte: u8) -> EventId {
665        EventId::from_byte_array([byte; 32])
666    }
667
668    /// Rows of notes that start at `starts`, the first of them note 1.
669    fn rows(starts: &[f32]) -> Vec<Row> {
670        starts.iter().enumerate().map(|(nth, start)| Row::of_note(id(nth as u8 + 1), *start)).collect()
671    }
672
673    /// Where a step from `here` leads with no row marked: where the list
674    /// is scrolled to.
675    fn scrolled(rows: &[Row], here: f32, step: Step) -> Option<f32> {
676        stepped(rows, here, None, step).map(|(_, start)| start)
677    }
678
679    #[test]
680    fn a_step_puts_the_next_note_or_the_one_before_at_the_top_of_what_is_in_view() {
681        // Four rows, of 100, 250, 80 and 300 points.
682        let rows = rows(&[0.0, 100.0, 350.0, 430.0]);
683
684        // From the top, down a note at a time, and no further than the last.
685        assert_eq!(scrolled(&rows, 0.0, Step::Next), Some(100.0));
686        assert_eq!(scrolled(&rows, 100.0, Step::Next), Some(350.0));
687        assert_eq!(scrolled(&rows, 350.0, Step::Next), Some(430.0));
688        assert_eq!(scrolled(&rows, 430.0, Step::Next), None);
689        assert_eq!(scrolled(&rows, 600.0, Step::Next), None, "part of the way down the last note");
690
691        // And back up, no further than the first.
692        assert_eq!(scrolled(&rows, 430.0, Step::Previous), Some(350.0));
693        assert_eq!(scrolled(&rows, 100.0, Step::Previous), Some(0.0));
694        assert_eq!(scrolled(&rows, 0.0, Step::Previous), None);
695
696        // Part of the way down a note, the next is the one under it, and
697        // the one before is the top of the note itself.
698        assert_eq!(scrolled(&rows, 180.0, Step::Next), Some(350.0));
699        assert_eq!(scrolled(&rows, 180.0, Step::Previous), Some(100.0));
700
701        // Where the list is scrolled to is not kept to the last fraction.
702        assert_eq!(scrolled(&rows, 99.6, Step::Next), Some(350.0));
703        assert_eq!(scrolled(&rows, 100.4, Step::Previous), Some(0.0));
704
705        assert_eq!(scrolled(&[], 0.0, Step::Next), None);
706        assert_eq!(scrolled(&[], 0.0, Step::Previous), None);
707    }
708
709    #[test]
710    fn the_row_stepped_to_is_the_one_that_is_marked() {
711        let rows = rows(&[0.0, 100.0, 350.0, 430.0]);
712        assert_eq!(stepped(&rows, 0.0, None, Step::Next), Some((Some(1), 100.0)));
713        assert_eq!(stepped(&rows, 430.0, None, Step::Previous), Some((Some(2), 350.0)));
714    }
715
716    #[test]
717    fn from_a_marked_row_a_step_is_to_the_row_beside_it_wherever_the_list_can_scroll_to() {
718        // A thread that fits the popup: it is not scrolled at all, and
719        // none of its rows but the first is ever at the top.
720        let rows = rows(&[0.0, 100.0, 350.0, 430.0]);
721        assert_eq!(stepped(&rows, 0.0, Some(1), Step::Next), Some((Some(2), 350.0)));
722        assert_eq!(stepped(&rows, 0.0, Some(2), Step::Next), Some((Some(3), 430.0)));
723        assert_eq!(stepped(&rows, 0.0, Some(3), Step::Next), None, "the last row");
724        assert_eq!(stepped(&rows, 0.0, Some(3), Step::Previous), Some((Some(2), 350.0)));
725        assert_eq!(stepped(&rows, 0.0, Some(1), Step::Previous), Some((Some(0), 0.0)));
726        assert_eq!(stepped(&rows, 0.0, Some(0), Step::Previous), None, "the first row");
727    }
728
729    #[test]
730    fn home_goes_to_the_very_top_from_anywhere_but_there_and_marks_nothing() {
731        let rows = rows(&[0.0, 100.0, 350.0]);
732        assert_eq!(stepped(&rows, 350.0, Some(2), Step::Top), Some((None, 0.0)));
733        assert_eq!(stepped(&rows, 12.0, None, Step::Top), Some((None, 0.0)));
734        assert_eq!(stepped(&rows, 0.0, None, Step::Top), None);
735        assert_eq!(stepped(&rows, 0.4, None, Step::Top), None, "as good as there");
736        // At the top with a row marked, as in a list that doesn't scroll:
737        // the mark goes.
738        assert_eq!(stepped(&rows, 0.0, Some(1), Step::Top), Some((None, 0.0)));
739    }
740
741    #[test]
742    fn the_keyboard_is_at_the_marked_row_while_the_list_is_about_where_it_is() {
743        let rows = rows(&[0.0, 100.0, 350.0, 430.0]);
744        let view = 600.0;
745        // Put at the top of what is in view, or under it, in view.
746        assert_eq!(marked_row(&rows, Some(id(3)), 350.0, view), Some(2));
747        assert_eq!(marked_row(&rows, Some(id(3)), 0.0, view), Some(2));
748        assert_eq!(marked_row(&rows, Some(id(3)), 349.6, view), Some(2), "not kept to the last fraction");
749        // The list scrolled on past it, or back up from it out of view.
750        assert_eq!(marked_row(&rows, Some(id(3)), 400.0, view), None);
751        assert_eq!(marked_row(&rows, Some(id(4)), 0.0, 300.0), None);
752        // Nothing marked, and a mark whose row the list no longer has.
753        assert_eq!(marked_row(&rows, None, 0.0, view), None);
754        assert_eq!(marked_row(&rows, Some(id(9)), 0.0, view), None);
755    }
756
757    #[test]
758    fn with_nothing_marked_the_row_opened_is_the_one_at_the_top_of_what_is_in_view() {
759        let rows = rows(&[0.0, 100.0, 350.0, 430.0]);
760        assert_eq!(row_at_top(&rows, 0.0), Some(0));
761        assert_eq!(row_at_top(&rows, 100.0), Some(1), "put there by a step");
762        assert_eq!(row_at_top(&rows, 180.0), Some(1), "part of the way down it");
763        // With only its last line left, it is the one under it.
764        assert_eq!(row_at_top(&rows, 330.0), Some(2));
765        assert_eq!(row_at_top(&[], 0.0), None);
766    }
767
768    #[test]
769    fn on_a_page_whose_list_is_under_something_the_top_is_a_place_and_the_rows_follow_it() {
770        // Who someone is takes 300, and their notes are 120, 80 and 200 tall.
771        let rows = under(300.0, rows(&[0.0, 120.0, 200.0]));
772        let starts: Vec<f32> = rows.iter().map(|row| row.start).collect();
773        assert_eq!(starts, [0.0, 300.0, 420.0, 500.0]);
774        // The top is no row: nothing to mark, and nothing to open.
775        assert_eq!((rows[0].key, rows[0].leads), (None, None));
776        assert_eq!((rows[1].key, rows[1].leads), (Some(id(1)), Some(Leads::Thread(id(1)))));
777
778        // From the very top, the first note; from there, back to the top.
779        assert_eq!(stepped(&rows, 0.0, None, Step::Next), Some((Some(1), 300.0)));
780        assert_eq!(stepped(&rows, 300.0, Some(1), Step::Previous), Some((Some(0), 0.0)));
781        assert_eq!(stepped(&rows, 300.0, Some(1), Step::Next), Some((Some(2), 420.0)));
782        // Part of the way down who they are, their first note is next.
783        assert_eq!(scrolled(&rows, 150.0, Step::Next), Some(300.0));
784        assert_eq!(scrolled(&rows, 150.0, Step::Previous), Some(0.0));
785
786        // With no notes yet, there is only the top.
787        let alone = under(300.0, Vec::new());
788        assert_eq!(alone.len(), 1);
789        assert_eq!(stepped(&alone, 0.0, None, Step::Next), None);
790    }
791}