1use std::collections::{HashMap, HashSet};
43
44use nostr_sdk::prelude::{EventId, PublicKey};
45
46use crate::nostr::models::Note;
47
48#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct ThreadRow {
51 pub note: Note,
52 pub depth: usize,
55}
56
57#[derive(Debug)]
59pub struct Thread {
60 focused: EventId,
61 rows: Vec<ThreadRow>,
62}
63
64fn reading_order(note: &Note) -> (u64, EventId) {
67 (note.created_at, note.id)
68}
69
70fn arrange(mut notes: HashMap<EventId, Note>) -> Vec<ThreadRow> {
76 let mut tops: Vec<EventId> = Vec::new();
77 let mut answers: HashMap<EventId, Vec<EventId>> = HashMap::new();
78 for note in notes.values() {
79 let under = note
80 .reply_to
81 .and_then(|reply| [reply.parent, reply.root].into_iter().find(|id| *id != note.id && notes.contains_key(id)));
82 match under {
83 Some(parent) => answers.entry(parent).or_default().push(note.id),
84 None => tops.push(note.id),
85 }
86 }
87 let newest_first = |ids: &mut Vec<EventId>| {
89 ids.sort_by_key(|id| std::cmp::Reverse(notes.get(id).map(reading_order)));
90 };
91 newest_first(&mut tops);
92 answers.values_mut().for_each(newest_first);
93
94 let mut rows = Vec::with_capacity(notes.len());
95 let mut next: Vec<(EventId, usize)> = tops.into_iter().map(|id| (id, 0)).collect();
96 while let Some((id, depth)) = next.pop() {
97 if let Some(below) = answers.remove(&id) {
98 next.extend(below.into_iter().map(|id| (id, depth + 1)));
99 }
100 if let Some(note) = notes.remove(&id) {
101 rows.push(ThreadRow { note, depth });
102 }
103 }
104 rows
105}
106
107impl Thread {
108 pub fn new(focused: EventId, note: Option<Note>) -> Self {
111 let rows = note.filter(|note| note.id == focused).map(|note| ThreadRow { note, depth: 0 }).into_iter().collect();
112 Self { focused, rows }
113 }
114
115 pub fn focused(&self) -> EventId {
117 self.focused
118 }
119
120 pub fn rows(&self) -> &[ThreadRow] {
122 &self.rows
123 }
124
125 pub fn contains(&self, id: EventId) -> bool {
127 self.rows.iter().any(|row| row.note.id == id)
128 }
129
130 pub fn focused_row(&self) -> Option<usize> {
132 self.rows.iter().position(|row| row.note.id == self.focused)
133 }
134
135 pub fn has_replies(&self) -> bool {
137 self.rows.iter().any(|row| row.note.reply_to.is_some_and(|reply| reply.parent == self.focused))
138 }
139
140 pub fn merge(&mut self, notes: impl IntoIterator<Item = Note>) -> Vec<PublicKey> {
146 let mut known: HashMap<EventId, Note> =
147 std::mem::take(&mut self.rows).into_iter().map(|row| (row.note.id, row.note)).collect();
148 let mut people = Vec::new();
149 let mut seen = HashSet::new();
150 for note in notes {
151 if known.get(¬e.id).is_none_or(|known| known.quoted_count() < note.quoted_count()) {
152 people.extend(note.people().filter(|person| seen.insert(*person)));
153 }
154 known.insert(note.id, note);
155 }
156 self.rows = arrange(known);
157 people
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use super::Thread;
164 use crate::nostr::content;
165 use crate::nostr::models::{Note, ReplyTo};
166 use nostr_sdk::prelude::{EventId, Keys, Kind, PublicKey};
167
168 fn id(byte: u8) -> EventId {
169 EventId::from_byte_array([byte; 32])
170 }
171
172 fn note(byte: u8, created_at: u64, root: u8, parent: u8, author: PublicKey) -> Note {
175 Note {
176 id: id(byte),
177 kind: Kind::TextNote,
178 author,
179 created_at,
180 content: content::parse(&format!("note {byte}"), 100),
181 reply_to: (root != 0).then(|| ReplyTo { root: id(root), parent: id(parent) }),
182 quoted: Vec::new(),
183 }
184 }
185
186 fn shape(thread: &Thread) -> Vec<(u8, usize)> {
188 thread.rows().iter().map(|row| (row.note.id.as_bytes()[0], row.depth)).collect()
189 }
190
191 #[test]
192 fn every_note_sits_under_the_one_it_answers_oldest_answer_first() {
193 let a = Keys::generate().public_key();
194 let mut thread = Thread::new(id(3), None);
195 thread.merge([
198 note(5, 500, 1, 3, a),
199 note(4, 400, 1, 1, a),
200 note(1, 100, 0, 0, a),
201 note(3, 300, 1, 2, a),
202 note(2, 200, 1, 1, a),
203 ]);
204
205 assert_eq!(shape(&thread), [(1, 0), (2, 1), (3, 2), (5, 3), (4, 1)]);
206 assert_eq!(thread.focused_row(), Some(2));
207 assert!(thread.contains(id(5)) && !thread.contains(id(9)));
208 assert!(thread.has_replies());
209 }
210
211 #[test]
212 fn a_note_whose_parent_is_unknown_goes_under_the_root_or_else_to_the_top() {
213 let a = Keys::generate().public_key();
214 let mut thread = Thread::new(id(3), None);
216 thread.merge([note(3, 300, 1, 2, a), note(4, 400, 1, 3, a)]);
217 assert_eq!(shape(&thread), [(3, 0), (4, 1)], "neither parent nor root: at the top");
218
219 thread.merge([note(1, 100, 0, 0, a)]);
220 assert_eq!(shape(&thread), [(1, 0), (3, 1), (4, 2)], "the root is known: under it");
221
222 thread.merge([note(2, 200, 1, 1, a)]);
223 assert_eq!(shape(&thread), [(1, 0), (2, 1), (3, 2), (4, 3)], "the parent turned up");
224 }
225
226 #[test]
227 fn a_thread_starts_with_its_note_if_that_is_at_hand() {
228 let a = Keys::generate().public_key();
229 let thread = Thread::new(id(2), Some(note(2, 200, 1, 1, a)));
230 assert_eq!(shape(&thread), [(2, 0)]);
231 assert_eq!(thread.focused(), id(2));
232 assert!(!thread.has_replies());
233
234 let thread = Thread::new(id(2), None);
235 assert!(thread.rows().is_empty());
236 assert_eq!(thread.focused_row(), None);
237
238 assert!(Thread::new(id(2), Some(note(9, 900, 0, 0, a))).rows().is_empty(), "another note is not its start");
239 }
240
241 #[test]
242 fn merging_replaces_a_known_note_and_reports_only_the_people_of_new_ones() {
243 let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
244 let mut thread = Thread::new(id(1), Some(note(1, 100, 0, 0, a)));
245
246 let mut fuller = note(1, 100, 0, 0, a);
247 fuller.content = content::parse("all of note 1", 100);
248 let people = thread.merge([fuller.clone(), note(2, 200, 1, 1, b), note(3, 300, 1, 1, b)]);
249
250 assert_eq!(people, [b], "the author of the new notes, once");
251 assert_eq!(thread.rows()[0].note, fuller);
252 assert_eq!(shape(&thread), [(1, 0), (2, 1), (3, 1)]);
253
254 let c = Keys::generate().public_key();
257 let mut quoting = fuller.clone();
258 quoting.quoted = vec![note(9, 50, 0, 0, c)];
259 assert_eq!(thread.merge([quoting.clone(), note(2, 200, 1, 1, b)]), [a, c]);
260 assert_eq!(thread.rows()[0].note, quoting);
261 }
262
263 #[test]
264 fn answers_of_the_same_second_keep_one_order() {
265 let a = Keys::generate().public_key();
266 let mut one_way = Thread::new(id(1), None);
267 one_way.merge([note(1, 100, 0, 0, a), note(2, 200, 1, 1, a), note(3, 200, 1, 1, a)]);
268 let mut another = Thread::new(id(1), None);
269 another.merge([note(3, 200, 1, 1, a), note(2, 200, 1, 1, a), note(1, 100, 0, 0, a)]);
270 assert_eq!(shape(&one_way), shape(&another));
271 assert_eq!(shape(&one_way), [(1, 0), (2, 1), (3, 1)]);
272 }
273}