Skip to main content

cosmic_applet_avestruz/views/
search.rs

1// SPDX-License-Identifier: MIT
2
3//! The search view for Avestruz: where the search is typed, above the
4//! people it found or the notes, each a list of its own.
5
6use std::sync::LazyLock;
7
8use cosmic::Element;
9use cosmic::iced::widget::text::Wrapping;
10use cosmic::iced::{Alignment, Length, mouse};
11use cosmic::widget::{self, button, container, text, text_input};
12use nostr_sdk::prelude::PublicKey;
13
14use crate::fl;
15use crate::helpers::truncate_chars;
16use crate::messages::Message;
17use crate::nostr::models::{Note, display_name, short_npub};
18use crate::nostr::relay_lists::NIP_SEARCH;
19use crate::nostr::search::SearchFor;
20use crate::state::{AppModel, SearchPage, SearchProgress};
21use crate::views::components::note_row::relay_name;
22use crate::views::components::{
23    VirtualList, avatar, estimated_note_height, list_scroller, marking, note_row, opening_thread, status_line,
24};
25
26/// How wide someone's picture is among the people found: as in a note's
27/// row.
28const PERSON_AVATAR_SIZE: f32 = 36.0;
29
30/// How many characters of what someone says of themselves show under
31/// their name: about a line.
32const PERSON_ABOUT_CHARS: usize = 120;
33
34/// Where the search is typed, by which it is told to take the keyboard.
35static SEARCH_INPUT: LazyLock<widget::Id> = LazyLock::new(widget::Id::unique);
36
37/// The id of where the search is typed.
38pub fn search_input_id() -> widget::Id {
39    SEARCH_INPUT.clone()
40}
41
42impl AppModel {
43    /// The line above a search: the way back, where the search is typed,
44    /// and the button that searches, as Enter does.
45    fn view_search_header<'a>(&'a self, page: &'a SearchPage) -> Element<'a, Message> {
46        let id = page.id;
47        let back = button::icon(widget::icon::from_name("go-previous-symbolic"))
48            .tooltip(fl!("search-back"))
49            .on_press(Message::ClosePage);
50        let typed = text_input(fl!("search-placeholder"), &page.typed)
51            .id(search_input_id())
52            .on_input(move |typed| Message::SearchTyped(id, typed))
53            .on_submit(move |_| Message::Search(id))
54            .width(Length::Fill);
55        let go = button::icon(widget::icon::from_name("system-search-symbolic"))
56            .tooltip(fl!("search-go"))
57            .on_press_maybe((!page.typed.trim().is_empty()).then_some(Message::Search(id)));
58        widget::Row::new().push(back).push(typed).push(go).spacing(8).align_y(Alignment::Center).padding([4, 12]).into()
59    }
60
61    /// The choice between the people found and the notes: the one on show
62    /// stands out.
63    fn view_search_tabs(page: &SearchPage) -> Element<'_, Message> {
64        let tab = |what: SearchFor, label: String| {
65            let tab = if page.what == what { button::standard(label) } else { button::text(label) };
66            tab.on_press(Message::SearchShow(page.id, what))
67        };
68        widget::Row::new()
69            .push(tab(SearchFor::People, fl!("search-people")))
70            .push(tab(SearchFor::Notes, fl!("search-notes")))
71            .spacing(8)
72            .padding([0, 12, 4, 12])
73            .into()
74    }
75
76    /// One of the people found: their picture, their name, their key,
77    /// whether the account follows them, and the start of what they say
78    /// of themselves. A click opens their
79    /// profile.
80    fn view_person(&self, person: &PublicKey) -> Element<'_, Message> {
81        let name = display_name(&self.profiles, person);
82        let profile = self.profiles.get(person);
83        let picture = profile.and_then(|profile| profile.picture.as_deref());
84        let picture = avatar(&self.images, picture, person, &name, PERSON_AVATAR_SIZE);
85
86        // Cut rather than wrapped: every row is as tall as every other.
87        let line = |words: String, size: u16| container(text(words).size(size).wrapping(Wrapping::None)).clip(true);
88        // Told apart from whoever else goes by the name: the key, and
89        // whether the account follows them.
90        let followed = self.follows.as_ref().is_some_and(|follows| follows.contains(person));
91        let key = if followed { format!("{} · {}", short_npub(person), fl!("search-following")) } else { short_npub(person) };
92        let mut who = widget::Column::new()
93            .push(container(text(name.into_owned()).size(13).font(cosmic::font::bold()).wrapping(Wrapping::None)).clip(true))
94            .push(line(key, 11))
95            .spacing(2)
96            .width(Length::Fill);
97        if let Some(about) = profile.and_then(|profile| profile.about.as_deref()) {
98            let first_line = about.lines().next().unwrap_or_default();
99            who = who.push(line(truncate_chars(first_line, PERSON_ABOUT_CHARS).into_owned(), 11));
100        }
101        let mut row = widget::Row::new().push(picture).push(who).spacing(8).align_y(Alignment::Center).padding([6, 0]);
102        // Followed, or not any more, from here: one at a time, and once
103        // it is known who is followed.
104        let own = self.account.as_ref().is_some_and(|account| account.public_key == *person);
105        if self.can_publish() && !own && self.follows.is_some() {
106            let change = Message::Follow { person: *person, follow: !followed, first_list: false };
107            let label = if followed { fl!("profile-unfollow") } else { fl!("profile-follow") };
108            let follow = if followed { button::standard(label) } else { button::suggested(label) };
109            row = row.push(follow.on_press_maybe(self.follow_pending.is_none().then_some(change)));
110        }
111        widget::mouse_area(row).on_press(Message::OpenProfile(*person)).interaction(mouse::Interaction::Pointer).into()
112    }
113
114    /// The people a search found, the best match first.
115    fn view_people_found<'a>(&'a self, page: &'a SearchPage) -> Element<'a, Message> {
116        let people = page.people.iter().fold(widget::Column::new(), |people, person| people.push(self.view_person(person)));
117        list_scroller(&page.people_position, people)
118    }
119
120    /// The notes a search found, the best match first.
121    fn view_notes_found<'a>(&'a self, page: &'a SearchPage) -> Element<'a, Message> {
122        let context = self.row_context(&page.expanded, page.marked);
123        let sizes = context.sizes;
124        let list: VirtualList<'_, Note, _, Message, cosmic::Theme, cosmic::Renderer> = VirtualList::new(
125            &page.notes,
126            &page.heights,
127            |note: &Note| note.id,
128            move |note, width| estimated_note_height(note, sizes, width, context.expanded.has(&note.id)),
129            move |_index, note| marking(opening_thread(note_row(note, &context), note.id, &context), note.id, &context),
130        );
131        list_scroller(&page.notes_position, list)
132    }
133
134    /// What is under where the search is typed: what was found, or why
135    /// there is nothing to show.
136    fn view_search_body<'a>(&'a self, page: &'a SearchPage) -> Element<'a, Message> {
137        // A relay's address was typed: its notes are what there is to show.
138        if page.relay.is_some() && page.what == SearchFor::People {
139            return status_line(fl!("search-relay-people"));
140        }
141        // What is searched for is asked of the search relays, and with
142        // none there is nobody to ask. A relay's own notes are asked of it.
143        match self.search_relays() {
144            _ if page.relay.is_some() => {}
145            None => return status_line(fl!("search-reading-relays")),
146            Some(relays) if relays.is_empty() => {
147                let to_relays = button::standard(fl!("search-open-relays")).on_press(Message::OpenRelays);
148                return widget::Column::new()
149                    .push(status_line(fl!("search-no-relays")))
150                    .push(container(to_relays).width(Length::Fill).align_x(Alignment::Center).padding([0, 0, 16, 0]))
151                    .into();
152            }
153            Some(_) => {}
154        }
155        let found_none = match page.what {
156            SearchFor::People => page.people.is_empty(),
157            SearchFor::Notes => page.notes.is_empty(),
158        };
159        match page.progress(page.what) {
160            SearchProgress::Idle => status_line(fl!("search-hint")),
161            SearchProgress::Searching => status_line(fl!("search-searching")),
162            SearchProgress::Failed(why) => status_line(fl!("search-failed", error = why.as_str())),
163            SearchProgress::Found if found_none => status_line(fl!("search-nothing")),
164            SearchProgress::Found => match page.what {
165                SearchFor::People => self.view_people_found(page),
166                SearchFor::Notes => self.view_notes_found(page),
167            },
168        }
169    }
170
171    /// What the relay whose notes are on show says of itself, over them:
172    /// its address, its name, a line about it, and whether it searches.
173    fn view_relay_shown<'a>(page: &'a SearchPage) -> Option<Element<'a, Message>> {
174        let relay = page.relay.as_ref()?;
175        let mut said = vec![relay_name(relay).to_string()];
176        if let Some(info) = &page.relay_info {
177            // Many call themselves by their address.
178            said.extend(info.name.clone().filter(|name| name != relay_name(relay)));
179            said.extend(info.description.clone());
180            let searches = info.supports(NIP_SEARCH) == Some(true);
181            said.push(if searches { fl!("search-relay-searches") } else { fl!("search-relay-no-search") });
182        }
183        let line = text(said.join(" · ")).size(11).wrapping(Wrapping::WordOrGlyph).width(Length::Fill);
184        Some(container(line).padding([6, 12]).into())
185    }
186
187    /// Render the search view.
188    pub fn view_search<'a>(&'a self, page: &'a SearchPage) -> Element<'a, Message> {
189        widget::Column::new()
190            .push(self.view_search_header(page))
191            .push(Self::view_search_tabs(page))
192            .push(widget::divider::horizontal::default())
193            .push_maybe(Self::view_relay_shown(page))
194            .push(self.view_search_body(page))
195            .into()
196    }
197}