Skip to main content

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