Debian Codegraph @

crates/mdbook-html/src/html_handlebars/search.rs

raw
1 use super::static_files::StaticFiles;
2 use crate::html::{ChapterTree, Node};
3 use crate::theme::searcher;
4 use crate::utils::ToUrlPath;
5 use anyhow::{Result, bail};
6 use ego_tree::iter::Edge;
7 use elasticlunr::{Index, IndexBuilder};
8 use mdbook_core::book::Chapter;
9 use mdbook_core::config::{Search, SearchChapterSettings};
10 use mdbook_core::static_regex;
11 use serde::Serialize;
12 use std::borrow::Cow;
13 use std::collections::HashMap;
14 use std::path::{Path, PathBuf};
15 use tracing::{debug, warn};
16
17 const MAX_WORD_LENGTH_TO_INDEX: usize = 80;
18
19 /// Tokenizes in the same way as elasticlunr-rs (for English), but also drops long tokens.
20 fn tokenize(text: &str) -> Vec<String> {
21 text.split(|c: char| c.is_whitespace() || c == '-')
22 .filter(|s| !s.is_empty())
23 .map(|s| s.trim().to_lowercase())
24 .filter(|s| s.len() <= MAX_WORD_LENGTH_TO_INDEX)
25 .collect()
26 }
27
28 /// Creates all files required for search.
29 pub(super) fn create_files(
30 search_config: &Search,
31 static_files: &mut StaticFiles,
32 chapter_trees: &[ChapterTree<'_>],
33 ) -> Result<()> {
34 let mut index = IndexBuilder::new()
35 .add_field_with_tokenizer("title", Box::new(&tokenize))
36 .add_field_with_tokenizer("body", Box::new(&tokenize))
37 .add_field_with_tokenizer("breadcrumbs", Box::new(&tokenize))
38 .build();
39
40 // These are links to all of the headings in all of the chapters.
41 let mut doc_urls = Vec::new();
42
43 let chapter_configs = sort_search_config(&search_config.chapter);
44 validate_chapter_config(&chapter_configs, chapter_trees)?;
45
46 for ct in chapter_trees {
47 let path = settings_path(ct.chapter);
48 let chapter_settings = get_chapter_settings(&chapter_configs, path);
49 if !chapter_settings.enable.unwrap_or(true) {
50 continue;
51 }
52 index_chapter(&mut index, search_config, &mut doc_urls, ct)?;
53 }
54
55 let index = write_to_json(index, search_config, doc_urls)?;
56 debug!("Writing search index ✓");
57 if index.len() > 10_000_000 {
58 warn!("search index is very large ({} bytes)", index.len());
59 }
60
61 if search_config.copy_js {
62 static_files.add_builtin(
63 "searchindex.js",
64 // To reduce the size of the generated JSON by preventing all `"` characters to be
65 // escaped, we instead surround the string with much less common `'` character.
66 format!(
67 "window.search = Object.assign(window.search, JSON.parse('{}'));",
68 index.replace("\\", "\\\\").replace("'", "\\'")
69 )
70 .as_bytes(),
71 );
72 static_files.add_builtin("searcher.js", searcher::JS);
73 static_files.add_builtin("mark.min.js", searcher::MARK_JS);
74 static_files.add_builtin("elasticlunr.min.js", searcher::ELASTICLUNR_JS);
75 debug!("Copying search files ✓");
76 }
77
78 Ok(())
79 }
80
81 /// Uses the given arguments to construct a search document, then inserts it to the given index.
82 fn add_doc(
83 index: &mut Index,
84 doc_urls: &mut Vec<String>,
85 anchor_base: &str,
86 heading_id: &str,
87 items: &[&str],
88 ) {
89 let mut url = anchor_base.to_string();
90 if !heading_id.is_empty() {
91 url.push('#');
92 url.push_str(heading_id);
93 }
94
95 let doc_ref = doc_urls.len().to_string();
96 doc_urls.push(url);
97
98 let items = items.iter().map(|&x| collapse_whitespace(x.trim()));
99 index.add_doc(&doc_ref, items);
100 }
101
102 /// Adds the chapter to the search index.
103 fn index_chapter(
104 index: &mut Index,
105 search_config: &Search,
106 doc_urls: &mut Vec<String>,
107 chapter_tree: &ChapterTree<'_>,
108 ) -> Result<()> {
109 let anchor_base = chapter_tree.html_path.to_url_path();
110
111 let mut in_heading = false;
112 let max_section_depth = search_config.heading_split_level;
113 let mut section_id = None;
114 let mut heading = String::new();
115 let mut body = String::new();
116 let mut breadcrumbs = chapter_tree.chapter.parent_names.clone();
117
118 breadcrumbs.push(chapter_tree.chapter.name.clone());
119
120 let mut traverse = chapter_tree.tree.root().traverse();
121
122 while let Some(edge) = traverse.next() {
123 match edge {
124 Edge::Open(node) => match node.value() {
125 Node::Element(el) => {
126 if let Some(level) = el.heading_level()
127 && level <= max_section_depth
128 && let Some(heading_id) = el.attr("id")
129 {
130 if !heading.is_empty() {
131 // Section finished, the next heading is following now
132 // Write the data to the index, and clear it for the next section
133 add_doc(
134 index,
135 doc_urls,
136 &anchor_base,
137 section_id.unwrap(),
138 &[&heading, &body, &breadcrumbs.join(" » ")],
139 );
140 heading.clear();
141 body.clear();
142 breadcrumbs.pop();
143 }
144 section_id = Some(heading_id);
145 in_heading = true;
146 } else if matches!(el.name(), "script" | "style") {
147 // Skip this node.
148 while let Some(edge) = traverse.next() {
149 if let Edge::Close(close) = edge
150 && close == node
151 {
152 break;
153 }
154 }
155 // Insert spaces where HTML output would usually separate text
156 // to ensure words don't get merged together
157 } else if in_heading {
158 heading.push(' ');
159 } else {
160 body.push(' ');
161 }
162 }
163 Node::Text(text) => {
164 if in_heading {
165 heading.push_str(text);
166 } else {
167 body.push_str(text);
168 }
169 }
170 Node::Comment(_) => {}
171 Node::Fragment => {}
172 Node::RawData(_) => {}
173 },
174 Edge::Close(node) => match node.value() {
175 Node::Element(el) => {
176 if let Some(level) = el.heading_level()
177 && level <= max_section_depth
178 {
179 in_heading = false;
180 breadcrumbs.push(heading.clone());
181 }
182 }
183 _ => {}
184 },
185 }
186 }
187
188 if !body.is_empty() || !heading.is_empty() {
189 // Make sure the last section is added to the index
190 let title = if heading.is_empty() {
191 if let Some(chapter) = breadcrumbs.first() {
192 chapter
193 } else {
194 ""
195 }
196 } else {
197 &heading
198 };
199 add_doc(
200 index,
201 doc_urls,
202 &anchor_base,
203 section_id.unwrap_or_default(),
204 &[title, &body, &breadcrumbs.join(" » ")],
205 );
206 }
207
208 Ok(())
209 }
210
211 fn write_to_json(index: Index, search_config: &Search, doc_urls: Vec<String>) -> Result<String> {
212 use elasticlunr::config::{SearchBool, SearchOptions, SearchOptionsField};
213 use std::collections::BTreeMap;
214
215 #[derive(Serialize)]
216 struct ResultsOptions {
217 limit_results: u32,
218 teaser_word_count: u32,
219 }
220
221 #[derive(Serialize)]
222 struct SearchindexJson {
223 /// The options used for displaying search results
224 results_options: ResultsOptions,
225 /// The searchoptions for elasticlunr.js
226 search_options: SearchOptions,
227 /// Used to lookup a document's URL from an integer document ref.
228 doc_urls: Vec<String>,
229 /// The index for elasticlunr.js
230 index: elasticlunr::Index,
231 }
232
233 let mut fields = BTreeMap::new();
234 let mut opt = SearchOptionsField::default();
235 let mut insert_boost = |key: &str, boost| {
236 opt.boost = Some(boost);
237 fields.insert(key.into(), opt);
238 };
239 insert_boost("title", search_config.boost_title);
240 insert_boost("body", search_config.boost_paragraph);
241 insert_boost("breadcrumbs", search_config.boost_hierarchy);
242
243 let search_options = SearchOptions {
244 bool: if search_config.use_boolean_and {
245 SearchBool::And
246 } else {
247 SearchBool::Or
248 },
249 expand: search_config.expand,
250 fields,
251 };
252
253 let results_options = ResultsOptions {
254 limit_results: search_config.limit_results,
255 teaser_word_count: search_config.teaser_word_count,
256 };
257
258 let json_contents = SearchindexJson {
259 results_options,
260 search_options,
261 doc_urls,
262 index,
263 };
264
265 // By converting to serde_json::Value as an intermediary, we use a
266 // BTreeMap internally and can force a stable ordering of map keys.
267 let json_contents = serde_json::to_value(&json_contents)?;
268 let json_contents = serde_json::to_string(&json_contents)?;
269
270 Ok(json_contents)
271 }
272
273 fn settings_path(ch: &Chapter) -> &Path {
274 ch.source_path
275 .as_deref()
276 .unwrap_or_else(|| ch.path.as_deref().unwrap())
277 }
278
279 fn validate_chapter_config(
280 chapter_configs: &[(PathBuf, SearchChapterSettings)],
281 chapter_trees: &[ChapterTree<'_>],
282 ) -> Result<()> {
283 for (path, _) in chapter_configs {
284 let found = chapter_trees
285 .iter()
286 .any(|ct| settings_path(ct.chapter).starts_with(path));
287 if !found {
288 bail!(
289 "[output.html.search.chapter] key `{}` does not match any chapter paths",
290 path.display()
291 );
292 }
293 }
294 Ok(())
295 }
296
297 fn sort_search_config(
298 map: &HashMap<String, SearchChapterSettings>,
299 ) -> Vec<(PathBuf, SearchChapterSettings)> {
300 let mut settings: Vec<_> = map
301 .iter()
302 .map(|(key, value)| (PathBuf::from(key), value.clone()))
303 .collect();
304 // Note: This is case-sensitive, and assumes the author uses the same case
305 // as the actual filename.
306 settings.sort_by(|a, b| a.0.cmp(&b.0));
307 settings
308 }
309
310 fn get_chapter_settings(
311 chapter_configs: &[(PathBuf, SearchChapterSettings)],
312 source_path: &Path,
313 ) -> SearchChapterSettings {
314 let mut result = SearchChapterSettings::default();
315 for (path, config) in chapter_configs {
316 if source_path.starts_with(path) {
317 result.enable = config.enable.or(result.enable);
318 }
319 }
320 result
321 }
322
323 /// Replaces multiple consecutive whitespace characters with a single space character.
324 fn collapse_whitespace(text: &str) -> Cow<'_, str> {
325 static_regex!(WS, r"\s\s+");
326 WS.replace_all(text, " ")
327 }
328
329 #[test]
330 fn chapter_settings_priority() {
331 let cfg = r#"
332 [output.html.search.chapter]
333 "cli/watch.md" = { enable = true }
334 "cli" = { enable = false }
335 "cli/inner/foo.md" = { enable = false }
336 "cli/inner" = { enable = true }
337 "foo" = {} # Just to make sure empty table is allowed.
338 "#;
339 let cfg: mdbook_core::config::Config = toml::from_str(cfg).unwrap();
340 let html = cfg.html_config().unwrap();
341 let chapter_configs = sort_search_config(&html.search.unwrap().chapter);
342 for (path, enable) in [
343 ("foo.md", None),
344 ("cli/watch.md", Some(true)),
345 ("cli/index.md", Some(false)),
346 ("cli/inner/index.md", Some(true)),
347 ("cli/inner/foo.md", Some(false)),
348 ] {
349 let mut settings = SearchChapterSettings::default();
350 settings.enable = enable;
351 assert_eq!(
352 get_chapter_settings(&chapter_configs, Path::new(path)),
353 settings
354 );
355 }
356 }
357
358 #[cfg(test)]
359 mod tests {
360 use super::*;
361
362 #[test]
363 fn test_tokenize_basic() {
364 assert_eq!(tokenize("hello world"), vec!["hello", "world"]);
365 }
366
367 #[test]
368 fn test_tokenize_with_hyphens() {
369 assert_eq!(
370 tokenize("hello-world test-case"),
371 vec!["hello", "world", "test", "case"]
372 );
373 }
374
375 #[test]
376 fn test_tokenize_mixed_whitespace() {
377 assert_eq!(
378 tokenize("hello\tworld\ntest\r\ncase"),
379 vec!["hello", "world", "test", "case"]
380 );
381 }
382
383 #[test]
384 fn test_tokenize_empty_string() {
385 assert_eq!(tokenize(""), Vec::<String>::new());
386 }
387
388 #[test]
389 fn test_tokenize_only_whitespace() {
390 assert_eq!(tokenize(" \t\n "), Vec::<String>::new());
391 }
392
393 #[test]
394 fn test_tokenize_case_normalization() {
395 assert_eq!(tokenize("Hello WORLD Test"), vec!["hello", "world", "test"]);
396 }
397
398 #[test]
399 fn test_tokenize_trim_whitespace() {
400 assert_eq!(tokenize(" hello world "), vec!["hello", "world"]);
401 }
402
403 #[test]
404 fn test_tokenize_long_words_filtered() {
405 let long_word = "a".repeat(MAX_WORD_LENGTH_TO_INDEX + 1);
406 let short_word = "a".repeat(MAX_WORD_LENGTH_TO_INDEX);
407 let input = format!("{} hello {}", long_word, short_word);
408 assert_eq!(tokenize(&input), vec!["hello", &short_word]);
409 }
410
411 #[test]
412 fn test_tokenize_max_length_word() {
413 let max_word = "a".repeat(MAX_WORD_LENGTH_TO_INDEX);
414 assert_eq!(tokenize(&max_word), vec![max_word]);
415 }
416
417 #[test]
418 fn test_tokenize_special_characters() {
419 assert_eq!(
420 tokenize("hello,world.test!case?"),
421 vec!["hello,world.test!case?"]
422 );
423 }
424
425 #[test]
426 fn test_tokenize_unicode() {
427 assert_eq!(
428 tokenize("café naïve résumé"),
429 vec!["café", "naïve", "résumé"]
430 );
431 }
432
433 #[test]
434 fn test_tokenize_unicode_rtl_hebre() {
435 assert_eq!(tokenize("שלום עולם"), vec!["שלום", "עולם"]);
436 }
437
438 #[test]
439 fn test_tokenize_numbers() {
440 assert_eq!(
441 tokenize("test123 456-789 hello"),
442 vec!["test123", "456", "789", "hello"]
443 );
444 }
445 }