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/// Computes the relative site-root asset base prefix (`"./"` for root locale `"/"`, `"../"` for `"/en/"`, etc.) working under both root and subpath deployments.
589///
590/// # Arguments
591///
592/// - `&str` - Active locale prefix (for example `"/"`, `"/en/"`, `"/ja/"`).
593///
594/// # Returns
595///
596/// - `String` - Relative URL prefix reaching the built site root (`"./"`, `"../"`, ...).
597#[must_use]
598pub fn asset_base_for_locale_prefix(locale_prefix: &str) -> String {
599    let depth: usize = locale_prefix
600        .trim()
601        .split('/')
602        .filter(|seg: &&str| !seg.is_empty())
603        .count();
604    if depth == 0 {
605        "./".to_string()
606    } else {
607        "../".repeat(depth)
608    }
609}
610
611/// Resolves a portable relative locale-switch URL from `active_locale_prefix` to `target_locale_prefix` working under both `/` and `/pages/docs/`.
612///
613/// # Arguments
614///
615/// - `&str` - Currently active locale prefix (for example `"/"` or `"/en/"`).
616/// - `&str` - Destination locale prefix (for example `"/"`, `"/en/"`, `"/ja/"`).
617///
618/// # Returns
619///
620/// - `String` - Relative navigation href targeting the destination locale directory.
621#[must_use]
622pub fn resolve_locale_switch_href(
623    active_locale_prefix: &str,
624    target_locale_prefix: &str,
625) -> String {
626    let base: String = asset_base_for_locale_prefix(active_locale_prefix);
627    let target_rel: &str = target_locale_prefix.trim().trim_start_matches('/');
628    if target_rel.is_empty() {
629        base
630    } else if target_rel.ends_with('/') {
631        format!("{base}{target_rel}")
632    } else {
633        format!("{base}{target_rel}/")
634    }
635}
636
637/// Draws a precision Lucide / SF-Symbols style hollow Sun vector icon on a normalized 24ร—24 optical box.
638///
639/// # Arguments
640///
641/// - `Rect` - Target logical bounding box.
642/// - `&mut DisplayList` - Destination vector draw command list.
643/// - `Color` - Foreground stroke color.
644fn draw_docs_sun_icon(bounds: Rect, dl: &mut DisplayList, color: Color) {
645    let w: f32 = bounds.get_width().max(8.0);
646    let h: f32 = bounds.get_height().max(8.0);
647    let side: f32 = w.min(h);
648    let ox: f32 = bounds.get_x() + (w - side) * 0.5;
649    let oy: f32 = bounds.get_y() + (h - side) * 0.5;
650    let u: f32 = side / 24.0;
651    let sw: f32 = (1.75 * u).clamp(1.25, 2.2);
652    let cx: f32 = ox + 12.0 * u;
653    let cy: f32 = oy + 12.0 * u;
654    let r: f32 = 4.2 * u;
655    dl.push(DrawCommand::FillRoundedRect {
656        rect: Rect::new(cx - r, cy - r, r * 2.0, r * 2.0),
657        color: COLOR_TRANSPARENT,
658        radius: CornerRadius::all(r),
659        border: Border::new(sw, color),
660    });
661    let r_in: f32 = 7.0 * u;
662    let r_out: f32 = 9.4 * u;
663    for i in 0..8usize {
664        let angle: f32 = (i as f32) * (TAU / 8.0);
665        let cos_a: f32 = angle.cos();
666        let sin_a: f32 = angle.sin();
667        dl.push(DrawCommand::Line {
668            from: Point::new(cx + cos_a * r_in, cy + sin_a * r_in),
669            to: Point::new(cx + cos_a * r_out, cy + sin_a * r_out),
670            color,
671            width: sw,
672        });
673    }
674}
675
676/// Draws a smooth analytical Lucide `MoonStar` crescent + upper-right 4-point sparkle vector icon on a 24ร—24 optical box.
677///
678/// # Arguments
679///
680/// - `Rect` - Target logical bounding box.
681/// - `&mut DisplayList` - Destination vector draw command list.
682/// - `Color` - Foreground stroke color.
683fn draw_docs_moon_star_icon(bounds: Rect, dl: &mut DisplayList, color: Color) {
684    let w: f32 = bounds.get_width().max(8.0);
685    let h: f32 = bounds.get_height().max(8.0);
686    let side: f32 = w.min(h);
687    let ox: f32 = bounds.get_x() + (w - side) * 0.5;
688    let oy: f32 = bounds.get_y() + (h - side) * 0.5;
689    let u: f32 = side / 24.0;
690    let sw: f32 = (1.75 * u).clamp(1.25, 2.2);
691    let ocx: f32 = ox + 11.4 * u;
692    let ocy: f32 = oy + 12.6 * u;
693    let orad: f32 = 8.4 * u;
694    let outer_start: f32 = -1.78;
695    let outer_end: f32 = 0.42;
696    let steps: usize = 20;
697    let mut prev: Point = Point::new(
698        ocx + outer_start.cos() * orad,
699        ocy + outer_start.sin() * orad,
700    );
701    for s in 1..=steps {
702        let t: f32 = (s as f32) / (steps as f32);
703        let a: f32 = outer_start - t * (TAU - (outer_end - outer_start));
704        let cur: Point = Point::new(ocx + a.cos() * orad, ocy + a.sin() * orad);
705        dl.push(DrawCommand::Line {
706            from: prev,
707            to: cur,
708            color,
709            width: sw,
710        });
711        prev = cur;
712    }
713    let p_end: Point = prev;
714    let p_start: Point = Point::new(
715        ocx + outer_start.cos() * orad,
716        ocy + outer_start.sin() * orad,
717    );
718    let icx: f32 = ox + 15.6 * u;
719    let icy: f32 = oy + 8.6 * u;
720    let irad: f32 = 6.2 * u;
721    let a0: f32 = (p_end.get_y() - icy).atan2(p_end.get_x() - icx);
722    let a1: f32 = (p_start.get_y() - icy).atan2(p_start.get_x() - icx);
723    let mut delta: f32 = a1 - a0;
724    if delta < 0.0 {
725        delta += TAU;
726    }
727    if delta > PI {
728        delta -= TAU;
729    }
730    let mut inner_prev: Point = p_end;
731    let inner_steps: usize = 14;
732    for s in 1..=inner_steps {
733        let t: f32 = (s as f32) / (inner_steps as f32);
734        let a: f32 = a0 + t * delta;
735        let cur: Point = Point::new(icx + a.cos() * irad, icy + a.sin() * irad);
736        dl.push(DrawCommand::Line {
737            from: inner_prev,
738            to: cur,
739            color,
740            width: sw,
741        });
742        inner_prev = cur;
743    }
744    let sx: f32 = ox + 18.4 * u;
745    let sy: f32 = oy + 5.6 * u;
746    let s_arm: f32 = 2.4 * u;
747    let s_sw: f32 = (1.35 * u).clamp(1.0, 1.8);
748    dl.push(DrawCommand::Line {
749        from: Point::new(sx - s_arm, sy),
750        to: Point::new(sx + s_arm, sy),
751        color,
752        width: s_sw,
753    });
754    dl.push(DrawCommand::Line {
755        from: Point::new(sx, sy - s_arm),
756        to: Point::new(sx, sy + s_arm),
757        color,
758        width: s_sw,
759    });
760}
761
762/// Draws a precision Lucide-style 8-tooth gear vector icon with smooth crowns and concentric center ring on a 24ร—24 optical box.
763///
764/// # Arguments
765///
766/// - `Rect` - Target logical bounding box.
767/// - `&mut DisplayList` - Destination vector draw command list.
768/// - `Color` - Foreground stroke color.
769fn draw_docs_gear_icon(bounds: Rect, dl: &mut DisplayList, color: Color) {
770    let w: f32 = bounds.get_width().max(8.0);
771    let h: f32 = bounds.get_height().max(8.0);
772    let side: f32 = w.min(h);
773    let ox: f32 = bounds.get_x() + (w - side) * 0.5;
774    let oy: f32 = bounds.get_y() + (h - side) * 0.5;
775    let u: f32 = side / 24.0;
776    let sw: f32 = (1.75 * u).clamp(1.25, 2.2);
777    let cx: f32 = ox + 12.0 * u;
778    let cy: f32 = oy + 12.0 * u;
779    let r_hole: f32 = 3.1 * u;
780    dl.push(DrawCommand::FillRoundedRect {
781        rect: Rect::new(cx - r_hole, cy - r_hole, r_hole * 2.0, r_hole * 2.0),
782        color: COLOR_TRANSPARENT,
783        radius: CornerRadius::all(r_hole),
784        border: Border::new(sw, color),
785    });
786    let r_valley: f32 = 6.5 * u;
787    let r_crown: f32 = 9.2 * u;
788    let teeth: usize = 8;
789    let samples: usize = teeth * 8;
790    let mut prev: Option<Point> = None;
791    let mut first: Option<Point> = None;
792    for s in 0..samples {
793        let a: f32 = (s as f32) * (TAU / (samples as f32)) - FRAC_PI_2;
794        let wave: f32 = ((teeth as f32) * (a + FRAC_PI_2)).cos();
795        let shaped: f32 = (wave * 1.45).clamp(-1.0, 1.0);
796        let t: f32 = (shaped + 1.0) * 0.5;
797        let rad: f32 = r_valley + (r_crown - r_valley) * t;
798        let cur: Point = Point::new(cx + a.cos() * rad, cy + a.sin() * rad);
799        if let Some(p) = prev {
800            dl.push(DrawCommand::Line {
801                from: p,
802                to: cur,
803                color,
804                width: sw,
805            });
806        } else {
807            first = Some(cur);
808        }
809        prev = Some(cur);
810    }
811    if let (Some(p), Some(f)) = (prev, first) {
812        dl.push(DrawCommand::Line {
813            from: p,
814            to: f,
815            color,
816            width: sw,
817        });
818    }
819}
820
821/// Renders the site footer row with localized MIT license attribution followed inline directly by `footer_items` (such as ICP filing numbers) in a single unified row.
822///
823/// # Arguments
824///
825/// - `&DocSite` - Documentation site containing footer text and `footer_items`.
826/// - `ThemeTokens` - Active design tokens.
827///
828/// # Returns
829///
830/// - `NodeId` - Mounted footer container handle.
831pub fn mount_docs_footer(site: &DocSite, tokens: ThemeTokens) -> NodeId {
832    let p: ThemePalette = tokens.get_palette();
833    let license_text: String = if site.get_footer().trim().is_empty() {
834        DOCS_DEFAULT_FOOTER.to_string()
835    } else {
836        site.get_footer().trim().to_string()
837    };
838    let footer_link: String = site.get_footer_link().trim().to_string();
839    let asset_base: String = asset_base_for_locale_prefix(site.get_locale_prefix().as_str());
840    let mut row_children: Vec<NodeId> = Vec::with_capacity(site.get_footer_items().len() * 2 + 3);
841    if !footer_link.is_empty() {
842        let link_target: String = footer_link.clone();
843        let on_click_license = move |_: &UiEvent| {
844            #[cfg(target_arch = "wasm32")]
845            open_browser_url(&link_target, true);
846            #[cfg(not(target_arch = "wasm32"))]
847            {
848                let _: &str = link_target.as_str();
849            }
850        };
851        row_children.push(view! {
852            row {
853                style: {
854                    align: AlignItems::Center
855                    cursor: CursorIcon::Pointer
856                }
857                role: A11yRole::Link
858                a11y_label: license_text.clone()
859                on_click: on_click_license
860                text {
861                    style: {
862                        font_size: 12.0
863                        color: p.get_muted_foreground()
864                        selectable: true
865                    }
866                    { license_text }
867                }
868            }
869        });
870    } else {
871        row_children.push(view! {
872            text {
873                style: {
874                    font_size: 12.0
875                    color: p.get_muted_foreground()
876                    selectable: true
877                }
878                { license_text }
879            }
880        });
881    }
882    for item in site.get_footer_items().iter() {
883        let label: String = item.get_text().trim().to_string();
884        if label.is_empty() {
885            continue;
886        }
887        row_children.push(view! {
888            text {
889                style: {
890                    font_size: 12.0
891                    color: p.get_muted_foreground()
892                }
893                { DOCS_FOOTER_SEP }
894            }
895        });
896        let target_url: String = item.get_link().trim().to_string();
897        let icon_url: String = item.get_icon().trim().to_string();
898        let a11y_txt: String = if item.get_alt().trim().is_empty() {
899            label.clone()
900        } else {
901            format!("{} ({})", label, item.get_alt().trim())
902        };
903        let has_icon: bool = !icon_url.is_empty();
904        let icon_node_opt: Option<NodeId> = if has_icon {
905            let resolved_icon: String =
906                resolve_markdown_asset_url(icon_url.as_str(), asset_base.as_str());
907            if let Some(buf) = cached_network_image(&resolved_icon) {
908                let ctx: Context = current_context();
909                Some(ctx.get_scene().with_write(
910                    |tree: &mut SceneTree| {
911                        let mut st: Style = Style::default();
912                        st.get_mut_layout()
913                            .set_width(Length::Px(14.0))
914                            .set_height(Length::Px(14.0))
915                            .set_flex_shrink(0.0);
916                        tree.create_image(buf, st)
917                    },
918                    NodeId::default(),
919                ))
920            } else {
921                None
922            }
923        } else {
924            None
925        };
926        let on_click_item = move |_: &UiEvent| {
927            #[cfg(target_arch = "wasm32")]
928            if !target_url.is_empty() {
929                open_browser_url(&target_url, true);
930            }
931            #[cfg(not(target_arch = "wasm32"))]
932            {
933                let _: &str = target_url.as_str();
934            }
935        };
936        row_children.push(view! {
937            row {
938                style: {
939                    align: AlignItems::Center
940                    gap: SPACE_XS
941                    cursor: CursorIcon::Pointer
942                }
943                role: A11yRole::Link
944                a11y_label: a11y_txt
945                on_click: on_click_item
946                if let Some(ic) = icon_node_opt {
947                    { ic }
948                }
949                text {
950                    style: {
951                        font_size: 12.0
952                        color: p.get_primary()
953                        selectable: true
954                    }
955                    { label }
956                }
957            }
958        });
959    }
960    row_children.push(view! {
961        text {
962            style: {
963                font_size: 12.0
964                color: p.get_muted_foreground()
965            }
966            { format!("{DOCS_FOOTER_SEP}{EUV_DOCS_RELEASE_MARKER}") }
967        }
968    });
969    view! {
970        column {
971            style: {
972                width: Length::Percent(100.0)
973                gap: SPACE_SM
974                padding: Edges::new(SPACE_MD, 0.0, SPACE_SM, 0.0)
975            }
976            EuvDivider {
977                tokens: tokens
978            }
979            row {
980                style: {
981                    width: Length::Percent(100.0)
982                    flex_wrap: FlexWrap::Wrap
983                    align: AlignItems::Center
984                    gap: 4.0
985                }
986                ..row_children
987            }
988        }
989    }
990}
991
992/// Renders a `home: true` landing page with hero banner, CTA buttons, stat KPI grid, feature cards, Markdown body, and `/api/page-artifacts` catalog.
993///
994/// # Arguments
995///
996/// - `&DocPage` - Home page carrying hero, actions, stats, features, and body Markdown.
997/// - `&DocsViewerState` - Shared reactive viewer state.
998/// - `ThemeTokens` - Active design tokens.
999///
1000/// # Returns
1001///
1002/// - `NodeId` - Mounted landing page container node.
1003fn mount_doc_home_page(page: &DocPage, state: &DocsViewerState, tokens: ThemeTokens) -> NodeId {
1004    let p: ThemePalette = tokens.get_palette();
1005    let hero_title: String = page
1006        .try_get_hero_text()
1007        .clone()
1008        .filter(|s: &String| !s.trim().is_empty())
1009        .unwrap_or_else(|| page.get_title().clone());
1010    let hero_sub: String = if !page.get_summary().trim().is_empty() {
1011        page.get_summary().clone()
1012    } else {
1013        state.get_site().get_tagline().clone()
1014    };
1015    let action_buttons: Vec<NodeId> = page
1016        .get_actions()
1017        .iter()
1018        .map(|act: &DocHomeAction| {
1019            let link_url: String = act.get_link().clone();
1020            let site_c: Rc<DocSite> = Rc::clone(state.get_site());
1021            let route_sig: Signal<String> = state.get_active_route();
1022            let toc_sig: Signal<String> = state.get_active_toc_slug();
1023            let on_act = move |_: &UiEvent| {
1024                navigate_doc_href(&link_url, &site_c, route_sig, toc_sig);
1025            };
1026            let variant: EuvButtonVariant = if act
1027                .get_kind()
1028                .eq_ignore_ascii_case(DOCS_HOME_ACTION_PRIMARY)
1029            {
1030                EuvButtonVariant::Primary
1031            } else {
1032                EuvButtonVariant::Outline
1033            };
1034            view! {
1035                EuvButton {
1036                    label: act.get_text().clone()
1037                    variant: variant
1038                    tokens: tokens
1039                    on_click: on_act
1040                }
1041            }
1042        })
1043        .collect();
1044    let stat_cards: Vec<NodeId> = page
1045        .get_stats()
1046        .iter()
1047        .map(|st: &DocHomeStat| {
1048            let label_str: String = if st.get_icon().is_empty() {
1049                st.get_label().clone()
1050            } else {
1051                format!("{} {}", st.get_icon(), st.get_label())
1052            };
1053            view! {
1054                EuvStatCard {
1055                    label: label_str
1056                    value: st.get_value().clone()
1057                    caption: String::new()
1058                    tokens: tokens
1059                }
1060            }
1061        })
1062        .collect();
1063    let feature_cards: Vec<NodeId> = page
1064        .get_features()
1065        .iter()
1066        .map(|feat: &DocHomeFeature| {
1067            let link_url: String = feat.get_link().clone();
1068            let site_c: Rc<DocSite> = Rc::clone(state.get_site());
1069            let route_sig: Signal<String> = state.get_active_route();
1070            let toc_sig: Signal<String> = state.get_active_toc_slug();
1071            let on_open_feat = move |_: &UiEvent| {
1072                navigate_doc_href(&link_url, &site_c, route_sig, toc_sig);
1073            };
1074            let has_link: bool = !feat.get_link().trim().is_empty();
1075            view! {
1076                EuvCard {
1077                    title: feat.get_title().clone()
1078                    tokens: tokens
1079                    text {
1080                        style: {
1081                            width: Length::Percent(100.0)
1082                            font_size: 13.0
1083                            color: p.get_muted_foreground()
1084                            selectable: true
1085                        }
1086                        { feat.get_details().clone() }
1087                    }
1088                    if has_link {
1089                        EuvButton {
1090                            label: DOCS_CATALOG_OPEN_BTN.to_string()
1091                            variant: EuvButtonVariant::Ghost
1092                            tokens: tokens
1093                            on_click: on_open_feat
1094                        }
1095                    }
1096                }
1097            }
1098        })
1099        .collect();
1100    let site_for_link: Rc<DocSite> = Rc::clone(state.get_site());
1101    let route_for_link: Signal<String> = state.get_active_route();
1102    let toc_for_link: Signal<String> = state.get_active_toc_slug();
1103    let asset_base: String = state.asset_base();
1104    let md_body: NodeId = if !page.get_markdown_body().trim().is_empty() {
1105        EuvMarkdown::new(page.get_markdown_body().clone(), tokens)
1106            .style(style! {
1107                text_select: TextSelectMode::SelectAndCopy
1108            })
1109            .asset_base(asset_base)
1110            .on_link(move |url: &str| {
1111                navigate_doc_href(url, &site_for_link, route_for_link, toc_for_link);
1112            })
1113            .mount()
1114    } else {
1115        view! {
1116            column {
1117                style: {
1118                    width: Length::Percent(100.0)
1119                }
1120            }
1121        }
1122    };
1123    let catalog_node: NodeId = mount_docs_catalog(state, tokens);
1124    let (prev_opt, next_opt): (Option<EuvDocPagerLink>, Option<EuvDocPagerLink>) =
1125        state.pager_links_for_route(page.get_route());
1126    let pager_route: Signal<String> = state.get_active_route();
1127    let pager_node: NodeId = EuvDocPager::new(prev_opt, next_opt, pager_route, tokens)
1128        .prev_label(state.get_site().resolved_prev_label())
1129        .next_label(state.get_site().resolved_next_label())
1130        .mount();
1131    let footer_node: NodeId = mount_docs_footer(state.get_site(), tokens);
1132    let mut action_row: EuvActionRow = EuvActionRow::new();
1133    for btn in action_buttons.into_iter() {
1134        action_row = action_row.child(btn);
1135    }
1136    let action_bar: NodeId = action_row.mount();
1137    let mut stat_grid_builder: EuvStatGrid = EuvStatGrid::new();
1138    for card in stat_cards.into_iter() {
1139        stat_grid_builder = stat_grid_builder.card(card);
1140    }
1141    let stat_grid: NodeId = stat_grid_builder.mount();
1142    view! {
1143        column {
1144            style: {
1145                width: Length::Percent(100.0)
1146                gap: SPACE_LG
1147            }
1148            EuvCard {
1149                title: hero_title
1150                subtitle: hero_sub
1151                tokens: tokens
1152                if !page.get_actions().is_empty() {
1153                    { action_bar }
1154                }
1155            }
1156            if !page.get_stats().is_empty() {
1157                { stat_grid }
1158            }
1159            if !feature_cards.is_empty() {
1160                column {
1161                    style: {
1162                        width: Length::Percent(100.0)
1163                        gap: SPACE_SM
1164                    }
1165                    EuvHeader {
1166                        title: DOCS_HOME_FEATURES_TITLE.to_string()
1167                        subtitle: String::new()
1168                        tokens: tokens
1169                    }
1170                    grid {
1171                        style: {
1172                            columns: 2
1173                            width: Length::Percent(100.0)
1174                            gap: SPACE_SM
1175                        }
1176                        ..feature_cards
1177                    }
1178                }
1179            }
1180            { md_body }
1181            { catalog_node }
1182            { pager_node }
1183            { footer_node }
1184        }
1185    }
1186}
1187
1188/// Renders a standard documentation article page purely from `euv-ui` components (`EuvBreadcrumb`, `EuvDocMetaBar`, `EuvHeader`, `EuvDocToc`, `EuvMarkdown`, `EuvDivider`, `EuvDocPager`, `EuvFooter`).
1189///
1190/// # Arguments
1191///
1192/// - `&DocPage` - Documentation page to render.
1193/// - `&DocsViewerState` - Shared reactive viewer state for route, TOC, and pager interactivity.
1194/// - `ThemeTokens` - Active design tokens.
1195///
1196/// # Returns
1197///
1198/// - `NodeId` - Mounted article page container node.
1199pub fn mount_doc_page_with_context(
1200    page: &DocPage,
1201    state: &DocsViewerState,
1202    tokens: ThemeTokens,
1203) -> NodeId {
1204    if page.get_is_home() {
1205        return mount_doc_home_page(page, state, tokens);
1206    }
1207    let breadcrumb_segments: Vec<String> = vec![
1208        state.get_site().get_title().clone(),
1209        page.get_section().clone(),
1210        page.get_title().clone(),
1211    ];
1212    let mut meta_bar: EuvDocMetaBar = EuvDocMetaBar::new(
1213        page.get_section().clone(),
1214        page.reading_minutes(),
1215        page.word_count(),
1216        tokens,
1217    )
1218    .source_path(page.get_route().clone());
1219    if let Some(updated) = page.try_get_updated().as_deref() {
1220        meta_bar = meta_bar.updated(updated);
1221    }
1222    let meta_node: NodeId = meta_bar.mount();
1223    let show_subtitle: bool = {
1224        let sum: &str = page.get_summary().trim();
1225        !sum.is_empty() && !sum.eq_ignore_ascii_case(page.get_title().trim())
1226    };
1227    let subtitle_str: String = if show_subtitle {
1228        page.get_summary().clone()
1229    } else {
1230        String::new()
1231    };
1232    let toc_items: Vec<EuvDocTocItem> = page
1233        .get_toc()
1234        .iter()
1235        .map(|it: &DocTocItem| {
1236            EuvDocTocItem::new(
1237                it.get_level(),
1238                it.get_slug().clone(),
1239                it.get_title().clone(),
1240            )
1241        })
1242        .collect();
1243    let toc_slug_sig: Signal<String> = state.get_active_toc_slug();
1244    let toc_node_opt: Option<NodeId> = if toc_items.is_empty() {
1245        None
1246    } else {
1247        let toc_click_sig: Signal<String> = toc_slug_sig;
1248        Some(
1249            EuvDocToc::new(toc_items, toc_slug_sig, tokens)
1250                .title(state.get_site().resolved_toc_label())
1251                .on_select(move |slug: &str| {
1252                    let _: bool = toc_click_sig.set_if_changed(slug.to_string());
1253                })
1254                .mount(),
1255        )
1256    };
1257    let site_for_link: Rc<DocSite> = Rc::clone(state.get_site());
1258    let route_for_link: Signal<String> = state.get_active_route();
1259    let toc_for_link: Signal<String> = state.get_active_toc_slug();
1260    let asset_base: String = state.asset_base();
1261    let body_node: NodeId = if !page.get_markdown_body().trim().is_empty() {
1262        EuvMarkdown::new(page.get_markdown_body().clone(), tokens)
1263            .style(style! {
1264                text_select: TextSelectMode::SelectAndCopy
1265            })
1266            .asset_base(asset_base.clone())
1267            .on_link(move |url: &str| {
1268                navigate_doc_href(url, &site_for_link, route_for_link, toc_for_link);
1269            })
1270            .mount()
1271    } else {
1272        mount_fallback_doc_blocks(page, &asset_base, tokens)
1273    };
1274    let (prev_opt, next_opt): (Option<EuvDocPagerLink>, Option<EuvDocPagerLink>) =
1275        state.pager_links_for_route(page.get_route());
1276    let pager_route: Signal<String> = state.get_active_route();
1277    let pager_node: NodeId = EuvDocPager::new(prev_opt, next_opt, pager_route, tokens)
1278        .prev_label(state.get_site().resolved_prev_label())
1279        .next_label(state.get_site().resolved_next_label())
1280        .mount();
1281    let footer_node: NodeId = mount_docs_footer(state.get_site(), tokens);
1282    let doc_main_col: NodeId = view! {
1283        column {
1284            style: {
1285                flex_grow: 1.0
1286                flex_shrink: 1.0
1287                min_width: Length::Px(0.0)
1288                width: Length::Percent(100.0)
1289                gap: SPACE_MD
1290            }
1291            EuvBreadcrumb {
1292                segments: breadcrumb_segments
1293                tokens: tokens
1294            }
1295            { meta_node }
1296            EuvHeader {
1297                title: page.get_title().clone()
1298                subtitle: subtitle_str
1299                tokens: tokens
1300            }
1301            { body_node }
1302            EuvDivider {
1303                tokens: tokens
1304            }
1305            { pager_node }
1306            { footer_node }
1307        }
1308    };
1309    let Some(toc_node) = toc_node_opt else {
1310        return doc_main_col;
1311    };
1312    let ctx: Context = current_context();
1313    let vp_sig: Signal<Size> = ctx.get_viewport_size();
1314    let mut wide_row_node: NodeId = NodeId::default();
1315    let mut inline_toc_host: NodeId = NodeId::default();
1316    let mut right_toc_host: NodeId = NodeId::default();
1317    let layout_root: NodeId = view! {
1318        column {
1319            style: {
1320                width: Length::Percent(100.0)
1321                gap: SPACE_MD
1322            }
1323            column {
1324                node_ref: inline_toc_host
1325                style: {
1326                    width: Length::Percent(100.0)
1327                    display: Display::None
1328                }
1329            }
1330            row {
1331                node_ref: wide_row_node
1332                style: {
1333                    width: Length::Percent(100.0)
1334                    align: AlignItems::Start
1335                    gap: SPACE_LG
1336                }
1337                { doc_main_col }
1338                column {
1339                    node_ref: right_toc_host
1340                    style: {
1341                        width: Length::Px(DOCS_RIGHT_TOC_WIDTH)
1342                        flex_shrink: 0.0
1343                        display: Display::None
1344                    }
1345                }
1346            }
1347        }
1348    };
1349    let scene_toc: SceneHandle = ctx.get_scene().clone();
1350    let (toc_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1351        Effect::new(move || {
1352            let vp: Size = vp_sig.get();
1353            let is_wide: bool = vp.get_width() >= DOCS_WIDE_TOC_BREAKPOINT;
1354            scene_toc.with_write(
1355                |tree: &mut SceneTree| {
1356                    let target_host: NodeId = if is_wide {
1357                        right_toc_host
1358                    } else {
1359                        inline_toc_host
1360                    };
1361                    let cur_parent: Option<NodeId> =
1362                        tree.get_node(toc_node).and_then(SceneNode::parent_id);
1363                    if cur_parent != Some(target_host) {
1364                        tree.append_child(target_host, toc_node);
1365                    }
1366                    let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1367                    let dirty_mask: u16 = dirty_l | DIRTY_PAINT;
1368                    if let Some(n) = tree.get_node_mut(right_toc_host) {
1369                        n.get_mut_style().get_mut_layout().set_display(if is_wide {
1370                            Display::Flex
1371                        } else {
1372                            Display::None
1373                        });
1374                        tree.mark_dirty(right_toc_host, dirty_mask);
1375                    }
1376                    if let Some(n) = tree.get_node_mut(inline_toc_host) {
1377                        n.get_mut_style().get_mut_layout().set_display(if is_wide {
1378                            Display::None
1379                        } else {
1380                            Display::Flex
1381                        });
1382                        tree.mark_dirty(inline_toc_host, dirty_mask);
1383                    }
1384                    tree.mark_dirty(wide_row_node, dirty_mask);
1385                },
1386                (),
1387            );
1388        })
1389    });
1390    ctx.get_scene().with_write(
1391        |tree: &mut SceneTree| {
1392            tree.attach_scope(layout_root, toc_scope);
1393        },
1394        (),
1395    );
1396    layout_root
1397}
1398
1399/// Renders structured `DocBlock` nodes when a `DocPage` has no raw Markdown body text.
1400///
1401/// # Arguments
1402///
1403/// - `&DocPage` - Documentation page holding pre-parsed blocks.
1404/// - `&str` - Relative site-root asset base prefix (`"./"` or `"../"`).
1405/// - `ThemeTokens` - Active design tokens.
1406///
1407/// # Returns
1408///
1409/// - `NodeId` - Mounted fallback block column handle.
1410fn mount_fallback_doc_blocks(page: &DocPage, asset_base: &str, tokens: ThemeTokens) -> NodeId {
1411    view! {
1412        column {
1413            style: {
1414                width: Length::Percent(100.0)
1415                gap: SPACE_MD
1416            }
1417            for block in page.get_blocks().iter() {
1418                match block {
1419                    DocBlock::Heading { level, text, .. } => {
1420                        EuvMarkdownHeading {
1421                            level: *level
1422                            text: text.clone()
1423                            tokens: tokens
1424                        }
1425                    }
1426                    DocBlock::Paragraph(text) => {
1427                        EuvMarkdownParagraph {
1428                            inlines: parse_markdown_inlines(text)
1429                            tokens: tokens
1430                            asset_base: asset_base
1431                        }
1432                    }
1433                    DocBlock::ListItem(text) => EuvMarkdownList {
1434                        ordered: false
1435                        items: vec![EuvMarkdownListItem::new(text.clone(), 0, None)]
1436                        tokens: tokens
1437                    },
1438                    DocBlock::BlockQuote(text) => EuvMarkdownQuote {
1439                        kind: EuvMarkdownAlertKind::Quote
1440                        lines: vec![text.clone()]
1441                        tokens: tokens
1442                    },
1443                    DocBlock::Table { headers, rows } => EuvMarkdownTable {
1444                        headers: headers.clone()
1445                        alignments: vec![EuvMarkdownAlign::Left; headers.len()]
1446                        rows: rows.clone()
1447                        tokens: tokens
1448                    },
1449                    DocBlock::Image { alt, src } => {
1450                        EuvMarkdownImage {
1451                            alt: alt.clone()
1452                            url: src.clone()
1453                            tokens: tokens
1454                            asset_base: asset_base
1455                        }
1456                    }
1457                    DocBlock::HorizontalRule => EuvMarkdownDivider {
1458                        tokens: tokens
1459                    },
1460                    DocBlock::Code { language, code } => {
1461                        EuvCodeBlock {
1462                            code: code.clone()
1463                            tokens: tokens
1464                            language: language.clone()
1465                            line_numbers: true
1466                            selectable: true
1467                        }
1468                    }
1469                }
1470            }
1471        }
1472    }
1473}
1474
1475/// Renders a single standalone `DocPage` (meta bar, header, interactive TOC, and full `EuvMarkdown`) as native `euv-ui` nodes.
1476///
1477/// # Arguments
1478///
1479/// - `&DocPage` - Documentation page to mount.
1480/// - `ThemeTokens` - Active design tokens.
1481///
1482/// # Returns
1483///
1484/// - `NodeId` - Mounted page container node.
1485pub fn mount_doc_page(page: &DocPage, tokens: ThemeTokens) -> NodeId {
1486    let mut meta_bar: EuvDocMetaBar = EuvDocMetaBar::new(
1487        page.get_section().clone(),
1488        page.reading_minutes(),
1489        page.word_count(),
1490        tokens,
1491    )
1492    .source_path(page.get_route().clone());
1493    if let Some(updated) = page.try_get_updated().as_deref() {
1494        meta_bar = meta_bar.updated(updated);
1495    }
1496    let meta_node: NodeId = meta_bar.mount();
1497    let toc_items: Vec<EuvDocTocItem> = page
1498        .get_toc()
1499        .iter()
1500        .map(|it: &DocTocItem| {
1501            EuvDocTocItem::new(
1502                it.get_level(),
1503                it.get_slug().clone(),
1504                it.get_title().clone(),
1505            )
1506        })
1507        .collect();
1508    let toc_sig: Signal<String> = Signal::new(
1509        toc_items
1510            .first()
1511            .map(|it: &EuvDocTocItem| it.get_slug().clone())
1512            .unwrap_or_default(),
1513    );
1514    let toc_node_opt: Option<NodeId> = if toc_items.is_empty() {
1515        None
1516    } else {
1517        Some(EuvDocToc::new(toc_items, toc_sig, tokens).mount())
1518    };
1519    let body_node: NodeId = if !page.get_markdown_body().trim().is_empty() {
1520        EuvMarkdown::new(page.get_markdown_body().clone(), tokens)
1521            .style(style! {
1522                text_select: TextSelectMode::SelectAndCopy
1523            })
1524            .asset_base("./")
1525            .mount()
1526    } else {
1527        mount_fallback_doc_blocks(page, "./", tokens)
1528    };
1529    view! {
1530        column {
1531            style: {
1532                width: Length::Percent(100.0)
1533                gap: SPACE_MD
1534            }
1535            { meta_node }
1536            EuvHeader {
1537                title: page.get_title().clone()
1538                subtitle: page.get_summary().clone()
1539                tokens: tokens
1540            }
1541            if let Some(toc_node) = toc_node_opt {
1542                { toc_node }
1543            }
1544            { body_node }
1545        }
1546    }
1547}
1548
1549/// Registers every page in `state.site` lazily onto `state.router` with `PageRetention::Freeze`.
1550///
1551/// # Arguments
1552///
1553/// - `&DocsViewerState` - Shared reactive viewer state.
1554fn ensure_docs_routes_registered(state: &DocsViewerState) {
1555    if state.get_router_ready().replace(true) {
1556        return;
1557    }
1558    let mut router: EuvRouter = state.get_router().clone();
1559    for page in state.get_site().get_pages().iter() {
1560        let route_pattern: String = page.get_route().clone();
1561        let route_path: String = route_pattern.clone();
1562        let route_title: String = page.get_title().clone();
1563        let st: DocsViewerState = state.clone();
1564        router = router.route_with_retention(
1565            &route_pattern,
1566            &route_title,
1567            PageRetention::Freeze,
1568            move |_: &EuvRouteMatch| {
1569                let tok: ThemeTokens = untracked(|| st.get_theme().get_tokens().get());
1570                match st.get_site().find_by_route(&route_path) {
1571                    Some(p) => mount_doc_page_with_context(p, &st, tok),
1572                    None => view! {
1573                        EuvEmpty {
1574                            title: EMPTY_PAGE_TITLE.to_string()
1575                            description: EMPTY_PAGE_MSG.to_string()
1576                            tokens: tok
1577                        }
1578                    },
1579                }
1580            },
1581        );
1582    }
1583    let _: EuvRouter = router;
1584}
1585
1586/// Mounts the full showcase-parity reactive documentation shell (`EuvAppShell`, `EuvRouter` `PageRetention::Freeze`, live search, `EuvCommand` modal, 17-scheme theme controls, `EuvDocSectionNav`, and mobile `EuvBottomNav`).
1587///
1588/// # Arguments
1589///
1590/// - `&DocsViewerState` - Shared reactive documentation viewer state.
1591///
1592/// # Returns
1593///
1594/// - `NodeId` - Mounted documentation application root handle.
1595pub fn mount_docs_viewer_with_state(state: &DocsViewerState) -> NodeId {
1596    provide_theme(state.get_theme().clone());
1597    ensure_docs_routes_registered(state);
1598    let tokens: ThemeTokens = untracked(|| state.get_theme().get_tokens().get());
1599    let active_route: Signal<String> = state.get_active_route();
1600    let search_query: Signal<String> = state.get_search_query();
1601    let cmd_open: Signal<bool> = state.get_cmd_open();
1602    let cmd_query: Signal<String> = state.get_cmd_query();
1603    let all_pages: &[DocPage] = state.get_site().get_pages().as_slice();
1604    let mut cmd_routes: Vec<String> = Vec::with_capacity(all_pages.len());
1605    let mut cmd_items: Vec<String> = Vec::with_capacity(all_pages.len() + 2);
1606    for page in all_pages.iter() {
1607        cmd_routes.push(page.get_route().clone());
1608        cmd_items.push(format!("{} โ€” {}", page.get_title(), page.get_section()));
1609    }
1610    let toggle_idx: usize = cmd_items.len();
1611    cmd_items.push(CMD_ACTION_TOGGLE_MODE.to_string());
1612    let scheme_idx: usize = cmd_items.len();
1613    cmd_items.push(CMD_ACTION_NEXT_SCHEME.to_string());
1614    let cmd_sel: Signal<Option<usize>> = Signal::new(None);
1615    let cmd_list: NodeId = view! {
1616        EuvCommand {
1617            items: cmd_items
1618            selected: cmd_sel
1619            tokens: tokens
1620            query: cmd_query
1621            placeholder: CMD_PLACEHOLDER
1622        }
1623    };
1624    let cmd_state: DocsViewerState = state.clone();
1625    let (cmd_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1626        Effect::new(move || {
1627            if let Some(idx) = cmd_sel.get() {
1628                if let Some(target) = cmd_routes.get(idx) {
1629                    let _: bool = active_route.set_if_changed(target.clone());
1630                } else if idx == toggle_idx {
1631                    cmd_state.toggle_theme_mode();
1632                } else if idx == scheme_idx {
1633                    cmd_state.next_scheme();
1634                }
1635                let _: bool = cmd_sel.set_if_changed(None);
1636                let _: bool = cmd_open.set_if_changed(false);
1637            }
1638        })
1639    });
1640    let cmd_modal: NodeId = view! {
1641        EuvModal {
1642            open: cmd_open
1643            title: CMD_MODAL_TITLE.to_string()
1644            body: cmd_list
1645            tokens: tokens
1646        }
1647    };
1648    let rctx: Context = current_context();
1649    let theme_memo: Memo<ThemeTokens> = state.get_theme().get_tokens();
1650    let prev_modal_tok: Rc<Cell<ThemeTokens>> = Rc::new(Cell::new(tokens));
1651    let modal_theme_ctx: Context = rctx.clone();
1652    let (modal_theme_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1653        Effect::new(move || {
1654            let next_tok: ThemeTokens = theme_memo.get();
1655            let old_tok: ThemeTokens = prev_modal_tok.replace(next_tok);
1656            if old_tok == next_tok {
1657                return;
1658            }
1659            modal_theme_ctx.get_scene().with_write(
1660                |tree: &mut SceneTree| {
1661                    remap_subtree_theme_in_place(tree, cmd_modal, old_tok, next_tok);
1662                },
1663                (),
1664            );
1665        })
1666    });
1667    rctx.get_scene().with_write(
1668        |tree: &mut SceneTree| {
1669            tree.attach_scope(cmd_modal, cmd_scope);
1670            tree.attach_scope(cmd_modal, modal_theme_scope);
1671        },
1672        (),
1673    );
1674    let router: EuvRouter = state.get_router().clone();
1675    let cur_route: String = active_route.get_untracked();
1676    if router.get_current_path().get_untracked() != cur_route {
1677        router.replace(&cur_route);
1678    }
1679    let breadcrumb_sig: Signal<String> = Signal::new(state.breadcrumb_for_route(&cur_route));
1680    let page_pad_sig: Signal<Edges> = Signal::new(Edges::all(SPACE_LG));
1681    let swipe_routes: Vec<String> = state.ordered_routes();
1682    let state_sync: DocsViewerState = state.clone();
1683    let router_sync_in: EuvRouter = router.clone();
1684    let router_path_sig: Signal<String> = router.get_current_path();
1685    let (sync_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1686        let _: Effect = Effect::new(move || {
1687            let target: String = active_route.get();
1688            let _: bool = breadcrumb_sig.set_if_changed(state_sync.breadcrumb_for_route(&target));
1689            if router_sync_in.get_current_path().get_untracked() != target {
1690                router_sync_in.push(&target);
1691            }
1692        });
1693        Effect::new(move || {
1694            let rp: String = router_path_sig.get();
1695            if active_route.get_untracked() != rp {
1696                let _: bool = active_route.set_if_changed(rp);
1697            }
1698        })
1699    });
1700    let state_fallback: DocsViewerState = state.clone();
1701    let outlet_node: NodeId = router
1702        .outlet(move |matched: &EuvRouteMatch| {
1703            let tok: ThemeTokens = untracked(|| state_fallback.get_theme().get_tokens().get());
1704            match state_fallback
1705                .get_site()
1706                .find_by_route(matched.get_path())
1707                .or_else(|| state_fallback.get_site().get_pages().first())
1708            {
1709                Some(p) => mount_doc_page_with_context(p, &state_fallback, tok),
1710                None => view! {
1711                    EuvEmpty {
1712                        title: EMPTY_PAGE_TITLE.to_string()
1713                        description: EMPTY_PAGE_MSG.to_string()
1714                        tokens: tok
1715                    }
1716                },
1717            }
1718        })
1719        .with_theme(state.get_theme().clone())
1720        .with_page_padding(page_pad_sig)
1721        .with_route_order(swipe_routes.clone())
1722        .mount();
1723    rctx.get_scene().with_write(
1724        |tree: &mut SceneTree| {
1725            tree.attach_scope(outlet_node, sync_scope);
1726        },
1727        (),
1728    );
1729    let total_visible: usize = swipe_routes.len();
1730    let sidebar_state: DocsViewerState = state.clone();
1731    let build_sidebar_nav = move || -> Vec<NodeId> {
1732        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
1733        let q: String = search_query.get();
1734        let (matched_count, groups): (usize, Vec<EuvDocSectionGroup>) =
1735            sidebar_state.filtered_section_groups(&q);
1736        let badge_lbl: String = format!("{matched_count} / {total_visible}");
1737        let mut nodes: Vec<NodeId> = Vec::with_capacity(2);
1738        if !q.trim().is_empty() {
1739            nodes.push(view! {
1740                row {
1741                    style: {
1742                        width: Length::Percent(100.0)
1743                        justify: JustifyContent::SpaceBetween
1744                        align: AlignItems::Center
1745                    }
1746                    EuvBadge {
1747                        label: badge_lbl
1748                        tone: if matched_count > 0 {
1749                            EuvTone::Primary
1750                        } else {
1751                            EuvTone::Warning
1752                        }
1753                        tokens: live_tok
1754                    }
1755                }
1756            });
1757        }
1758        if groups.is_empty() {
1759            nodes.push(view! {
1760                EuvEmpty {
1761                    title: EMPTY_SEARCH_TITLE.to_string()
1762                    description: EMPTY_SEARCH_DESC.to_string()
1763                    tokens: live_tok
1764                }
1765            });
1766        } else {
1767            nodes.push(view! {
1768                EuvDocSectionNav {
1769                    groups: groups
1770                    active_route: active_route
1771                    tokens: live_tok
1772                }
1773            });
1774        }
1775        nodes
1776    };
1777    let sidebar_node: NodeId = view! {
1778        column {
1779            style: {
1780                width: Length::Percent(100.0)
1781                gap: SPACE_SM
1782            }
1783            EuvInput {
1784                value: search_query
1785                placeholder: SEARCH_PLACEHOLDER.to_string()
1786                tokens: tokens
1787            }
1788            column {
1789                style: {
1790                    width: Length::Percent(100.0)
1791                    gap: SPACE_SM
1792                }
1793                bind_children: build_sidebar_nav
1794            }
1795        }
1796    };
1797    let theme_mode_sig: Signal<ThemeMode> = state.get_theme().get_mode();
1798    let icon_btn_style_desk = move || -> Style {
1799        let live_tok: ThemeTokens = use_live_tokens(tokens);
1800        let live_p: ThemePalette = live_tok.get_palette();
1801        let live_g: ThemeGeometry = live_tok.get_geometry();
1802        Style::default()
1803            .row()
1804            .width(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
1805            .height(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
1806            .justify(JustifyContent::Center)
1807            .align(AlignItems::Center)
1808            .background(live_p.get_background())
1809            .border(live_g.get_border_width(), live_p.get_border())
1810            .radius(live_g.get_radius_md())
1811            .cursor(CursorIcon::Pointer)
1812    };
1813    let icon_btn_style_mob = move || -> Style {
1814        let live_tok: ThemeTokens = use_live_tokens(tokens);
1815        let live_p: ThemePalette = live_tok.get_palette();
1816        let live_g: ThemeGeometry = live_tok.get_geometry();
1817        Style::default()
1818            .row()
1819            .width(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
1820            .height(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
1821            .justify(JustifyContent::Center)
1822            .align(AlignItems::Center)
1823            .background(live_p.get_background())
1824            .border(live_g.get_border_width(), live_p.get_border())
1825            .radius(live_g.get_radius_md())
1826            .cursor(CursorIcon::Pointer)
1827    };
1828    let paint_search_desk = move |bounds: Rect, dl: &mut DisplayList| {
1829        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1830        draw_euv_icon(EuvIconName::Search, bounds, dl, live_p.get_foreground());
1831    };
1832    let paint_search_mob = move |bounds: Rect, dl: &mut DisplayList| {
1833        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1834        draw_euv_icon(EuvIconName::Search, bounds, dl, live_p.get_foreground());
1835    };
1836    let paint_scheme_desk = move |bounds: Rect, dl: &mut DisplayList| {
1837        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1838        draw_docs_gear_icon(bounds, dl, live_p.get_primary());
1839    };
1840    let paint_scheme_mob = move |bounds: Rect, dl: &mut DisplayList| {
1841        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1842        draw_docs_gear_icon(bounds, dl, live_p.get_primary());
1843    };
1844    let paint_mode_desk = move |bounds: Rect, dl: &mut DisplayList| {
1845        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1846        match theme_mode_sig.get_untracked() {
1847            ThemeMode::Dark => draw_docs_sun_icon(bounds, dl, live_p.get_foreground()),
1848            ThemeMode::Light => draw_docs_moon_star_icon(bounds, dl, live_p.get_foreground()),
1849        }
1850    };
1851    let paint_mode_mob = move |bounds: Rect, dl: &mut DisplayList| {
1852        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1853        match theme_mode_sig.get_untracked() {
1854            ThemeMode::Dark => draw_docs_sun_icon(bounds, dl, live_p.get_foreground()),
1855            ThemeMode::Light => draw_docs_moon_star_icon(bounds, dl, live_p.get_foreground()),
1856        }
1857    };
1858    let st_scheme_desk: DocsViewerState = state.clone();
1859    let st_scheme_mob: DocsViewerState = state.clone();
1860    let st_mode_desk: DocsViewerState = state.clone();
1861    let st_mode_mob: DocsViewerState = state.clone();
1862    let on_open_cmd_desk = move |_: &UiEvent| {
1863        let _: bool = cmd_open.set_if_changed(true);
1864    };
1865    let on_open_cmd_mob = move |_: &UiEvent| {
1866        let _: bool = cmd_open.set_if_changed(true);
1867    };
1868    let on_next_scheme_desk = move |_: &UiEvent| {
1869        st_scheme_desk.next_scheme();
1870    };
1871    let on_next_scheme_mob = move |_: &UiEvent| {
1872        st_scheme_mob.next_scheme();
1873    };
1874    let on_toggle_mode_desk = move |_: &UiEvent| {
1875        st_mode_desk.toggle_theme_mode();
1876    };
1877    let on_toggle_mode_mob = move |_: &UiEvent| {
1878        st_mode_mob.toggle_theme_mode();
1879    };
1880    let locale_buttons: Vec<NodeId> = if state.get_site().get_locales().len() > 1 {
1881        let active_prefix: &str = state.get_site().get_locale_prefix().as_str();
1882        state
1883            .get_site()
1884            .get_locales()
1885            .iter()
1886            .map(|loc: &DocLocaleConfig| {
1887                let prefix_url: String =
1888                    resolve_locale_switch_href(active_prefix, loc.get_prefix().as_str());
1889                let is_cur: bool = loc.get_prefix().as_str() == active_prefix;
1890                let short_lbl: String = loc.get_dir().to_ascii_uppercase();
1891                let on_switch_loc = move |_: &UiEvent| {
1892                    #[cfg(target_arch = "wasm32")]
1893                    open_browser_url(&prefix_url, false);
1894                    #[cfg(not(target_arch = "wasm32"))]
1895                    {
1896                        let _: &str = prefix_url.as_str();
1897                    }
1898                };
1899                view! {
1900                    EuvButton {
1901                        label: short_lbl
1902                        variant: if is_cur {
1903                            EuvButtonVariant::Primary
1904                        } else {
1905                            EuvButtonVariant::Ghost
1906                        }
1907                        tokens: tokens
1908                        on_click: on_switch_loc
1909                    }
1910                }
1911            })
1912            .collect()
1913    } else {
1914        Vec::new()
1915    };
1916    let top_actions: NodeId = view! {
1917        row {
1918            style: {
1919                gap: SPACE_XS
1920                align: AlignItems::Center
1921            }
1922            ..locale_buttons
1923            row {
1924                bind_style: icon_btn_style_desk
1925                role: A11yRole::Button
1926                a11y_label: BTN_SEARCH_A11Y.to_string()
1927                on_click: on_open_cmd_desk
1928                canvas {
1929                    style: {
1930                        width: Length::Px(15.0)
1931                        height: Length::Px(15.0)
1932                    }
1933                    painter: paint_search_desk
1934                }
1935            }
1936            row {
1937                bind_style: icon_btn_style_desk
1938                role: A11yRole::Button
1939                a11y_label: BTN_SCHEME_A11Y.to_string()
1940                on_click: on_next_scheme_desk
1941                canvas {
1942                    style: {
1943                        width: Length::Px(15.0)
1944                        height: Length::Px(15.0)
1945                    }
1946                    painter: paint_scheme_desk
1947                }
1948            }
1949            row {
1950                bind_style: icon_btn_style_desk
1951                role: A11yRole::Button
1952                a11y_label: BTN_MODE_A11Y.to_string()
1953                on_click: on_toggle_mode_desk
1954                canvas {
1955                    style: {
1956                        width: Length::Px(15.0)
1957                        height: Length::Px(15.0)
1958                    }
1959                    painter: paint_mode_desk
1960                }
1961            }
1962        }
1963    };
1964    let mobile_actions: NodeId = view! {
1965        row {
1966            style: {
1967                gap: SPACE_XS
1968                align: AlignItems::Center
1969            }
1970            row {
1971                bind_style: icon_btn_style_mob
1972                role: A11yRole::Button
1973                a11y_label: BTN_SEARCH_A11Y.to_string()
1974                on_click: on_open_cmd_mob
1975                canvas {
1976                    style: {
1977                        width: Length::Px(14.0)
1978                        height: Length::Px(14.0)
1979                    }
1980                    painter: paint_search_mob
1981                }
1982            }
1983            row {
1984                bind_style: icon_btn_style_mob
1985                role: A11yRole::Button
1986                a11y_label: BTN_SCHEME_A11Y.to_string()
1987                on_click: on_next_scheme_mob
1988                canvas {
1989                    style: {
1990                        width: Length::Px(14.0)
1991                        height: Length::Px(14.0)
1992                    }
1993                    painter: paint_scheme_mob
1994                }
1995            }
1996            row {
1997                bind_style: icon_btn_style_mob
1998                role: A11yRole::Button
1999                a11y_label: BTN_MODE_A11Y.to_string()
2000                on_click: on_toggle_mode_mob
2001                canvas {
2002                    style: {
2003                        width: Length::Px(14.0)
2004                        height: Length::Px(14.0)
2005                    }
2006                    painter: paint_mode_mob
2007                }
2008            }
2009        }
2010    };
2011    let bottom_items: Vec<EuvNavItem> = state.bottom_nav_items();
2012    let home_route_path: String = state.home_route();
2013    let catalog_open: Signal<bool> = state.get_catalog_drawer_open();
2014    let bnav_route: Signal<String> =
2015        Signal::new(if active_route.get_untracked() == home_route_path {
2016            home_route_path.clone()
2017        } else {
2018            DOCS_BNAV_CATALOG_ROUTE.to_string()
2019        });
2020    let home_for_bnav: String = home_route_path.clone();
2021    let home_for_sync: String = home_route_path;
2022    let vp_for_drawer: Signal<Size> = rctx.get_viewport_size();
2023    let (bnav_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2024        let _: Effect = Effect::new(move || {
2025            let picked: String = bnav_route.get();
2026            if picked == DOCS_BNAV_CATALOG_ROUTE {
2027                let _: bool = catalog_open.set_if_changed(true);
2028            } else if picked == home_for_bnav {
2029                let _: bool = catalog_open.set_if_changed(false);
2030                if active_route.get_untracked() != home_for_bnav {
2031                    let _: bool = active_route.set_if_changed(home_for_bnav.clone());
2032                }
2033            }
2034        });
2035        let _: Effect = Effect::new(move || {
2036            let cur: String = active_route.get();
2037            let _: bool = catalog_open.set_if_changed(false);
2038            let next_tab: String = if cur == home_for_sync {
2039                home_for_sync.clone()
2040            } else {
2041                String::new()
2042            };
2043            if bnav_route.get_untracked() != next_tab {
2044                let _: bool = bnav_route.set_if_changed(next_tab);
2045            }
2046        });
2047        let _: Effect = Effect::new(move || {
2048            let open_now: bool = catalog_open.get();
2049            if !open_now && bnav_route.get_untracked() == DOCS_BNAV_CATALOG_ROUTE {
2050                let cur: String = active_route.get_untracked();
2051                let _: bool = bnav_route.set_if_changed(cur);
2052            }
2053        });
2054        Effect::new(move || {
2055            let vp: Size = vp_for_drawer.get();
2056            if vp.get_width() >= 960.0 {
2057                let _: bool = catalog_open.set_if_changed(false);
2058            }
2059        })
2060    });
2061    let bottom_nav_opt: Option<NodeId> = if bottom_items.len() >= 2 {
2062        Some(view! {
2063            EuvBottomNav {
2064                items: bottom_items
2065                active_route: bnav_route
2066                tokens: tokens
2067            }
2068        })
2069    } else {
2070        None
2071    };
2072    let mut shell: EuvAppShell = EuvAppShell::new(
2073        state.get_site().get_title().clone(),
2074        sidebar_node,
2075        outlet_node,
2076        tokens,
2077    )
2078    .route(active_route)
2079    .drawer_open(catalog_open)
2080    .top_bar_actions(top_actions)
2081    .mobile_header_actions(mobile_actions)
2082    .breadcrumb(breadcrumb_sig)
2083    .swipe_routes(swipe_routes)
2084    .theme(state.get_theme().clone())
2085    .page_padding(page_pad_sig);
2086    if let Some(bnav) = bottom_nav_opt {
2087        shell = shell.bottom_nav(bnav);
2088    }
2089    let shell_node: NodeId = shell.mount();
2090    rctx.get_scene().with_write(
2091        |tree: &mut SceneTree| {
2092            tree.attach_scope(shell_node, bnav_scope);
2093        },
2094        (),
2095    );
2096    view! {
2097        column {
2098            style: {
2099                width: Length::Percent(100.0)
2100                height: Length::Percent(100.0)
2101            }
2102            { shell_node }
2103            { cmd_modal }
2104        }
2105    }
2106}
2107
2108/// Mounts the cross-platform reactive showcase-parity documentation viewer for `site` using `euv-ui`.
2109///
2110/// # Arguments
2111///
2112/// - `&DocSite` - Parsed documentation site.
2113/// - `Signal<String>` - Active route path signal.
2114/// - `Signal<String>` - Search query input signal.
2115/// - `ThemeTokens` - Active design tokens.
2116///
2117/// # Returns
2118///
2119/// - `NodeId` - Mounted reactive documentation shell node.
2120pub fn mount_docs_viewer(
2121    site: &DocSite,
2122    active_route: Signal<String>,
2123    search_query: Signal<String>,
2124    tokens: ThemeTokens,
2125) -> NodeId {
2126    let state: DocsViewerState =
2127        DocsViewerState::new(site.clone(), active_route, search_query, tokens);
2128    mount_docs_viewer_with_state(&state)
2129}
2130
2131/// Launches the documentation viewer app and steps one headless or native frame.
2132///
2133/// # Arguments
2134///
2135/// - `&DocSite` - Loaded documentation site.
2136/// - `bool` - When `true`, renders headlessly via `HeadlessPlatform`.
2137///
2138/// # Returns
2139///
2140/// - `Result<FrameStats, PlatformError>` - Frame render telemetry.
2141pub fn render_docs_smoke(site: &DocSite, headless: bool) -> Result<FrameStats, PlatformError> {
2142    render_docs_app(site, headless, false)
2143}
2144
2145/// Launches the documentation viewer app in either single-frame or interactive event-loop mode.
2146///
2147/// # Arguments
2148///
2149/// - `&DocSite` - Loaded documentation site.
2150/// - `bool` - When `true`, renders headlessly via `HeadlessPlatform`.
2151/// - `bool` - When `true` and not headless, runs the interactive frame loop until window close.
2152///
2153/// # Returns
2154///
2155/// - `Result<FrameStats, PlatformError>` - Final rendered frame telemetry.
2156pub fn render_docs_app(
2157    site: &DocSite,
2158    headless: bool,
2159    interactive: bool,
2160) -> Result<FrameStats, PlatformError> {
2161    EuvOverlayStack::clear();
2162    reset_fullscreen_state();
2163    clear_provided_theme();
2164    let mut window_cfg: WindowConfig = WindowConfig::default();
2165    window_cfg
2166        .set_title(DOCS_WINDOW_TITLE.to_string())
2167        .set_size(DOCS_WINDOW_WIDTH, DOCS_WINDOW_HEIGHT)
2168        .set_render(RenderConfig::software())
2169        .set_icon(Some(euv_brand_logo_image()));
2170    let mut app_cfg: AppConfig = AppConfig::default();
2171    app_cfg.set_window(window_cfg);
2172    let mut app: App = if headless {
2173        App::headless(app_cfg)?
2174    } else {
2175        App::new(app_cfg)?
2176    };
2177    let initial_route: String = site
2178        .get_pages()
2179        .first()
2180        .map(|p: &DocPage| p.get_route().clone())
2181        .unwrap_or_else(|| "/".to_string());
2182    let active_route: Signal<String> = Signal::new(initial_route);
2183    let search_query: Signal<String> = Signal::new(String::new());
2184    let tokens: ThemeTokens = ThemeTokens::resolve(active_feature_scheme(), ThemeMode::Light);
2185    let state: DocsViewerState =
2186        DocsViewerState::new(site.clone(), active_route, search_query, tokens);
2187    let mount_state: DocsViewerState = state.clone();
2188    let _: NodeId = app.mount(move || mount_docs_viewer_with_state(&mount_state));
2189    let limit: Option<u64> = if interactive && !headless {
2190        None
2191    } else {
2192        Some(1)
2193    };
2194    app.run_frames(limit)
2195}
2196
2197/// Resolves a candidate path or locale-prefixed path against `site` pages, normalizing duplicate slashes and `.html` suffixes.
2198///
2199/// # Arguments
2200///
2201/// - `&DocSite` - Loaded documentation site.
2202/// - `&str` - Raw path fragment or URL pathname candidate.
2203///
2204/// # Returns
2205///
2206/// - `Option<String>` - Matching canonical page route when found.
2207fn resolve_docs_candidate_path(site: &DocSite, raw_path: &str) -> Option<String> {
2208    let without_query: &str = raw_path.split(['?', '#']).next().unwrap_or("").trim();
2209    let mut segments: Vec<&str> = without_query
2210        .split('/')
2211        .filter(|seg: &&str| !seg.is_empty())
2212        .collect();
2213    if segments
2214        .last()
2215        .is_some_and(|last: &&str| last.eq_ignore_ascii_case(DOCS_SUFFIX_INDEX_HTML))
2216    {
2217        let _: Option<&str> = segments.pop();
2218    }
2219    let normalized_segments: Vec<String> = segments
2220        .into_iter()
2221        .map(|seg: &str| {
2222            seg.strip_suffix(DOCS_SUFFIX_HTML)
2223                .unwrap_or(seg)
2224                .to_string()
2225        })
2226        .filter(|seg: &String| !seg.is_empty())
2227        .collect();
2228    let candidate: String = if normalized_segments.is_empty() {
2229        "/".to_string()
2230    } else {
2231        format!("/{}", normalized_segments.join("/"))
2232    };
2233    if let Some(found) = site.find_by_route(&candidate) {
2234        return Some(found.get_route().clone());
2235    }
2236    if let Some(first_seg) = normalized_segments.first() {
2237        let active_locale: &str = site.get_locale_prefix().trim_matches('/');
2238        let matches_builtin: bool = DOCS_KNOWN_LOCALE_SEGMENTS
2239            .iter()
2240            .any(|loc: &&str| loc.eq_ignore_ascii_case(first_seg));
2241        let matches_active: bool =
2242            !active_locale.is_empty() && active_locale.eq_ignore_ascii_case(first_seg);
2243        let matches_configured: bool = site.get_locales().iter().any(|loc: &DocLocaleConfig| {
2244            let dir_match: bool = loc.get_dir().eq_ignore_ascii_case(first_seg);
2245            let pref_match: bool = loc
2246                .get_prefix()
2247                .trim_matches('/')
2248                .eq_ignore_ascii_case(first_seg);
2249            dir_match || pref_match
2250        });
2251        let is_known_locale: bool = [matches_builtin, matches_active, matches_configured]
2252            .into_iter()
2253            .any(|matched: bool| matched);
2254        if is_known_locale {
2255            let rest: &[String] = &normalized_segments[1..];
2256            let stripped: String = if rest.is_empty() {
2257                "/".to_string()
2258            } else {
2259                format!("/{}", rest.join("/"))
2260            };
2261            if let Some(found) = site.find_by_route(&stripped) {
2262                return Some(found.get_route().clone());
2263            }
2264        }
2265    }
2266    None
2267}
2268
2269/// Normalizes browser `location.hash` and `location.pathname` into a valid `DocSite` route and optional heading anchor slug.
2270///
2271/// # Arguments
2272///
2273/// - `&DocSite` - Loaded documentation site.
2274/// - `&str` - Raw `window.location.hash` value.
2275/// - `&str` - Raw `window.location.pathname` value.
2276///
2277/// # Returns
2278///
2279/// - `(String, Option<String>)` - Resolved canonical route path and optional heading anchor slug.
2280#[must_use]
2281pub fn normalize_docs_history_target(
2282    site: &DocSite,
2283    raw_hash: &str,
2284    raw_pathname: &str,
2285) -> (String, Option<String>) {
2286    let default_route: String = site
2287        .find_by_route("/")
2288        .or_else(|| site.get_pages().first())
2289        .map(|p: &DocPage| p.get_route().clone())
2290        .unwrap_or_else(|| "/".to_string());
2291    let path_fallback: String =
2292        resolve_docs_candidate_path(site, raw_pathname).unwrap_or_else(|| default_route.clone());
2293    let trimmed_hash: &str = raw_hash.trim().trim_start_matches('#').trim();
2294    if trimmed_hash.is_empty() {
2295        return (path_fallback, None);
2296    }
2297    if trimmed_hash.starts_with('/') {
2298        let (route_part, anchor_raw): (&str, Option<&str>) = match trimmed_hash.split_once('#') {
2299            Some((r, a)) => (r, Some(a)),
2300            None => (trimmed_hash, None),
2301        };
2302        let anchor: Option<String> = anchor_raw
2303            .map(str::trim)
2304            .filter(|a: &&str| !a.is_empty())
2305            .map(str::to_string);
2306        if route_part.trim_matches('/').is_empty() {
2307            return (path_fallback, anchor);
2308        }
2309        if let Some(found) = resolve_docs_candidate_path(site, route_part) {
2310            return (found, anchor);
2311        }
2312        return (default_route, None);
2313    }
2314    let (head_part, anchor_raw): (&str, Option<&str>) = match trimmed_hash.split_once('#') {
2315        Some((h, a)) => (h, Some(a)),
2316        None => (trimmed_hash, None),
2317    };
2318    let tail_anchor: Option<String> = anchor_raw
2319        .map(str::trim)
2320        .filter(|a: &&str| !a.is_empty())
2321        .map(str::to_string);
2322    if head_part.contains('/') {
2323        if let Some(found) = resolve_docs_candidate_path(site, head_part) {
2324            return (found, tail_anchor);
2325        }
2326        return (default_route, None);
2327    }
2328    (path_fallback, Some(head_part.to_string()))
2329}
2330
2331/// Applies an incoming browser history location (`popstate` / `hashchange`) to `app` and `state`, dismissing overlays and exiting fullscreen first.
2332///
2333/// # Arguments
2334///
2335/// - `&mut App` - Running documentation viewer application instance.
2336/// - `&DocsViewerState` - Shared reactive documentation viewer state.
2337/// - `&str` - Raw `window.location.hash` value.
2338/// - `&str` - Raw `window.location.pathname` value.
2339///
2340/// # Returns
2341///
2342/// - `String` - Normalized canonical documentation route applied to `state`.
2343pub fn apply_docs_history_navigation(
2344    app: &mut App,
2345    state: &DocsViewerState,
2346    raw_hash: &str,
2347    raw_pathname: &str,
2348) -> String {
2349    let (target_route, anchor): (String, Option<String>) =
2350        normalize_docs_history_target(state.get_site(), raw_hash, raw_pathname);
2351    let _: usize = EuvOverlayStack::dismiss_all();
2352    let _: bool = state.get_cmd_open().set_if_changed(false);
2353    if app.is_immersive_fullscreen() || is_fullscreen_active() || EuvOverlayStack::has_fullscreen()
2354    {
2355        let _: usize = sync_external_fullscreen_exit();
2356        app.set_immersive_fullscreen(false);
2357    }
2358    let _: bool = state
2359        .get_active_route()
2360        .set_if_changed(target_route.clone());
2361    let _: bool = state
2362        .get_active_toc_slug()
2363        .set_if_changed(anchor.unwrap_or_default());
2364    target_route
2365}
2366
2367/// Synchronizes the running WebAssembly documentation viewer from browser `popstate` or `hashchange` and immediately repaints.
2368///
2369/// # Arguments
2370///
2371/// - `&Window` - Active browser `Window`.
2372#[cfg(target_arch = "wasm32")]
2373fn web_docs_sync_from_browser_history(win: &Window) {
2374    let raw_hash: String = win.location().hash().unwrap_or_default();
2375    let raw_pathname: String = win.location().pathname().unwrap_or_default();
2376    let prev_guard: bool =
2377        WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
2378    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2379        if let Ok(mut borrow) = slot.try_borrow_mut()
2380            && let Some((app, state)) = borrow.as_mut()
2381        {
2382            let _: String = apply_docs_history_navigation(app, state, &raw_hash, &raw_pathname);
2383            let _: Result<FrameStats, PlatformError> = app.step_frame();
2384        }
2385    });
2386    WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
2387}
2388
2389/// Extracts plain UTF-8 clipboard text from a browser `paste` DOM event.
2390///
2391/// # Arguments
2392///
2393/// - `&web_sys::Event` - Browser DOM `paste` event.
2394///
2395/// # Returns
2396///
2397/// - `Option<String>` - Non-empty pasted text when available.
2398#[cfg(target_arch = "wasm32")]
2399fn web_docs_extract_paste_text(ev: &web_sys::Event) -> Option<String> {
2400    let data: JsValue =
2401        Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA)).ok()?;
2402    if data.is_null() || data.is_undefined() {
2403        return None;
2404    }
2405    let get_fn_val: JsValue = Reflect::get(&data, &JsValue::from_str(WEB_PROP_GET_DATA)).ok()?;
2406    let get_fn: Function = get_fn_val.dyn_into::<Function>().ok()?;
2407    let result: JsValue = get_fn
2408        .call1(&data, &JsValue::from_str(WEB_MIME_TEXT_PLAIN))
2409        .ok()?;
2410    result.as_string().filter(|s: &String| !s.is_empty())
2411}
2412
2413/// Returns `true` when the browser document currently has a standard or WebKit fullscreen element active.
2414///
2415/// # Arguments
2416///
2417/// - `&Document` - Active browser `Document`.
2418///
2419/// # Returns
2420///
2421/// - `bool` - `true` while browser fullscreen mode is active.
2422#[cfg(target_arch = "wasm32")]
2423fn web_docs_doc_is_fullscreen(doc: &Document) -> bool {
2424    if doc.fullscreen_element().is_some() {
2425        return true;
2426    }
2427    Reflect::get(
2428        doc.as_ref(),
2429        &JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
2430    )
2431    .ok()
2432    .map(|v: JsValue| !v.is_null() && !v.is_undefined())
2433    .unwrap_or(false)
2434}
2435
2436/// Attaches browser `popstate`, `hashchange`, `pageshow`, `blur`, `touchcancel`, `paste`, `fullscreenchange`, and color-scheme listeners once for the docs viewer.
2437///
2438/// # Arguments
2439///
2440/// - `&Window` - Active browser `Window`.
2441#[cfg(target_arch = "wasm32")]
2442fn web_docs_attach_browser_listeners(win: &Window) {
2443    let already_attached: bool =
2444        WEB_DOCS_LISTENERS_ATTACHED.with(|flag: &Cell<bool>| flag.replace(true));
2445    if already_attached {
2446        return;
2447    }
2448    let win_hist: Window = win.clone();
2449    let on_history: Closure<dyn FnMut(web_sys::Event)> =
2450        Closure::wrap(Box::new(move |_: web_sys::Event| {
2451            web_docs_sync_from_browser_history(&win_hist);
2452        }) as Box<dyn FnMut(web_sys::Event)>);
2453    drop(win.add_event_listener_with_callback(
2454        WEB_EVENT_POP_STATE,
2455        on_history.as_ref().unchecked_ref(),
2456    ));
2457    drop(win.add_event_listener_with_callback(
2458        WEB_EVENT_HASH_CHANGE,
2459        on_history.as_ref().unchecked_ref(),
2460    ));
2461    drop(win.add_event_listener_with_callback(
2462        WEB_EVENT_PAGE_SHOW,
2463        on_history.as_ref().unchecked_ref(),
2464    ));
2465    on_history.forget();
2466    let on_cancel: Closure<dyn FnMut(web_sys::Event)> =
2467        Closure::wrap(Box::new(move |_: web_sys::Event| {
2468            WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2469                if let Ok(mut borrow) = slot.try_borrow_mut()
2470                    && let Some((app, _)) = borrow.as_mut()
2471                {
2472                    let wid: WindowId = app.get_window_state().get_id();
2473                    app.dispatch_window_event(WindowEvent::PointerCancel(wid, 0));
2474                    let _: Result<FrameStats, PlatformError> = app.step_frame();
2475                }
2476            });
2477        }) as Box<dyn FnMut(web_sys::Event)>);
2478    drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_cancel.as_ref().unchecked_ref()));
2479    drop(win.add_event_listener_with_callback(
2480        WEB_EVENT_TOUCH_CANCEL,
2481        on_cancel.as_ref().unchecked_ref(),
2482    ));
2483    on_cancel.forget();
2484    let on_paste: Closure<dyn FnMut(web_sys::Event)> =
2485        Closure::wrap(Box::new(move |ev: web_sys::Event| {
2486            if let Some(pasted) = web_docs_extract_paste_text(&ev) {
2487                ev.prevent_default();
2488                WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2489                    if let Ok(mut borrow) = slot.try_borrow_mut()
2490                        && let Some((app, _)) = borrow.as_mut()
2491                    {
2492                        let wid: WindowId = app.get_window_state().get_id();
2493                        app.dispatch_window_event(WindowEvent::TextInput(wid, pasted));
2494                        let _: Result<FrameStats, PlatformError> = app.step_frame();
2495                    }
2496                });
2497            }
2498        }) as Box<dyn FnMut(web_sys::Event)>);
2499    drop(win.add_event_listener_with_callback(WEB_EVENT_PASTE, on_paste.as_ref().unchecked_ref()));
2500    on_paste.forget();
2501    if let Some(doc) = win.document() {
2502        let doc_fs: Document = doc.clone();
2503        let on_fs: Closure<dyn FnMut(web_sys::Event)> =
2504            Closure::wrap(Box::new(move |_: web_sys::Event| {
2505                if !web_docs_doc_is_fullscreen(&doc_fs) {
2506                    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2507                        if let Ok(mut borrow) = slot.try_borrow_mut()
2508                            && let Some((app, _)) = borrow.as_mut()
2509                            && (app.is_immersive_fullscreen()
2510                                || is_fullscreen_active()
2511                                || EuvOverlayStack::has_fullscreen())
2512                        {
2513                            let _: usize = sync_external_fullscreen_exit();
2514                            app.set_immersive_fullscreen(false);
2515                            let wid: WindowId = app.get_window_state().get_id();
2516                            let measured: SafeAreaInsets = web_query_safe_area_insets();
2517                            app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, measured));
2518                            let _: Result<FrameStats, PlatformError> = app.step_frame();
2519                        }
2520                    });
2521                }
2522            }) as Box<dyn FnMut(web_sys::Event)>);
2523        drop(doc.add_event_listener_with_callback(
2524            WEB_EVENT_FULLSCREEN_CHANGE,
2525            on_fs.as_ref().unchecked_ref(),
2526        ));
2527        drop(doc.add_event_listener_with_callback(
2528            WEB_EVENT_WEBKIT_FULLSCREEN_CHANGE,
2529            on_fs.as_ref().unchecked_ref(),
2530        ));
2531        on_fs.forget();
2532    }
2533    if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
2534        let mql_cb: MediaQueryList = mql.clone();
2535        let on_theme: Closure<dyn FnMut(web_sys::Event)> =
2536            Closure::wrap(Box::new(move |_: web_sys::Event| {
2537                let next_theme: ThemeMode = if mql_cb.matches() {
2538                    ThemeMode::Dark
2539                } else {
2540                    ThemeMode::Light
2541                };
2542                WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2543                    if let Ok(mut borrow) = slot.try_borrow_mut()
2544                        && let Some((app, _)) = borrow.as_mut()
2545                    {
2546                        let wid: WindowId = app.get_window_state().get_id();
2547                        app.dispatch_window_event(WindowEvent::ThemeChanged(wid, next_theme));
2548                        let _: Result<FrameStats, PlatformError> = app.step_frame();
2549                    }
2550                });
2551            }) as Box<dyn FnMut(web_sys::Event)>);
2552        drop(
2553            mql.add_event_listener_with_callback(
2554                WEB_EVENT_CHANGE,
2555                on_theme.as_ref().unchecked_ref(),
2556            ),
2557        );
2558        on_theme.forget();
2559    }
2560}
2561
2562/// Boots the persistent WebAssembly showcase-parity documentation viewer from a serialized `DocSite` JSON bundle.
2563///
2564/// # Arguments
2565///
2566/// - `&str` - Compact UTF-8 JSON payload produced for the active locale bundle.
2567///
2568/// # Returns
2569///
2570/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
2571#[cfg(target_arch = "wasm32")]
2572pub fn boot_wasm_docs_bundle(bundle_json: &str) -> u64 {
2573    let site: DocSite = serde_json::from_str::<DocSite>(bundle_json).unwrap_or_else(|_| {
2574        DocSite::new(
2575            DOCS_SITE_TITLE.to_string(),
2576            DOCS_SITE_TAGLINE.to_string(),
2577            Vec::new(),
2578        )
2579    });
2580    boot_wasm_docs_site(site)
2581}
2582
2583/// Boots the persistent WebAssembly showcase-parity documentation viewer from a split plaintext shell and `EUVZ`-compressed bodies.
2584///
2585/// # Arguments
2586///
2587/// - `&str` - Compact plaintext `DocSite` shell JSON carrying metadata and TOC headings.
2588/// - `&[u8]` - `EUVZ`-compressed page body payload bytes.
2589///
2590/// # Returns
2591///
2592/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
2593#[cfg(target_arch = "wasm32")]
2594pub fn boot_wasm_docs_compressed_bundle(shell_json: &str, compressed_bodies: &[u8]) -> u64 {
2595    let site: DocSite = unpack_site_bundle(shell_json, compressed_bodies).unwrap_or_else(|_| {
2596        DocSite::new(
2597            DOCS_SITE_TITLE.to_string(),
2598            DOCS_SITE_TAGLINE.to_string(),
2599            Vec::new(),
2600        )
2601    });
2602    boot_wasm_docs_site(site)
2603}
2604
2605/// Mounts the hydrated `DocSite` into the persistent WebAssembly viewer runtime and renders the initial frame.
2606///
2607/// # Arguments
2608///
2609/// - `DocSite` - Hydrated documentation site for the active locale.
2610///
2611/// # Returns
2612///
2613/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
2614#[cfg(target_arch = "wasm32")]
2615fn boot_wasm_docs_site(site: DocSite) -> u64 {
2616    console_error_panic_hook::set_once();
2617    reset_reactive_runtime();
2618    EuvOverlayStack::clear();
2619    reset_fullscreen_state();
2620    clear_provided_theme();
2621    let mut window_cfg: WindowConfig = WindowConfig::default();
2622    window_cfg
2623        .set_title(format!("{} ยท {EUV_DOCS_RELEASE_MARKER}", site.get_title()))
2624        .set_size(DOCS_WINDOW_WIDTH, DOCS_WINDOW_HEIGHT)
2625        .set_render(RenderConfig::software());
2626    let mut app_cfg: AppConfig = AppConfig::default();
2627    app_cfg.set_window(window_cfg);
2628    let mut app: App = match App::new(app_cfg) {
2629        Ok(a) => a,
2630        Err(_) => return 0,
2631    };
2632    let (initial_route, initial_anchor): (String, Option<String>) = if let Some(win) = window() {
2633        let raw_hash: String = win.location().hash().unwrap_or_default();
2634        let raw_pathname: String = win.location().pathname().unwrap_or_default();
2635        normalize_docs_history_target(&site, &raw_hash, &raw_pathname)
2636    } else {
2637        let fallback: String = site
2638            .get_pages()
2639            .first()
2640            .map(|p: &DocPage| p.get_route().clone())
2641            .unwrap_or_else(|| "/".to_string());
2642        (fallback, None)
2643    };
2644    let active_route: Signal<String> = Signal::new(initial_route);
2645    let search_query: Signal<String> = Signal::new(String::new());
2646    let tokens: ThemeTokens = ThemeTokens::resolve(active_feature_scheme(), ThemeMode::Light);
2647    let state: DocsViewerState = DocsViewerState::new(site, active_route, search_query, tokens);
2648    if let Some(anchor) = initial_anchor {
2649        let _: bool = state.get_active_toc_slug().set_if_changed(anchor);
2650    }
2651    let has_home: bool = state
2652        .get_site()
2653        .get_pages()
2654        .iter()
2655        .any(|p: &DocPage| p.get_is_home());
2656    let mount_state: DocsViewerState = state.clone();
2657    let _: NodeId = app.mount(move || mount_docs_viewer_with_state(&mount_state));
2658    let route_watch: Signal<String> = state.get_active_route();
2659    let site_watch: Rc<DocSite> = state.get_site().clone();
2660    let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2661        Effect::new(move || {
2662            let r: String = route_watch.get();
2663            if WEB_DOCS_SYNCING_FROM_HISTORY.with(Cell::get) {
2664                return;
2665            }
2666            if let Some(win) = window() {
2667                let raw_hash: String = win.location().hash().unwrap_or_default();
2668                let raw_pathname: String = win.location().pathname().unwrap_or_default();
2669                let (cur_route, _): (String, Option<String>) =
2670                    normalize_docs_history_target(&site_watch, &raw_hash, &raw_pathname);
2671                if cur_route != r {
2672                    let target_hash: String = format!("#{r}");
2673                    let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
2674                }
2675            }
2676        })
2677    });
2678    let root_id: NodeId = app
2679        .get_scene()
2680        .with_read(SceneTree::get_root, NodeId::default());
2681    app.get_scene().with_write(
2682        |tree: &mut SceneTree| {
2683            tree.attach_scope(root_id, hash_scope);
2684        },
2685        (),
2686    );
2687    let hash: u64 = app
2688        .step_frame()
2689        .map(|stats: FrameStats| stats.get_frame_hash())
2690        .unwrap_or(0);
2691    let fetch_state: DocsViewerState = state.clone();
2692    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2693        if let Ok(mut borrow) = slot.try_borrow_mut() {
2694            *borrow = Some((app, state));
2695        }
2696    });
2697    if let Some(win) = window() {
2698        web_docs_attach_browser_listeners(&win);
2699    }
2700    if has_home {
2701        trigger_wasm_catalog_fetch(&fetch_state);
2702    }
2703    hash
2704}
2705
2706/// Switches the active route in the running WebAssembly documentation viewer and renders immediately.
2707///
2708/// # Arguments
2709///
2710/// - `&str` - Canonical route path.
2711///
2712/// # Returns
2713///
2714/// - `u64` - Rendered frame hash.
2715#[cfg(target_arch = "wasm32")]
2716pub fn wasm_docs_render_route(route: &str) -> u64 {
2717    let prev_guard: bool =
2718        WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
2719    let raw_pathname: String = window()
2720        .and_then(|win: Window| win.location().pathname().ok())
2721        .unwrap_or_default();
2722    let frame_hash: u64 =
2723        WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2724            let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut()
2725            {
2726                Ok(guard) => guard,
2727                Err(_) => return 0,
2728            };
2729            let Some((app, state)) = borrow.as_mut() else {
2730                return 0;
2731            };
2732            let _: String = apply_docs_history_navigation(app, state, route, &raw_pathname);
2733            app.step_frame()
2734                .map(|stats: FrameStats| stats.get_frame_hash())
2735                .unwrap_or(0)
2736        });
2737    WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
2738    frame_hash
2739}
2740
2741/// Dispatches a browser pointer move event into the running WebAssembly documentation viewer.
2742///
2743/// # Arguments
2744///
2745/// - `f32` - Logical X coordinate inside the canvas.
2746/// - `f32` - Logical Y coordinate inside the canvas.
2747///
2748/// # Returns
2749///
2750/// - `u64` - Rendered frame hash.
2751#[cfg(target_arch = "wasm32")]
2752pub fn wasm_docs_pointer_move(x: f32, y: f32) -> u64 {
2753    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2754        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
2755            Ok(guard) => guard,
2756            Err(_) => return 0,
2757        };
2758        let Some((app, _)) = borrow.as_mut() else {
2759            return 0;
2760        };
2761        let wid: WindowId = app.get_window_state().get_id();
2762        app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
2763        app.step_frame()
2764            .map(|stats: FrameStats| stats.get_frame_hash())
2765            .unwrap_or(0)
2766    })
2767}
2768
2769/// Dispatches a browser pointer press event into the running WebAssembly documentation viewer.
2770///
2771/// # Arguments
2772///
2773/// - `f32` - Logical X coordinate inside the canvas.
2774/// - `f32` - Logical Y coordinate inside the canvas.
2775///
2776/// # Returns
2777///
2778/// - `u64` - Rendered frame hash.
2779#[cfg(target_arch = "wasm32")]
2780pub fn wasm_docs_pointer_down(x: f32, y: f32) -> u64 {
2781    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2782        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
2783            Ok(guard) => guard,
2784            Err(_) => return 0,
2785        };
2786        let Some((app, _)) = borrow.as_mut() else {
2787            return 0;
2788        };
2789        let wid: WindowId = app.get_window_state().get_id();
2790        app.dispatch_window_event(WindowEvent::PointerDown(wid, PointerEvent::mouse(x, y)));
2791        app.step_frame()
2792            .map(|stats: FrameStats| stats.get_frame_hash())
2793            .unwrap_or(0)
2794    })
2795}
2796
2797/// Dispatches a browser pointer release event into the running WebAssembly documentation viewer.
2798///
2799/// # Arguments
2800///
2801/// - `f32` - Logical X coordinate inside the canvas.
2802/// - `f32` - Logical Y coordinate inside the canvas.
2803///
2804/// # Returns
2805///
2806/// - `u64` - Rendered frame hash.
2807#[cfg(target_arch = "wasm32")]
2808pub fn wasm_docs_pointer_up(x: f32, y: f32) -> u64 {
2809    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2810        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
2811            Ok(guard) => guard,
2812            Err(_) => return 0,
2813        };
2814        let Some((app, _)) = borrow.as_mut() else {
2815            return 0;
2816        };
2817        let wid: WindowId = app.get_window_state().get_id();
2818        app.dispatch_window_event(WindowEvent::PointerUp(wid, PointerEvent::mouse(x, y)));
2819        app.step_frame()
2820            .map(|stats: FrameStats| stats.get_frame_hash())
2821            .unwrap_or(0)
2822    })
2823}
2824
2825/// Dispatches a browser pointer event (`0=move`, `1=down`, `2=up`, `3=cancel`) with full touch/mouse device metadata into the running WebAssembly documentation viewer.
2826///
2827/// # Arguments
2828///
2829/// - `u8` - Event kind (`0` move, `1` down, `2` up, `3` cancel).
2830/// - `u32` - Browser DOM `PointerEvent.pointerId`.
2831/// - `bool` - Whether the source pointer is a touch contact (`PointerDevice::Touch`).
2832/// - `f32` - Logical X coordinate inside the canvas.
2833/// - `f32` - Logical Y coordinate inside the canvas.
2834/// - `f32` - Normalized contact pressure (`0.0..=1.0`).
2835///
2836/// # Returns
2837///
2838/// - `u64` - Rendered frame hash.
2839#[cfg(target_arch = "wasm32")]
2840pub fn wasm_docs_pointer_event(
2841    kind: u8,
2842    pointer_id: u32,
2843    is_touch: bool,
2844    x: f32,
2845    y: f32,
2846    pressure: f32,
2847) -> u64 {
2848    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2849        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
2850            Ok(guard) => guard,
2851            Err(_) => return 0,
2852        };
2853        let Some((app, _)) = borrow.as_mut() else {
2854            return 0;
2855        };
2856        let wid: WindowId = app.get_window_state().get_id();
2857        let pid: u64 = u64::from(pointer_id);
2858        let device: PointerDevice = if is_touch {
2859            PointerDevice::Touch
2860        } else {
2861            PointerDevice::Mouse
2862        };
2863        let ptr: PointerEvent = PointerEvent::new(
2864            pid,
2865            device,
2866            Point::new(x, y),
2867            PointerButton::Primary,
2868            pressure.clamp(0.0, 1.0),
2869            Modifiers::default(),
2870        );
2871        match kind {
2872            1 => app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr)),
2873            2 => app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr)),
2874            3 => app.dispatch_window_event(WindowEvent::PointerCancel(wid, pid)),
2875            _ => app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr)),
2876        }
2877        app.step_frame()
2878            .map(|stats: FrameStats| stats.get_frame_hash())
2879            .unwrap_or(0)
2880    })
2881}
2882
2883/// Dispatches a browser wheel scroll delta into the running WebAssembly documentation viewer.
2884///
2885/// # Arguments
2886///
2887/// - `f32` - Horizontal scroll delta.
2888/// - `f32` - Vertical scroll delta.
2889///
2890/// # Returns
2891///
2892/// - `u64` - Rendered frame hash.
2893#[cfg(target_arch = "wasm32")]
2894pub fn wasm_docs_scroll(dx: f32, dy: f32) -> u64 {
2895    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2896        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
2897            Ok(guard) => guard,
2898            Err(_) => return 0,
2899        };
2900        let Some((app, _)) = borrow.as_mut() else {
2901            return 0;
2902        };
2903        let wid: WindowId = app.get_window_state().get_id();
2904        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
2905        app.step_frame()
2906            .map(|stats: FrameStats| stats.get_frame_hash())
2907            .unwrap_or(0)
2908    })
2909}
2910
2911/// Dispatches a browser wheel scroll delta anchored at logical pointer `(x, y)` so scrolling over any container works immediately.
2912///
2913/// # Arguments
2914///
2915/// - `f32` - Logical pointer X coordinate inside the canvas.
2916/// - `f32` - Logical pointer Y coordinate inside the canvas.
2917/// - `f32` - Horizontal scroll delta in CSS pixels.
2918/// - `f32` - Vertical scroll delta in CSS pixels.
2919///
2920/// # Returns
2921///
2922/// - `u64` - Rendered frame hash.
2923#[cfg(target_arch = "wasm32")]
2924pub fn wasm_docs_scroll_at(x: f32, y: f32, dx: f32, dy: f32) -> u64 {
2925    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2926        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
2927            Ok(guard) => guard,
2928            Err(_) => return 0,
2929        };
2930        let Some((app, _)) = borrow.as_mut() else {
2931            return 0;
2932        };
2933        let wid: WindowId = app.get_window_state().get_id();
2934        app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
2935        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
2936        app.step_frame()
2937            .map(|stats: FrameStats| stats.get_frame_hash())
2938            .unwrap_or(0)
2939    })
2940}
2941
2942/// Re-queries real browser CSS `env(safe-area-inset-*)` values and dispatches `WindowEvent::SafeAreaChanged` only when insets actually change.
2943///
2944/// # Returns
2945///
2946/// - `u64` - Rendered frame hash.
2947#[cfg(target_arch = "wasm32")]
2948pub fn wasm_docs_sync_safe_area() -> u64 {
2949    let measured: SafeAreaInsets = web_query_safe_area_insets();
2950    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2951        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
2952            Ok(guard) => guard,
2953            Err(_) => return 0,
2954        };
2955        let Some((app, _)) = borrow.as_mut() else {
2956            return 0;
2957        };
2958        let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
2959            SafeAreaInsets::default()
2960        } else {
2961            measured
2962        };
2963        let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
2964        if current == effective {
2965            return app.get_renderer().get_last_stats().get_frame_hash();
2966        }
2967        let wid: WindowId = app.get_window_state().get_id();
2968        app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
2969        app.step_frame()
2970            .map(|stats: FrameStats| stats.get_frame_hash())
2971            .unwrap_or(0)
2972    })
2973}
2974
2975/// Dispatches a browser keyboard event into the running WebAssembly documentation viewer.
2976///
2977/// # Arguments
2978///
2979/// - `&str` - DOM `KeyboardEvent.key` string.
2980///
2981/// # Returns
2982///
2983/// - `u64` - Rendered frame hash.
2984#[cfg(target_arch = "wasm32")]
2985pub fn wasm_docs_key_down(key: &str) -> u64 {
2986    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
2987        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
2988            Ok(guard) => guard,
2989            Err(_) => return 0,
2990        };
2991        let Some((app, _)) = borrow.as_mut() else {
2992            return 0;
2993        };
2994        let wid: WindowId = app.get_window_state().get_id();
2995        let code: KeyCode = match key {
2996            WEB_KEY_ENTER => KeyCode::Enter,
2997            WEB_KEY_BACKSPACE => KeyCode::Backspace,
2998            WEB_KEY_DELETE => KeyCode::Delete,
2999            WEB_KEY_ESCAPE => KeyCode::Escape,
3000            WEB_KEY_TAB => KeyCode::Tab,
3001            WEB_KEY_SPACE => KeyCode::Space,
3002            WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
3003            WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
3004            WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
3005            WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
3006            WEB_KEY_PAGE_UP => KeyCode::PageUp,
3007            WEB_KEY_PAGE_DOWN => KeyCode::PageDown,
3008            WEB_KEY_HOME => KeyCode::Home,
3009            WEB_KEY_END => KeyCode::End,
3010            other => other
3011                .chars()
3012                .next()
3013                .map(KeyCode::Character)
3014                .unwrap_or(KeyCode::Unknown),
3015        };
3016        app.dispatch_window_event(WindowEvent::KeyDown(
3017            wid,
3018            KeyEvent::new(code, Modifiers::default(), false),
3019        ));
3020        if key.chars().count() == 1 {
3021            app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
3022        }
3023        app.step_frame()
3024            .map(|stats: FrameStats| stats.get_frame_hash())
3025            .unwrap_or(0)
3026    })
3027}
3028
3029/// Advances animations or repaints the running WebAssembly documentation viewer whenever animations or async image/data loads dirty the scene.
3030///
3031/// # Arguments
3032///
3033/// - `f32` - Elapsed seconds since the previous animation frame.
3034///
3035/// # Returns
3036///
3037/// - `u64` - Rendered frame hash.
3038#[cfg(target_arch = "wasm32")]
3039pub fn wasm_docs_tick(dt_secs: f32) -> u64 {
3040    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
3041        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
3042            Ok(guard) => guard,
3043            Err(_) => return 0,
3044        };
3045        let Some((app, _)) = borrow.as_mut() else {
3046            return 0;
3047        };
3048        if dt_secs <= 0.0 || app.has_active_animations() || take_frame_needed() {
3049            return app
3050                .step_game_frame(dt_secs.max(0.0))
3051                .map(|stats: FrameStats| stats.get_frame_hash())
3052                .unwrap_or(0);
3053        }
3054        app.get_renderer().get_last_stats().get_frame_hash()
3055    })
3056}
3057
3058/// Resizes the WebAssembly documentation viewer canvas and logical viewport immediately, synchronizing real browser safe-area insets.
3059///
3060/// # Arguments
3061///
3062/// - `u32` - Logical viewport width in CSS pixels.
3063/// - `u32` - Logical viewport height in CSS pixels.
3064/// - `f32` - Active browser `window.devicePixelRatio`.
3065///
3066/// # Returns
3067///
3068/// - `u64` - Rendered frame hash.
3069#[cfg(target_arch = "wasm32")]
3070pub fn wasm_docs_resize(width: u32, height: u32, dpr: f32) -> u64 {
3071    let measured_safe: SafeAreaInsets = web_query_safe_area_insets();
3072    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
3073        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
3074            Ok(guard) => guard,
3075            Err(_) => return 0,
3076        };
3077        let Some((app, _)) = borrow.as_mut() else {
3078            return 0;
3079        };
3080        let w: u32 = width.max(320);
3081        let h: u32 = height.max(320);
3082        let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
3083            dpr.clamp(0.5, 4.5)
3084        } else {
3085            1.0
3086        };
3087        let phys_w: u32 = ((w as f64) * (scale as f64)).round().max(1.0) as u32;
3088        let phys_h: u32 = ((h as f64) * (scale as f64)).round().max(1.0) as u32;
3089        if let Some(win) = window()
3090            && let Some(doc) = win.document()
3091            && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
3092            && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
3093        {
3094            if canvas.width() != phys_w {
3095                canvas.set_width(phys_w);
3096            }
3097            if canvas.height() != phys_h {
3098                canvas.set_height(phys_h);
3099            }
3100        }
3101        app.set_exact_physical_viewport(phys_w, phys_h, scale);
3102        app.get_scene().with_write(
3103            |tree: &mut SceneTree| {
3104                let root: NodeId = tree.get_root();
3105                let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
3106                tree.mark_dirty(root, dirty_l | DIRTY_PAINT);
3107            },
3108            (),
3109        );
3110        let effective_safe: SafeAreaInsets = if app.is_immersive_fullscreen() {
3111            SafeAreaInsets::default()
3112        } else {
3113            measured_safe
3114        };
3115        let current_safe: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
3116        if current_safe != effective_safe {
3117            let wid: WindowId = app.get_window_state().get_id();
3118            app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective_safe));
3119        }
3120        let first_hash: u64 = app
3121            .step_frame()
3122            .map(|stats: FrameStats| stats.get_frame_hash())
3123            .unwrap_or(0);
3124        let final_hash: u64 = if take_frame_needed() || app.has_active_animations() {
3125            app.step_frame()
3126                .map(|stats: FrameStats| stats.get_frame_hash())
3127                .unwrap_or(first_hash)
3128        } else {
3129            first_hash
3130        };
3131        notify_frame_needed();
3132        final_hash
3133    })
3134}