Skip to main content

euv_docs/viewer/
fn.rs

1use super::*;
2
3/// Returns whether a catalog artifact name segment contains only lowercase ASCII letters, digits, or interior hyphens.
4///
5/// # Arguments
6///
7/// - `&str` - Candidate artifact path segment.
8///
9/// # Returns
10///
11/// - `bool` - `true` when safe to interpolate into `/pages/<name>/`.
12fn is_safe_catalog_segment(seg: &str) -> bool {
13    !seg.is_empty()
14        && !seg.starts_with('-')
15        && !seg.ends_with('-')
16        && seg
17            .bytes()
18            .all(|b: u8| b.is_ascii_lowercase() || b.is_ascii_digit() || b == DOCS_BYTE_DASH)
19}
20
21/// Validates a published artifact name (`name` or `org/repo`) against path traversal and unsafe characters.
22///
23/// # Arguments
24///
25/// - `&str` - Artifact name string from `/api/page-artifacts`.
26///
27/// # Returns
28///
29/// - `bool` - `true` when the name is a valid bare or qualified artifact identifier.
30fn is_safe_catalog_name(name: &str) -> bool {
31    if name.is_empty() || name.len() > 63 {
32        return false;
33    }
34    let parts: Vec<&str> = name.split('/').collect();
35    if parts.len() > 2 {
36        return false;
37    }
38    parts.iter().all(|seg: &&str| is_safe_catalog_segment(seg))
39}
40
41/// Validates that a digest string is a 64-character lowercase hexadecimal SHA-256 hash.
42///
43/// # Arguments
44///
45/// - `&str` - Candidate SHA-256 digest string.
46///
47/// # Returns
48///
49/// - `bool` - `true` when properly formatted.
50fn is_valid_sha256_hex(digest: &str) -> bool {
51    digest.len() == 64
52        && digest
53            .bytes()
54            .all(|b: u8| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
55}
56
57/// Parses and validates a `/api/page-artifacts` JSON response into `DocsCatalogArtifact` entries.
58///
59/// # Arguments
60///
61/// - `&str` - Raw UTF-8 JSON body returned by `/api/page-artifacts`.
62///
63/// # Returns
64///
65/// - `Result<Vec<DocsCatalogArtifact>, String>` - Validated catalog artifacts or shape error message.
66pub fn parse_catalog_artifacts_json(raw: &str) -> Result<Vec<DocsCatalogArtifact>, String> {
67    let val: Value = serde_json::from_str(raw).map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
68    let expected_count: Option<u64> = val.get(DOCS_CATALOG_FIELD_COUNT).and_then(Value::as_u64);
69    let arr: &[Value] = if let Some(list) = val.as_array() {
70        list.as_slice()
71    } else if let Some(list) = val.get(DOCS_CATALOG_FIELD_ITEMS).and_then(Value::as_array) {
72        list.as_slice()
73    } else if let Some(list) = val
74        .get(DOCS_CATALOG_FIELD_ARTIFACTS)
75        .and_then(Value::as_array)
76    {
77        list.as_slice()
78    } else if let Some(list) = val.get(DOCS_CATALOG_FIELD_DATA).and_then(Value::as_array) {
79        list.as_slice()
80    } else {
81        return Err(DOCS_CATALOG_ERR_SHAPE.to_string());
82    };
83    let mut parsed: Vec<DocsCatalogArtifact> = Vec::with_capacity(arr.len());
84    for entry in arr.iter() {
85        let name: String = entry
86            .get(DOCS_CATALOG_FIELD_NAME)
87            .and_then(Value::as_str)
88            .ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?
89            .to_string();
90        if !is_safe_catalog_name(&name) {
91            return Err(DOCS_CATALOG_ERR_SHAPE.to_string());
92        }
93        let file_count: u64 = entry
94            .get(DOCS_CATALOG_FIELD_FILES)
95            .and_then(Value::as_u64)
96            .ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?;
97        let total_bytes: u64 = entry
98            .get(DOCS_CATALOG_FIELD_BYTES)
99            .and_then(Value::as_u64)
100            .ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?;
101        let sha256: String = entry
102            .get(DOCS_CATALOG_FIELD_SHA)
103            .and_then(Value::as_str)
104            .ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?
105            .to_string();
106        if !is_valid_sha256_hex(&sha256) {
107            return Err(DOCS_CATALOG_ERR_SHAPE.to_string());
108        }
109        let updated_at: i64 = entry
110            .get(DOCS_CATALOG_FIELD_UPDATED)
111            .and_then(Value::as_i64)
112            .ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?;
113        parsed.push(DocsCatalogArtifact::new(
114            name,
115            file_count,
116            total_bytes,
117            sha256,
118            updated_at,
119        ));
120    }
121    if let Some(count) = expected_count
122        && (count as usize) != parsed.len()
123    {
124        return Err(DOCS_CATALOG_ERR_SHAPE.to_string());
125    }
126    Ok(parsed)
127}
128
129/// Formats a byte count into a human-readable size string paired with raw bytes for tooltip inspection.
130///
131/// # Arguments
132///
133/// - `u64` - Total payload size in bytes.
134///
135/// # Returns
136///
137/// - `String` - Formatted size string (for example `"1.42 MB (1488976 B)"`).
138#[must_use]
139pub fn format_catalog_bytes(bytes: u64) -> String {
140    if bytes >= 1_048_576 {
141        let mb: f64 = (bytes as f64) / 1_048_576.0;
142        format!("{mb:.2} MB ({bytes} B)")
143    } else if bytes >= 1024 {
144        let kb: f64 = (bytes as f64) / 1024.0;
145        format!("{kb:.1} KB ({bytes} B)")
146    } else {
147        format!("{bytes} B")
148    }
149}
150
151/// Formats a Unix epoch second timestamp into an ISO-8601 UTC string (`YYYY-MM-DD HH:MM:SS UTC`).
152///
153/// # Arguments
154///
155/// - `i64` - Unix timestamp in seconds.
156///
157/// # Returns
158///
159/// - `String` - Formatted UTC timestamp string.
160#[must_use]
161pub fn format_catalog_utc(timestamp: i64) -> String {
162    DateTime::from_timestamp(timestamp, 0)
163        .map(|dt: DateTime<Utc>| dt.format("%Y-%m-%d %H:%M:%S UTC").to_string())
164        .unwrap_or_else(|| format!("{timestamp} UTC"))
165}
166
167/// Resolves localized UI strings for the `/api/page-artifacts` catalog from `lang`.
168///
169/// # Arguments
170///
171/// - `&str` - Active BCP 47 language code (for example `"zh-CN"`, `"en-US"`, `"ja-JP"`, `"ko-KR"`).
172///
173/// # Returns
174///
175/// - `[&'static str; 7]` - `[title, loading, error, retry, files, size, updated]` labels.
176fn catalog_locale_labels(lang: &str) -> [&'static str; 7] {
177    let lower: String = lang.to_ascii_lowercase();
178    if lower.starts_with(DOCS_LANG_PREFIX_ZH) {
179        [
180            DOCS_CATALOG_TITLE_ZH,
181            DOCS_CATALOG_LOADING_ZH,
182            DOCS_CATALOG_ERROR_ZH,
183            DOCS_CATALOG_RETRY_ZH,
184            DOCS_CATALOG_FILES_ZH,
185            DOCS_CATALOG_SIZE_ZH,
186            DOCS_CATALOG_UPDATED_ZH,
187        ]
188    } else if lower.starts_with(DOCS_LANG_PREFIX_JA) {
189        [
190            DOCS_CATALOG_TITLE_JA,
191            DOCS_CATALOG_LOADING_JA,
192            DOCS_CATALOG_ERROR_JA,
193            DOCS_CATALOG_RETRY_JA,
194            DOCS_CATALOG_FILES_JA,
195            DOCS_CATALOG_SIZE_JA,
196            DOCS_CATALOG_UPDATED_JA,
197        ]
198    } else if lower.starts_with(DOCS_LANG_PREFIX_KO) {
199        [
200            DOCS_CATALOG_TITLE_KO,
201            DOCS_CATALOG_LOADING_KO,
202            DOCS_CATALOG_ERROR_KO,
203            DOCS_CATALOG_RETRY_KO,
204            DOCS_CATALOG_FILES_KO,
205            DOCS_CATALOG_SIZE_KO,
206            DOCS_CATALOG_UPDATED_KO,
207        ]
208    } else {
209        [
210            DOCS_CATALOG_TITLE_EN,
211            DOCS_CATALOG_LOADING_EN,
212            DOCS_CATALOG_ERROR_EN,
213            DOCS_CATALOG_RETRY_EN,
214            DOCS_CATALOG_FILES_EN,
215            DOCS_CATALOG_SIZE_EN,
216            DOCS_CATALOG_UPDATED_EN,
217        ]
218    }
219}
220
221/// Opens an external URL or site-relative path in the host browser when running on WebAssembly.
222///
223/// # Arguments
224///
225/// - `&str` - Destination URL or path.
226/// - `bool` - When `true`, opens in a new browser tab; otherwise navigates the current tab.
227#[cfg(target_arch = "wasm32")]
228fn open_browser_url(url: &str, new_tab: bool) {
229    let Some(win) = window() else {
230        return;
231    };
232    if new_tab {
233        if let Ok(open_val) = Reflect::get(&win, &JsValue::from_str(WEB_JS_OPEN))
234            && let Ok(open_fn) = open_val.dyn_into::<Function>()
235        {
236            let _: Result<JsValue, JsValue> = open_fn.call3(
237                &win,
238                &JsValue::from_str(url),
239                &JsValue::from_str(WEB_JS_BLANK),
240                &JsValue::from_str(WEB_JS_NOOPENER),
241            );
242        }
243    } else {
244        let _: Result<(), JsValue> = win.location().set_href(url);
245    }
246}
247
248/// Navigates to an internal documentation route or delegates external URLs cleanly.
249///
250/// # Arguments
251///
252/// - `&str` - Clicked Markdown link or button destination.
253/// - `&DocSite` - Loaded documentation site for internal route resolution.
254/// - `Signal<String>` - Active route signal.
255/// - `Signal<String>` - Active TOC anchor slug signal.
256fn navigate_doc_href(
257    href: &str,
258    site: &DocSite,
259    active_route: Signal<String>,
260    active_toc_slug: Signal<String>,
261) {
262    let trimmed: &str = href.trim();
263    if trimmed.is_empty() {
264        return;
265    }
266    if let Some(anchor) = trimmed.strip_prefix('#') {
267        if !anchor.is_empty() {
268            let _: bool = active_toc_slug.set_if_changed(anchor.to_string());
269        }
270        return;
271    }
272    let lower: String = trimmed.to_ascii_lowercase();
273    if lower.starts_with(DOCS_URL_SCHEME_HTTP)
274        || lower.starts_with(DOCS_URL_SCHEME_HTTPS)
275        || lower.starts_with(DOCS_URL_SCHEME_MAILTO)
276    {
277        #[cfg(target_arch = "wasm32")]
278        open_browser_url(trimmed, true);
279        return;
280    }
281    if let Some(page) = site.find_by_route(trimmed) {
282        let _: bool = active_route.set_if_changed(page.get_route().clone());
283        let _: bool = active_toc_slug.set_if_changed(String::new());
284        return;
285    }
286    let clean: &str = trimmed
287        .split('#')
288        .next()
289        .unwrap_or(trimmed)
290        .trim_end_matches(".md")
291        .trim_end_matches(".html")
292        .trim_end_matches('/');
293    if let Some(page) = site.find_by_route(clean) {
294        let _: bool = active_route.set_if_changed(page.get_route().clone());
295        let _: bool = active_toc_slug.set_if_changed(String::new());
296    } else {
297        #[cfg(target_arch = "wasm32")]
298        open_browser_url(trimmed, false);
299    }
300}
301
302/// Triggers an asynchronous browser `fetch("/api/page-artifacts")` request populating `state` catalog signals on WebAssembly.
303///
304/// # Arguments
305///
306/// - `&DocsViewerState` - Shared documentation viewer state receiving parsed artifacts or error status.
307#[cfg(target_arch = "wasm32")]
308fn trigger_wasm_catalog_fetch(state: &DocsViewerState) {
309    let items_sig: Signal<Vec<DocsCatalogArtifact>> = state.get_catalog_items();
310    let loading_sig: Signal<bool> = state.get_catalog_loading();
311    let error_sig: Signal<bool> = state.get_catalog_error();
312    let _: bool = loading_sig.set_if_changed(true);
313    let _: bool = error_sig.set_if_changed(false);
314    spawn_local(async move {
315        let fetched: Result<Vec<DocsCatalogArtifact>, String> = fetch_catalog_wasm().await;
316        let _: bool = loading_sig.set_if_changed(false);
317        match fetched {
318            Ok(list) => {
319                let _: bool = items_sig.set(list);
320                let _: bool = error_sig.set_if_changed(false);
321            }
322            Err(_) => {
323                let _: bool = error_sig.set_if_changed(true);
324            }
325        }
326        let _: u64 = wasm_docs_tick(0.0);
327    });
328}
329
330/// Fetches `/api/page-artifacts` via `window.fetch` using `js_sys::Reflect` so zero extra `web-sys` features are required.
331///
332/// # Returns
333///
334/// - `Result<Vec<DocsCatalogArtifact>, String>` - Parsed public catalog entries or failure reason.
335#[cfg(target_arch = "wasm32")]
336async fn fetch_catalog_wasm() -> Result<Vec<DocsCatalogArtifact>, String> {
337    let win: Window = window().ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?;
338    let fetch_val: JsValue = Reflect::get(&win, &JsValue::from_str(WEB_JS_FETCH))
339        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
340    let fetch_fn: Function = fetch_val
341        .dyn_into::<Function>()
342        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
343    let promise_val: JsValue = fetch_fn
344        .call1(&win, &JsValue::from_str(DOCS_CATALOG_API_PATH))
345        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
346    let promise: Promise = promise_val
347        .dyn_into::<Promise>()
348        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
349    let resp: JsValue = JsFuture::from(promise)
350        .await
351        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
352    let ok_flag: bool = Reflect::get(&resp, &JsValue::from_str(WEB_JS_OK))
353        .ok()
354        .and_then(|v: JsValue| v.as_bool())
355        .unwrap_or(false);
356    if !ok_flag {
357        return Err(DOCS_CATALOG_ERR_SHAPE.to_string());
358    }
359    let text_val: JsValue = Reflect::get(&resp, &JsValue::from_str(WEB_JS_TEXT))
360        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
361    let text_fn: Function = text_val
362        .dyn_into::<Function>()
363        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
364    let text_promise_val: JsValue = text_fn
365        .call0(&resp)
366        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
367    let text_promise: Promise = text_promise_val
368        .dyn_into::<Promise>()
369        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
370    let body_val: JsValue = JsFuture::from(text_promise)
371        .await
372        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
373    let body_str: String = body_val
374        .as_string()
375        .ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?;
376    parse_catalog_artifacts_json(&body_str)
377}
378
379/// Renders the compiled Rust `/api/page-artifacts` public catalog section with loading, localized error/retry, and expandable SHA-256 cards.
380///
381/// # Arguments
382///
383/// - `&DocsViewerState` - Shared reactive viewer state carrying catalog signals.
384/// - `ThemeTokens` - Active design tokens.
385///
386/// # Returns
387///
388/// - `NodeId` - Mounted catalog section container node.
389pub fn mount_docs_catalog(state: &DocsViewerState, tokens: ThemeTokens) -> NodeId {
390    let lang: String = state.get_site().resolved_lang().to_string();
391    let [
392        title_lbl,
393        loading_lbl,
394        err_lbl,
395        retry_lbl,
396        files_lbl,
397        size_lbl,
398        updated_lbl,
399    ]: [&'static str; 7] = catalog_locale_labels(&lang);
400    let state_body: DocsViewerState = state.clone();
401    let build_catalog_children = move || -> Vec<NodeId> {
402        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
403        let p: ThemePalette = live_tok.get_palette();
404        let is_loading: bool = state_body.get_catalog_loading().get();
405        let is_error: bool = state_body.get_catalog_error().get();
406        let items: Vec<DocsCatalogArtifact> = state_body.get_catalog_items().get();
407        if is_loading {
408            return vec![view! {
409                EuvAlert {
410                    title: title_lbl.to_string()
411                    description: loading_lbl.to_string()
412                    tone: EuvTone::Primary
413                    tokens: live_tok
414                }
415            }];
416        }
417        if is_error {
418            let retry_state: DocsViewerState = state_body.clone();
419            let on_retry = move |_: &UiEvent| {
420                #[cfg(target_arch = "wasm32")]
421                trigger_wasm_catalog_fetch(&retry_state);
422                #[cfg(not(target_arch = "wasm32"))]
423                {
424                    let _: bool = retry_state.get_catalog_error().set_if_changed(false);
425                }
426            };
427            return vec![view! {
428                column {
429                    style: {
430                        width: Length::Percent(100.0)
431                        gap: SPACE_SM
432                    }
433                    EuvAlert {
434                        title: title_lbl.to_string()
435                        description: err_lbl.to_string()
436                        tone: EuvTone::Warning
437                        tokens: live_tok
438                    }
439                    EuvButton {
440                        label: retry_lbl.to_string()
441                        tokens: live_tok
442                        on_click: on_retry
443                    }
444                }
445            }];
446        }
447        if items.is_empty() {
448            return vec![view! {
449                EuvEmpty {
450                    title: title_lbl.to_string()
451                    description: format!("{DOCS_CATALOG_EMPTY_EN} ({DOCS_CATALOG_CARD_CLASS})")
452                    tokens: live_tok
453                }
454            }];
455        }
456        let mut cards: Vec<NodeId> = Vec::with_capacity(items.len());
457        for art in items.into_iter() {
458            let art_name: String = art.get_name().clone();
459            let page_href: String = format!("/pages/{art_name}/");
460            let files_tag: String = format!("{files_lbl}: {}", art.get_file_count());
461            let size_tag: String = format!(
462                "{size_lbl}: {}",
463                format_catalog_bytes(art.get_total_bytes())
464            );
465            let updated_tag: String = format!(
466                "{updated_lbl}: {}",
467                format_catalog_utc(art.get_updated_at())
468            );
469            let sha_full: String = art.get_sha256().clone();
470            let sha_copy_val: String = sha_full.clone();
471            let copied_sig: Signal<bool> = Signal::new(false);
472            let sha_open_sig: Signal<bool> = Signal::new(false);
473            let on_copy_sha = move |_: &UiEvent| {
474                let ctx: Context = current_context();
475                let _: bool = ctx.copy_to_clipboard(&sha_copy_val);
476                let _: bool = copied_sig.set_if_changed(true);
477            };
478            let copy_lbl_fn = move || -> String {
479                if copied_sig.get() {
480                    DOCS_CATALOG_SHA_COPIED.to_string()
481                } else {
482                    DOCS_CATALOG_SHA_COPY.to_string()
483                }
484            };
485            let open_href: String = page_href.clone();
486            let on_open_art = move |_: &UiEvent| {
487                #[cfg(target_arch = "wasm32")]
488                open_browser_url(&open_href, true);
489                #[cfg(not(target_arch = "wasm32"))]
490                {
491                    let _: &str = open_href.as_str();
492                }
493            };
494            let sha_body: NodeId = view! {
495                column {
496                    style: {
497                        width: Length::Percent(100.0)
498                        gap: SPACE_XS
499                    }
500                    text {
501                        style: {
502                            width: Length::Percent(100.0)
503                            font_size: 11.5
504                            font_family: FontFamily::Monospace
505                            color: p.get_muted_foreground()
506                            selectable: true
507                        }
508                        { sha_full }
509                    }
510                    EuvButton {
511                        label: DOCS_CATALOG_SHA_COPY.to_string()
512                        tokens: live_tok
513                        on_click: on_copy_sha
514                    }
515                    text {
516                        style: {
517                            font_size: 11.0
518                            color: p.get_muted_foreground()
519                        }
520                        { copy_lbl_fn }
521                    }
522                }
523            };
524            let card_node: NodeId = view! {
525                EuvCard {
526                    title: art_name
527                    subtitle: updated_tag
528                    tokens: live_tok
529                    row {
530                        style: {
531                            width: Length::Percent(100.0)
532                            flex_wrap: FlexWrap::Wrap
533                            gap: SPACE_XS
534                            align: AlignItems::Center
535                        }
536                        role: A11yRole::Group
537                        a11y_label: DOCS_CATALOG_CARD_CLASS.to_string()
538                        EuvTag {
539                            label: files_tag
540                            tokens: live_tok
541                        }
542                        EuvTag {
543                            label: size_tag
544                            tokens: live_tok
545                        }
546                        EuvButton {
547                            label: DOCS_CATALOG_OPEN_BTN.to_string()
548                            tokens: live_tok
549                            on_click: on_open_art
550                        }
551                    }
552                    EuvCollapsible {
553                        open: sha_open_sig
554                        title: "SHA-256".to_string()
555                        content: sha_body
556                        tokens: live_tok
557                    }
558                }
559            };
560            cards.push(card_node);
561        }
562        cards
563    };
564    view! {
565        column {
566            style: {
567                width: Length::Percent(100.0)
568                gap: SPACE_SM
569            }
570            role: A11yRole::Region
571            a11y_label: DOCS_CATALOG_CARD_CLASS.to_string()
572            EuvHeader {
573                title: title_lbl.to_string()
574                subtitle: DOCS_CATALOG_API_PATH.to_string()
575                tokens: tokens
576            }
577            column {
578                style: {
579                    width: Length::Percent(100.0)
580                    gap: SPACE_SM
581                }
582                bind_children: build_catalog_children
583            }
584        }
585    }
586}
587
588/// Renders the site footer row including localized license attribution, externally supplied `footer_items`, and release marker metadata.
589///
590/// # Arguments
591///
592/// - `&DocSite` - Documentation site containing footer text and `footer_items`.
593/// - `ThemeTokens` - Active design tokens.
594///
595/// # Returns
596///
597/// - `NodeId` - Mounted footer container handle.
598pub fn mount_docs_footer(site: &DocSite, tokens: ThemeTokens) -> NodeId {
599    let p: ThemePalette = tokens.get_palette();
600    let footer_text: String = if site.get_footer().trim().is_empty() {
601        format!("{DOCS_DEFAULT_FOOTER} ยท {EUV_DOCS_RELEASE_MARKER}")
602    } else {
603        format!("{} ยท {EUV_DOCS_RELEASE_MARKER}", site.get_footer().trim())
604    };
605    let footer_item_nodes: Vec<NodeId> = site
606        .get_footer_items()
607        .iter()
608        .map(|item: &DocFooterItem| {
609            let label: String = item.get_text().clone();
610            let target_url: String = item.get_link().clone();
611            let a11y_txt: String = if item.get_alt().is_empty() {
612                label.clone()
613            } else {
614                format!("{} ({})", label, item.get_alt())
615            };
616            let on_click_item = move |_: &UiEvent| {
617                #[cfg(target_arch = "wasm32")]
618                if !target_url.is_empty() {
619                    open_browser_url(&target_url, true);
620                }
621                #[cfg(not(target_arch = "wasm32"))]
622                {
623                    let _: &str = target_url.as_str();
624                }
625            };
626            view! {
627                row {
628                    style: {
629                        align: AlignItems::Center
630                        gap: SPACE_XS
631                        cursor: CursorIcon::Pointer
632                    }
633                    role: A11yRole::Link
634                    a11y_label: a11y_txt
635                    on_click: on_click_item
636                    text {
637                        style: {
638                            font_size: 12.0
639                            color: p.get_primary()
640                            selectable: true
641                        }
642                        { label }
643                    }
644                }
645            }
646        })
647        .collect();
648    view! {
649        column {
650            style: {
651                width: Length::Percent(100.0)
652                gap: SPACE_XS
653                padding: Edges::new(SPACE_MD, 0.0, SPACE_SM, 0.0)
654            }
655            EuvDivider {
656                tokens: tokens
657            }
658            EuvFooter {
659                text: footer_text
660                tokens: tokens
661            }
662            if !footer_item_nodes.is_empty() {
663                row {
664                    style: {
665                        width: Length::Percent(100.0)
666                        flex_wrap: FlexWrap::Wrap
667                        align: AlignItems::Center
668                        gap: SPACE_MD
669                    }
670                    ..footer_item_nodes
671                }
672            }
673        }
674    }
675}
676
677/// Renders a `home: true` landing page with hero banner, CTA buttons, stat KPI grid, feature cards, Markdown body, and `/api/page-artifacts` catalog.
678///
679/// # Arguments
680///
681/// - `&DocPage` - Home page carrying hero, actions, stats, features, and body Markdown.
682/// - `&DocsViewerState` - Shared reactive viewer state.
683/// - `ThemeTokens` - Active design tokens.
684///
685/// # Returns
686///
687/// - `NodeId` - Mounted landing page container node.
688fn mount_doc_home_page(page: &DocPage, state: &DocsViewerState, tokens: ThemeTokens) -> NodeId {
689    let p: ThemePalette = tokens.get_palette();
690    let hero_title: String = page
691        .try_get_hero_text()
692        .clone()
693        .filter(|s: &String| !s.trim().is_empty())
694        .unwrap_or_else(|| page.get_title().clone());
695    let hero_sub: String = if !page.get_summary().trim().is_empty() {
696        page.get_summary().clone()
697    } else {
698        state.get_site().get_tagline().clone()
699    };
700    let action_buttons: Vec<NodeId> = page
701        .get_actions()
702        .iter()
703        .map(|act: &DocHomeAction| {
704            let link_url: String = act.get_link().clone();
705            let site_c: Rc<DocSite> = Rc::clone(state.get_site());
706            let route_sig: Signal<String> = state.get_active_route();
707            let toc_sig: Signal<String> = state.get_active_toc_slug();
708            let on_act = move |_: &UiEvent| {
709                navigate_doc_href(&link_url, &site_c, route_sig, toc_sig);
710            };
711            let variant: EuvButtonVariant = if act
712                .get_kind()
713                .eq_ignore_ascii_case(DOCS_HOME_ACTION_PRIMARY)
714            {
715                EuvButtonVariant::Primary
716            } else {
717                EuvButtonVariant::Outline
718            };
719            view! {
720                EuvButton {
721                    label: act.get_text().clone()
722                    variant: variant
723                    tokens: tokens
724                    on_click: on_act
725                }
726            }
727        })
728        .collect();
729    let stat_cards: Vec<NodeId> = page
730        .get_stats()
731        .iter()
732        .map(|st: &DocHomeStat| {
733            let label_str: String = if st.get_icon().is_empty() {
734                st.get_label().clone()
735            } else {
736                format!("{} {}", st.get_icon(), st.get_label())
737            };
738            view! {
739                EuvStatCard {
740                    label: label_str
741                    value: st.get_value().clone()
742                    caption: String::new()
743                    tokens: tokens
744                }
745            }
746        })
747        .collect();
748    let feature_cards: Vec<NodeId> = page
749        .get_features()
750        .iter()
751        .map(|feat: &DocHomeFeature| {
752            let link_url: String = feat.get_link().clone();
753            let site_c: Rc<DocSite> = Rc::clone(state.get_site());
754            let route_sig: Signal<String> = state.get_active_route();
755            let toc_sig: Signal<String> = state.get_active_toc_slug();
756            let on_open_feat = move |_: &UiEvent| {
757                navigate_doc_href(&link_url, &site_c, route_sig, toc_sig);
758            };
759            let has_link: bool = !feat.get_link().trim().is_empty();
760            view! {
761                EuvCard {
762                    title: feat.get_title().clone()
763                    tokens: tokens
764                    text {
765                        style: {
766                            width: Length::Percent(100.0)
767                            font_size: 13.0
768                            color: p.get_muted_foreground()
769                            selectable: true
770                        }
771                        { feat.get_details().clone() }
772                    }
773                    if has_link {
774                        EuvButton {
775                            label: DOCS_CATALOG_OPEN_BTN.to_string()
776                            variant: EuvButtonVariant::Ghost
777                            tokens: tokens
778                            on_click: on_open_feat
779                        }
780                    }
781                }
782            }
783        })
784        .collect();
785    let site_for_link: Rc<DocSite> = Rc::clone(state.get_site());
786    let route_for_link: Signal<String> = state.get_active_route();
787    let toc_for_link: Signal<String> = state.get_active_toc_slug();
788    let md_body: NodeId = if !page.get_markdown_body().trim().is_empty() {
789        EuvMarkdown::new(page.get_markdown_body().clone(), tokens)
790            .selectable(true)
791            .on_link(move |url: &str| {
792                navigate_doc_href(url, &site_for_link, route_for_link, toc_for_link);
793            })
794            .mount()
795    } else {
796        view! {
797            column {
798                style: {
799                    width: Length::Percent(100.0)
800                }
801            }
802        }
803    };
804    let catalog_node: NodeId = mount_docs_catalog(state, tokens);
805    let (prev_opt, next_opt): (Option<EuvDocPagerLink>, Option<EuvDocPagerLink>) =
806        state.pager_links_for_route(page.get_route());
807    let pager_route: Signal<String> = state.get_active_route();
808    let pager_node: NodeId = EuvDocPager::new(prev_opt, next_opt, pager_route, tokens)
809        .prev_label(state.get_site().resolved_prev_label())
810        .next_label(state.get_site().resolved_next_label())
811        .mount();
812    let footer_node: NodeId = mount_docs_footer(state.get_site(), tokens);
813    let mut action_row: EuvActionRow = EuvActionRow::new();
814    for btn in action_buttons.into_iter() {
815        action_row = action_row.child(btn);
816    }
817    let action_bar: NodeId = action_row.mount();
818    let mut stat_grid_builder: EuvStatGrid = EuvStatGrid::new();
819    for card in stat_cards.into_iter() {
820        stat_grid_builder = stat_grid_builder.card(card);
821    }
822    let stat_grid: NodeId = stat_grid_builder.mount();
823    view! {
824        column {
825            style: {
826                width: Length::Percent(100.0)
827                gap: SPACE_LG
828            }
829            EuvCard {
830                title: hero_title
831                subtitle: hero_sub
832                tokens: tokens
833                if !page.get_actions().is_empty() {
834                    { action_bar }
835                }
836            }
837            if !page.get_stats().is_empty() {
838                { stat_grid }
839            }
840            if !feature_cards.is_empty() {
841                column {
842                    style: {
843                        width: Length::Percent(100.0)
844                        gap: SPACE_SM
845                    }
846                    EuvHeader {
847                        title: DOCS_HOME_FEATURES_TITLE.to_string()
848                        subtitle: String::new()
849                        tokens: tokens
850                    }
851                    grid {
852                        style: {
853                            columns: 2
854                            width: Length::Percent(100.0)
855                            gap: SPACE_SM
856                        }
857                        ..feature_cards
858                    }
859                }
860            }
861            { md_body }
862            { catalog_node }
863            { pager_node }
864            { footer_node }
865        }
866    }
867}
868
869/// Renders a standard documentation article page purely from `euv-ui` components (`EuvBreadcrumb`, `EuvDocMetaBar`, `EuvHeader`, `EuvDocToc`, `EuvMarkdown`, `EuvDivider`, `EuvDocPager`, `EuvFooter`).
870///
871/// # Arguments
872///
873/// - `&DocPage` - Documentation page to render.
874/// - `&DocsViewerState` - Shared reactive viewer state for route, TOC, and pager interactivity.
875/// - `ThemeTokens` - Active design tokens.
876///
877/// # Returns
878///
879/// - `NodeId` - Mounted article page container node.
880pub fn mount_doc_page_with_context(
881    page: &DocPage,
882    state: &DocsViewerState,
883    tokens: ThemeTokens,
884) -> NodeId {
885    if page.get_is_home() {
886        return mount_doc_home_page(page, state, tokens);
887    }
888    let breadcrumb_segments: Vec<String> = vec![
889        state.get_site().get_title().clone(),
890        page.get_section().clone(),
891        page.get_title().clone(),
892    ];
893    let mut meta_bar: EuvDocMetaBar = EuvDocMetaBar::new(
894        page.get_section().clone(),
895        page.reading_minutes(),
896        page.word_count(),
897        tokens,
898    )
899    .source_path(page.get_route().clone());
900    if let Some(updated) = page.try_get_updated().as_deref() {
901        meta_bar = meta_bar.updated(updated);
902    }
903    let meta_node: NodeId = meta_bar.mount();
904    let show_subtitle: bool = {
905        let sum: &str = page.get_summary().trim();
906        !sum.is_empty() && !sum.eq_ignore_ascii_case(page.get_title().trim())
907    };
908    let subtitle_str: String = if show_subtitle {
909        page.get_summary().clone()
910    } else {
911        String::new()
912    };
913    let toc_items: Vec<EuvDocTocItem> = page
914        .get_toc()
915        .iter()
916        .map(|it: &DocTocItem| {
917            EuvDocTocItem::new(
918                it.get_level(),
919                it.get_slug().clone(),
920                it.get_title().clone(),
921            )
922        })
923        .collect();
924    let toc_slug_sig: Signal<String> = state.get_active_toc_slug();
925    let toc_node_opt: Option<NodeId> = if toc_items.is_empty() {
926        None
927    } else {
928        let toc_click_sig: Signal<String> = toc_slug_sig;
929        Some(
930            EuvDocToc::new(toc_items, toc_slug_sig, tokens)
931                .title(state.get_site().resolved_toc_label())
932                .on_select(move |slug: &str| {
933                    let _: bool = toc_click_sig.set_if_changed(slug.to_string());
934                })
935                .mount(),
936        )
937    };
938    let site_for_link: Rc<DocSite> = Rc::clone(state.get_site());
939    let route_for_link: Signal<String> = state.get_active_route();
940    let toc_for_link: Signal<String> = state.get_active_toc_slug();
941    let body_node: NodeId = if !page.get_markdown_body().trim().is_empty() {
942        EuvMarkdown::new(page.get_markdown_body().clone(), tokens)
943            .selectable(true)
944            .on_link(move |url: &str| {
945                navigate_doc_href(url, &site_for_link, route_for_link, toc_for_link);
946            })
947            .mount()
948    } else {
949        mount_fallback_doc_blocks(page, tokens)
950    };
951    let (prev_opt, next_opt): (Option<EuvDocPagerLink>, Option<EuvDocPagerLink>) =
952        state.pager_links_for_route(page.get_route());
953    let pager_route: Signal<String> = state.get_active_route();
954    let pager_node: NodeId = EuvDocPager::new(prev_opt, next_opt, pager_route, tokens)
955        .prev_label(state.get_site().resolved_prev_label())
956        .next_label(state.get_site().resolved_next_label())
957        .mount();
958    let footer_node: NodeId = mount_docs_footer(state.get_site(), tokens);
959    view! {
960        column {
961            style: {
962                width: Length::Percent(100.0)
963                gap: SPACE_MD
964            }
965            EuvBreadcrumb {
966                segments: breadcrumb_segments
967                tokens: tokens
968            }
969            { meta_node }
970            EuvHeader {
971                title: page.get_title().clone()
972                subtitle: subtitle_str
973                tokens: tokens
974            }
975            if let Some(toc_node) = toc_node_opt {
976                { toc_node }
977            }
978            { body_node }
979            EuvDivider {
980                tokens: tokens
981            }
982            { pager_node }
983            { footer_node }
984        }
985    }
986}
987
988/// Renders structured `DocBlock` nodes when a `DocPage` has no raw Markdown body text.
989///
990/// # Arguments
991///
992/// - `&DocPage` - Documentation page holding pre-parsed blocks.
993/// - `ThemeTokens` - Active design tokens.
994///
995/// # Returns
996///
997/// - `NodeId` - Mounted fallback block column handle.
998fn mount_fallback_doc_blocks(page: &DocPage, tokens: ThemeTokens) -> NodeId {
999    view! {
1000        column {
1001            style: {
1002                width: Length::Percent(100.0)
1003                gap: SPACE_MD
1004            }
1005            for block in page.get_blocks().iter() {
1006                match block {
1007                    DocBlock::Heading { level, text, .. } => {
1008                        EuvMarkdownHeading {
1009                            level: *level
1010                            text: text.clone()
1011                            tokens: tokens
1012                        }
1013                    }
1014                    DocBlock::Paragraph(text) => {
1015                        EuvMarkdownParagraph {
1016                            inlines: parse_markdown_inlines(text)
1017                            tokens: tokens
1018                        }
1019                    }
1020                    DocBlock::ListItem(text) => EuvMarkdownList {
1021                        ordered: false
1022                        items: vec![EuvMarkdownListItem::new(text.clone(), 0, None)]
1023                        tokens: tokens
1024                    },
1025                    DocBlock::BlockQuote(text) => EuvMarkdownQuote {
1026                        kind: EuvMarkdownAlertKind::Quote
1027                        lines: vec![text.clone()]
1028                        tokens: tokens
1029                    },
1030                    DocBlock::Table { headers, rows } => EuvMarkdownTable {
1031                        headers: headers.clone()
1032                        alignments: vec![EuvMarkdownAlign::Left; headers.len()]
1033                        rows: rows.clone()
1034                        tokens: tokens
1035                    },
1036                    DocBlock::Image { alt, src } => {
1037                        EuvMarkdownImage {
1038                            alt: alt.clone()
1039                            url: src.clone()
1040                            tokens: tokens
1041                        }
1042                    }
1043                    DocBlock::HorizontalRule => EuvMarkdownDivider {
1044                        tokens: tokens
1045                    },
1046                    DocBlock::Code { language, code } => {
1047                        EuvCodeBlock {
1048                            code: code.clone()
1049                            tokens: tokens
1050                            language: language.clone()
1051                            line_numbers: true
1052                            selectable: true
1053                        }
1054                    }
1055                }
1056            }
1057        }
1058    }
1059}
1060
1061/// Renders a single standalone `DocPage` (meta bar, header, interactive TOC, and full `EuvMarkdown`) as native `euv-ui` nodes.
1062///
1063/// # Arguments
1064///
1065/// - `&DocPage` - Documentation page to mount.
1066/// - `ThemeTokens` - Active design tokens.
1067///
1068/// # Returns
1069///
1070/// - `NodeId` - Mounted page container node.
1071pub fn mount_doc_page(page: &DocPage, tokens: ThemeTokens) -> NodeId {
1072    let mut meta_bar: EuvDocMetaBar = EuvDocMetaBar::new(
1073        page.get_section().clone(),
1074        page.reading_minutes(),
1075        page.word_count(),
1076        tokens,
1077    )
1078    .source_path(page.get_route().clone());
1079    if let Some(updated) = page.try_get_updated().as_deref() {
1080        meta_bar = meta_bar.updated(updated);
1081    }
1082    let meta_node: NodeId = meta_bar.mount();
1083    let toc_items: Vec<EuvDocTocItem> = page
1084        .get_toc()
1085        .iter()
1086        .map(|it: &DocTocItem| {
1087            EuvDocTocItem::new(
1088                it.get_level(),
1089                it.get_slug().clone(),
1090                it.get_title().clone(),
1091            )
1092        })
1093        .collect();
1094    let toc_sig: Signal<String> = Signal::new(
1095        toc_items
1096            .first()
1097            .map(|it: &EuvDocTocItem| it.get_slug().clone())
1098            .unwrap_or_default(),
1099    );
1100    let toc_node_opt: Option<NodeId> = if toc_items.is_empty() {
1101        None
1102    } else {
1103        Some(EuvDocToc::new(toc_items, toc_sig, tokens).mount())
1104    };
1105    let body_node: NodeId = if !page.get_markdown_body().trim().is_empty() {
1106        view! {
1107            EuvMarkdown {
1108                source: page.get_markdown_body().clone()
1109                tokens: tokens
1110                selectable: true
1111            }
1112        }
1113    } else {
1114        mount_fallback_doc_blocks(page, tokens)
1115    };
1116    view! {
1117        column {
1118            style: {
1119                width: Length::Percent(100.0)
1120                gap: SPACE_MD
1121            }
1122            { meta_node }
1123            EuvHeader {
1124                title: page.get_title().clone()
1125                subtitle: page.get_summary().clone()
1126                tokens: tokens
1127            }
1128            if let Some(toc_node) = toc_node_opt {
1129                { toc_node }
1130            }
1131            { body_node }
1132        }
1133    }
1134}
1135
1136/// Registers every page in `state.site` lazily onto `state.router` with `PageRetention::Freeze`.
1137///
1138/// # Arguments
1139///
1140/// - `&DocsViewerState` - Shared reactive viewer state.
1141fn ensure_docs_routes_registered(state: &DocsViewerState) {
1142    if state.get_router_ready().replace(true) {
1143        return;
1144    }
1145    let mut router: EuvRouter = state.get_router().clone();
1146    for page in state.get_site().get_pages().iter() {
1147        let route_pattern: String = page.get_route().clone();
1148        let route_path: String = route_pattern.clone();
1149        let route_title: String = page.get_title().clone();
1150        let st: DocsViewerState = state.clone();
1151        router = router.route_with_retention(
1152            &route_pattern,
1153            &route_title,
1154            PageRetention::Freeze,
1155            move |_: &EuvRouteMatch| {
1156                let tok: ThemeTokens = untracked(|| st.get_theme().get_tokens().get());
1157                match st.get_site().find_by_route(&route_path) {
1158                    Some(p) => mount_doc_page_with_context(p, &st, tok),
1159                    None => view! {
1160                        EuvEmpty {
1161                            title: EMPTY_PAGE_TITLE.to_string()
1162                            description: EMPTY_PAGE_MSG.to_string()
1163                            tokens: tok
1164                        }
1165                    },
1166                }
1167            },
1168        );
1169    }
1170    let _: EuvRouter = router;
1171}
1172
1173/// Mounts the full showcase-parity reactive documentation shell (`EuvAppShell`, `EuvRouter` `PageRetention::Freeze`, live search, `EuvCommand` modal, 17-scheme theme controls, `EuvDocSectionNav`, and mobile `EuvBottomNav`).
1174///
1175/// # Arguments
1176///
1177/// - `&DocsViewerState` - Shared reactive documentation viewer state.
1178///
1179/// # Returns
1180///
1181/// - `NodeId` - Mounted documentation application root handle.
1182pub fn mount_docs_viewer_with_state(state: &DocsViewerState) -> NodeId {
1183    provide_theme(state.get_theme().clone());
1184    ensure_docs_routes_registered(state);
1185    let tokens: ThemeTokens = untracked(|| state.get_theme().get_tokens().get());
1186    let active_route: Signal<String> = state.get_active_route();
1187    let search_query: Signal<String> = state.get_search_query();
1188    let cmd_open: Signal<bool> = state.get_cmd_open();
1189    let cmd_query: Signal<String> = state.get_cmd_query();
1190    let all_pages: &[DocPage] = state.get_site().get_pages().as_slice();
1191    let mut cmd_routes: Vec<String> = Vec::with_capacity(all_pages.len());
1192    let mut cmd_items: Vec<String> = Vec::with_capacity(all_pages.len() + 2);
1193    for page in all_pages.iter() {
1194        cmd_routes.push(page.get_route().clone());
1195        cmd_items.push(format!("{} โ€” {}", page.get_title(), page.get_section()));
1196    }
1197    let toggle_idx: usize = cmd_items.len();
1198    cmd_items.push(CMD_ACTION_TOGGLE_MODE.to_string());
1199    let scheme_idx: usize = cmd_items.len();
1200    cmd_items.push(CMD_ACTION_NEXT_SCHEME.to_string());
1201    let cmd_sel: Signal<Option<usize>> = Signal::new(None);
1202    let cmd_list: NodeId = view! {
1203        EuvCommand {
1204            items: cmd_items
1205            selected: cmd_sel
1206            tokens: tokens
1207            query: cmd_query
1208            placeholder: CMD_PLACEHOLDER
1209        }
1210    };
1211    let cmd_state: DocsViewerState = state.clone();
1212    let (cmd_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1213        Effect::new(move || {
1214            if let Some(idx) = cmd_sel.get() {
1215                if let Some(target) = cmd_routes.get(idx) {
1216                    let _: bool = active_route.set_if_changed(target.clone());
1217                } else if idx == toggle_idx {
1218                    cmd_state.toggle_theme_mode();
1219                } else if idx == scheme_idx {
1220                    cmd_state.next_scheme();
1221                }
1222                let _: bool = cmd_sel.set_if_changed(None);
1223                let _: bool = cmd_open.set_if_changed(false);
1224            }
1225        })
1226    });
1227    let cmd_modal: NodeId = view! {
1228        EuvModal {
1229            open: cmd_open
1230            title: CMD_MODAL_TITLE.to_string()
1231            body: cmd_list
1232            tokens: tokens
1233        }
1234    };
1235    let rctx: Context = current_context();
1236    let theme_memo: Memo<ThemeTokens> = state.get_theme().get_tokens();
1237    let prev_modal_tok: Rc<Cell<ThemeTokens>> = Rc::new(Cell::new(tokens));
1238    let modal_theme_ctx: Context = rctx.clone();
1239    let (modal_theme_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1240        Effect::new(move || {
1241            let next_tok: ThemeTokens = theme_memo.get();
1242            let old_tok: ThemeTokens = prev_modal_tok.replace(next_tok);
1243            if old_tok == next_tok {
1244                return;
1245            }
1246            modal_theme_ctx.get_scene().with_write(
1247                |tree: &mut SceneTree| {
1248                    remap_subtree_theme_in_place(tree, cmd_modal, old_tok, next_tok);
1249                },
1250                (),
1251            );
1252        })
1253    });
1254    rctx.get_scene().with_write(
1255        |tree: &mut SceneTree| {
1256            tree.attach_scope(cmd_modal, cmd_scope);
1257            tree.attach_scope(cmd_modal, modal_theme_scope);
1258        },
1259        (),
1260    );
1261    let router: EuvRouter = state.get_router().clone();
1262    let cur_route: String = active_route.get_untracked();
1263    if router.get_current_path().get_untracked() != cur_route {
1264        router.replace(&cur_route);
1265    }
1266    let breadcrumb_sig: Signal<String> = Signal::new(state.breadcrumb_for_route(&cur_route));
1267    let page_pad_sig: Signal<Edges> = Signal::new(Edges::all(SPACE_LG));
1268    let swipe_routes: Vec<String> = state.ordered_routes();
1269    let state_sync: DocsViewerState = state.clone();
1270    let router_sync_in: EuvRouter = router.clone();
1271    let router_path_sig: Signal<String> = router.get_current_path();
1272    let (sync_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1273        let _: Effect = Effect::new(move || {
1274            let target: String = active_route.get();
1275            let _: bool = breadcrumb_sig.set_if_changed(state_sync.breadcrumb_for_route(&target));
1276            if router_sync_in.get_current_path().get_untracked() != target {
1277                router_sync_in.push(&target);
1278            }
1279        });
1280        Effect::new(move || {
1281            let rp: String = router_path_sig.get();
1282            if active_route.get_untracked() != rp {
1283                let _: bool = active_route.set_if_changed(rp);
1284            }
1285        })
1286    });
1287    let state_fallback: DocsViewerState = state.clone();
1288    let outlet_node: NodeId = router
1289        .outlet(move |matched: &EuvRouteMatch| {
1290            let tok: ThemeTokens = untracked(|| state_fallback.get_theme().get_tokens().get());
1291            match state_fallback
1292                .get_site()
1293                .find_by_route(matched.get_path())
1294                .or_else(|| state_fallback.get_site().get_pages().first())
1295            {
1296                Some(p) => mount_doc_page_with_context(p, &state_fallback, tok),
1297                None => view! {
1298                    EuvEmpty {
1299                        title: EMPTY_PAGE_TITLE.to_string()
1300                        description: EMPTY_PAGE_MSG.to_string()
1301                        tokens: tok
1302                    }
1303                },
1304            }
1305        })
1306        .with_theme(state.get_theme().clone())
1307        .with_page_padding(page_pad_sig)
1308        .with_route_order(swipe_routes.clone())
1309        .mount();
1310    rctx.get_scene().with_write(
1311        |tree: &mut SceneTree| {
1312            tree.attach_scope(outlet_node, sync_scope);
1313        },
1314        (),
1315    );
1316    let total_visible: usize = swipe_routes.len();
1317    let sidebar_state: DocsViewerState = state.clone();
1318    let build_sidebar_nav = move || -> Vec<NodeId> {
1319        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
1320        let q: String = search_query.get();
1321        let (matched_count, groups): (usize, Vec<EuvDocSectionGroup>) =
1322            sidebar_state.filtered_section_groups(&q);
1323        let badge_lbl: String = format!("{matched_count} / {total_visible}");
1324        let mut nodes: Vec<NodeId> = Vec::with_capacity(2);
1325        if !q.trim().is_empty() {
1326            nodes.push(view! {
1327                row {
1328                    style: {
1329                        width: Length::Percent(100.0)
1330                        justify: JustifyContent::SpaceBetween
1331                        align: AlignItems::Center
1332                    }
1333                    EuvBadge {
1334                        label: badge_lbl
1335                        tone: if matched_count > 0 {
1336                            EuvTone::Primary
1337                        } else {
1338                            EuvTone::Warning
1339                        }
1340                        tokens: live_tok
1341                    }
1342                }
1343            });
1344        }
1345        if groups.is_empty() {
1346            nodes.push(view! {
1347                EuvEmpty {
1348                    title: EMPTY_SEARCH_TITLE.to_string()
1349                    description: EMPTY_SEARCH_DESC.to_string()
1350                    tokens: live_tok
1351                }
1352            });
1353        } else {
1354            nodes.push(view! {
1355                EuvDocSectionNav {
1356                    groups: groups
1357                    active_route: active_route
1358                    tokens: live_tok
1359                }
1360            });
1361        }
1362        nodes
1363    };
1364    let sidebar_node: NodeId = view! {
1365        column {
1366            style: {
1367                width: Length::Percent(100.0)
1368                gap: SPACE_SM
1369            }
1370            EuvInput {
1371                value: search_query
1372                placeholder: SEARCH_PLACEHOLDER.to_string()
1373                tokens: tokens
1374            }
1375            column {
1376                style: {
1377                    width: Length::Percent(100.0)
1378                    gap: SPACE_SM
1379                }
1380                bind_children: build_sidebar_nav
1381            }
1382        }
1383    };
1384    let theme_mode_sig: Signal<ThemeMode> = state.get_theme().get_mode();
1385    let icon_btn_style_desk = move || -> Style {
1386        let live_tok: ThemeTokens = use_live_tokens(tokens);
1387        let live_p: ThemePalette = live_tok.get_palette();
1388        let live_g: ThemeGeometry = live_tok.get_geometry();
1389        Style::default()
1390            .row()
1391            .width(Length::Px(30.0))
1392            .height(Length::Px(30.0))
1393            .justify(JustifyContent::Center)
1394            .align(AlignItems::Center)
1395            .background(live_p.get_background())
1396            .border(live_g.get_border_width(), live_p.get_border())
1397            .radius(live_g.get_radius_md())
1398            .cursor(CursorIcon::Pointer)
1399    };
1400    let icon_btn_style_mob = move || -> Style {
1401        let live_tok: ThemeTokens = use_live_tokens(tokens);
1402        let live_p: ThemePalette = live_tok.get_palette();
1403        let live_g: ThemeGeometry = live_tok.get_geometry();
1404        Style::default()
1405            .row()
1406            .width(Length::Px(28.0))
1407            .height(Length::Px(28.0))
1408            .justify(JustifyContent::Center)
1409            .align(AlignItems::Center)
1410            .background(live_p.get_background())
1411            .border(live_g.get_border_width(), live_p.get_border())
1412            .radius(live_g.get_radius_md())
1413            .cursor(CursorIcon::Pointer)
1414    };
1415    let paint_search_desk = move |bounds: Rect, dl: &mut DisplayList| {
1416        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1417        draw_euv_icon(EuvIconName::Search, bounds, dl, live_p.get_foreground());
1418    };
1419    let paint_search_mob = move |bounds: Rect, dl: &mut DisplayList| {
1420        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1421        draw_euv_icon(EuvIconName::Search, bounds, dl, live_p.get_foreground());
1422    };
1423    let paint_scheme_desk = move |bounds: Rect, dl: &mut DisplayList| {
1424        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1425        draw_euv_icon(EuvIconName::Palette, bounds, dl, live_p.get_primary());
1426    };
1427    let paint_scheme_mob = move |bounds: Rect, dl: &mut DisplayList| {
1428        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1429        draw_euv_icon(EuvIconName::Palette, bounds, dl, live_p.get_primary());
1430    };
1431    let paint_mode_desk = move |bounds: Rect, dl: &mut DisplayList| {
1432        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1433        let glyph: EuvIconName = match theme_mode_sig.get_untracked() {
1434            ThemeMode::Dark => EuvIconName::Sun,
1435            ThemeMode::Light => EuvIconName::Moon,
1436        };
1437        draw_euv_icon(glyph, bounds, dl, live_p.get_foreground());
1438    };
1439    let paint_mode_mob = move |bounds: Rect, dl: &mut DisplayList| {
1440        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1441        let glyph: EuvIconName = match theme_mode_sig.get_untracked() {
1442            ThemeMode::Dark => EuvIconName::Sun,
1443            ThemeMode::Light => EuvIconName::Moon,
1444        };
1445        draw_euv_icon(glyph, bounds, dl, live_p.get_foreground());
1446    };
1447    let st_scheme_desk: DocsViewerState = state.clone();
1448    let st_scheme_mob: DocsViewerState = state.clone();
1449    let st_mode_desk: DocsViewerState = state.clone();
1450    let st_mode_mob: DocsViewerState = state.clone();
1451    let on_open_cmd_desk = move |_: &UiEvent| {
1452        let _: bool = cmd_open.set_if_changed(true);
1453    };
1454    let on_open_cmd_mob = move |_: &UiEvent| {
1455        let _: bool = cmd_open.set_if_changed(true);
1456    };
1457    let on_next_scheme_desk = move |_: &UiEvent| {
1458        st_scheme_desk.next_scheme();
1459    };
1460    let on_next_scheme_mob = move |_: &UiEvent| {
1461        st_scheme_mob.next_scheme();
1462    };
1463    let on_toggle_mode_desk = move |_: &UiEvent| {
1464        st_mode_desk.toggle_theme_mode();
1465    };
1466    let on_toggle_mode_mob = move |_: &UiEvent| {
1467        st_mode_mob.toggle_theme_mode();
1468    };
1469    let locale_buttons: Vec<NodeId> = if state.get_site().get_locales().len() > 1 {
1470        let active_prefix: &str = state.get_site().get_locale_prefix().as_str();
1471        state
1472            .get_site()
1473            .get_locales()
1474            .iter()
1475            .map(|loc: &DocLocaleConfig| {
1476                let prefix_url: String = loc.get_prefix().clone();
1477                let is_cur: bool = loc.get_prefix().as_str() == active_prefix;
1478                let short_lbl: String = loc.get_dir().to_ascii_uppercase();
1479                let on_switch_loc = move |_: &UiEvent| {
1480                    #[cfg(target_arch = "wasm32")]
1481                    open_browser_url(&prefix_url, false);
1482                    #[cfg(not(target_arch = "wasm32"))]
1483                    {
1484                        let _: &str = prefix_url.as_str();
1485                    }
1486                };
1487                view! {
1488                    EuvButton {
1489                        label: short_lbl
1490                        variant: if is_cur {
1491                            EuvButtonVariant::Primary
1492                        } else {
1493                            EuvButtonVariant::Ghost
1494                        }
1495                        tokens: tokens
1496                        on_click: on_switch_loc
1497                    }
1498                }
1499            })
1500            .collect()
1501    } else {
1502        Vec::new()
1503    };
1504    let top_actions: NodeId = view! {
1505        row {
1506            style: {
1507                gap: SPACE_XS
1508                align: AlignItems::Center
1509            }
1510            ..locale_buttons
1511            row {
1512                bind_style: icon_btn_style_desk
1513                role: A11yRole::Button
1514                a11y_label: BTN_SEARCH_A11Y.to_string()
1515                on_click: on_open_cmd_desk
1516                canvas {
1517                    style: {
1518                        width: Length::Px(15.0)
1519                        height: Length::Px(15.0)
1520                    }
1521                    painter: paint_search_desk
1522                }
1523            }
1524            row {
1525                bind_style: icon_btn_style_desk
1526                role: A11yRole::Button
1527                a11y_label: BTN_SCHEME_A11Y.to_string()
1528                on_click: on_next_scheme_desk
1529                canvas {
1530                    style: {
1531                        width: Length::Px(15.0)
1532                        height: Length::Px(15.0)
1533                    }
1534                    painter: paint_scheme_desk
1535                }
1536            }
1537            row {
1538                bind_style: icon_btn_style_desk
1539                role: A11yRole::Button
1540                a11y_label: BTN_MODE_A11Y.to_string()
1541                on_click: on_toggle_mode_desk
1542                canvas {
1543                    style: {
1544                        width: Length::Px(15.0)
1545                        height: Length::Px(15.0)
1546                    }
1547                    painter: paint_mode_desk
1548                }
1549            }
1550        }
1551    };
1552    let mobile_actions: NodeId = view! {
1553        row {
1554            style: {
1555                gap: SPACE_XS
1556                align: AlignItems::Center
1557            }
1558            row {
1559                bind_style: icon_btn_style_mob
1560                role: A11yRole::Button
1561                a11y_label: BTN_SEARCH_A11Y.to_string()
1562                on_click: on_open_cmd_mob
1563                canvas {
1564                    style: {
1565                        width: Length::Px(14.0)
1566                        height: Length::Px(14.0)
1567                    }
1568                    painter: paint_search_mob
1569                }
1570            }
1571            row {
1572                bind_style: icon_btn_style_mob
1573                role: A11yRole::Button
1574                a11y_label: BTN_SCHEME_A11Y.to_string()
1575                on_click: on_next_scheme_mob
1576                canvas {
1577                    style: {
1578                        width: Length::Px(14.0)
1579                        height: Length::Px(14.0)
1580                    }
1581                    painter: paint_scheme_mob
1582                }
1583            }
1584            row {
1585                bind_style: icon_btn_style_mob
1586                role: A11yRole::Button
1587                a11y_label: BTN_MODE_A11Y.to_string()
1588                on_click: on_toggle_mode_mob
1589                canvas {
1590                    style: {
1591                        width: Length::Px(14.0)
1592                        height: Length::Px(14.0)
1593                    }
1594                    painter: paint_mode_mob
1595                }
1596            }
1597        }
1598    };
1599    let bottom_items: Vec<EuvNavItem> = state.bottom_nav_items();
1600    let bottom_nav_opt: Option<NodeId> = if bottom_items.len() >= 2 {
1601        Some(view! {
1602            EuvBottomNav {
1603                items: bottom_items
1604                active_route: active_route
1605                tokens: tokens
1606            }
1607        })
1608    } else {
1609        None
1610    };
1611    let mut shell: EuvAppShell = EuvAppShell::new(
1612        state.get_site().get_title().clone(),
1613        sidebar_node,
1614        outlet_node,
1615        tokens,
1616    )
1617    .route(active_route)
1618    .top_bar_actions(top_actions)
1619    .mobile_header_actions(mobile_actions)
1620    .breadcrumb(breadcrumb_sig)
1621    .swipe_routes(swipe_routes)
1622    .theme(state.get_theme().clone())
1623    .page_padding(page_pad_sig);
1624    if let Some(bnav) = bottom_nav_opt {
1625        shell = shell.bottom_nav(bnav);
1626    }
1627    let shell_node: NodeId = shell.mount();
1628    view! {
1629        column {
1630            style: {
1631                width: Length::Percent(100.0)
1632                height: Length::Percent(100.0)
1633            }
1634            { shell_node }
1635            { cmd_modal }
1636        }
1637    }
1638}
1639
1640/// Mounts the cross-platform reactive showcase-parity documentation viewer for `site` using `euv-ui`.
1641///
1642/// # Arguments
1643///
1644/// - `&DocSite` - Parsed documentation site.
1645/// - `Signal<String>` - Active route path signal.
1646/// - `Signal<String>` - Search query input signal.
1647/// - `ThemeTokens` - Active design tokens.
1648///
1649/// # Returns
1650///
1651/// - `NodeId` - Mounted reactive documentation shell node.
1652pub fn mount_docs_viewer(
1653    site: &DocSite,
1654    active_route: Signal<String>,
1655    search_query: Signal<String>,
1656    tokens: ThemeTokens,
1657) -> NodeId {
1658    let state: DocsViewerState =
1659        DocsViewerState::new(site.clone(), active_route, search_query, tokens);
1660    mount_docs_viewer_with_state(&state)
1661}
1662
1663/// Launches the documentation viewer app and steps one headless or native frame.
1664///
1665/// # Arguments
1666///
1667/// - `&DocSite` - Loaded documentation site.
1668/// - `bool` - When `true`, renders headlessly via `HeadlessPlatform`.
1669///
1670/// # Returns
1671///
1672/// - `Result<FrameStats, PlatformError>` - Frame render telemetry.
1673pub fn render_docs_smoke(site: &DocSite, headless: bool) -> Result<FrameStats, PlatformError> {
1674    render_docs_app(site, headless, false)
1675}
1676
1677/// Launches the documentation viewer app in either single-frame or interactive event-loop mode.
1678///
1679/// # Arguments
1680///
1681/// - `&DocSite` - Loaded documentation site.
1682/// - `bool` - When `true`, renders headlessly via `HeadlessPlatform`.
1683/// - `bool` - When `true` and not headless, runs the interactive frame loop until window close.
1684///
1685/// # Returns
1686///
1687/// - `Result<FrameStats, PlatformError>` - Final rendered frame telemetry.
1688pub fn render_docs_app(
1689    site: &DocSite,
1690    headless: bool,
1691    interactive: bool,
1692) -> Result<FrameStats, PlatformError> {
1693    EuvOverlayStack::clear();
1694    reset_fullscreen_state();
1695    clear_provided_theme();
1696    let mut window_cfg: WindowConfig = WindowConfig::default();
1697    window_cfg
1698        .set_title(DOCS_WINDOW_TITLE.to_string())
1699        .set_size(DOCS_WINDOW_WIDTH, DOCS_WINDOW_HEIGHT)
1700        .set_render(RenderConfig::software())
1701        .set_icon(Some(euv_brand_logo_image()));
1702    let mut app_cfg: AppConfig = AppConfig::default();
1703    app_cfg.set_window(window_cfg);
1704    let mut app: App = if headless {
1705        App::headless(app_cfg)?
1706    } else {
1707        App::new(app_cfg)?
1708    };
1709    let initial_route: String = site
1710        .get_pages()
1711        .first()
1712        .map(|p: &DocPage| p.get_route().clone())
1713        .unwrap_or_else(|| "/".to_string());
1714    let active_route: Signal<String> = Signal::new(initial_route);
1715    let search_query: Signal<String> = Signal::new(String::new());
1716    let tokens: ThemeTokens = ThemeTokens::resolve(active_feature_scheme(), ThemeMode::Light);
1717    let state: DocsViewerState =
1718        DocsViewerState::new(site.clone(), active_route, search_query, tokens);
1719    let mount_state: DocsViewerState = state.clone();
1720    let _: NodeId = app.mount(move || mount_docs_viewer_with_state(&mount_state));
1721    let limit: Option<u64> = if interactive && !headless {
1722        None
1723    } else {
1724        Some(1)
1725    };
1726    app.run_frames(limit)
1727}
1728
1729/// Boots the persistent WebAssembly showcase-parity documentation viewer from a serialized `DocSite` JSON bundle.
1730///
1731/// # Arguments
1732///
1733/// - `&str` - Compact UTF-8 JSON payload produced for the active locale bundle.
1734///
1735/// # Returns
1736///
1737/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
1738#[cfg(target_arch = "wasm32")]
1739pub fn boot_wasm_docs_bundle(bundle_json: &str) -> u64 {
1740    console_error_panic_hook::set_once();
1741    reset_reactive_runtime();
1742    EuvOverlayStack::clear();
1743    reset_fullscreen_state();
1744    clear_provided_theme();
1745    let site: DocSite = serde_json::from_str::<DocSite>(bundle_json).unwrap_or_else(|_| {
1746        DocSite::new(
1747            DOCS_SITE_TITLE.to_string(),
1748            DOCS_SITE_TAGLINE.to_string(),
1749            Vec::new(),
1750        )
1751    });
1752    let mut window_cfg: WindowConfig = WindowConfig::default();
1753    window_cfg
1754        .set_title(format!("{} ยท {EUV_DOCS_RELEASE_MARKER}", site.get_title()))
1755        .set_size(DOCS_WINDOW_WIDTH, DOCS_WINDOW_HEIGHT)
1756        .set_render(RenderConfig::software());
1757    let mut app_cfg: AppConfig = AppConfig::default();
1758    app_cfg.set_window(window_cfg);
1759    let mut app: App = match App::new(app_cfg) {
1760        Ok(a) => a,
1761        Err(_) => return 0,
1762    };
1763    let initial_route: String = site
1764        .get_pages()
1765        .first()
1766        .map(|p: &DocPage| p.get_route().clone())
1767        .unwrap_or_else(|| "/".to_string());
1768    let active_route: Signal<String> = Signal::new(initial_route);
1769    if let Some(win) = window()
1770        && let Ok(hash_str) = win.location().hash()
1771    {
1772        let cleaned: &str = hash_str.trim_start_matches('#');
1773        if cleaned.starts_with('/')
1774            && let Some(found) = site.find_by_route(cleaned)
1775        {
1776            let _: bool = active_route.set_if_changed(found.get_route().clone());
1777        }
1778    }
1779    let search_query: Signal<String> = Signal::new(String::new());
1780    let tokens: ThemeTokens = ThemeTokens::resolve(active_feature_scheme(), ThemeMode::Light);
1781    let state: DocsViewerState = DocsViewerState::new(site, active_route, search_query, tokens);
1782    let has_home: bool = state
1783        .get_site()
1784        .get_pages()
1785        .iter()
1786        .any(|p: &DocPage| p.get_is_home());
1787    let mount_state: DocsViewerState = state.clone();
1788    let _: NodeId = app.mount(move || mount_docs_viewer_with_state(&mount_state));
1789    let route_watch: Signal<String> = state.get_active_route();
1790    let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1791        Effect::new(move || {
1792            let r: String = route_watch.get();
1793            if let Some(win) = window() {
1794                let target_hash: String = format!("#{r}");
1795                if win.location().hash().ok().as_deref() != Some(target_hash.as_str()) {
1796                    let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
1797                }
1798            }
1799        })
1800    });
1801    let root_id: NodeId = app
1802        .get_scene()
1803        .with_read(SceneTree::get_root, NodeId::default());
1804    app.get_scene().with_write(
1805        |tree: &mut SceneTree| {
1806            tree.attach_scope(root_id, hash_scope);
1807        },
1808        (),
1809    );
1810    let hash: u64 = app
1811        .step_frame()
1812        .map(|stats: FrameStats| stats.get_frame_hash())
1813        .unwrap_or(0);
1814    let fetch_state: DocsViewerState = state.clone();
1815    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
1816        if let Ok(mut borrow) = slot.try_borrow_mut() {
1817            *borrow = Some((app, state));
1818        }
1819    });
1820    if has_home {
1821        trigger_wasm_catalog_fetch(&fetch_state);
1822    }
1823    hash
1824}
1825
1826/// Switches the active route in the running WebAssembly documentation viewer and renders immediately.
1827///
1828/// # Arguments
1829///
1830/// - `&str` - Canonical route path.
1831///
1832/// # Returns
1833///
1834/// - `u64` - Rendered frame hash.
1835#[cfg(target_arch = "wasm32")]
1836pub fn wasm_docs_render_route(route: &str) -> u64 {
1837    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
1838        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
1839            Ok(guard) => guard,
1840            Err(_) => return 0,
1841        };
1842        let Some((app, state)) = borrow.as_mut() else {
1843            return 0;
1844        };
1845        let target: String = state
1846            .get_site()
1847            .find_by_route(route)
1848            .map(|p: &DocPage| p.get_route().clone())
1849            .unwrap_or_else(|| route.to_string());
1850        let _: bool = state.get_active_route().set_if_changed(target);
1851        app.step_frame()
1852            .map(|stats: FrameStats| stats.get_frame_hash())
1853            .unwrap_or(0)
1854    })
1855}
1856
1857/// Dispatches a browser pointer move event into the running WebAssembly documentation viewer.
1858///
1859/// # Arguments
1860///
1861/// - `f32` - Logical X coordinate inside the canvas.
1862/// - `f32` - Logical Y coordinate inside the canvas.
1863///
1864/// # Returns
1865///
1866/// - `u64` - Rendered frame hash.
1867#[cfg(target_arch = "wasm32")]
1868pub fn wasm_docs_pointer_move(x: f32, y: f32) -> u64 {
1869    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
1870        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
1871            Ok(guard) => guard,
1872            Err(_) => return 0,
1873        };
1874        let Some((app, _)) = borrow.as_mut() else {
1875            return 0;
1876        };
1877        let wid: WindowId = app.get_window_state().get_id();
1878        app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1879        app.step_frame()
1880            .map(|stats: FrameStats| stats.get_frame_hash())
1881            .unwrap_or(0)
1882    })
1883}
1884
1885/// Dispatches a browser pointer press event into the running WebAssembly documentation viewer.
1886///
1887/// # Arguments
1888///
1889/// - `f32` - Logical X coordinate inside the canvas.
1890/// - `f32` - Logical Y coordinate inside the canvas.
1891///
1892/// # Returns
1893///
1894/// - `u64` - Rendered frame hash.
1895#[cfg(target_arch = "wasm32")]
1896pub fn wasm_docs_pointer_down(x: f32, y: f32) -> u64 {
1897    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
1898        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
1899            Ok(guard) => guard,
1900            Err(_) => return 0,
1901        };
1902        let Some((app, _)) = borrow.as_mut() else {
1903            return 0;
1904        };
1905        let wid: WindowId = app.get_window_state().get_id();
1906        app.dispatch_window_event(WindowEvent::PointerDown(wid, PointerEvent::mouse(x, y)));
1907        app.step_frame()
1908            .map(|stats: FrameStats| stats.get_frame_hash())
1909            .unwrap_or(0)
1910    })
1911}
1912
1913/// Dispatches a browser pointer release event into the running WebAssembly documentation viewer.
1914///
1915/// # Arguments
1916///
1917/// - `f32` - Logical X coordinate inside the canvas.
1918/// - `f32` - Logical Y coordinate inside the canvas.
1919///
1920/// # Returns
1921///
1922/// - `u64` - Rendered frame hash.
1923#[cfg(target_arch = "wasm32")]
1924pub fn wasm_docs_pointer_up(x: f32, y: f32) -> u64 {
1925    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
1926        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
1927            Ok(guard) => guard,
1928            Err(_) => return 0,
1929        };
1930        let Some((app, _)) = borrow.as_mut() else {
1931            return 0;
1932        };
1933        let wid: WindowId = app.get_window_state().get_id();
1934        app.dispatch_window_event(WindowEvent::PointerUp(wid, PointerEvent::mouse(x, y)));
1935        app.step_frame()
1936            .map(|stats: FrameStats| stats.get_frame_hash())
1937            .unwrap_or(0)
1938    })
1939}
1940
1941/// Dispatches a browser wheel scroll delta into the running WebAssembly documentation viewer.
1942///
1943/// # Arguments
1944///
1945/// - `f32` - Horizontal scroll delta.
1946/// - `f32` - Vertical scroll delta.
1947///
1948/// # Returns
1949///
1950/// - `u64` - Rendered frame hash.
1951#[cfg(target_arch = "wasm32")]
1952pub fn wasm_docs_scroll(dx: f32, dy: f32) -> u64 {
1953    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
1954        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
1955            Ok(guard) => guard,
1956            Err(_) => return 0,
1957        };
1958        let Some((app, _)) = borrow.as_mut() else {
1959            return 0;
1960        };
1961        let wid: WindowId = app.get_window_state().get_id();
1962        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1963        app.step_frame()
1964            .map(|stats: FrameStats| stats.get_frame_hash())
1965            .unwrap_or(0)
1966    })
1967}
1968
1969/// Dispatches a browser keyboard event into the running WebAssembly documentation viewer.
1970///
1971/// # Arguments
1972///
1973/// - `&str` - DOM `KeyboardEvent.key` string.
1974///
1975/// # Returns
1976///
1977/// - `u64` - Rendered frame hash.
1978#[cfg(target_arch = "wasm32")]
1979pub fn wasm_docs_key_down(key: &str) -> u64 {
1980    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
1981        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
1982            Ok(guard) => guard,
1983            Err(_) => return 0,
1984        };
1985        let Some((app, _)) = borrow.as_mut() else {
1986            return 0;
1987        };
1988        let wid: WindowId = app.get_window_state().get_id();
1989        let code: KeyCode = match key {
1990            WEB_KEY_ENTER => KeyCode::Enter,
1991            WEB_KEY_BACKSPACE => KeyCode::Backspace,
1992            WEB_KEY_DELETE => KeyCode::Delete,
1993            WEB_KEY_ESCAPE => KeyCode::Escape,
1994            WEB_KEY_TAB => KeyCode::Tab,
1995            WEB_KEY_SPACE => KeyCode::Space,
1996            WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
1997            WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
1998            WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
1999            WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
2000            other => other
2001                .chars()
2002                .next()
2003                .map(KeyCode::Character)
2004                .unwrap_or(KeyCode::Unknown),
2005        };
2006        app.dispatch_window_event(WindowEvent::KeyDown(
2007            wid,
2008            KeyEvent::new(code, Modifiers::default(), false),
2009        ));
2010        if key.chars().count() == 1 {
2011            app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
2012        }
2013        app.step_frame()
2014            .map(|stats: FrameStats| stats.get_frame_hash())
2015            .unwrap_or(0)
2016    })
2017}
2018
2019/// Advances animations or repaints the running WebAssembly documentation viewer.
2020///
2021/// # Arguments
2022///
2023/// - `f32` - Elapsed seconds since the previous animation frame.
2024///
2025/// # Returns
2026///
2027/// - `u64` - Rendered frame hash.
2028#[cfg(target_arch = "wasm32")]
2029pub fn wasm_docs_tick(dt_secs: f32) -> u64 {
2030    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2031        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
2032            Ok(guard) => guard,
2033            Err(_) => return 0,
2034        };
2035        let Some((app, _)) = borrow.as_mut() else {
2036            return 0;
2037        };
2038        if dt_secs <= 0.0 || app.has_active_animations() {
2039            return app
2040                .step_game_frame(dt_secs.max(0.0))
2041                .map(|stats: FrameStats| stats.get_frame_hash())
2042                .unwrap_or(0);
2043        }
2044        app.get_renderer().get_last_stats().get_frame_hash()
2045    })
2046}
2047
2048/// Resizes the WebAssembly documentation viewer canvas and logical viewport immediately.
2049///
2050/// # Arguments
2051///
2052/// - `u32` - Logical viewport width in CSS pixels.
2053/// - `u32` - Logical viewport height in CSS pixels.
2054/// - `f32` - Active browser `window.devicePixelRatio`.
2055///
2056/// # Returns
2057///
2058/// - `u64` - Rendered frame hash.
2059#[cfg(target_arch = "wasm32")]
2060pub fn wasm_docs_resize(width: u32, height: u32, dpr: f32) -> u64 {
2061    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2062        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
2063            Ok(guard) => guard,
2064            Err(_) => return 0,
2065        };
2066        let Some((app, _)) = borrow.as_mut() else {
2067            return 0;
2068        };
2069        let w: u32 = width.max(320);
2070        let h: u32 = height.max(320);
2071        let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
2072            dpr.clamp(0.5, 4.5)
2073        } else {
2074            1.0
2075        };
2076        let phys_w: u32 = ((w as f64) * (scale as f64)).round().max(1.0) as u32;
2077        let phys_h: u32 = ((h as f64) * (scale as f64)).round().max(1.0) as u32;
2078        if let Some(win) = window()
2079            && let Some(doc) = win.document()
2080            && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2081            && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2082        {
2083            if canvas.width() != phys_w {
2084                canvas.set_width(phys_w);
2085            }
2086            if canvas.height() != phys_h {
2087                canvas.set_height(phys_h);
2088            }
2089        }
2090        app.set_exact_physical_viewport(phys_w, phys_h, scale);
2091        app.step_frame()
2092            .map(|stats: FrameStats| stats.get_frame_hash())
2093            .unwrap_or(0)
2094    })
2095}