euv_docs/model/impl.rs
1use super::*;
2
3/// Search, metadata, and lookup utilities for `DocSite`.
4impl DocSite {
5 /// Applies site-level and locale-level presentation metadata onto this site.
6 ///
7 /// # Arguments
8 ///
9 /// - `&Self` - Mutable documentation site reference.
10 /// - `&DocSiteConfig` - Shared site frontmatter configuration.
11 /// - `Option<&DocLocaleConfig>` - Optional active locale configuration.
12 pub(crate) fn apply_locale_metadata(
13 &mut self,
14 cfg: &DocSiteConfig,
15 locale: Option<&DocLocaleConfig>,
16 ) {
17 self.set_release_marker(EUV_DOCS_RELEASE_MARKER.to_string());
18 if let Some(logo) = cfg.get_site().try_get_logo().as_deref()
19 && !logo.trim().is_empty()
20 {
21 self.set_logo(logo.trim().to_string());
22 }
23 if let Some(link) = cfg.get_site().try_get_footer_link().as_deref()
24 && !link.trim().is_empty()
25 {
26 self.set_footer_link(link.trim().to_string());
27 }
28 self.set_footer_items(cfg.get_site().get_footer_items().clone());
29 self.set_locales(unique_locales(cfg.get_locales()));
30 if let Some(loc) = locale {
31 self.set_lang(if loc.get_lang().trim().is_empty() {
32 DOCS_DEFAULT_LANG.to_string()
33 } else {
34 loc.get_lang().trim().to_string()
35 });
36 self.set_locale_prefix(loc.get_prefix().clone());
37 if let Some(f) = loc.try_get_footer().as_deref() {
38 self.set_footer(f.to_string());
39 } else if let Some(f) = cfg.get_site().try_get_footer().as_deref() {
40 self.set_footer(f.to_string());
41 }
42 self.set_toc_label(
43 loc.try_get_toc_label()
44 .clone()
45 .unwrap_or_else(|| DOCS_DEFAULT_TOC_LABEL.to_string()),
46 );
47 self.set_prev_label(
48 loc.try_get_prev_label()
49 .clone()
50 .unwrap_or_else(|| DOCS_DEFAULT_PREV_LABEL.to_string()),
51 );
52 self.set_next_label(
53 loc.try_get_next_label()
54 .clone()
55 .unwrap_or_else(|| DOCS_DEFAULT_NEXT_LABEL.to_string()),
56 );
57 self.set_navbar(loc.get_navbar().clone());
58 } else {
59 self.set_lang(DOCS_DEFAULT_LANG.to_string());
60 self.set_locale_prefix("/".to_string());
61 if let Some(f) = cfg.get_site().try_get_footer().as_deref() {
62 self.set_footer(f.to_string());
63 }
64 self.set_toc_label(DOCS_DEFAULT_TOC_LABEL.to_string());
65 self.set_prev_label(DOCS_DEFAULT_PREV_LABEL.to_string());
66 self.set_next_label(DOCS_DEFAULT_NEXT_LABEL.to_string());
67 }
68 }
69
70 /// Returns the resolved BCP 47 language tag, defaulting to `"en-US"`.
71 ///
72 /// # Arguments
73 ///
74 /// - `&Self` - Documentation site reference.
75 ///
76 /// # Returns
77 ///
78 /// - `&str` - Active HTML language tag.
79 #[must_use]
80 pub fn resolved_lang(&self) -> &str {
81 let lang: &str = self.get_lang().trim();
82 if lang.is_empty() {
83 DOCS_DEFAULT_LANG
84 } else {
85 lang
86 }
87 }
88
89 /// Returns the resolved localized TOC title label.
90 ///
91 /// # Arguments
92 ///
93 /// - `&Self` - Documentation site reference.
94 ///
95 /// # Returns
96 ///
97 /// - `&str` - Localized TOC title label.
98 #[must_use]
99 pub fn resolved_toc_label(&self) -> &str {
100 let lbl: &str = self.get_toc_label().trim();
101 if lbl.is_empty() {
102 DOCS_DEFAULT_TOC_LABEL
103 } else {
104 lbl
105 }
106 }
107
108 /// Returns the resolved localized previous-page pager label.
109 ///
110 /// # Arguments
111 ///
112 /// - `&Self` - Documentation site reference.
113 ///
114 /// # Returns
115 ///
116 /// - `&str` - Localized previous-page label.
117 #[must_use]
118 pub fn resolved_prev_label(&self) -> &str {
119 let lbl: &str = self.get_prev_label().trim();
120 if lbl.is_empty() {
121 DOCS_DEFAULT_PREV_LABEL
122 } else {
123 lbl
124 }
125 }
126
127 /// Returns the resolved localized next-page pager label.
128 ///
129 /// # Arguments
130 ///
131 /// - `&Self` - Documentation site reference.
132 ///
133 /// # Returns
134 ///
135 /// - `&str` - Localized next-page label.
136 #[must_use]
137 pub fn resolved_next_label(&self) -> &str {
138 let lbl: &str = self.get_next_label().trim();
139 if lbl.is_empty() {
140 DOCS_DEFAULT_NEXT_LABEL
141 } else {
142 lbl
143 }
144 }
145
146 /// Searches pages matching `query` (case-insensitive) across title, route, and content blocks.
147 ///
148 /// # Arguments
149 ///
150 /// - `&Self` - Documentation site reference.
151 /// - `&str` - Search query text.
152 ///
153 /// # Returns
154 ///
155 /// - `Vec<&DocPage>` - Matching pages in display order.
156 #[must_use]
157 pub fn search(&self, query: &str) -> Vec<&DocPage> {
158 let needle: String = query.trim().to_ascii_lowercase();
159 if needle.is_empty() {
160 return self.get_pages().iter().collect();
161 }
162 self.get_pages()
163 .iter()
164 .filter(|page: &&DocPage| page.matches_query(&needle))
165 .collect()
166 }
167
168 /// Looks up a page by its canonical route path (normalizing trailing slashes and `.html`).
169 ///
170 /// # Arguments
171 ///
172 /// - `&Self` - Documentation site reference.
173 /// - `&str` - Route path to locate.
174 ///
175 /// # Returns
176 ///
177 /// - `Option<&DocPage>` - Matching page if present.
178 #[must_use]
179 pub fn find_by_route(&self, route: &str) -> Option<&DocPage> {
180 if let Some(exact) = self
181 .get_pages()
182 .iter()
183 .find(|page: &&DocPage| page.get_route() == route)
184 {
185 return Some(exact);
186 }
187 let cleaned: &str = route
188 .split('#')
189 .next()
190 .unwrap_or(route)
191 .split('?')
192 .next()
193 .unwrap_or(route)
194 .trim_end_matches('/')
195 .trim_end_matches(".html");
196 let normalized: String = if cleaned.is_empty() {
197 "/".to_string()
198 } else if cleaned.starts_with('/') {
199 cleaned.to_string()
200 } else {
201 format!("/{cleaned}")
202 };
203 self.get_pages()
204 .iter()
205 .find(|page: &&DocPage| page.get_route() == &normalized)
206 }
207
208 /// Builds compact full-text search index entries for every page in this site.
209 ///
210 /// # Arguments
211 ///
212 /// - `&Self` - Documentation site reference.
213 ///
214 /// # Returns
215 ///
216 /// - `Vec<SearchIndexEntry>` - Ordered search records ready for JSON serialization.
217 #[must_use]
218 pub fn search_entries(&self) -> Vec<SearchIndexEntry> {
219 self.get_pages()
220 .iter()
221 .map(|page: &DocPage| {
222 let headings: Vec<String> = page
223 .get_toc()
224 .iter()
225 .map(|item: &DocTocItem| item.get_title().clone())
226 .collect();
227 let mut excerpt: String = String::new();
228 for block in page.get_blocks().iter() {
229 if excerpt.len() >= 360 {
230 break;
231 }
232 match block {
233 DocBlock::Paragraph(text)
234 | DocBlock::ListItem(text)
235 | DocBlock::BlockQuote(text) => {
236 if !excerpt.is_empty() {
237 excerpt.push(' ');
238 }
239 excerpt.push_str(text);
240 }
241 DocBlock::Table { headers, rows } => {
242 for h in headers.iter() {
243 if !excerpt.is_empty() {
244 excerpt.push(' ');
245 }
246 excerpt.push_str(h);
247 }
248 for r in rows.iter().take(3) {
249 for cell in r.iter() {
250 if !excerpt.is_empty() {
251 excerpt.push(' ');
252 }
253 excerpt.push_str(cell);
254 }
255 }
256 }
257 DocBlock::Image { alt, .. } => {
258 if !alt.is_empty() {
259 if !excerpt.is_empty() {
260 excerpt.push(' ');
261 }
262 excerpt.push_str(alt);
263 }
264 }
265 DocBlock::Heading { .. }
266 | DocBlock::Code { .. }
267 | DocBlock::HorizontalRule => {}
268 }
269 }
270 if excerpt.is_empty() && !page.get_markdown_body().trim().is_empty() {
271 excerpt.push_str(page.get_markdown_body().trim());
272 }
273 let trimmed: String = excerpt.chars().take(360).collect();
274 SearchIndexEntry::new(
275 page.get_route().clone(),
276 page.get_title().clone(),
277 page.get_section().clone(),
278 page.get_summary().clone(),
279 headings,
280 trimmed,
281 )
282 })
283 .collect()
284 }
285}
286
287/// Query matching, reading-time estimation, and frontmatter metadata helpers for `DocPage`.
288impl DocPage {
289 /// Stores the raw Markdown body slice for full-fidelity HTML and native rendering.
290 ///
291 /// # Arguments
292 ///
293 /// - `&Self` - Mutable documentation page reference.
294 /// - `String` - Raw Markdown body text without frontmatter.
295 pub(crate) fn set_markdown_body(&mut self, body: String) {
296 self.markdown_body = body;
297 }
298
299 /// Returns a mutable reference to the raw Markdown body string for bundle packing.
300 ///
301 /// # Arguments
302 ///
303 /// - `&Self` - Mutable documentation page reference.
304 ///
305 /// # Returns
306 ///
307 /// - `&mut String` - Mutable Markdown body reference.
308 pub(crate) fn get_mut_markdown_body(&mut self) -> &mut String {
309 &mut self.markdown_body
310 }
311
312 /// Replaces the structured fallback content blocks for this page.
313 ///
314 /// # Arguments
315 ///
316 /// - `&Self` - Mutable documentation page reference.
317 /// - `Vec<DocBlock>` - Structured content blocks.
318 pub(crate) fn set_blocks(&mut self, blocks: Vec<DocBlock>) {
319 self.blocks = blocks;
320 }
321
322 /// Returns a mutable reference to the structured content blocks vector for bundle packing.
323 ///
324 /// # Arguments
325 ///
326 /// - `&Self` - Mutable documentation page reference.
327 ///
328 /// # Returns
329 ///
330 /// - `&mut Vec<DocBlock>` - Mutable blocks vector reference.
331 pub(crate) fn get_mut_blocks(&mut self) -> &mut Vec<DocBlock> {
332 &mut self.blocks
333 }
334
335 /// Stores optional last-updated frontmatter stamp.
336 ///
337 /// # Arguments
338 ///
339 /// - `&Self` - Mutable documentation page reference.
340 /// - `Option<String>` - Optional date or version string.
341 pub(crate) fn set_updated(&mut self, updated: Option<String>) {
342 self.updated = updated;
343 }
344
345 /// Stores landing-page frontmatter metadata (`home`, `heroText`, `actions`, `stats`, `features`).
346 ///
347 /// # Arguments
348 ///
349 /// - `&Self` - Mutable documentation page reference.
350 /// - `bool` - Whether this page uses the home landing layout.
351 /// - `Option<String>` - Optional hero display heading.
352 /// - `Vec<DocHomeAction>` - Landing-page call-to-action buttons.
353 /// - `Vec<DocHomeStat>` - Landing-page metric tiles.
354 /// - `Vec<DocHomeFeature>` - Landing-page feature cards.
355 pub(crate) fn set_home_meta(
356 &mut self,
357 is_home: bool,
358 hero_text: Option<String>,
359 actions: Vec<DocHomeAction>,
360 stats: Vec<DocHomeStat>,
361 features: Vec<DocHomeFeature>,
362 ) {
363 self.is_home = is_home;
364 self.hero_text = hero_text;
365 self.actions = actions;
366 self.stats = stats;
367 self.features = features;
368 }
369
370 /// Marks whether this page should be omitted from sidebar navigation trees.
371 ///
372 /// # Arguments
373 ///
374 /// - `&Self` - Mutable documentation page reference.
375 /// - `bool` - `true` when `sidebar: false` is set in frontmatter.
376 pub(crate) fn set_hide_sidebar(&mut self, hide: bool) {
377 self.hide_sidebar = hide;
378 }
379
380 /// Stores filesystem source path and directory-index metadata on this page.
381 ///
382 /// # Arguments
383 ///
384 /// - `&Self` - Mutable documentation page reference.
385 /// - `String` - Normalized forward-slash relative path inside the locale root.
386 /// - `bool` - `true` when originated from `README.md` or `index.md`.
387 pub(crate) fn set_source_meta(&mut self, rel_path: String, is_dir_index: bool) {
388 self.source_rel_path = rel_path;
389 self.is_dir_index = is_dir_index;
390 }
391
392 /// Stores directory frontmatter properties (`index`, `expanded`, `dir.*`) on this page.
393 ///
394 /// # Arguments
395 ///
396 /// - `&Self` - Mutable documentation page reference.
397 /// - `bool` - Whether `index: false` was specified.
398 /// - `Option<bool>` - Optional `expanded:` preference.
399 /// - `Option<i32>` - Optional `dir.order` sort priority.
400 /// - `Option<String>` - Optional `dir.text` display label.
401 /// - `Option<bool>` - Optional `dir.collapsible` preference.
402 pub(crate) fn set_dir_meta(
403 &mut self,
404 index_disabled: bool,
405 dir_expanded: Option<bool>,
406 dir_order: Option<i32>,
407 dir_text: Option<String>,
408 dir_collapsible: Option<bool>,
409 ) {
410 self.index_disabled = index_disabled;
411 self.dir_expanded = dir_expanded;
412 self.dir_order = dir_order;
413 self.dir_text = dir_text;
414 self.dir_collapsible = dir_collapsible;
415 }
416
417 /// Stores page-level password, publication date, and category metadata.
418 ///
419 /// # Arguments
420 ///
421 /// - `&Self` - Mutable documentation page reference.
422 /// - `Option<String>` - Optional page or directory password.
423 /// - `Option<String>` - Optional `date:` value.
424 /// - `Vec<String>` - Optional `category:` list.
425 pub(crate) fn set_page_meta(
426 &mut self,
427 password: Option<String>,
428 date: Option<String>,
429 categories: Vec<String>,
430 ) {
431 self.password = password;
432 self.date = date;
433 self.categories = categories;
434 }
435
436 /// Assigns a directory-inherited password onto this page.
437 ///
438 /// # Arguments
439 ///
440 /// - `&Self` - Mutable documentation page reference.
441 /// - `String` - Inherited password string.
442 pub(crate) fn set_inherited_password(&mut self, pw: String) {
443 self.password = Some(pw);
444 }
445
446 /// Returns `true` when this page contains readable body content (Markdown body, blocks, or home hero/catalog).
447 ///
448 /// # Arguments
449 ///
450 /// - `&Self` - Documentation page reference.
451 ///
452 /// # Returns
453 ///
454 /// - `bool` - Whether rendering this page produces visible document content.
455 #[must_use]
456 pub fn has_readable_content(&self) -> bool {
457 self.get_is_home()
458 || !self.get_markdown_body().trim().is_empty()
459 || !self.get_blocks().is_empty()
460 }
461
462 /// Returns the normalized directory path owning this page (`""` for root-level files, `"euv/core"` for `euv/core/README.md` or `euv/core/app.md`).
463 ///
464 /// # Arguments
465 ///
466 /// - `&Self` - Documentation page reference.
467 ///
468 /// # Returns
469 ///
470 /// - `String` - Forward-slash relative directory path without leading or trailing slashes.
471 #[must_use]
472 pub fn directory_path(&self) -> String {
473 let rel: &str = self.get_source_rel_path().trim();
474 if !rel.is_empty() {
475 return match rel.rsplit_once('/') {
476 Some((dir, _)) => dir.to_string(),
477 None => String::new(),
478 };
479 }
480 let trimmed: &str = self.get_route().trim_matches('/');
481 if trimmed.is_empty() {
482 return String::new();
483 }
484 if self.get_is_dir_index() {
485 return trimmed.to_string();
486 }
487 match trimmed.rsplit_once('/') {
488 Some((dir, _)) => dir.to_string(),
489 None => String::new(),
490 }
491 }
492
493 /// Returns the raw Markdown body slice without frontmatter.
494 ///
495 /// # Arguments
496 ///
497 /// - `&Self` - Documentation page reference.
498 ///
499 /// # Returns
500 ///
501 /// - `&str` - Raw Markdown body text.
502 #[must_use]
503 pub fn markdown_source(&self) -> &str {
504 self.get_markdown_body().as_str()
505 }
506
507 /// Estimates the word count of this document across prose and Markdown source.
508 ///
509 /// # Arguments
510 ///
511 /// - `&Self` - Documentation page reference.
512 ///
513 /// # Returns
514 ///
515 /// - `usize` - Estimated readable word count.
516 #[must_use]
517 pub fn word_count(&self) -> usize {
518 let body: &str = self.get_markdown_body().as_str();
519 if !body.trim().is_empty() {
520 let ws_words: usize = body.split_whitespace().count();
521 let cjk_chars: usize = body
522 .chars()
523 .filter(|c: &char| {
524 let cp: u32 = *c as u32;
525 (0x4E00..=0x9FFF).contains(&cp)
526 || (0x3040..=0x30FF).contains(&cp)
527 || (0xAC00..=0xD7AF).contains(&cp)
528 })
529 .count();
530 return ws_words.saturating_add(cjk_chars / 2).max(1);
531 }
532 let mut words: usize = 0;
533 for block in self.get_blocks().iter() {
534 match block {
535 DocBlock::Heading { text, .. }
536 | DocBlock::Paragraph(text)
537 | DocBlock::ListItem(text)
538 | DocBlock::BlockQuote(text) => {
539 words += text.split_whitespace().count();
540 }
541 DocBlock::Code { code, .. } => {
542 words += code.split_whitespace().count() / 2;
543 }
544 DocBlock::Table { headers, rows } => {
545 for h in headers.iter() {
546 words += h.split_whitespace().count();
547 }
548 for r in rows.iter() {
549 for cell in r.iter() {
550 words += cell.split_whitespace().count();
551 }
552 }
553 }
554 DocBlock::Image { alt, .. } => {
555 words += alt.split_whitespace().count();
556 }
557 DocBlock::HorizontalRule => {}
558 }
559 }
560 words.max(1)
561 }
562
563 /// Estimates the reading time in whole minutes (`>= 1`).
564 ///
565 /// # Arguments
566 ///
567 /// - `&Self` - Documentation page reference.
568 ///
569 /// # Returns
570 ///
571 /// - `usize` - Estimated reading time in minutes.
572 #[must_use]
573 pub fn reading_minutes(&self) -> usize {
574 let words: usize = self.word_count();
575 words.div_ceil(DOCS_WORDS_PER_MINUTE).max(1)
576 }
577
578 /// Returns `true` if `needle` (already lowercased) matches the title, route, summary, or any block.
579 ///
580 /// # Arguments
581 ///
582 /// - `&Self` - Documentation page reference.
583 /// - `&str` - Lowercased search query.
584 ///
585 /// # Returns
586 ///
587 /// - `bool` - Whether the page matches.
588 #[must_use]
589 pub fn matches_query(&self, needle: &str) -> bool {
590 if self.get_title().to_ascii_lowercase().contains(needle)
591 || self.get_route().to_ascii_lowercase().contains(needle)
592 || self.get_summary().to_ascii_lowercase().contains(needle)
593 {
594 return true;
595 }
596 if !self.get_markdown_body().is_empty()
597 && self
598 .get_markdown_body()
599 .to_ascii_lowercase()
600 .contains(needle)
601 {
602 return true;
603 }
604 self.get_blocks()
605 .iter()
606 .any(|block: &DocBlock| match block {
607 DocBlock::Heading { text, .. } => text.to_ascii_lowercase().contains(needle),
608 DocBlock::Paragraph(text)
609 | DocBlock::ListItem(text)
610 | DocBlock::BlockQuote(text) => text.to_ascii_lowercase().contains(needle),
611 DocBlock::Code { code, .. } => code.to_ascii_lowercase().contains(needle),
612 DocBlock::Image { alt, .. } => alt.to_ascii_lowercase().contains(needle),
613 DocBlock::Table { headers, rows } => {
614 let in_headers: bool = headers
615 .iter()
616 .any(|h: &String| h.to_ascii_lowercase().contains(needle));
617 let in_rows: bool = rows.iter().any(|row: &Vec<String>| {
618 row.iter()
619 .any(|cell: &String| cell.to_ascii_lowercase().contains(needle))
620 });
621 in_headers || in_rows
622 }
623 DocBlock::HorizontalRule => false,
624 })
625 }
626}
627
628/// Tree traversal and lookup utilities for `DocCatalogNode`.
629impl DocCatalogNode {
630 /// Returns `true` when this node or any descendant owns `target_route`.
631 ///
632 /// # Arguments
633 ///
634 /// - `&Self` - Catalog node reference.
635 /// - `&str` - Canonical route path to test.
636 ///
637 /// # Returns
638 ///
639 /// - `bool` - Whether `target_route` matches this node or lies inside its subtree.
640 #[must_use]
641 pub fn contains_route(&self, target_route: &str) -> bool {
642 if self.try_get_route().as_deref() == Some(target_route) {
643 return true;
644 }
645 self.get_children()
646 .iter()
647 .any(|child: &DocCatalogNode| child.contains_route(target_route))
648 }
649
650 /// Resolves the canonical click navigation target for this catalog node (`route` when readable, else `first_child_route`).
651 ///
652 /// # Arguments
653 ///
654 /// - `&Self` - Catalog node reference.
655 ///
656 /// # Returns
657 ///
658 /// - `Option<&str>` - Destination route to navigate to when activated.
659 #[must_use]
660 pub fn click_target_route(&self) -> Option<&str> {
661 if self.get_has_own_content()
662 && let Some(r) = self.try_get_route().as_deref()
663 {
664 return Some(r);
665 }
666 if !self.get_is_dir() {
667 return self.try_get_route().as_deref();
668 }
669 if !self.get_index_disabled() {
670 return self.try_get_first_child_route().as_deref();
671 }
672 None
673 }
674
675 /// Recursively sorts child nodes by numeric `order`, directory/file priority, title, and key, and populates `first_child_route`.
676 ///
677 /// # Arguments
678 ///
679 /// - `&Self` - Mutable catalog node reference.
680 pub(crate) fn finalize_recursive(&mut self) {
681 for child in self.get_mut_children().iter_mut() {
682 child.finalize_recursive();
683 }
684 if self.get_is_dir()
685 && self.get_order() == 100
686 && !self.get_has_own_content()
687 && let Some(min_child_order) = self
688 .get_children()
689 .iter()
690 .map(DocCatalogNode::get_order)
691 .min()
692 {
693 let _: &mut Self = self.set_order(min_child_order);
694 }
695 self.get_mut_children()
696 .sort_by(|a: &DocCatalogNode, b: &DocCatalogNode| {
697 let a_root: bool = a.try_get_route().as_deref() == Some("/");
698 let b_root: bool = b.try_get_route().as_deref() == Some("/");
699 if a_root && !b_root {
700 return Ordering::Less;
701 }
702 if b_root && !a_root {
703 return Ordering::Greater;
704 }
705 a.get_order()
706 .cmp(&b.get_order())
707 .then_with(|| {
708 a.get_title()
709 .to_ascii_lowercase()
710 .cmp(&b.get_title().to_ascii_lowercase())
711 })
712 .then_with(|| a.get_key().cmp(b.get_key()))
713 });
714 let first_descendant: Option<String> =
715 self.get_children().iter().find_map(|c: &DocCatalogNode| {
716 if c.get_has_own_content()
717 && !c.get_index_disabled()
718 && let Some(r) = c.try_get_route().as_deref()
719 {
720 return Some(r.to_string());
721 }
722 c.try_get_first_child_route().clone().or_else(|| {
723 if c.get_has_own_content() {
724 c.try_get_route().clone()
725 } else {
726 None
727 }
728 })
729 });
730 let _: &mut Self = self.set_first_child_route(first_descendant);
731 }
732
733 /// Appends every readable page route inside this subtree in canonical depth-first catalog order.
734 ///
735 /// # Arguments
736 ///
737 /// - `&Self` - Catalog node reference.
738 /// - `&mut Vec<String>` - Output ordered route list.
739 pub(crate) fn collect_readable_routes(&self, out: &mut Vec<String>) {
740 if self.get_has_own_content()
741 && let Some(r) = self.try_get_route().as_deref()
742 && !out.iter().any(|existing: &String| existing.as_str() == r)
743 {
744 out.push(r.to_string());
745 }
746 for child in self.get_children().iter() {
747 child.collect_readable_routes(out);
748 }
749 }
750}
751
752/// Hierarchical tree construction for `DocTocTreeNode`.
753impl DocTocTreeNode {
754 /// Converts a flat heading list into a nested tree matching heading levels (`h1..=h4`).
755 ///
756 /// # Arguments
757 ///
758 /// - `&[DocTocItem]` - Flat document heading entries in document order.
759 ///
760 /// # Returns
761 ///
762 /// - `Vec<Self>` - Top-level tree roots with deeper headings nested under their parent heading.
763 #[must_use]
764 pub fn from_flat(items: &[DocTocItem]) -> Vec<Self> {
765 /// Recursively attaches `incoming` under the deepest trailing node with a shallower heading level.
766 ///
767 /// # Arguments
768 ///
769 /// - `&mut Vec<DocTocTreeNode>` - Mutable sibling node list at the current depth.
770 /// - `DocTocTreeNode` - Incoming heading tree node to insert.
771 fn insert_node(roots: &mut Vec<DocTocTreeNode>, incoming: DocTocTreeNode) {
772 if let Some(last) = roots.last_mut()
773 && incoming.get_item().get_level() > last.get_item().get_level()
774 {
775 insert_node(last.get_mut_children(), incoming);
776 return;
777 }
778 roots.push(incoming);
779 }
780 let mut roots: Vec<Self> = Vec::new();
781 for it in items.iter() {
782 insert_node(
783 &mut roots,
784 Self {
785 item: it.clone(),
786 children: Vec::new(),
787 },
788 );
789 }
790 roots
791 }
792
793 /// Returns `true` when this heading node or any nested child matches `slug`.
794 ///
795 /// # Arguments
796 ///
797 /// - `&Self` - Tree node reference.
798 /// - `&str` - Active heading anchor slug.
799 ///
800 /// # Returns
801 ///
802 /// - `bool` - Whether `slug` appears in this subtree.
803 #[must_use]
804 pub fn contains_slug(&self, slug: &str) -> bool {
805 if !slug.is_empty() && self.get_item().get_slug().as_str() == slug {
806 return true;
807 }
808 self.get_children()
809 .iter()
810 .any(|child: &DocTocTreeNode| child.contains_slug(slug))
811 }
812}
813
814/// Filesystem-mirrored directory catalog tree builder on `DocSite`.
815impl DocSite {
816 /// Formats a raw directory segment name into a readable fallback folder label.
817 ///
818 /// # Arguments
819 ///
820 /// - `&str` - Raw directory segment name.
821 ///
822 /// # Returns
823 ///
824 /// - `String` - Human-readable fallback directory label.
825 fn fallback_dir_label(seg: &str) -> String {
826 let trimmed: &str = seg.trim();
827 if trimmed.is_empty() {
828 return DOCS_DEFAULT_TOC_LABEL.to_string();
829 }
830 trimmed.to_string()
831 }
832
833 /// Builds the recursive filesystem-mirrored directory catalog tree strictly matching the docs hierarchy.
834 ///
835 /// # Arguments
836 ///
837 /// - `&Self` - Documentation site reference.
838 ///
839 /// # Returns
840 ///
841 /// - `Vec<DocCatalogNode>` - Deterministically ordered top-level catalog entries.
842 #[must_use]
843 pub fn catalog_tree(&self) -> Vec<DocCatalogNode> {
844 let mut virtual_root: DocCatalogNode = DocCatalogNode {
845 key: String::new(),
846 title: String::new(),
847 route: None,
848 first_child_route: None,
849 is_dir: true,
850 index_disabled: false,
851 has_own_content: false,
852 expanded_pref: Some(true),
853 collapsible: false,
854 order: 0,
855 locked: false,
856 children: Vec::new(),
857 };
858 let mut dir_index_pages: HashMap<String, &DocPage> = HashMap::new();
859 for page in self.get_pages().iter() {
860 if page.get_hide_sidebar() {
861 continue;
862 }
863 if page.get_is_dir_index() {
864 let dir_key: String = page.directory_path();
865 if !dir_key.is_empty() {
866 let _: Option<&DocPage> = dir_index_pages.insert(dir_key, page);
867 }
868 }
869 }
870 /// Ensures every directory prefix in `dir_path` exists under `root`, seeding directory metadata from `dir_index_pages`.
871 ///
872 /// # Arguments
873 ///
874 /// - `&mut DocCatalogNode` - Mutable virtual root node.
875 /// - `&str` - Relative slash-separated directory path.
876 /// - `&HashMap<String, &DocPage>` - Pre-indexed directory `README.md` metadata map.
877 fn ensure_dir_chain(
878 root: &mut DocCatalogNode,
879 dir_path: &str,
880 dir_index_pages: &HashMap<String, &DocPage>,
881 ) {
882 if dir_path.is_empty() {
883 return;
884 }
885 let mut cur_node: &mut DocCatalogNode = root;
886 let mut acc_key: String = String::new();
887 for seg in dir_path.split('/') {
888 if seg.is_empty() {
889 continue;
890 }
891 if !acc_key.is_empty() {
892 acc_key.push('/');
893 }
894 acc_key.push_str(seg);
895 let pos_opt: Option<usize> = cur_node
896 .get_children()
897 .iter()
898 .position(|c: &DocCatalogNode| c.get_is_dir() && c.get_key() == &acc_key);
899 let idx: usize = match pos_opt {
900 Some(i) => i,
901 None => {
902 let meta_opt: Option<&&DocPage> = dir_index_pages.get(&acc_key);
903 let (title, route, has_content, idx_dis, exp_pref, coll, order, locked): (
904 String,
905 Option<String>,
906 bool,
907 bool,
908 Option<bool>,
909 bool,
910 i32,
911 bool,
912 ) = if let Some(&dir_page) = meta_opt {
913 let lbl: String = dir_page
914 .try_get_dir_text()
915 .as_deref()
916 .filter(|s: &&str| !s.trim().is_empty())
917 .map(|s: &str| s.trim().to_string())
918 .unwrap_or_else(|| dir_page.get_title().clone());
919 let readable: bool = dir_page.has_readable_content();
920 let eff_order: i32 =
921 dir_page.get_dir_order().unwrap_or(dir_page.get_order());
922 (
923 lbl,
924 Some(dir_page.get_route().clone()),
925 readable,
926 dir_page.get_index_disabled(),
927 dir_page.get_dir_expanded(),
928 dir_page.get_dir_collapsible().unwrap_or(true),
929 eff_order,
930 dir_page.try_get_password().is_some(),
931 )
932 } else {
933 (
934 DocSite::fallback_dir_label(seg),
935 None,
936 false,
937 false,
938 None,
939 true,
940 100,
941 false,
942 )
943 };
944 cur_node.get_mut_children().push(DocCatalogNode {
945 key: acc_key.clone(),
946 title,
947 route,
948 first_child_route: None,
949 is_dir: true,
950 index_disabled: idx_dis,
951 has_own_content: has_content,
952 expanded_pref: exp_pref,
953 collapsible: coll,
954 order,
955 locked,
956 children: Vec::new(),
957 });
958 cur_node.get_children().len() - 1
959 }
960 };
961 cur_node = &mut cur_node.get_mut_children()[idx];
962 }
963 }
964 for page in self.get_pages().iter() {
965 if page.get_hide_sidebar() {
966 continue;
967 }
968 let dir_path: String = page.directory_path();
969 if page.get_is_dir_index() && !dir_path.is_empty() {
970 ensure_dir_chain(&mut virtual_root, &dir_path, &dir_index_pages);
971 continue;
972 }
973 ensure_dir_chain(&mut virtual_root, &dir_path, &dir_index_pages);
974 let mut parent: &mut DocCatalogNode = &mut virtual_root;
975 if !dir_path.is_empty() {
976 let mut acc_key: String = String::new();
977 for seg in dir_path.split('/') {
978 if seg.is_empty() {
979 continue;
980 }
981 if !acc_key.is_empty() {
982 acc_key.push('/');
983 }
984 acc_key.push_str(seg);
985 if let Some(pos) = parent
986 .children
987 .iter()
988 .position(|c: &DocCatalogNode| c.get_is_dir() && c.get_key() == &acc_key)
989 {
990 parent = &mut parent.children[pos];
991 }
992 }
993 }
994 let readable: bool = page.has_readable_content();
995 let route_str: String = page.get_route().clone();
996 let exists_dir_same_route: bool = parent
997 .children
998 .iter()
999 .any(|c: &DocCatalogNode| c.try_get_route().as_deref() == Some(route_str.as_str()));
1000 if !exists_dir_same_route {
1001 parent.children.push(DocCatalogNode {
1002 key: route_str.clone(),
1003 title: page.get_title().clone(),
1004 route: Some(route_str),
1005 first_child_route: None,
1006 is_dir: false,
1007 index_disabled: false,
1008 has_own_content: readable,
1009 expanded_pref: None,
1010 collapsible: false,
1011 order: page.get_order(),
1012 locked: page.try_get_password().is_some(),
1013 children: Vec::new(),
1014 });
1015 }
1016 }
1017 virtual_root.finalize_recursive();
1018 virtual_root.children
1019 }
1020
1021 /// Returns all visible readable routes in canonical depth-first directory catalog order.
1022 ///
1023 /// # Arguments
1024 ///
1025 /// - `&Self` - Documentation site reference.
1026 ///
1027 /// # Returns
1028 ///
1029 /// - `Vec<String>` - Ordered readable canonical routes suitable for swipe routing and prev/next pagination.
1030 #[must_use]
1031 pub fn catalog_ordered_routes(&self) -> Vec<String> {
1032 let tree: Vec<DocCatalogNode> = self.catalog_tree();
1033 let mut out: Vec<String> = Vec::with_capacity(self.get_pages().len());
1034 for node in tree.iter() {
1035 node.collect_readable_routes(&mut out);
1036 }
1037 if out.is_empty() {
1038 for page in self.get_pages().iter() {
1039 if !page.get_hide_sidebar() {
1040 out.push(page.get_route().clone());
1041 }
1042 }
1043 }
1044 out
1045 }
1046}