notesmachine/server/nm-trees/src/make_tree.rs

76 lines
2.7 KiB
Rust

use crate::structs::{Note, Page};
use nm_store::NoteKind;
fn make_note_tree_from(rawnotes: &[nm_store::Note], root_id: &str) -> Note {
let the_note = {
let foundroots: Vec<&nm_store::Note> = rawnotes.iter().filter(|note| note.id == root_id).collect();
debug_assert!(foundroots.len() == 1);
foundroots.iter().next().unwrap().clone()
};
// The special case of the root node must be filtered out here to
// prevent the first pass from smashing the stack in an infinite
// loop. The root node is identified by the type 'root' and
// having its `id` and `parent_id` be equal. Numeric comparisons
// are faster.
let mut children = rawnotes
.iter()
.filter(|note| note.parent_id.is_some() && note.parent_id.unwrap() == root_id && note.id != the_note.id)
.map(|note| make_note_tree_from(rawnotes, &note.id))
.collect::<Vec<Note>>();
children.sort_unstable_by(|a, b| a.location.cmp(&b.location));
Note {
id: the_note.id,
parent_id: the_note.parent_id,
content: the_note.content,
kind: the_note.kind.to_string(),
location: the_note.location,
creation_date: the_note.creation_date,
updated_date: the_note.updated_date,
lastview_date: the_note.updated_date,
deleted_date: the_note.deleted_date,
children: children,
}
}
pub(crate) fn make_note_tree(rawnotes: &[nm_store::Note]) -> Note {
let the_root = {
let foundroots: Vec<&nm_store::Note> = rawnotes.iter().filter(|note| note.kind == NoteKind::Kasten).collect();
debug_assert!(foundroots.len() == 1);
foundroots.iter().next().unwrap().clone()
};
make_note_tree_from(&rawnotes, &the_root.id)
}
fn add_child(rawnotes: &[nm_store::Note], acc: &mut Vec<Note>, note_id: &str) -> Vec<Note> {
let child = rawnotes
.iter()
.find(|note| note.parent_id.is_some() && note.parent_id.unwrap() == note_id);
if let Some(c) = child {
acc.push(Note {
id: c.id,
parent_id: Some(note_id.to_string()),
content: c.content,
kind: c.kind.to_string(),
location: c.location,
creation_date: c.creation_date,
updated_date: c.updated_date,
lastview_date: c.updated_date,
deleted_date: c.deleted_date,
children: vec![],
});
add_child(rawnotes, acc, &c.id)
} else {
acc.to_vec()
}
}
pub(crate) fn make_backreferences(rawnotes: &[nm_store::Note]) -> Vec<Vec<Note>> {
rawnotes
.iter()
.filter(|note| note.parent_id.is_none() && note.kind == NoteKind::Kasten)
.map(|root| add_child(rawnotes, &mut Vec::<Note>::new(), &root.id))
.collect()
}