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 let trimmed: String = excerpt.chars().take(360).collect();
271 SearchIndexEntry::new(
272 page.get_route().clone(),
273 page.get_title().clone(),
274 page.get_section().clone(),
275 page.get_summary().clone(),
276 headings,
277 trimmed,
278 )
279 })
280 .collect()
281 }
282}
283
284/// Query matching, reading-time estimation, and frontmatter metadata helpers for `DocPage`.
285impl DocPage {
286 /// Stores the raw Markdown body slice for full-fidelity HTML and native rendering.
287 ///
288 /// # Arguments
289 ///
290 /// - `&Self` - Mutable documentation page reference.
291 /// - `String` - Raw Markdown body text without frontmatter.
292 pub(crate) fn set_markdown_body(&mut self, body: String) {
293 self.markdown_body = body;
294 }
295
296 /// Stores optional last-updated frontmatter stamp.
297 ///
298 /// # Arguments
299 ///
300 /// - `&Self` - Mutable documentation page reference.
301 /// - `Option<String>` - Optional date or version string.
302 pub(crate) fn set_updated(&mut self, updated: Option<String>) {
303 self.updated = updated;
304 }
305
306 /// Stores landing-page frontmatter metadata (`home`, `heroText`, `actions`, `stats`, `features`).
307 ///
308 /// # Arguments
309 ///
310 /// - `&Self` - Mutable documentation page reference.
311 /// - `bool` - Whether this page uses the home landing layout.
312 /// - `Option<String>` - Optional hero display heading.
313 /// - `Vec<DocHomeAction>` - Landing-page call-to-action buttons.
314 /// - `Vec<DocHomeStat>` - Landing-page metric tiles.
315 /// - `Vec<DocHomeFeature>` - Landing-page feature cards.
316 pub(crate) fn set_home_meta(
317 &mut self,
318 is_home: bool,
319 hero_text: Option<String>,
320 actions: Vec<DocHomeAction>,
321 stats: Vec<DocHomeStat>,
322 features: Vec<DocHomeFeature>,
323 ) {
324 self.is_home = is_home;
325 self.hero_text = hero_text;
326 self.actions = actions;
327 self.stats = stats;
328 self.features = features;
329 }
330
331 /// Marks whether this page should be omitted from sidebar navigation trees.
332 ///
333 /// # Arguments
334 ///
335 /// - `&Self` - Mutable documentation page reference.
336 /// - `bool` - `true` when `sidebar: false` is set in frontmatter.
337 pub(crate) fn set_hide_sidebar(&mut self, hide: bool) {
338 self.hide_sidebar = hide;
339 }
340
341 /// Returns the raw Markdown body slice without frontmatter.
342 ///
343 /// # Arguments
344 ///
345 /// - `&Self` - Documentation page reference.
346 ///
347 /// # Returns
348 ///
349 /// - `&str` - Raw Markdown body text.
350 #[must_use]
351 pub fn markdown_source(&self) -> &str {
352 self.get_markdown_body().as_str()
353 }
354
355 /// Estimates the word count of this document across prose and Markdown source.
356 ///
357 /// # Arguments
358 ///
359 /// - `&Self` - Documentation page reference.
360 ///
361 /// # Returns
362 ///
363 /// - `usize` - Estimated readable word count.
364 #[must_use]
365 pub fn word_count(&self) -> usize {
366 let body: &str = self.get_markdown_body().as_str();
367 if !body.trim().is_empty() {
368 let ws_words: usize = body.split_whitespace().count();
369 let cjk_chars: usize = body
370 .chars()
371 .filter(|c: &char| {
372 let cp: u32 = *c as u32;
373 (0x4E00..=0x9FFF).contains(&cp)
374 || (0x3040..=0x30FF).contains(&cp)
375 || (0xAC00..=0xD7AF).contains(&cp)
376 })
377 .count();
378 return ws_words.saturating_add(cjk_chars / 2).max(1);
379 }
380 let mut words: usize = 0;
381 for block in self.get_blocks().iter() {
382 match block {
383 DocBlock::Heading { text, .. }
384 | DocBlock::Paragraph(text)
385 | DocBlock::ListItem(text)
386 | DocBlock::BlockQuote(text) => {
387 words += text.split_whitespace().count();
388 }
389 DocBlock::Code { code, .. } => {
390 words += code.split_whitespace().count() / 2;
391 }
392 DocBlock::Table { headers, rows } => {
393 for h in headers.iter() {
394 words += h.split_whitespace().count();
395 }
396 for r in rows.iter() {
397 for cell in r.iter() {
398 words += cell.split_whitespace().count();
399 }
400 }
401 }
402 DocBlock::Image { alt, .. } => {
403 words += alt.split_whitespace().count();
404 }
405 DocBlock::HorizontalRule => {}
406 }
407 }
408 words.max(1)
409 }
410
411 /// Estimates the reading time in whole minutes (`>= 1`).
412 ///
413 /// # Arguments
414 ///
415 /// - `&Self` - Documentation page reference.
416 ///
417 /// # Returns
418 ///
419 /// - `usize` - Estimated reading time in minutes.
420 #[must_use]
421 pub fn reading_minutes(&self) -> usize {
422 let words: usize = self.word_count();
423 words.div_ceil(DOCS_WORDS_PER_MINUTE).max(1)
424 }
425
426 /// Returns `true` if `needle` (already lowercased) matches the title, route, summary, or any block.
427 ///
428 /// # Arguments
429 ///
430 /// - `&Self` - Documentation page reference.
431 /// - `&str` - Lowercased search query.
432 ///
433 /// # Returns
434 ///
435 /// - `bool` - Whether the page matches.
436 #[must_use]
437 pub fn matches_query(&self, needle: &str) -> bool {
438 if self.get_title().to_ascii_lowercase().contains(needle)
439 || self.get_route().to_ascii_lowercase().contains(needle)
440 || self.get_summary().to_ascii_lowercase().contains(needle)
441 {
442 return true;
443 }
444 self.get_blocks()
445 .iter()
446 .any(|block: &DocBlock| match block {
447 DocBlock::Heading { text, .. } => text.to_ascii_lowercase().contains(needle),
448 DocBlock::Paragraph(text)
449 | DocBlock::ListItem(text)
450 | DocBlock::BlockQuote(text) => text.to_ascii_lowercase().contains(needle),
451 DocBlock::Code { code, .. } => code.to_ascii_lowercase().contains(needle),
452 DocBlock::Image { alt, .. } => alt.to_ascii_lowercase().contains(needle),
453 DocBlock::Table { headers, rows } => {
454 let in_headers: bool = headers
455 .iter()
456 .any(|h: &String| h.to_ascii_lowercase().contains(needle));
457 let in_rows: bool = rows.iter().any(|row: &Vec<String>| {
458 row.iter()
459 .any(|cell: &String| cell.to_ascii_lowercase().contains(needle))
460 });
461 in_headers || in_rows
462 }
463 DocBlock::HorizontalRule => false,
464 })
465 }
466}