zola/components/search/src/lib.rs

81 lines
2.3 KiB
Rust
Raw Normal View History

2018-03-15 17:58:32 +00:00
extern crate elasticlunr;
#[macro_use]
extern crate lazy_static;
extern crate ammonia;
2018-03-20 20:27:33 +00:00
#[macro_use]
2018-03-15 17:58:32 +00:00
extern crate errors;
extern crate content;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
2018-03-20 20:27:33 +00:00
use elasticlunr::{Index, Language};
2018-03-15 17:58:32 +00:00
use content::Section;
2018-03-20 20:27:33 +00:00
use errors::Result;
2018-03-15 17:58:32 +00:00
pub const ELASTICLUNR_JS: &'static str = include_str!("elasticlunr.min.js");
lazy_static! {
static ref AMMONIA: ammonia::Builder<'static> = {
let mut clean_content = HashSet::new();
clean_content.insert("script");
clean_content.insert("style");
let mut builder = ammonia::Builder::new();
builder
.tags(HashSet::new())
.tag_attributes(HashMap::new())
.generic_attributes(HashSet::new())
.link_rel(None)
.allowed_classes(HashMap::new())
.clean_content_tags(clean_content);
builder
};
}
2018-03-20 20:27:33 +00:00
/// Returns the generated JSON index with all the documents of the site added using
/// the language given
/// Errors if the language given is not available in Elasticlunr
2018-03-15 17:58:32 +00:00
/// TODO: is making `in_search_index` apply to subsections of a `false` section useful?
2018-03-20 20:27:33 +00:00
pub fn build_index(sections: &HashMap<PathBuf, Section>, lang: &str) -> Result<String> {
let language = match Language::from_code(lang) {
Some(l) => l,
None => { bail!("Tried to build search index for language {} which is not supported", lang); }
};
let mut index = Index::with_language(language, &["title", "body"]);
2018-03-15 17:58:32 +00:00
for section in sections.values() {
add_section_to_index(&mut index, section);
}
2018-03-20 20:27:33 +00:00
Ok(index.to_json())
2018-03-15 17:58:32 +00:00
}
fn add_section_to_index(index: &mut Index, section: &Section) {
if !section.meta.in_search_index {
return;
}
// Don't index redirecting sections
if section.meta.redirect_to.is_none() {
index.add_doc(
&section.permalink,
&[&section.meta.title.clone().unwrap_or(String::new()), &AMMONIA.clean(&section.content).to_string()],
);
}
for page in &section.pages {
2018-03-21 15:18:24 +00:00
if !page.meta.in_search_index || page.meta.draft {
2018-03-15 17:58:32 +00:00
continue;
}
index.add_doc(
&page.permalink,
&[&page.meta.title.clone().unwrap_or(String::new()), &AMMONIA.clean(&page.content).to_string()],
);
}
}