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 /// Finds a catalog node matching canonical route or relative directory key inside this subtree.
734 ///
735 /// # Arguments
736 ///
737 /// - `&Self` - Catalog node reference.
738 /// - `&str` - Canonical route (for example `"/essay"` or `"/euv/core/app"`).
739 ///
740 /// # Returns
741 ///
742 /// - `Option<&Self>` - Matching catalog node if found.
743 #[must_use]
744 pub fn find_by_route_or_key(&self, route: &str) -> Option<&Self> {
745 let trimmed: &str = route.trim_matches('/');
746 if self.try_get_route().as_deref() == Some(route)
747 || (!trimmed.is_empty() && self.get_key().trim_matches('/') == trimmed)
748 {
749 return Some(self);
750 }
751 for child in self.get_children().iter() {
752 if let Some(found) = child.find_by_route_or_key(route) {
753 return Some(found);
754 }
755 }
756 None
757 }
758
759 /// Appends every readable page route inside this subtree in canonical depth-first catalog order.
760 ///
761 /// # Arguments
762 ///
763 /// - `&Self` - Catalog node reference.
764 /// - `&mut Vec<String>` - Output ordered route list.
765 pub(crate) fn collect_readable_routes(&self, out: &mut Vec<String>) {
766 if self.get_has_own_content()
767 && let Some(r) = self.try_get_route().as_deref()
768 && !out.iter().any(|existing: &String| existing.as_str() == r)
769 {
770 out.push(r.to_string());
771 }
772 for child in self.get_children().iter() {
773 child.collect_readable_routes(out);
774 }
775 }
776}
777
778/// Hierarchical tree construction for `DocTocTreeNode`.
779impl DocTocTreeNode {
780 /// Converts a flat heading list into a nested tree matching heading levels (`h1..=h4`).
781 ///
782 /// # Arguments
783 ///
784 /// - `&[DocTocItem]` - Flat document heading entries in document order.
785 ///
786 /// # Returns
787 ///
788 /// - `Vec<Self>` - Top-level tree roots with deeper headings nested under their parent heading.
789 #[must_use]
790 pub fn from_flat(items: &[DocTocItem]) -> Vec<Self> {
791 /// Recursively attaches `incoming` under the deepest trailing node with a shallower heading level.
792 ///
793 /// # Arguments
794 ///
795 /// - `&mut Vec<DocTocTreeNode>` - Mutable sibling node list at the current depth.
796 /// - `DocTocTreeNode` - Incoming heading tree node to insert.
797 fn insert_node(roots: &mut Vec<DocTocTreeNode>, incoming: DocTocTreeNode) {
798 if let Some(last) = roots.last_mut()
799 && incoming.get_item().get_level() > last.get_item().get_level()
800 {
801 insert_node(last.get_mut_children(), incoming);
802 return;
803 }
804 roots.push(incoming);
805 }
806 let mut roots: Vec<Self> = Vec::new();
807 for it in items.iter() {
808 insert_node(
809 &mut roots,
810 Self {
811 item: it.clone(),
812 children: Vec::new(),
813 },
814 );
815 }
816 roots
817 }
818
819 /// Returns `true` when this heading node or any nested child matches `slug`.
820 ///
821 /// # Arguments
822 ///
823 /// - `&Self` - Tree node reference.
824 /// - `&str` - Active heading anchor slug.
825 ///
826 /// # Returns
827 ///
828 /// - `bool` - Whether `slug` appears in this subtree.
829 #[must_use]
830 pub fn contains_slug(&self, slug: &str) -> bool {
831 if !slug.is_empty() && self.get_item().get_slug().as_str() == slug {
832 return true;
833 }
834 self.get_children()
835 .iter()
836 .any(|child: &DocTocTreeNode| child.contains_slug(slug))
837 }
838}
839
840/// Filesystem-mirrored directory catalog tree builder on `DocSite`.
841impl DocSite {
842 /// Formats a raw directory segment name into a readable fallback folder label.
843 ///
844 /// # Arguments
845 ///
846 /// - `&str` - Raw directory segment name.
847 ///
848 /// # Returns
849 ///
850 /// - `String` - Human-readable fallback directory label.
851 fn fallback_dir_label(seg: &str) -> String {
852 let trimmed: &str = seg.trim();
853 if trimmed.is_empty() {
854 return DOCS_DEFAULT_TOC_LABEL.to_string();
855 }
856 trimmed.to_string()
857 }
858
859 /// Builds the recursive filesystem-mirrored directory catalog tree strictly matching the docs hierarchy.
860 ///
861 /// # Arguments
862 ///
863 /// - `&Self` - Documentation site reference.
864 ///
865 /// # Returns
866 ///
867 /// - `Vec<DocCatalogNode>` - Deterministically ordered top-level catalog entries.
868 #[must_use]
869 pub fn catalog_tree(&self) -> Vec<DocCatalogNode> {
870 let mut virtual_root: DocCatalogNode = DocCatalogNode {
871 key: String::new(),
872 title: String::new(),
873 route: None,
874 first_child_route: None,
875 is_dir: true,
876 index_disabled: false,
877 has_own_content: false,
878 expanded_pref: Some(true),
879 collapsible: false,
880 order: 0,
881 locked: false,
882 children: Vec::new(),
883 };
884 let mut dir_index_pages: HashMap<String, &DocPage> = HashMap::new();
885 for page in self.get_pages().iter() {
886 if page.get_hide_sidebar() {
887 continue;
888 }
889 if page.get_is_dir_index() {
890 let dir_key: String = page.directory_path();
891 if !dir_key.is_empty() {
892 let _: Option<&DocPage> = dir_index_pages.insert(dir_key, page);
893 }
894 }
895 }
896 /// Ensures every directory prefix in `dir_path` exists under `root`, seeding directory metadata from `dir_index_pages`.
897 ///
898 /// # Arguments
899 ///
900 /// - `&mut DocCatalogNode` - Mutable virtual root node.
901 /// - `&str` - Relative slash-separated directory path.
902 /// - `&HashMap<String, &DocPage>` - Pre-indexed directory `README.md` metadata map.
903 fn ensure_dir_chain(
904 root: &mut DocCatalogNode,
905 dir_path: &str,
906 dir_index_pages: &HashMap<String, &DocPage>,
907 ) {
908 if dir_path.is_empty() {
909 return;
910 }
911 let mut cur_node: &mut DocCatalogNode = root;
912 let mut acc_key: String = String::new();
913 for seg in dir_path.split('/') {
914 if seg.is_empty() {
915 continue;
916 }
917 if !acc_key.is_empty() {
918 acc_key.push('/');
919 }
920 acc_key.push_str(seg);
921 let pos_opt: Option<usize> = cur_node
922 .get_children()
923 .iter()
924 .position(|c: &DocCatalogNode| c.get_is_dir() && c.get_key() == &acc_key);
925 let idx: usize = match pos_opt {
926 Some(i) => i,
927 None => {
928 let meta_opt: Option<&&DocPage> = dir_index_pages.get(&acc_key);
929 let (title, route, has_content, idx_dis, exp_pref, coll, order, locked): (
930 String,
931 Option<String>,
932 bool,
933 bool,
934 Option<bool>,
935 bool,
936 i32,
937 bool,
938 ) = if let Some(&dir_page) = meta_opt {
939 let lbl: String = dir_page
940 .try_get_dir_text()
941 .as_deref()
942 .filter(|s: &&str| !s.trim().is_empty())
943 .map(|s: &str| s.trim().to_string())
944 .unwrap_or_else(|| dir_page.get_title().clone());
945 let readable: bool = dir_page.has_readable_content();
946 let eff_order: i32 =
947 dir_page.get_dir_order().unwrap_or(dir_page.get_order());
948 (
949 lbl,
950 Some(dir_page.get_route().clone()),
951 readable,
952 dir_page.get_index_disabled(),
953 dir_page.get_dir_expanded(),
954 dir_page.get_dir_collapsible().unwrap_or(true),
955 eff_order,
956 dir_page.try_get_password().is_some(),
957 )
958 } else {
959 (
960 DocSite::fallback_dir_label(seg),
961 None,
962 false,
963 false,
964 None,
965 true,
966 100,
967 false,
968 )
969 };
970 cur_node.get_mut_children().push(DocCatalogNode {
971 key: acc_key.clone(),
972 title,
973 route,
974 first_child_route: None,
975 is_dir: true,
976 index_disabled: idx_dis,
977 has_own_content: has_content,
978 expanded_pref: exp_pref,
979 collapsible: coll,
980 order,
981 locked,
982 children: Vec::new(),
983 });
984 cur_node.get_children().len() - 1
985 }
986 };
987 cur_node = &mut cur_node.get_mut_children()[idx];
988 }
989 }
990 for page in self.get_pages().iter() {
991 if page.get_hide_sidebar() {
992 continue;
993 }
994 let dir_path: String = page.directory_path();
995 if page.get_is_dir_index() && !dir_path.is_empty() {
996 ensure_dir_chain(&mut virtual_root, &dir_path, &dir_index_pages);
997 continue;
998 }
999 ensure_dir_chain(&mut virtual_root, &dir_path, &dir_index_pages);
1000 let mut parent: &mut DocCatalogNode = &mut virtual_root;
1001 if !dir_path.is_empty() {
1002 let mut acc_key: String = String::new();
1003 for seg in dir_path.split('/') {
1004 if seg.is_empty() {
1005 continue;
1006 }
1007 if !acc_key.is_empty() {
1008 acc_key.push('/');
1009 }
1010 acc_key.push_str(seg);
1011 if let Some(pos) = parent
1012 .children
1013 .iter()
1014 .position(|c: &DocCatalogNode| c.get_is_dir() && c.get_key() == &acc_key)
1015 {
1016 parent = &mut parent.children[pos];
1017 }
1018 }
1019 }
1020 let readable: bool = page.has_readable_content();
1021 let route_str: String = page.get_route().clone();
1022 let exists_dir_same_route: bool = parent
1023 .children
1024 .iter()
1025 .any(|c: &DocCatalogNode| c.try_get_route().as_deref() == Some(route_str.as_str()));
1026 if !exists_dir_same_route {
1027 parent.children.push(DocCatalogNode {
1028 key: route_str.clone(),
1029 title: page.get_title().clone(),
1030 route: Some(route_str),
1031 first_child_route: None,
1032 is_dir: false,
1033 index_disabled: false,
1034 has_own_content: readable,
1035 expanded_pref: None,
1036 collapsible: false,
1037 order: page.get_order(),
1038 locked: page.try_get_password().is_some(),
1039 children: Vec::new(),
1040 });
1041 }
1042 }
1043 virtual_root.finalize_recursive();
1044 virtual_root.children
1045 }
1046
1047 /// Resolves any candidate route or folder path (including empty-README, `index: false`, or README-less folders) to a readable document route.
1048 ///
1049 /// # Arguments
1050 ///
1051 /// - `&Self` - Documentation site reference.
1052 /// - `&str` - Candidate canonical route (for example `"/essay"`, `"/euv/core"`, `"/euv/ui/component/button"`).
1053 ///
1054 /// # Returns
1055 ///
1056 /// - `Option<String>` - Resolved readable document route when found in the site or catalog tree.
1057 #[must_use]
1058 pub fn resolve_readable_route(&self, route: &str) -> Option<String> {
1059 let normalized: String = {
1060 let t: &str = route.trim().trim_end_matches('/');
1061 if t.is_empty() {
1062 "/".to_string()
1063 } else if t.starts_with('/') {
1064 t.to_string()
1065 } else {
1066 format!("/{t}")
1067 }
1068 };
1069 let tree: Vec<DocCatalogNode> = self.catalog_tree();
1070 for root in tree.iter() {
1071 if let Some(node) = root.find_by_route_or_key(&normalized) {
1072 if !node.get_is_dir() || (node.get_has_own_content() && !node.get_index_disabled())
1073 {
1074 if let Some(r) = node.try_get_route().as_deref() {
1075 return Some(r.to_string());
1076 }
1077 } else if let Some(first) = node.try_get_first_child_route().as_deref() {
1078 return Some(first.to_string());
1079 } else if let Some(r) = node.try_get_route().as_deref() {
1080 return Some(r.to_string());
1081 }
1082 }
1083 }
1084 self.find_by_route(&normalized)
1085 .map(|p: &DocPage| p.get_route().clone())
1086 }
1087
1088 /// Returns all visible readable routes in canonical depth-first directory catalog order.
1089 ///
1090 /// # Arguments
1091 ///
1092 /// - `&Self` - Documentation site reference.
1093 ///
1094 /// # Returns
1095 ///
1096 /// - `Vec<String>` - Ordered readable canonical routes suitable for swipe routing and prev/next pagination.
1097 #[must_use]
1098 pub fn catalog_ordered_routes(&self) -> Vec<String> {
1099 let tree: Vec<DocCatalogNode> = self.catalog_tree();
1100 let mut out: Vec<String> = Vec::with_capacity(self.get_pages().len());
1101 for node in tree.iter() {
1102 node.collect_readable_routes(&mut out);
1103 }
1104 if out.is_empty() {
1105 for page in self.get_pages().iter() {
1106 if !page.get_hide_sidebar() {
1107 out.push(page.get_route().clone());
1108 }
1109 }
1110 }
1111 out
1112 }
1113}