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        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    /// Returns the raw Markdown body slice without frontmatter.
381    ///
382    /// # Arguments
383    ///
384    /// - `&Self` - Documentation page reference.
385    ///
386    /// # Returns
387    ///
388    /// - `&str` - Raw Markdown body text.
389    #[must_use]
390    pub fn markdown_source(&self) -> &str {
391        self.get_markdown_body().as_str()
392    }
393
394    /// Estimates the word count of this document across prose and Markdown source.
395    ///
396    /// # Arguments
397    ///
398    /// - `&Self` - Documentation page reference.
399    ///
400    /// # Returns
401    ///
402    /// - `usize` - Estimated readable word count.
403    #[must_use]
404    pub fn word_count(&self) -> usize {
405        let body: &str = self.get_markdown_body().as_str();
406        if !body.trim().is_empty() {
407            let ws_words: usize = body.split_whitespace().count();
408            let cjk_chars: usize = body
409                .chars()
410                .filter(|c: &char| {
411                    let cp: u32 = *c as u32;
412                    (0x4E00..=0x9FFF).contains(&cp)
413                        || (0x3040..=0x30FF).contains(&cp)
414                        || (0xAC00..=0xD7AF).contains(&cp)
415                })
416                .count();
417            return ws_words.saturating_add(cjk_chars / 2).max(1);
418        }
419        let mut words: usize = 0;
420        for block in self.get_blocks().iter() {
421            match block {
422                DocBlock::Heading { text, .. }
423                | DocBlock::Paragraph(text)
424                | DocBlock::ListItem(text)
425                | DocBlock::BlockQuote(text) => {
426                    words += text.split_whitespace().count();
427                }
428                DocBlock::Code { code, .. } => {
429                    words += code.split_whitespace().count() / 2;
430                }
431                DocBlock::Table { headers, rows } => {
432                    for h in headers.iter() {
433                        words += h.split_whitespace().count();
434                    }
435                    for r in rows.iter() {
436                        for cell in r.iter() {
437                            words += cell.split_whitespace().count();
438                        }
439                    }
440                }
441                DocBlock::Image { alt, .. } => {
442                    words += alt.split_whitespace().count();
443                }
444                DocBlock::HorizontalRule => {}
445            }
446        }
447        words.max(1)
448    }
449
450    /// Estimates the reading time in whole minutes (`>= 1`).
451    ///
452    /// # Arguments
453    ///
454    /// - `&Self` - Documentation page reference.
455    ///
456    /// # Returns
457    ///
458    /// - `usize` - Estimated reading time in minutes.
459    #[must_use]
460    pub fn reading_minutes(&self) -> usize {
461        let words: usize = self.word_count();
462        words.div_ceil(DOCS_WORDS_PER_MINUTE).max(1)
463    }
464
465    /// Returns `true` if `needle` (already lowercased) matches the title, route, summary, or any block.
466    ///
467    /// # Arguments
468    ///
469    /// - `&Self` - Documentation page reference.
470    /// - `&str` - Lowercased search query.
471    ///
472    /// # Returns
473    ///
474    /// - `bool` - Whether the page matches.
475    #[must_use]
476    pub fn matches_query(&self, needle: &str) -> bool {
477        if self.get_title().to_ascii_lowercase().contains(needle)
478            || self.get_route().to_ascii_lowercase().contains(needle)
479            || self.get_summary().to_ascii_lowercase().contains(needle)
480        {
481            return true;
482        }
483        if !self.get_markdown_body().is_empty()
484            && self
485                .get_markdown_body()
486                .to_ascii_lowercase()
487                .contains(needle)
488        {
489            return true;
490        }
491        self.get_blocks()
492            .iter()
493            .any(|block: &DocBlock| match block {
494                DocBlock::Heading { text, .. } => text.to_ascii_lowercase().contains(needle),
495                DocBlock::Paragraph(text)
496                | DocBlock::ListItem(text)
497                | DocBlock::BlockQuote(text) => text.to_ascii_lowercase().contains(needle),
498                DocBlock::Code { code, .. } => code.to_ascii_lowercase().contains(needle),
499                DocBlock::Image { alt, .. } => alt.to_ascii_lowercase().contains(needle),
500                DocBlock::Table { headers, rows } => {
501                    let in_headers: bool = headers
502                        .iter()
503                        .any(|h: &String| h.to_ascii_lowercase().contains(needle));
504                    let in_rows: bool = rows.iter().any(|row: &Vec<String>| {
505                        row.iter()
506                            .any(|cell: &String| cell.to_ascii_lowercase().contains(needle))
507                    });
508                    in_headers || in_rows
509                }
510                DocBlock::HorizontalRule => false,
511            })
512    }
513}