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.bytes().all(|blue_val: u8| {
17            blue_val.is_ascii_lowercase() || blue_val.is_ascii_digit() || blue_val == DOCS_BYTE_DASH
18        })
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(|blue_val: u8| blue_val.is_ascii_hexdigit() && !blue_val.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    if val.get(DOCS_CATALOG_FIELD_SUCCESS).and_then(Value::as_bool) == Some(false) {
69        return Err(DOCS_CATALOG_ERR_SHAPE.to_string());
70    }
71    let container: &Value = val
72        .get(DOCS_CATALOG_FIELD_DATA)
73        .filter(|item_val: &&Value| item_val.is_object())
74        .unwrap_or(&val);
75    let expected_count: Option<u64> = container
76        .get(DOCS_CATALOG_FIELD_COUNT)
77        .or_else(|| val.get(DOCS_CATALOG_FIELD_COUNT))
78        .and_then(Value::as_u64);
79    let arr: &[Value] = if let Some(list) = val.as_array() {
80        list.as_slice()
81    } else if let Some(list) = container
82        .get(DOCS_CATALOG_FIELD_ARTIFACTS)
83        .and_then(Value::as_array)
84    {
85        list.as_slice()
86    } else if let Some(list) = container
87        .get(DOCS_CATALOG_FIELD_ITEMS)
88        .and_then(Value::as_array)
89    {
90        list.as_slice()
91    } else if let Some(list) = val.get(DOCS_CATALOG_FIELD_DATA).and_then(Value::as_array) {
92        list.as_slice()
93    } else {
94        return Err(DOCS_CATALOG_ERR_SHAPE.to_string());
95    };
96    let mut parsed: Vec<DocsCatalogArtifact> = Vec::with_capacity(arr.len());
97    for entry in arr.iter() {
98        let name: String = entry
99            .get(DOCS_CATALOG_FIELD_NAME)
100            .and_then(Value::as_str)
101            .ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?
102            .to_string();
103        if !is_safe_catalog_name(&name) {
104            return Err(DOCS_CATALOG_ERR_SHAPE.to_string());
105        }
106        let file_count: u64 = entry
107            .get(DOCS_CATALOG_FIELD_FILES)
108            .or_else(|| entry.get(DOCS_CATALOG_FIELD_FILES_SNAKE))
109            .and_then(Value::as_u64)
110            .ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?;
111        let total_bytes: u64 = entry
112            .get(DOCS_CATALOG_FIELD_BYTES)
113            .or_else(|| entry.get(DOCS_CATALOG_FIELD_BYTES_SNAKE))
114            .and_then(Value::as_u64)
115            .ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?;
116        let sha256: String = entry
117            .get(DOCS_CATALOG_FIELD_SHA)
118            .and_then(Value::as_str)
119            .ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?
120            .to_string();
121        if !is_valid_sha256_hex(&sha256) {
122            return Err(DOCS_CATALOG_ERR_SHAPE.to_string());
123        }
124        let updated_at: i64 = entry
125            .get(DOCS_CATALOG_FIELD_UPDATED)
126            .or_else(|| entry.get(DOCS_CATALOG_FIELD_UPDATED_SNAKE))
127            .and_then(Value::as_i64)
128            .ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?;
129        parsed.push(DocsCatalogArtifact::new(
130            name,
131            file_count,
132            total_bytes,
133            sha256,
134            updated_at,
135        ));
136    }
137    if let Some(count) = expected_count
138        && (count as usize) != parsed.len()
139    {
140        return Err(DOCS_CATALOG_ERR_SHAPE.to_string());
141    }
142    Ok(parsed)
143}
144
145/// Formats a byte count into a human-readable size string paired with raw bytes for tooltip inspection.
146///
147/// # Arguments
148///
149/// - `u64` - Total payload size in bytes.
150///
151/// # Returns
152///
153/// - `String` - Formatted size string (for example `"1.42 MB (1488976 B)"`).
154#[must_use]
155pub fn format_catalog_bytes(bytes: u64) -> String {
156    if bytes >= 1_048_576 {
157        let mb: f64 = (bytes as f64) / 1_048_576.0;
158        format!("{mb:.2} MB ({bytes} B)")
159    } else if bytes >= 1024 {
160        let kb: f64 = (bytes as f64) / 1024.0;
161        format!("{kb:.1} KB ({bytes} B)")
162    } else {
163        format!("{bytes} B")
164    }
165}
166
167/// Formats a Unix epoch second timestamp into an ISO-8601 UTC string (`YYYY-MM-DD HH:MM:SS UTC`).
168///
169/// # Arguments
170///
171/// - `i64` - Unix timestamp in seconds.
172///
173/// # Returns
174///
175/// - `String` - Formatted UTC timestamp string.
176#[must_use]
177pub fn format_catalog_utc(timestamp: i64) -> String {
178    DateTime::from_timestamp(timestamp, 0)
179        .map(|dt: DateTime<Utc>| dt.format("%Y-%m-%d %H:%M:%S UTC").to_string())
180        .unwrap_or_else(|| format!("{timestamp} UTC"))
181}
182
183/// Resolves localized UI strings for the `/api/page-artifacts` catalog from `lang`.
184///
185/// # Arguments
186///
187/// - `&str` - Active BCP 47 language code (for example `"zh-CN"`, `"en-US"`, `"ja-JP"`, `"ko-KR"`).
188///
189/// # Returns
190///
191/// - `[&'static str; 7]` - `[title, loading, error, retry, files, size, updated]` labels.
192fn catalog_locale_labels(lang: &str) -> [&'static str; 7] {
193    let lower: String = lang.to_ascii_lowercase();
194    if lower.starts_with(DOCS_LANG_PREFIX_ZH) {
195        [
196            DOCS_CATALOG_TITLE_ZH,
197            DOCS_CATALOG_LOADING_ZH,
198            DOCS_CATALOG_ERROR_ZH,
199            DOCS_CATALOG_RETRY_ZH,
200            DOCS_CATALOG_FILES_ZH,
201            DOCS_CATALOG_SIZE_ZH,
202            DOCS_CATALOG_UPDATED_ZH,
203        ]
204    } else if lower.starts_with(DOCS_LANG_PREFIX_JA) {
205        [
206            DOCS_CATALOG_TITLE_JA,
207            DOCS_CATALOG_LOADING_JA,
208            DOCS_CATALOG_ERROR_JA,
209            DOCS_CATALOG_RETRY_JA,
210            DOCS_CATALOG_FILES_JA,
211            DOCS_CATALOG_SIZE_JA,
212            DOCS_CATALOG_UPDATED_JA,
213        ]
214    } else if lower.starts_with(DOCS_LANG_PREFIX_KO) {
215        [
216            DOCS_CATALOG_TITLE_KO,
217            DOCS_CATALOG_LOADING_KO,
218            DOCS_CATALOG_ERROR_KO,
219            DOCS_CATALOG_RETRY_KO,
220            DOCS_CATALOG_FILES_KO,
221            DOCS_CATALOG_SIZE_KO,
222            DOCS_CATALOG_UPDATED_KO,
223        ]
224    } else {
225        [
226            DOCS_CATALOG_TITLE_EN,
227            DOCS_CATALOG_LOADING_EN,
228            DOCS_CATALOG_ERROR_EN,
229            DOCS_CATALOG_RETRY_EN,
230            DOCS_CATALOG_FILES_EN,
231            DOCS_CATALOG_SIZE_EN,
232            DOCS_CATALOG_UPDATED_EN,
233        ]
234    }
235}
236
237/// Opens an external URL or site-relative path in the host browser when running on WebAssembly.
238///
239/// # Arguments
240///
241/// - `&str` - Destination URL or path.
242/// - `bool` - When `true`, opens in a new browser tab; otherwise navigates the current tab.
243#[cfg(target_arch = "wasm32")]
244fn open_browser_url(url: &str, new_tab: bool) {
245    let Some(win) = window() else {
246        return;
247    };
248    if new_tab {
249        if let Ok(open_val) = Reflect::get(&win, &JsValue::from_str(WEB_JS_OPEN))
250            && let Ok(open_fn) = open_val.dyn_into::<Function>()
251        {
252            let _: Result<JsValue, JsValue> = open_fn.call3(
253                &win,
254                &JsValue::from_str(url),
255                &JsValue::from_str(WEB_JS_BLANK),
256                &JsValue::from_str(WEB_JS_NOOPENER),
257            );
258        }
259    } else {
260        let _: Result<(), JsValue> = win.location().set_href(url);
261    }
262}
263
264/// Navigates to an internal documentation route or delegates external URLs cleanly.
265///
266/// # Arguments
267///
268/// - `&str` - Clicked Markdown link or button destination.
269/// - `&DocSite` - Loaded documentation site for internal route resolution.
270/// - `Signal<String>` - Active route signal.
271/// - `Signal<String>` - Active TOC anchor slug signal.
272fn navigate_doc_href(
273    href: &str,
274    site: &DocSite,
275    active_route: Signal<String>,
276    active_toc_slug: Signal<String>,
277) {
278    let trimmed: &str = href.trim();
279    if trimmed.is_empty() {
280        return;
281    }
282    if let Some(anchor) = trimmed.strip_prefix('#') {
283        if !anchor.is_empty() {
284            let _: bool = active_toc_slug.set_if_changed(anchor.to_string());
285        }
286        return;
287    }
288    let lower: String = trimmed.to_ascii_lowercase();
289    if lower.starts_with(DOCS_URL_SCHEME_HTTP)
290        || lower.starts_with(DOCS_URL_SCHEME_HTTPS)
291        || lower.starts_with(DOCS_URL_SCHEME_MAILTO)
292    {
293        #[cfg(target_arch = "wasm32")]
294        open_browser_url(trimmed, true);
295        #[cfg(not(target_arch = "wasm32"))]
296        {
297            let _: bool = open_external_url(trimmed);
298        }
299        return;
300    }
301    if let Some(page) = site.find_by_route(trimmed) {
302        let _: bool = active_route.set_if_changed(page.get_route().clone());
303        let _: bool = active_toc_slug.set_if_changed(String::new());
304        return;
305    }
306    let clean: &str = trimmed
307        .split('#')
308        .next()
309        .unwrap_or(trimmed)
310        .trim_end_matches(".md")
311        .trim_end_matches(".html")
312        .trim_end_matches('/');
313    if let Some(page) = site.find_by_route(clean) {
314        let _: bool = active_route.set_if_changed(page.get_route().clone());
315        let _: bool = active_toc_slug.set_if_changed(String::new());
316    } else {
317        #[cfg(target_arch = "wasm32")]
318        open_browser_url(trimmed, false);
319    }
320}
321
322/// Triggers an asynchronous browser `fetch("/api/page-artifacts")` request populating `state` catalog signals on WebAssembly.
323///
324/// # Arguments
325///
326/// - `&DocsViewerState` - Shared documentation viewer state receiving parsed artifacts or error status.
327#[cfg(target_arch = "wasm32")]
328fn trigger_wasm_catalog_fetch(state: &DocsViewerState) {
329    let items_sig: Signal<Vec<DocsCatalogArtifact>> = state.get_catalog_items();
330    let loading_sig: Signal<bool> = state.get_catalog_loading();
331    let error_sig: Signal<bool> = state.get_catalog_error();
332    let _: bool = loading_sig.set_if_changed(true);
333    let _: bool = error_sig.set_if_changed(false);
334    spawn_local(async move {
335        let fetched: Result<Vec<DocsCatalogArtifact>, String> = fetch_catalog_wasm().await;
336        let _: bool = loading_sig.set_if_changed(false);
337        match fetched {
338            Ok(list) => {
339                let _: bool = items_sig.set(list);
340                let _: bool = error_sig.set_if_changed(false);
341            }
342            Err(_) => {
343                let _: bool = error_sig.set_if_changed(true);
344            }
345        }
346        let _: u64 = wasm_docs_tick(0.0);
347    });
348}
349
350/// Fetches `/api/page-artifacts` via `window.fetch` using `js_sys::Reflect` so zero extra `web-sys` features are required.
351///
352/// # Returns
353///
354/// - `Result<Vec<DocsCatalogArtifact>, String>` - Parsed public catalog entries or failure reason.
355#[cfg(target_arch = "wasm32")]
356async fn fetch_catalog_wasm() -> Result<Vec<DocsCatalogArtifact>, String> {
357    let win: Window = window().ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?;
358    let fetch_val: JsValue = Reflect::get(&win, &JsValue::from_str(WEB_JS_FETCH))
359        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
360    let fetch_fn: Function = fetch_val
361        .dyn_into::<Function>()
362        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
363    let promise_val: JsValue = fetch_fn
364        .call1(&win, &JsValue::from_str(DOCS_CATALOG_API_PATH))
365        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
366    let promise: Promise = promise_val
367        .dyn_into::<Promise>()
368        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
369    let resp: JsValue = JsFuture::from(promise)
370        .await
371        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
372    let ok_flag: bool = Reflect::get(&resp, &JsValue::from_str(WEB_JS_OK))
373        .ok()
374        .and_then(|item_val: JsValue| item_val.as_bool())
375        .unwrap_or(false);
376    if !ok_flag {
377        return Err(DOCS_CATALOG_ERR_SHAPE.to_string());
378    }
379    let text_val: JsValue = Reflect::get(&resp, &JsValue::from_str(WEB_JS_TEXT))
380        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
381    let text_fn: Function = text_val
382        .dyn_into::<Function>()
383        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
384    let text_promise_val: JsValue = text_fn
385        .call0(&resp)
386        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
387    let text_promise: Promise = text_promise_val
388        .dyn_into::<Promise>()
389        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
390    let body_val: JsValue = JsFuture::from(text_promise)
391        .await
392        .map_err(|_| DOCS_CATALOG_ERR_SHAPE.to_string())?;
393    let body_str: String = body_val
394        .as_string()
395        .ok_or_else(|| DOCS_CATALOG_ERR_SHAPE.to_string())?;
396    parse_catalog_artifacts_json(&body_str)
397}
398
399/// Renders the compiled Rust `/api/page-artifacts` public catalog section with loading, localized error/retry, and expandable SHA-256 cards.
400///
401/// # Arguments
402///
403/// - `&DocsViewerState` - Shared reactive viewer state carrying catalog signals.
404/// - `ThemeTokens` - Active design tokens.
405///
406/// # Returns
407///
408/// - `NodeId` - Mounted catalog section container node.
409pub fn mount_docs_catalog(state: &DocsViewerState, tokens: ThemeTokens) -> NodeId {
410    let lang: String = state.get_site().resolved_lang().to_string();
411    let [
412        title_lbl,
413        loading_lbl,
414        err_lbl,
415        retry_lbl,
416        files_lbl,
417        size_lbl,
418        updated_lbl,
419    ]: [&'static str; 7] = catalog_locale_labels(&lang);
420    let state_body: DocsViewerState = state.clone();
421    let build_catalog_children = move || -> Vec<NodeId> {
422        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
423        let palette: ThemePalette = live_tok.get_palette();
424        let is_loading: bool = state_body.get_catalog_loading().get();
425        let is_error: bool = state_body.get_catalog_error().get();
426        let items: Vec<DocsCatalogArtifact> = state_body.get_catalog_items().get();
427        if is_loading {
428            return vec![view! {
429                EuvAlert {
430                    title: title_lbl.to_string()
431                    description: loading_lbl.to_string()
432                    tone: EuvTone::Primary
433                    tokens: live_tok
434                }
435            }];
436        }
437        if is_error {
438            let retry_state: DocsViewerState = state_body.clone();
439            let on_retry = move |_: &UiEvent| {
440                #[cfg(target_arch = "wasm32")]
441                trigger_wasm_catalog_fetch(&retry_state);
442                #[cfg(not(target_arch = "wasm32"))]
443                {
444                    let _: bool = retry_state.get_catalog_error().set_if_changed(false);
445                }
446            };
447            return vec![{
448                let column_group_zeta_style: Style = style! {
449                    Width(Length::Percent(100.0))
450                    Gap(SPACE_SM)
451                };
452                view! {
453                    column {
454                        style: column_group_zeta_style
455                        EuvAlert {
456                            title: title_lbl.to_string()
457                            description: err_lbl.to_string()
458                            tone: EuvTone::Warning
459                            tokens: live_tok
460                        }
461                        EuvButton {
462                            label: retry_lbl.to_string()
463                            tokens: live_tok
464                            on_click: on_retry
465                        }
466                    }
467                }
468            }];
469        }
470        if items.is_empty() {
471            return vec![view! {
472                EuvEmpty {
473                    title: title_lbl.to_string()
474                    description: format!("{DOCS_CATALOG_EMPTY_EN} ({DOCS_CATALOG_CARD_CLASS})")
475                    tokens: live_tok
476                }
477            }];
478        }
479        let mut cards: Vec<NodeId> = Vec::with_capacity(items.len());
480        for art in items.into_iter() {
481            let art_name: String = art.get_name().clone();
482            let page_href: String = format!("/pages/{art_name}/");
483            let files_tag: String = format!("{files_lbl}: {}", art.get_file_count());
484            let size_tag: String = format!(
485                "{size_lbl}: {}",
486                format_catalog_bytes(art.get_total_bytes())
487            );
488            let updated_tag: String = format!(
489                "{updated_lbl}: {}",
490                format_catalog_utc(art.get_updated_at())
491            );
492            let sha_full: String = art.get_sha256().clone();
493            let sha_copy_val: String = sha_full.clone();
494            let copied_sig: Signal<bool> = Signal::new(false);
495            let sha_open_sig: Signal<bool> = Signal::new(false);
496            let on_copy_sha = move |_: &UiEvent| {
497                let ctx: Context = current_context();
498                let _: bool = ctx.copy_to_clipboard(&sha_copy_val);
499                let _: bool = copied_sig.set_if_changed(true);
500            };
501            let copy_lbl_fn = move || -> String {
502                if copied_sig.get() {
503                    DOCS_CATALOG_SHA_COPIED.to_string()
504                } else {
505                    DOCS_CATALOG_SHA_COPY.to_string()
506                }
507            };
508            let open_href: String = page_href.clone();
509            let opened_sig: Signal<String> = state_body.get_last_opened_url();
510            let on_open_art = move |_: &UiEvent| {
511                let _: bool = opened_sig.set_if_changed(open_href.clone());
512                #[cfg(target_arch = "wasm32")]
513                open_browser_url(&open_href, true);
514            };
515            let column_group_epsilon_style: Style = style! {
516                Width(Length::Percent(100.0))
517                Gap(SPACE_XS)
518            };
519            let text_eighth_style: Style = style! {
520                Width(Length::Percent(100.0))
521                FontSize(11.5)
522                FontFamily::Monospace
523                TextColor(palette.get_muted_foreground())
524                Selectable(true)
525            };
526            let text_ninth_style: Style = style! {
527                FontSize(11.0)
528                TextColor(palette.get_muted_foreground())
529            };
530            let sha_body: NodeId = view! {
531                column {
532                    style: column_group_epsilon_style
533                    text {
534                        style: text_eighth_style
535                        { sha_full }
536                    }
537                    EuvButton {
538                        label: DOCS_CATALOG_SHA_COPY.to_string()
539                        tokens: live_tok
540                        on_click: on_copy_sha
541                    }
542                    text {
543                        style: text_ninth_style
544                        { copy_lbl_fn }
545                    }
546                }
547            };
548            let card_hov: Signal<bool> = Signal::new(false);
549            let on_card_enter = move |_: &UiEvent| {
550                let _: bool = card_hov.set_if_changed(true);
551            };
552            let on_card_leave = move |_: &UiEvent| {
553                let _: bool = card_hov.set_if_changed(false);
554            };
555            let card_wrap_style = move || -> Style {
556                let tok: ThemeTokens = use_live_tokens(tokens);
557                let lp: ThemePalette = tok.get_palette();
558                let lg: ThemeGeometry = tok.get_geometry();
559                let hovered: bool = card_hov.get();
560                let wrap_bg: Color = if hovered {
561                    lp.get_accent().with_alpha(96)
562                } else {
563                    COLOR_TRANSPARENT
564                };
565                style! {
566                    FlexDirection::Column
567                    Width(Length::Percent(100.0))
568                    Padding(Edges::all(SPACE_XS))
569                    Radius(lg.get_radius_lg() + SPACE_XS)
570                    Background(wrap_bg)
571                    Overflow::Hidden
572                    CursorIcon::Pointer
573                }
574            };
575            let row_fifteenth_style: Style = style! {
576                Width(Length::Percent(100.0))
577                FlexWrap::Wrap
578                Gap(SPACE_XS)
579                AlignItems::Center
580            };
581            let column_group_delta_style: Style = style! {
582                Width(Length::Percent(100.0))
583                StopEventPropagation(true)
584            };
585            let card_node: NodeId = view! {
586                column {
587                    bind_style: card_wrap_style
588                    role: A11yRole::Link
589                    a11y_label: art_name.clone()
590                    on_click: on_open_art
591                    on_pointer_enter: on_card_enter
592                    on_pointer_leave: on_card_leave
593                    EuvCard {
594                        title: art_name
595                        subtitle: updated_tag
596                        tokens: live_tok
597                        row {
598                            style: row_fifteenth_style
599                            role: A11yRole::Group
600                            a11y_label: DOCS_CATALOG_CARD_CLASS.to_string()
601                            EuvTag {
602                                label: files_tag
603                                tokens: live_tok
604                            }
605                            EuvTag {
606                                label: size_tag
607                                tokens: live_tok
608                            }
609                        }
610                        column {
611                            style: column_group_delta_style
612                            EuvCollapsible {
613                                open: sha_open_sig
614                                title: "SHA-256".to_string()
615                                content: sha_body
616                                tokens: live_tok
617                            }
618                        }
619                    }
620                }
621            };
622            cards.push(card_node);
623        }
624        cards
625    };
626    let column_group_gamma_style: Style = style! {
627        Width(Length::Percent(100.0))
628        Gap(SPACE_SM)
629    };
630    view! {
631        column {
632            style: column_group_gamma_style
633            role: A11yRole::Region
634            a11y_label: DOCS_CATALOG_CARD_CLASS.to_string()
635            EuvHeader {
636                title: title_lbl.to_string()
637                subtitle: DOCS_CATALOG_API_PATH.to_string()
638                tokens: tokens
639            }
640            column {
641                style: column_group_gamma_style
642                bind_children: build_catalog_children
643            }
644        }
645    }
646}
647
648/// Computes the relative site-root asset base prefix (`"./"` for root locale `"/"`, `"../"` for `"/en/"`, etc.) working under both root and subpath deployments.
649///
650/// # Arguments
651///
652/// - `&str` - Active locale prefix (for example `"/"`, `"/en/"`, `"/ja/"`).
653///
654/// # Returns
655///
656/// - `String` - Relative URL prefix reaching the built site root (`"./"`, `"../"`, ...).
657#[must_use]
658pub fn asset_base_for_locale_prefix(locale_prefix: &str) -> String {
659    let depth: usize = locale_prefix
660        .trim()
661        .split('/')
662        .filter(|seg: &&str| !seg.is_empty())
663        .count();
664    if depth == 0 {
665        "./".to_string()
666    } else {
667        "../".repeat(depth)
668    }
669}
670
671/// Resolves a portable relative locale-switch URL from `active_locale_prefix` to `target_locale_prefix` working under both `/` and `/pages/docs/`.
672///
673/// # Arguments
674///
675/// - `&str` - Currently active locale prefix (for example `"/"` or `"/en/"`).
676/// - `&str` - Destination locale prefix (for example `"/"`, `"/en/"`, `"/ja/"`).
677///
678/// # Returns
679///
680/// - `String` - Relative navigation href targeting the destination locale directory.
681#[must_use]
682pub fn resolve_locale_switch_href(
683    active_locale_prefix: &str,
684    target_locale_prefix: &str,
685) -> String {
686    let base: String = asset_base_for_locale_prefix(active_locale_prefix);
687    let target_rel: &str = target_locale_prefix.trim().trim_start_matches('/');
688    if target_rel.is_empty() {
689        base
690    } else if target_rel.ends_with('/') {
691        format!("{base}{target_rel}")
692    } else {
693        format!("{base}{target_rel}/")
694    }
695}
696
697/// Builds a locale-switch navigation URL combining `base_url` and `target_locale_prefix` while preserving `active_route` and optional `active_anchor` in the hash fragment.
698///
699/// # Arguments
700///
701/// - `&str` - Base site URL or relative site-root prefix (for example `"/pages/docs/"`, `"./"`, or `"../"`).
702/// - `&str` - Destination locale prefix (for example `"/"`, `"/en/"`, or `"/ja/"`).
703/// - `&str` - Currently active documentation route path (for example `"/euv/ui/component/button"`).
704/// - `Option<&str>` - Optional active TOC heading anchor slug (for example `Some("props")`).
705///
706/// # Returns
707///
708/// - `String` - Locale-switch URL preserving the current page route and optional `#anchor`.
709#[must_use]
710pub fn build_locale_switch_url(
711    base_url: &str,
712    target_locale_prefix: &str,
713    active_route: &str,
714    active_anchor: Option<&str>,
715) -> String {
716    let trimmed_base: &str = base_url.trim();
717    let normalized_base: String = if trimmed_base.is_empty() {
718        "./".to_string()
719    } else if trimmed_base.ends_with('/') {
720        trimmed_base.to_string()
721    } else {
722        format!("{trimmed_base}/")
723    };
724    let target_rel: &str = target_locale_prefix.trim().trim_start_matches('/');
725    let dir_url: String = if target_rel.is_empty() {
726        normalized_base
727    } else if target_rel.ends_with('/') {
728        format!("{normalized_base}{target_rel}")
729    } else {
730        format!("{normalized_base}{target_rel}/")
731    };
732    let route_trim: &str = active_route.trim().trim_start_matches('#').trim();
733    let norm_route: String = if route_trim.is_empty() || route_trim == "/" {
734        "/".to_string()
735    } else if route_trim.starts_with('/') {
736        route_trim.to_string()
737    } else {
738        format!("/{route_trim}")
739    };
740    let clean_anchor: Option<&str> = active_anchor
741        .map(|text_value: &str| text_value.trim().trim_start_matches('#').trim())
742        .filter(|alpha_val: &&str| !alpha_val.is_empty());
743    match (norm_route.as_str(), clean_anchor) {
744        ("/", None) => dir_url,
745        ("/", Some(anchor)) => format!("{dir_url}#/#{anchor}"),
746        (route, None) => format!("{dir_url}#{route}"),
747        (route, Some(anchor)) => format!("{dir_url}#{route}#{anchor}"),
748    }
749}
750
751/// Derives the site-root URL directory from `pathname` and `active_locale_prefix`, tolerating missing trailing slashes and `index.html`.
752///
753/// # Arguments
754///
755/// - `&str` - Browser `window.location.pathname` (for example `"/pages/docs/en"` or `"/pages/docs/en/index.html"`).
756/// - `&str` - Active locale prefix (for example `"/"` or `"/en/"`).
757///
758/// # Returns
759///
760/// - `String` - Normalized site-root directory path ending in `'/'` (for example `"/pages/docs/"`).
761#[must_use]
762pub fn resolve_site_root_from_pathname(pathname: &str, active_locale_prefix: &str) -> String {
763    let mut trimmed: &str = pathname.trim();
764    if trimmed.is_empty() {
765        return asset_base_for_locale_prefix(active_locale_prefix);
766    }
767    if trimmed.ends_with(DOCS_HTML_FILE_SUFFIX)
768        && let Some((dir, _)) = trimmed.rsplit_once('/')
769    {
770        trimmed = dir;
771    }
772    let clean_path: String = format!("/{}/", trimmed.trim_matches('/')).replace("//", "/");
773    let loc_trimmed: &str = active_locale_prefix.trim().trim_matches('/');
774    if loc_trimmed.is_empty() {
775        return clean_path;
776    }
777    let loc_suffix: String = format!("/{loc_trimmed}/");
778    if let Some(root_prefix) = clean_path.strip_suffix(loc_suffix.as_str()) {
779        if root_prefix.is_empty() {
780            "/".to_string()
781        } else {
782            format!("{root_prefix}/")
783        }
784    } else {
785        asset_base_for_locale_prefix(active_locale_prefix)
786    }
787}
788
789/// Formats a compact `(route, scroll_y, active_slug)` session-storage payload for scroll-position restoration across refreshes.
790///
791/// # Arguments
792///
793/// - `&str` - Active canonical route path.
794/// - `f32` - Current vertical scroll offset in logical pixels.
795/// - `&str` - Active TOC heading anchor slug (may be empty).
796///
797/// # Returns
798///
799/// - `String` - Pipe-delimited serialized snapshot string.
800#[cfg(any(target_arch = "wasm32", test))]
801#[must_use]
802pub(crate) fn format_docs_scroll_snapshot(route: &str, scroll_y: f32, active_slug: &str) -> String {
803    format!("{:.2}|{route}|{active_slug}", scroll_y.max(0.0))
804}
805
806/// Parses a serialized `DOCS_SCROLL_STORAGE_KEY` snapshot matching `expected_route`.
807///
808/// # Arguments
809///
810/// - `&str` - Raw `sessionStorage` string payload.
811/// - `&str` - Expected canonical route path.
812///
813/// # Returns
814///
815/// - `Option<(f32, Option<String>)>` - Restored `(scroll_y, optional_slug)` when `expected_route` matches.
816#[cfg(any(target_arch = "wasm32", test))]
817#[must_use]
818pub(crate) fn parse_docs_scroll_snapshot(
819    raw: &str,
820    expected_route: &str,
821) -> Option<(f32, Option<String>)> {
822    let mut parts: SplitN<'_, char> = raw.splitn(3, '|');
823    let y_str: &str = parts.next()?.trim();
824    let route_str: &str = parts.next()?.trim();
825    let slug_str: &str = parts.next().unwrap_or("").trim();
826    if route_str != expected_route {
827        return None;
828    }
829    let scroll_y: f32 = y_str.parse::<f32>().ok()?.max(0.0);
830    let slug_opt: Option<String> = (!slug_str.is_empty()).then(|| slug_str.to_string());
831    Some((scroll_y, slug_opt))
832}
833
834/// Computes normalized 24×24 viewbox origin, unit scale, and Lucide-grade stroke width centered inside `bounds`.
835///
836/// # Arguments
837///
838/// - `Rect` - Target logical bounding box.
839///
840/// # Returns
841///
842/// - `(f32, f32, f32, f32)` - Tuple `(ox, oy, u, stroke_width)`.
843fn docs_icon_basis(bounds: Rect) -> (f32, f32, f32, f32) {
844    let width_val: f32 = bounds.get_width().max(8.0);
845    let height_val: f32 = bounds.get_height().max(8.0);
846    let side: f32 = width_val.min(height_val);
847    let ox: f32 = bounds.get_x() + (width_val - side) * 0.5;
848    let oy: f32 = bounds.get_y() + (height_val - side) * 0.5;
849    let tex_u: f32 = side / 24.0;
850    let stroke_width: f32 = (1.75 * tex_u).clamp(1.2, 2.0);
851    (ox, oy, tex_u, stroke_width)
852}
853
854/// Emits a line segment with precision rounded endcaps into `dl`.
855///
856/// # Arguments
857///
858/// - `&mut DisplayList` - Destination vector draw command list.
859/// - `Point` - Segment start point.
860/// - `Point` - Segment end point.
861/// - `Color` - Stroke color.
862/// - `f32` - Stroke width in logical pixels.
863fn docs_rounded_stroke(
864    display_list: &mut DisplayList,
865    from: Point,
866    to: Point,
867    color: Color,
868    width: f32,
869) {
870    display_list.push(DrawCommand::Line {
871        from,
872        to,
873        color,
874        width,
875    });
876}
877
878/// Returns the human-readable display label for a built-in `DesignScheme`.
879///
880/// # Arguments
881///
882/// - `DesignScheme` - Target design scheme variant.
883///
884/// # Returns
885///
886/// - `&'static str` - Clean display title shown in theme dropdown menus.
887#[must_use]
888pub fn docs_scheme_display_label(scheme: DesignScheme) -> &'static str {
889    match scheme {
890        DesignScheme::Shadcn => "Shadcn",
891        DesignScheme::Cupertino => "Cupertino",
892        DesignScheme::Material => "Material",
893        DesignScheme::Fluent => "Fluent",
894        DesignScheme::AntDesign => "Ant Design",
895        DesignScheme::Bootstrap => "Bootstrap",
896        DesignScheme::DaisyUi => "DaisyUI",
897        DesignScheme::Geist => "Geist",
898        DesignScheme::HeroUi => "HeroUI",
899        DesignScheme::Linear => "Linear",
900        DesignScheme::Mantine => "Mantine",
901        DesignScheme::Monochrome => "Monochrome",
902        DesignScheme::Notion => "Notion",
903        DesignScheme::Park => "Park UI",
904        DesignScheme::Radix => "Radix",
905        DesignScheme::Stripe => "Stripe",
906        DesignScheme::Supabase => "Supabase",
907    }
908}
909
910/// Draws a Lucide-grade 24×24 search magnifying glass icon into `dl`.
911///
912/// # Arguments
913///
914/// - `Rect` - Target logical bounding box.
915/// - `&mut DisplayList` - Destination vector draw command list.
916/// - `Color` - Foreground stroke color.
917fn draw_docs_search_icon(bounds: Rect, display_list: &mut DisplayList, color: Color) {
918    let (ox, oy, tex_u, stroke_width): (f32, f32, f32, f32) = docs_icon_basis(bounds);
919    let lens_d: f32 = 13.6 * tex_u;
920    display_list.push(DrawCommand::FillRoundedRect {
921        rect: Rect::new(ox + 4.0 * tex_u, oy + 4.0 * tex_u, lens_d, lens_d),
922        color: COLOR_TRANSPARENT,
923        radius: CornerRadius::all(RADIUS_PILL),
924        border: Border::new(stroke_width, color),
925    });
926    docs_rounded_stroke(
927        display_list,
928        Point::new(ox + 15.2 * tex_u, oy + 15.2 * tex_u),
929        Point::new(ox + 20.2 * tex_u, oy + 20.2 * tex_u),
930        color,
931        stroke_width,
932    );
933}
934
935/// Draws a Lucide-grade 24×24 `Globe` multi-language vector icon (outer circle, equator, and dual meridian arcs) into `dl`.
936///
937/// # Arguments
938///
939/// - `Rect` - Target logical bounding box.
940/// - `&mut DisplayList` - Destination vector draw command list.
941/// - `Color` - Foreground stroke color.
942fn draw_docs_globe_icon(bounds: Rect, display_list: &mut DisplayList, color: Color) {
943    let (ox, oy, tex_u, stroke_width): (f32, f32, f32, f32) = docs_icon_basis(bounds);
944    let cx: f32 = ox + 12.0 * tex_u;
945    let cy: f32 = oy + 12.0 * tex_u;
946    let red_val: f32 = 9.0 * tex_u;
947    display_list.push(DrawCommand::FillRoundedRect {
948        rect: Rect::new(cx - red_val, cy - red_val, red_val * 2.0, red_val * 2.0),
949        color: COLOR_TRANSPARENT,
950        radius: CornerRadius::all(RADIUS_PILL),
951        border: Border::new(stroke_width, color),
952    });
953    display_list.push(DrawCommand::Line {
954        from: Point::new(cx - red_val + stroke_width * 0.4, cy),
955        to: Point::new(cx + red_val - stroke_width * 0.4, cy),
956        color,
957        width: stroke_width,
958    });
959    let rx: f32 = 4.2 * tex_u;
960    let steps: usize = 16;
961    for sign in [-1.0_f32, 1.0_f32].into_iter() {
962        let mut prev: Point = Point::new(cx, cy - red_val);
963        for source_val in 1..=steps {
964            let blend_factor: f32 = (source_val as f32) / (steps as f32);
965            let ang: f32 = -FRAC_PI_2 + blend_factor * PI;
966            let px: f32 = cx + sign * rx * ang.cos();
967            let py: f32 = cy + red_val * ang.sin();
968            let cur: Point = Point::new(px, py);
969            display_list.push(DrawCommand::Line {
970                from: prev,
971                to: cur,
972                color,
973                width: stroke_width,
974            });
975            prev = cur;
976        }
977    }
978}
979
980/// Draws a Lucide-grade 24×24 `Palette` vector icon with an active theme accent swatch dot into `dl`.
981///
982/// # Arguments
983///
984/// - `Rect` - Target logical bounding box.
985/// - `&mut DisplayList` - Destination vector draw command list.
986/// - `Color` - Foreground stroke color.
987/// - `Color` - Active theme primary accent color rendered inside the swatch dot.
988fn draw_docs_palette_icon(
989    bounds: Rect,
990    display_list: &mut DisplayList,
991    color: Color,
992    accent: Color,
993) {
994    let (ox, oy, tex_u, stroke_width): (f32, f32, f32, f32) = docs_icon_basis(bounds);
995    let cx: f32 = ox + 12.0 * tex_u;
996    let cy: f32 = oy + 12.0 * tex_u;
997    let red_val: f32 = 8.8 * tex_u;
998    let start_ang: f32 = 0.56;
999    let end_ang: f32 = TAU - 0.12;
1000    let p_start: Point = Point::new(
1001        cx + red_val * start_ang.cos(),
1002        cy + red_val * start_ang.sin(),
1003    );
1004    let arc_steps: usize = 22;
1005    let mut prev: Point = p_start;
1006    for source_val in 1..=arc_steps {
1007        let blend_factor: f32 = (source_val as f32) / (arc_steps as f32);
1008        let alpha_val: f32 = start_ang + (end_ang - start_ang) * blend_factor;
1009        let cur: Point = Point::new(
1010            cx + red_val * alpha_val.cos(),
1011            cy + red_val * alpha_val.sin(),
1012        );
1013        display_list.push(DrawCommand::Line {
1014            from: prev,
1015            to: cur,
1016            color,
1017            width: stroke_width,
1018        });
1019        prev = cur;
1020    }
1021    let notch: [Point; 7] = [
1022        prev,
1023        Point::new(ox + 17.6 * tex_u, oy + 11.4 * tex_u),
1024        Point::new(ox + 15.6 * tex_u, oy + 12.2 * tex_u),
1025        Point::new(ox + 14.8 * tex_u, oy + 13.6 * tex_u),
1026        Point::new(ox + 15.6 * tex_u, oy + 15.0 * tex_u),
1027        Point::new(ox + 17.4 * tex_u, oy + 15.8 * tex_u),
1028        p_start,
1029    ];
1030    for item_index in 0..6usize {
1031        display_list.push(DrawCommand::Line {
1032            from: notch[item_index],
1033            to: notch[item_index + 1],
1034            color,
1035            width: stroke_width,
1036        });
1037    }
1038    let dot_r: f32 = (1.35 * tex_u).max(1.0);
1039    for &(dx, dy) in [(7.6_f32, 10.0_f32), (11.2, 6.8), (15.6, 8.6)].iter() {
1040        display_list.push(DrawCommand::Circle {
1041            center: Point::new(ox + dx * tex_u, oy + dy * tex_u),
1042            radius: dot_r,
1043            color,
1044        });
1045    }
1046    let swatch_r: f32 = (2.15 * tex_u).max(1.5);
1047    display_list.push(DrawCommand::Circle {
1048        center: Point::new(ox + 9.2 * tex_u, oy + 15.2 * tex_u),
1049        radius: swatch_r,
1050        color: accent,
1051    });
1052}
1053
1054/// Draws a precision Lucide / SF-Symbols style hollow Sun vector icon on a normalized 24×24 optical box.
1055///
1056/// # Arguments
1057///
1058/// - `Rect` - Target logical bounding box.
1059/// - `&mut DisplayList` - Destination vector draw command list.
1060/// - `Color` - Foreground stroke color.
1061fn draw_docs_sun_icon(bounds: Rect, display_list: &mut DisplayList, color: Color) {
1062    let (ox, oy, tex_u, stroke_width): (f32, f32, f32, f32) = docs_icon_basis(bounds);
1063    let cx: f32 = ox + 12.0 * tex_u;
1064    let cy: f32 = oy + 12.0 * tex_u;
1065    let red_val: f32 = 4.2 * tex_u;
1066    display_list.push(DrawCommand::FillRoundedRect {
1067        rect: Rect::new(cx - red_val, cy - red_val, red_val * 2.0, red_val * 2.0),
1068        color: COLOR_TRANSPARENT,
1069        radius: CornerRadius::all(RADIUS_PILL),
1070        border: Border::new(stroke_width, color),
1071    });
1072    let r_in: f32 = 7.0 * tex_u;
1073    let r_out: f32 = 9.4 * tex_u;
1074    for item_index in 0..8usize {
1075        let angle: f32 = (item_index as f32) * (TAU / 8.0);
1076        let cos_a: f32 = angle.cos();
1077        let sin_a: f32 = angle.sin();
1078        docs_rounded_stroke(
1079            display_list,
1080            Point::new(cx + cos_a * r_in, cy + sin_a * r_in),
1081            Point::new(cx + cos_a * r_out, cy + sin_a * r_out),
1082            color,
1083            stroke_width,
1084        );
1085    }
1086}
1087
1088/// Draws a smooth analytical Lucide `MoonStar` crescent + upper-right 4-point sparkle vector icon on a 24×24 optical box.
1089///
1090/// # Arguments
1091///
1092/// - `Rect` - Target logical bounding box.
1093/// - `&mut DisplayList` - Destination vector draw command list.
1094/// - `Color` - Foreground stroke color.
1095fn draw_docs_moon_star_icon(bounds: Rect, display_list: &mut DisplayList, color: Color) {
1096    let (ox, oy, tex_u, stroke_width): (f32, f32, f32, f32) = docs_icon_basis(bounds);
1097    let c1x: f32 = 11.8;
1098    let c1y: f32 = 12.4;
1099    let r1: f32 = 8.2;
1100    let c2x: f32 = 16.4;
1101    let c2y: f32 = 8.2;
1102    let r2: f32 = 6.6;
1103    let dx: f32 = c2x - c1x;
1104    let dy: f32 = c2y - c1y;
1105    let dist: f32 = (dx * dx + dy * dy).sqrt();
1106    let base_ang: f32 = dy.atan2(dx);
1107    let a_dist: f32 = (r1 * r1 - r2 * r2 + dist * dist) / (2.0 * dist);
1108    let alpha1: f32 = (a_dist / r1).clamp(-1.0, 1.0).acos();
1109    let theta1_top: f32 = base_ang - alpha1;
1110    let theta1_bot: f32 = base_ang + alpha1;
1111    let theta1_end: f32 = theta1_top + TAU;
1112    let p_top_x: f32 = c1x + r1 * theta1_top.cos();
1113    let p_top_y: f32 = c1y + r1 * theta1_top.sin();
1114    let p_bot_x: f32 = c1x + r1 * theta1_bot.cos();
1115    let p_bot_y: f32 = c1y + r1 * theta1_bot.sin();
1116    let p_top: Point = Point::new(ox + p_top_x * tex_u, oy + p_top_y * tex_u);
1117    let p_bot: Point = Point::new(ox + p_bot_x * tex_u, oy + p_bot_y * tex_u);
1118    let outer_steps: usize = 20;
1119    let mut prev_outer: Point = p_bot;
1120    for step in 1..=outer_steps {
1121        let next_pt: Point = if step == outer_steps {
1122            p_top
1123        } else {
1124            let blend_factor: f32 = (step as f32) / (outer_steps as f32);
1125            let ang: f32 = theta1_bot + (theta1_end - theta1_bot) * blend_factor;
1126            Point::new(
1127                ox + (c1x + r1 * ang.cos()) * tex_u,
1128                oy + (c1y + r1 * ang.sin()) * tex_u,
1129            )
1130        };
1131        display_list.push(DrawCommand::Line {
1132            from: prev_outer,
1133            to: next_pt,
1134            color,
1135            width: stroke_width,
1136        });
1137        prev_outer = next_pt;
1138    }
1139    let mut theta2_top: f32 = (p_top_y - c2y).atan2(p_top_x - c2x);
1140    let theta2_bot: f32 = (p_bot_y - c2y).atan2(p_bot_x - c2x);
1141    if theta2_top < theta2_bot {
1142        theta2_top += TAU;
1143    }
1144    let inner_steps: usize = 14;
1145    let mut prev_inner: Point = p_top;
1146    for step in 1..=inner_steps {
1147        let next_pt: Point = if step == inner_steps {
1148            p_bot
1149        } else {
1150            let time_step: f32 = (step as f32) / (inner_steps as f32);
1151            let ang: f32 = theta2_top + (theta2_bot - theta2_top) * time_step;
1152            Point::new(
1153                ox + (c2x + r2 * ang.cos()) * tex_u,
1154                oy + (c2y + r2 * ang.sin()) * tex_u,
1155            )
1156        };
1157        display_list.push(DrawCommand::Line {
1158            from: prev_inner,
1159            to: next_pt,
1160            color,
1161            width: stroke_width,
1162        });
1163        prev_inner = next_pt;
1164    }
1165    let sx: f32 = ox + 17.8 * tex_u;
1166    let sy: f32 = oy + 6.4 * tex_u;
1167    let s_arm: f32 = 2.1 * tex_u;
1168    let s_sw: f32 = (1.45 * tex_u).clamp(1.05, 1.75);
1169    docs_rounded_stroke(
1170        display_list,
1171        Point::new(sx - s_arm, sy),
1172        Point::new(sx + s_arm, sy),
1173        color,
1174        s_sw,
1175    );
1176    docs_rounded_stroke(
1177        display_list,
1178        Point::new(sx, sy - s_arm),
1179        Point::new(sx, sy + s_arm),
1180        color,
1181        s_sw,
1182    );
1183}
1184
1185/// Draws a sleek disclosure chevron (`>` when collapsed, `v` when expanded) for catalog and TOC tree rows.
1186///
1187/// # Arguments
1188///
1189/// - `Rect` - Target logical bounding box.
1190/// - `&mut DisplayList` - Destination vector draw command list.
1191/// - `Color` - Stroke color.
1192/// - `bool` - `true` for expanded downward chevron, `false` for collapsed rightward chevron.
1193fn draw_docs_tree_chevron(
1194    bounds: Rect,
1195    display_list: &mut DisplayList,
1196    color: Color,
1197    expanded: bool,
1198) {
1199    let cx: f32 = bounds.get_x() + bounds.get_width() * 0.5;
1200    let cy: f32 = bounds.get_y() + bounds.get_height() * 0.5;
1201    let stroke_width: f32 = 1.5;
1202    if expanded {
1203        docs_rounded_stroke(
1204            display_list,
1205            Point::new(cx - 3.5, cy - 1.8),
1206            Point::new(cx, cy + 2.2),
1207            color,
1208            stroke_width,
1209        );
1210        docs_rounded_stroke(
1211            display_list,
1212            Point::new(cx, cy + 2.2),
1213            Point::new(cx + 3.5, cy - 1.8),
1214            color,
1215            stroke_width,
1216        );
1217    } else {
1218        docs_rounded_stroke(
1219            display_list,
1220            Point::new(cx - 1.8, cy - 3.5),
1221            Point::new(cx + 2.2, cy),
1222            color,
1223            stroke_width,
1224        );
1225        docs_rounded_stroke(
1226            display_list,
1227            Point::new(cx + 2.2, cy),
1228            Point::new(cx - 1.8, cy + 3.5),
1229            color,
1230            stroke_width,
1231        );
1232    }
1233}
1234
1235/// Builds ordered footer segments `(label, target_url, is_icp, icon_path, alt)` with non-ICP repo links first and ICP / `footer_items` strictly last.
1236///
1237/// # Arguments
1238///
1239/// - `&DocSite` - Documentation site containing footer text, link, and `footer_items`.
1240///
1241/// # Returns
1242///
1243/// - `Vec<(String, String, bool, String, String)>` - Non-empty ordered footer segments ready for symmetrical `|` rendering.
1244#[must_use]
1245pub fn build_docs_footer_segments(site: &DocSite) -> Vec<(String, String, bool, String, String)> {
1246    let non_icp_url: String = if site.get_footer_link().trim().is_empty() {
1247        DOCS_DEFAULT_REPO_URL.to_string()
1248    } else {
1249        site.get_footer_link().trim().to_string()
1250    };
1251    let raw_footer: &str = if site.get_footer().trim().is_empty() {
1252        DOCS_DEFAULT_FOOTER
1253    } else {
1254        site.get_footer().trim()
1255    };
1256    let mut segments: Vec<(String, String, bool, String, String)> =
1257        Vec::with_capacity(site.get_footer_items().len() + 4);
1258    for piece in raw_footer.split(['|', '|', '·']) {
1259        let trimmed: &str = piece.trim();
1260        if !trimmed.is_empty() {
1261            segments.push((
1262                trimmed.to_string(),
1263                non_icp_url.clone(),
1264                false,
1265                String::new(),
1266                String::new(),
1267            ));
1268        }
1269    }
1270    let release_str: &str = EUV_DOCS_RELEASE_MARKER.trim();
1271    if !release_str.is_empty() {
1272        segments.push((
1273            release_str.to_string(),
1274            non_icp_url,
1275            false,
1276            String::new(),
1277            String::new(),
1278        ));
1279    }
1280    for item in site.get_footer_items().iter() {
1281        let label: String = item.get_text().trim().to_string();
1282        if label.is_empty() {
1283            continue;
1284        }
1285        let target_url: String = item.get_link().trim().to_string();
1286        let icon_url: String = item.get_icon().trim().to_string();
1287        let alt_txt: String = item.get_alt().trim().to_string();
1288        segments.push((label, target_url, true, icon_url, alt_txt));
1289    }
1290    segments
1291}
1292
1293/// Renders the centered site footer row with non-ICP segments linking to the repository first, ICP / `footer_items` strictly last, and symmetrical `|` separators only between adjacent non-empty segments.
1294///
1295/// # Arguments
1296///
1297/// - `&DocSite` - Documentation site containing footer text and `footer_items`.
1298/// - `ThemeTokens` - Active design tokens.
1299///
1300/// # Returns
1301///
1302/// - `NodeId` - Mounted centered footer container handle.
1303pub fn mount_docs_footer(site: &DocSite, tokens: ThemeTokens) -> NodeId {
1304    mount_docs_footer_with_recorder(site, tokens, None)
1305}
1306
1307/// Renders the centered site footer row while optionally recording clicked external URLs into `opened_url_sig`.
1308///
1309/// # Arguments
1310///
1311/// - `&DocSite` - Documentation site containing footer text and `footer_items`.
1312/// - `ThemeTokens` - Active design tokens.
1313/// - `Option<Signal<String>>` - Optional URL recorder signal for deterministic click verification.
1314///
1315/// # Returns
1316///
1317/// - `NodeId` - Mounted centered footer container handle.
1318fn mount_docs_footer_with_recorder(
1319    site: &DocSite,
1320    tokens: ThemeTokens,
1321    opened_url_sig: Option<Signal<String>>,
1322) -> NodeId {
1323    let palette: ThemePalette = tokens.get_palette();
1324    let asset_base: String = asset_base_for_locale_prefix(site.get_locale_prefix().as_str());
1325    let segments: Vec<(String, String, bool, String, String)> = build_docs_footer_segments(site);
1326    let mut row_children: Vec<NodeId> = Vec::with_capacity(segments.len().saturating_mul(2));
1327    for (idx, (label, target_url, _, icon_url, alt_txt)) in segments.into_iter().enumerate() {
1328        if idx > 0 {
1329            row_children.push({
1330                let text_seventh_style: Style = style! {
1331                    FontSize(12.0)
1332                    TextColor(palette.get_muted_foreground())
1333                    TextAlign::Center
1334                };
1335                view! {
1336                    text {
1337                        style: text_seventh_style
1338                        { DOCS_FOOTER_SEP }
1339                    }
1340                }
1341            });
1342        }
1343        let a11y_txt: String = if alt_txt.is_empty() {
1344            label.clone()
1345        } else {
1346            format!("{label} ({alt_txt})")
1347        };
1348        let icon_node_opt: Option<NodeId> = if !icon_url.is_empty() {
1349            let resolved_icon: String =
1350                resolve_markdown_asset_url(icon_url.as_str(), asset_base.as_str());
1351            if let Some(buf) = cached_network_image(&resolved_icon) {
1352                let ctx: Context = current_context();
1353                Some(ctx.get_scene().with_write(
1354                    |tree: &mut SceneTree| {
1355                        let mut computed_style: Style = Style::default();
1356                        computed_style
1357                            .get_mut_layout()
1358                            .set_width(Length::Px(14.0))
1359                            .set_height(Length::Px(14.0))
1360                            .set_flex_shrink(0.0);
1361                        tree.create_image(buf, computed_style)
1362                    },
1363                    NodeId::default(),
1364                ))
1365            } else {
1366                None
1367            }
1368        } else {
1369            None
1370        };
1371        let click_url: String = target_url.clone();
1372        let on_click_seg = move |_: &UiEvent| {
1373            if !click_url.is_empty() {
1374                if let Some(sig) = opened_url_sig {
1375                    let _: bool = sig.set_if_changed(click_url.clone());
1376                }
1377                #[cfg(target_arch = "wasm32")]
1378                open_browser_url(&click_url, true);
1379            }
1380        };
1381        let text_color: Color = palette.get_muted_foreground();
1382        row_children.push({
1383            let row_fourteenth_style: Style = style! {
1384                AlignItems::Center
1385                JustifyContent::Center
1386                Padding(Edges::symmetric(SPACE_XS, SPACE_SM))
1387                Radius(tokens.get_geometry().get_radius_sm())
1388                Gap(SPACE_XS)
1389                CursorIcon::Pointer
1390            };
1391            let text_sixth_style: Style = style! {
1392                FontSize(12.0)
1393                FontWeight::Normal
1394                TextColor(text_color)
1395                TextAlign::Center
1396                Selectable(true)
1397            };
1398            view! {
1399                row {
1400                    style: row_fourteenth_style
1401                    role: A11yRole::Link
1402                    a11y_label: a11y_txt
1403                    on_click: on_click_seg
1404                    if let Some(ic) = icon_node_opt {
1405                        { ic }
1406                    }
1407                    text {
1408                        style: text_sixth_style
1409                        { label }
1410                    }
1411                }
1412            }
1413        });
1414    }
1415    let column_group_beta_style: Style = style! {
1416        Width(Length::Percent(100.0))
1417        AlignItems::Center
1418        Gap(SPACE_SM)
1419        Padding(Edges::new(SPACE_MD, SPACE_MD, SPACE_SM, SPACE_MD))
1420    };
1421    let row_thirteenth_style: Style = style! {
1422        Width(Length::Percent(100.0))
1423        FlexWrap::Wrap
1424        JustifyContent::Center
1425        AlignItems::Center
1426        Gap(DOCS_FOOTER_SEP_GAP)
1427        Padding(Edges::symmetric(0.0, SPACE_SM))
1428    };
1429    view! {
1430        column {
1431            style: column_group_beta_style
1432            EuvDivider {
1433                tokens: tokens
1434            }
1435            row {
1436                style: row_thirteenth_style
1437                ..row_children
1438            }
1439        }
1440    }
1441}
1442
1443/// Renders a `home: true` landing page with hero banner, CTA buttons, stat KPI grid, feature cards, Markdown body, and `/api/page-artifacts` catalog.
1444///
1445/// # Arguments
1446///
1447/// - `&DocPage` - Home page carrying hero, actions, stats, features, and body Markdown.
1448/// - `&DocsViewerState` - Shared reactive viewer state.
1449/// - `ThemeTokens` - Active design tokens.
1450///
1451/// # Returns
1452///
1453/// - `NodeId` - Mounted landing page container node.
1454fn mount_doc_home_page(page: &DocPage, state: &DocsViewerState, tokens: ThemeTokens) -> NodeId {
1455    let palette: ThemePalette = tokens.get_palette();
1456    let hero_title: String = page
1457        .try_get_hero_text()
1458        .clone()
1459        .filter(|text_value: &String| !text_value.trim().is_empty())
1460        .unwrap_or_else(|| page.get_title().clone());
1461    let hero_sub: String = if !page.get_summary().trim().is_empty() {
1462        page.get_summary().clone()
1463    } else {
1464        state.get_site().get_tagline().clone()
1465    };
1466    let action_buttons: Vec<NodeId> = page
1467        .get_actions()
1468        .iter()
1469        .map(|act: &DocHomeAction| {
1470            let link_url: String = act.get_link().clone();
1471            let site_c: Rc<DocSite> = Rc::clone(state.get_site());
1472            let route_sig: Signal<String> = state.get_active_route();
1473            let toc_sig: Signal<String> = state.get_active_toc_slug();
1474            let on_act = move |_: &UiEvent| {
1475                navigate_doc_href(&link_url, &site_c, route_sig, toc_sig);
1476            };
1477            let variant: EuvButtonVariant = if act
1478                .get_kind()
1479                .eq_ignore_ascii_case(DOCS_HOME_ACTION_PRIMARY)
1480            {
1481                EuvButtonVariant::Primary
1482            } else {
1483                EuvButtonVariant::Outline
1484            };
1485            view! {
1486                EuvButton {
1487                    label: act.get_text().clone()
1488                    variant: variant
1489                    tokens: tokens
1490                    on_click: on_act
1491                }
1492            }
1493        })
1494        .collect();
1495    let stat_cards: Vec<NodeId> = page
1496        .get_stats()
1497        .iter()
1498        .map(|stat_item: &DocHomeStat| {
1499            let label_str: String = if stat_item.get_icon().is_empty() {
1500                stat_item.get_label().clone()
1501            } else {
1502                format!("{} {}", stat_item.get_icon(), stat_item.get_label())
1503            };
1504            view! {
1505                EuvStatCard {
1506                    label: label_str
1507                    value: stat_item.get_value().clone()
1508                    caption: String::new()
1509                    tokens: tokens
1510                }
1511            }
1512        })
1513        .collect();
1514    let feature_cards: Vec<NodeId> = page
1515        .get_features()
1516        .iter()
1517        .map(|feat: &DocHomeFeature| {
1518            let link_url: String = feat.get_link().trim().to_string();
1519            let has_link: bool = !link_url.is_empty();
1520            let opened_sig: Signal<String> = state.get_last_opened_url();
1521            let feat_title: String = feat.get_title().clone();
1522            let card_hov: Signal<bool> = Signal::new(false);
1523            let on_feat_enter = move |_: &UiEvent| {
1524                if has_link {
1525                    let _: bool = card_hov.set_if_changed(true);
1526                }
1527            };
1528            let on_feat_leave = move |_: &UiEvent| {
1529                let _: bool = card_hov.set_if_changed(false);
1530            };
1531            let on_open_feat = move |_: &UiEvent| {
1532                if !has_link {
1533                    return;
1534                }
1535                let _: bool = opened_sig.set_if_changed(link_url.clone());
1536                #[cfg(target_arch = "wasm32")]
1537                open_browser_url(&link_url, true);
1538            };
1539            let feat_wrap_style = move || -> Style {
1540                let tok: ThemeTokens = use_live_tokens(tokens);
1541                let lp: ThemePalette = tok.get_palette();
1542                let lg: ThemeGeometry = tok.get_geometry();
1543                let hovered: bool = has_link && card_hov.get();
1544                let wrap_bg: Color = if hovered {
1545                    lp.get_accent().with_alpha(96)
1546                } else {
1547                    COLOR_TRANSPARENT
1548                };
1549                style! {
1550                    FlexDirection::Column
1551                    Width(Length::Percent(100.0))
1552                    if has_link {
1553                        Padding(Edges::all(SPACE_XS))
1554                    } else {
1555                        Padding(Edges::all(0.0))
1556                    }
1557                    Radius(lg.get_radius_lg() + if has_link { SPACE_XS } else { 0.0 })
1558                    Background(wrap_bg)
1559                    Overflow::Hidden
1560                    if has_link {
1561                        CursorIcon::Pointer
1562                    } else {
1563                        CursorIcon::Default
1564                    }
1565                }
1566            };
1567            let text_fifth_style: Style = style! {
1568                Width(Length::Percent(100.0))
1569                FontSize(13.0)
1570                TextColor(palette.get_muted_foreground())
1571                Selectable(true)
1572            };
1573            view! {
1574                column {
1575                    bind_style: feat_wrap_style
1576                    role: if has_link { A11yRole::Link } else { A11yRole::Group }
1577                    a11y_label: feat_title.clone()
1578                    on_click: on_open_feat
1579                    on_pointer_enter: on_feat_enter
1580                    on_pointer_leave: on_feat_leave
1581                    EuvCard {
1582                        title: feat_title
1583                        tokens: tokens
1584                        text {
1585                            style: text_fifth_style
1586                            { feat.get_details().clone() }
1587                        }
1588                    }
1589                }
1590            }
1591        })
1592        .collect();
1593    let site_for_link: Rc<DocSite> = Rc::clone(state.get_site());
1594    let route_for_link: Signal<String> = state.get_active_route();
1595    let toc_for_link: Signal<String> = state.get_active_toc_slug();
1596    let asset_base: String = state.asset_base();
1597    let md_body: NodeId = if !page.get_markdown_body().trim().is_empty() {
1598        EuvMarkdown::new(page.get_markdown_body().clone(), tokens)
1599            .style(style! {
1600                TextSelectMode::SelectAndCopy
1601            })
1602            .asset_base(asset_base)
1603            .on_link(move |url: &str| {
1604                navigate_doc_href(url, &site_for_link, route_for_link, toc_for_link);
1605            })
1606            .mount()
1607    } else {
1608        let column_group_alpha_style: Style = style! {
1609            Width(Length::Percent(100.0))
1610        };
1611        view! {
1612            column {
1613                style: column_group_alpha_style
1614            }
1615        }
1616    };
1617    let catalog_node: NodeId = mount_docs_catalog(state, tokens);
1618    let (prev_opt, next_opt): (Option<EuvDocPagerLink>, Option<EuvDocPagerLink>) =
1619        state.pager_links_for_route(page.get_route());
1620    let pager_route: Signal<String> = state.get_active_route();
1621    let pager_node: NodeId = EuvDocPager::new(prev_opt, next_opt, pager_route, tokens)
1622        .prev_label(state.get_site().resolved_prev_label())
1623        .next_label(state.get_site().resolved_next_label())
1624        .mount();
1625    let footer_node: NodeId = mount_docs_footer(state.get_site(), tokens);
1626    let mut action_row: EuvActionRow = EuvActionRow::new();
1627    for button_node in action_buttons.into_iter() {
1628        action_row = action_row.child(button_node);
1629    }
1630    let action_bar: NodeId = action_row.mount();
1631    let mut stat_grid_builder: EuvStatGrid = EuvStatGrid::new();
1632    for card in stat_cards.into_iter() {
1633        stat_grid_builder = stat_grid_builder.card(card);
1634    }
1635    let stat_grid: NodeId = stat_grid_builder.mount();
1636    let hero_brand_logo: ImageBuffer = euv_brand_logo_image();
1637    let geometry: ThemeGeometry = tokens.get_geometry();
1638    let column_eighteenth_style: Style = style! {
1639        Width(Length::Percent(100.0))
1640        Gap(SPACE_LG)
1641    };
1642    let row_eleventh_style: Style = style! {
1643        Width(Length::Percent(100.0))
1644        AlignItems::Center
1645        Gap(SPACE_MD)
1646    };
1647    let row_twelfth_style: Style = style! {
1648        Width(Length::Px(44.0))
1649        Height(Length::Px(44.0))
1650        FlexShrink(0.0)
1651        Radius(geometry.get_radius_md())
1652        Background(palette.get_background())
1653        Border::new(geometry.get_border_width(), palette.get_border())
1654        JustifyContent::Center
1655        AlignItems::Center
1656        Overflow::Hidden
1657    };
1658    let image_style: Style = style! {
1659        Width(Length::Px(40.0))
1660        Height(Length::Px(40.0))
1661    };
1662    let column_nineteenth_style: Style = style! {
1663        FlexGrow(1.0)
1664        FlexShrink(1.0)
1665        MinWidth(Length::Px(0.0))
1666        Gap(SPACE_XS)
1667    };
1668    let text_tertiary_style: Style = style! {
1669        Width(Length::Percent(100.0))
1670        FontSize(20.0)
1671        FontWeight::SemiBold
1672        TextColor(palette.get_foreground())
1673    };
1674    let text_quaternary_style: Style = style! {
1675        Width(Length::Percent(100.0))
1676        FontSize(13.5)
1677        FontWeight::Normal
1678        TextColor(palette.get_muted_foreground())
1679    };
1680    let column_twentieth_style: Style = style! {
1681        Width(Length::Percent(100.0))
1682        Gap(SPACE_SM)
1683    };
1684    let grid_style: Style = style! {
1685        GridColumns(2)
1686        Width(Length::Percent(100.0))
1687        Gap(SPACE_SM)
1688    };
1689    view! {
1690        column {
1691            style: column_eighteenth_style
1692            EuvCard {
1693                title: String::new()
1694                tokens: tokens
1695                row {
1696                    style: row_eleventh_style
1697                    row {
1698                        style: row_twelfth_style
1699                        image {
1700                            source: hero_brand_logo
1701                            style: image_style
1702                        }
1703                    }
1704                    column {
1705                        style: column_nineteenth_style
1706                        text {
1707                            style: text_tertiary_style
1708                            { hero_title }
1709                        }
1710                        if !hero_sub.trim().is_empty() {
1711                            text {
1712                                style: text_quaternary_style
1713                                { hero_sub }
1714                            }
1715                        }
1716                    }
1717                }
1718                if !page.get_actions().is_empty() {
1719                    { action_bar }
1720                }
1721            }
1722            if !page.get_stats().is_empty() {
1723                { stat_grid }
1724            }
1725            if !feature_cards.is_empty() {
1726                column {
1727                    style: column_twentieth_style
1728                    EuvHeader {
1729                        title: DOCS_HOME_FEATURES_TITLE.to_string()
1730                        subtitle: String::new()
1731                        tokens: tokens
1732                    }
1733                    grid {
1734                        style: grid_style
1735                        ..feature_cards
1736                    }
1737                }
1738            }
1739            { md_body }
1740            { catalog_node }
1741            { pager_node }
1742            { footer_node }
1743        }
1744    }
1745}
1746
1747/// Finds the nearest enclosing `ScrollView` ancestor of `node_id` in `tree`.
1748///
1749/// # Arguments
1750///
1751/// - `&SceneTree` - Active scene graph.
1752/// - `NodeId` - Starting descendant node.
1753///
1754/// # Returns
1755///
1756/// - `Option<NodeId>` - Enclosing scroll container handle when present.
1757fn find_enclosing_scroll_view(tree: &SceneTree, node_id: NodeId) -> Option<NodeId> {
1758    let mut cur: Option<NodeId> = tree.get_node(node_id).and_then(SceneNode::parent_id);
1759    while let Some(pid) = cur {
1760        if let Some(item_count) = tree.get_node(pid) {
1761            if matches!(item_count.get_kind(), NodeKind::ScrollView) {
1762                return Some(pid);
1763            }
1764            cur = item_count.parent_id();
1765        } else {
1766            break;
1767        }
1768    }
1769    None
1770}
1771
1772/// Resets vertical scroll offset to `0.0` on the active visible scroll view inside `root`.
1773///
1774/// # Arguments
1775///
1776/// - `&mut SceneTree` - Mutable scene graph.
1777/// - `NodeId` - Subtree root to search.
1778fn reset_active_scroll_in_subtree(tree: &mut SceneTree, root: NodeId) {
1779    let mut stack: Vec<NodeId> = vec![root];
1780    while let Some(nid) = stack.pop() {
1781        let Some(node) = tree.get_node(nid) else {
1782            continue;
1783        };
1784        if node.style_ref().get_layout().get_display() == Display::None {
1785            continue;
1786        }
1787        if matches!(node.get_kind(), NodeKind::ScrollView) {
1788            let cur: Point = node.get_layout_box().get_scroll_offset();
1789            if cur.get_y().abs() > 0.5 || cur.get_x().abs() > 0.5 {
1790                tree.set_scroll_offset(nid, Point::new(0.0, 0.0));
1791                tree.mark_dirty(nid, DIRTY_PAINT);
1792            }
1793        }
1794        for child in tree.children_vec(nid).into_iter() {
1795            stack.push(child);
1796        }
1797    }
1798}
1799
1800/// Normalizes a heading title for resilient TOC-to-scene matching (case-insensitive, stripped of inline code ticks and collapsed whitespace).
1801///
1802/// # Arguments
1803///
1804/// - `&str` - Raw heading title string.
1805///
1806/// # Returns
1807///
1808/// - `String` - Normalized lowercase heading comparison key.
1809#[must_use]
1810fn normalize_heading_match_key(raw: &str) -> String {
1811    let mut out: String = String::with_capacity(raw.len());
1812    let mut prev_space: bool = true;
1813    for ch in raw.chars() {
1814        if ch == '`' {
1815            continue;
1816        }
1817        if ch.is_whitespace() {
1818            if !prev_space {
1819                out.push(' ');
1820                prev_space = true;
1821            }
1822        } else {
1823            for low in ch.to_lowercase() {
1824                out.push(low);
1825            }
1826            prev_space = false;
1827        }
1828    }
1829    if out.ends_with(' ') {
1830        let _: Option<char> = out.pop();
1831    }
1832    out
1833}
1834
1835/// Resolves every TOC heading's exact content-space vertical coordinate `content_y = heading_rect.y - scroll_rect.y + cur_scroll_y` in document order.
1836///
1837/// # Arguments
1838///
1839/// - `&SceneTree` - Laid-out scene graph.
1840/// - `NodeId` - Mounted document Markdown body root handle.
1841/// - `NodeId` - Enclosing page `NodeKind::ScrollView` handle.
1842/// - `&[DocTocItem]` - Ordered page table-of-contents heading descriptors.
1843///
1844/// # Returns
1845///
1846/// - `Vec<(String, f32)>` - Matched `(slug, content_y)` pairs in canonical document order.
1847fn resolve_toc_heading_positions(
1848    tree: &SceneTree,
1849    body_root: NodeId,
1850    scroll_id: NodeId,
1851    toc_items: &[DocTocItem],
1852) -> Vec<(String, f32)> {
1853    if toc_items.is_empty() {
1854        return Vec::new();
1855    }
1856    let Some(scroll_rect) = tree.node_screen_bounds(scroll_id) else {
1857        return Vec::new();
1858    };
1859    if scroll_rect.get_height() < 2.0 {
1860        return Vec::new();
1861    }
1862    let cur_scroll_y: f32 = tree
1863        .get_node(scroll_id)
1864        .map(|scene_node: &SceneNode| {
1865            scene_node
1866                .get_layout_box()
1867                .get_scroll_offset()
1868                .get_y()
1869                .max(0.0)
1870        })
1871        .unwrap_or(0.0);
1872    let mut rendered_headings: Vec<(String, f32)> = Vec::new();
1873    let mut stack: Vec<NodeId> = vec![body_root];
1874    while let Some(nid) = stack.pop() {
1875        let Some(node) = tree.get_node(nid) else {
1876            continue;
1877        };
1878        if node.style_ref().get_layout().get_display() == Display::None {
1879            continue;
1880        }
1881        if let Some(a11y) = node.a11y_props_ref()
1882            && a11y.get_role() == A11yRole::Heading
1883            && let Some(bounds) = tree.node_screen_bounds(nid)
1884            && bounds.get_height() > 1.0
1885        {
1886            let content_y: f32 = (bounds.get_y() - scroll_rect.get_y() + cur_scroll_y).max(0.0);
1887            rendered_headings.push((
1888                normalize_heading_match_key(a11y.get_label().as_str()),
1889                content_y,
1890            ));
1891            continue;
1892        }
1893        if let NodeKind::Text(txt) = node.get_kind()
1894            && node.style_ref().get_text().get_font_size() >= 15.0
1895            && let Some(bounds) = tree.node_screen_bounds(nid)
1896            && bounds.get_height() > 1.0
1897        {
1898            let content_y: f32 = (bounds.get_y() - scroll_rect.get_y() + cur_scroll_y).max(0.0);
1899            rendered_headings.push((normalize_heading_match_key(txt.as_str()), content_y));
1900        }
1901        let children: Vec<NodeId> = tree.children_vec(nid);
1902        for child in children.into_iter().rev() {
1903            stack.push(child);
1904        }
1905    }
1906    let mut matched: Vec<(String, f32)> = Vec::with_capacity(toc_items.len());
1907    let mut search_from: usize = 0;
1908    for item in toc_items.iter() {
1909        let needle: String = normalize_heading_match_key(item.get_title().as_str());
1910        if needle.is_empty() {
1911            continue;
1912        }
1913        let mut found_pos: Option<(usize, f32)> = None;
1914        for (idx, (txt, cy)) in rendered_headings.iter().enumerate().skip(search_from) {
1915            if txt == &needle {
1916                found_pos = Some((idx, *cy));
1917                break;
1918            }
1919        }
1920        if found_pos.is_none() {
1921            for (idx, (txt, cy)) in rendered_headings.iter().enumerate().skip(search_from) {
1922                if txt.contains(&needle) || needle.contains(txt.as_str()) {
1923                    found_pos = Some((idx, *cy));
1924                    break;
1925                }
1926            }
1927        }
1928        if let Some((idx, cy)) = found_pos {
1929            search_from = idx + 1;
1930            matched.push((item.get_slug().clone(), cy));
1931        }
1932    }
1933    matched
1934}
1935
1936/// Scrolls the enclosing `ScrollView` to the exact `content_y` resolved for `target_slug`, returning the clamped scroll Y actually applied.
1937///
1938/// # Arguments
1939///
1940/// - `&mut SceneTree` - Mutable scene graph.
1941/// - `NodeId` - Mounted document body root.
1942/// - `NodeId` - Enclosing page `NodeKind::ScrollView` handle.
1943/// - `&[DocTocItem]` - Ordered page table-of-contents descriptors.
1944/// - `&str` - Target TOC heading anchor slug.
1945///
1946/// # Returns
1947///
1948/// - `Option<f32>` - Applied clamped `scroll_y` offset when the heading resolved in layout.
1949fn scroll_doc_to_toc_slug(
1950    tree: &mut SceneTree,
1951    body_root: NodeId,
1952    scroll_id: NodeId,
1953    toc_items: &[DocTocItem],
1954    target_slug: &str,
1955) -> Option<f32> {
1956    let scroll_bounds: Rect = tree.node_screen_bounds(scroll_id)?;
1957    if scroll_bounds.get_height() < 2.0 {
1958        return None;
1959    }
1960    let positions: Vec<(String, f32)> =
1961        resolve_toc_heading_positions(tree, body_root, scroll_id, toc_items);
1962    let content_y: f32 = positions
1963        .iter()
1964        .find(|(slug, _): &&(String, f32)| slug == target_slug)
1965        .map(|(_, cy): &(String, f32)| *cy)?;
1966    let (cur_scroll, content_h, scroll_view_h): (Point, f32, f32) = tree
1967        .get_node(scroll_id)
1968        .map(|scene_node: &SceneNode| {
1969            let layout_box: LayoutBox = scene_node.get_layout_box();
1970            let inner_h: f32 = layout_box.get_content_bounds().get_height();
1971            let resolved_h: f32 = if inner_h > 1.0 {
1972                inner_h
1973            } else {
1974                scroll_bounds.get_height()
1975            };
1976            (
1977                layout_box.get_scroll_offset(),
1978                layout_box.get_content_size().get_height(),
1979                resolved_h,
1980            )
1981        })
1982        .unwrap_or((Point::default(), 0.0, scroll_bounds.get_height()));
1983    let max_scroll: f32 = (content_h - scroll_view_h).max(0.0);
1984    let target_y: f32 = (content_y - 16.0).clamp(0.0, max_scroll);
1985    tree.set_scroll_offset(scroll_id, Point::new(cur_scroll.get_x(), target_y));
1986    tree.mark_dirty(scroll_id, DIRTY_PAINT);
1987    Some(target_y)
1988}
1989
1990/// Ensures `target_id` sits comfortably inside the visible viewport of `scroll_id`, scrolling only when outside the inset band.
1991///
1992/// # Arguments
1993///
1994/// - `&mut SceneTree` - Mutable scene graph with computed layout bounds.
1995/// - `NodeId` - Enclosing `NodeKind::ScrollView` handle.
1996/// - `NodeId` - Descendant item handle to bring into view.
1997/// - `f32` - Minimum vertical breathing margin in logical pixels.
1998///
1999/// # Returns
2000///
2001/// - `bool` - `true` when layout bounds were valid and visibility was verified or adjusted.
2002fn scroll_node_into_scroll_view(
2003    tree: &mut SceneTree,
2004    scroll_id: NodeId,
2005    target_id: NodeId,
2006    margin: f32,
2007) -> bool {
2008    if !tree.is_node_visible(scroll_id) || !tree.is_node_visible(target_id) {
2009        return false;
2010    }
2011    let Some(scroll_rect) = tree.node_screen_bounds(scroll_id) else {
2012        return false;
2013    };
2014    let Some(target_rect) = tree.node_screen_bounds(target_id) else {
2015        return false;
2016    };
2017    let item_h: f32 = target_rect.get_height();
2018    let (cur_off, content_h, inner_top_pad, view_h): (Point, f32, f32, f32) =
2019        match tree.get_node(scroll_id) {
2020            Some(scroll_node) => {
2021                let layout_box: LayoutBox = scroll_node.get_layout_box();
2022                let outer_bounds: Rect = layout_box.get_bounds();
2023                let inner_bounds: Rect = layout_box.get_content_bounds();
2024                let top_pad: f32 = (inner_bounds.get_y() - outer_bounds.get_y()).max(0.0);
2025                let resolved_h: f32 = if inner_bounds.get_height() > 1.0 {
2026                    inner_bounds.get_height()
2027                } else {
2028                    scroll_rect.get_height()
2029                };
2030                (
2031                    layout_box.get_scroll_offset(),
2032                    layout_box.get_content_size().get_height(),
2033                    top_pad,
2034                    resolved_h,
2035                )
2036            }
2037            None => return false,
2038        };
2039    if view_h < 2.0 || item_h < 1.0 {
2040        return false;
2041    }
2042    let max_scroll: f32 = (content_h - view_h).max(0.0);
2043    if max_scroll <= 0.5 {
2044        return true;
2045    }
2046    let view_top: f32 = scroll_rect.get_y() + inner_top_pad;
2047    let eff_margin: f32 = margin.min((view_h - item_h).max(0.0) * 0.4);
2048    let safe_top: f32 = view_top + eff_margin;
2049    let safe_bottom: f32 = view_top + view_h - eff_margin;
2050    let item_top: f32 = target_rect.get_y();
2051    let item_bottom: f32 = item_top + item_h;
2052    if item_top >= safe_top && item_bottom <= safe_bottom {
2053        return true;
2054    }
2055    let rel_top: f32 = cur_off.get_y() + (item_top - view_top);
2056    let centered: f32 = (rel_top - (view_h - item_h) * 0.5).clamp(0.0, max_scroll);
2057    if (centered - cur_off.get_y()).abs() > 0.5 {
2058        tree.set_scroll_offset(scroll_id, Point::new(cur_off.get_x(), centered));
2059        tree.mark_dirty(scroll_id, DIRTY_PAINT);
2060    }
2061    true
2062}
2063
2064/// Computes the currently active TOC heading slug matching the live scroll position of `body_root` inside `scroll_id`.
2065///
2066/// # Arguments
2067///
2068/// - `&SceneTree` - Laid-out scene graph.
2069/// - `NodeId` - Mounted document Markdown body root handle.
2070/// - `NodeId` - Enclosing page `NodeKind::ScrollView` handle.
2071/// - `&[DocTocItem]` - Ordered page table-of-contents heading descriptors.
2072///
2073/// # Returns
2074///
2075/// - `Option<String>` - Active heading slug closest to the reading viewport top.
2076fn compute_active_toc_slug_for_scroll(
2077    tree: &SceneTree,
2078    body_root: NodeId,
2079    scroll_id: NodeId,
2080    toc_items: &[DocTocItem],
2081) -> Option<String> {
2082    if toc_items.is_empty() {
2083        return None;
2084    }
2085    let scroll_rect: Rect = tree.node_screen_bounds(scroll_id)?;
2086    if scroll_rect.get_height() < 2.0 {
2087        return toc_items
2088            .first()
2089            .map(|it: &DocTocItem| it.get_slug().clone());
2090    }
2091    let (cur_y, content_h, scroll_view_h): (f32, f32, f32) = tree
2092        .get_node(scroll_id)
2093        .map(|scene_node: &SceneNode| {
2094            let layout_box: LayoutBox = scene_node.get_layout_box();
2095            let inner_h: f32 = layout_box.get_content_bounds().get_height();
2096            let resolved_h: f32 = if inner_h > 1.0 {
2097                inner_h
2098            } else {
2099                scroll_rect.get_height()
2100            };
2101            (
2102                layout_box.get_scroll_offset().get_y().max(0.0),
2103                layout_box.get_content_size().get_height(),
2104                resolved_h,
2105            )
2106        })
2107        .unwrap_or((0.0, 0.0, scroll_rect.get_height()));
2108    let max_scroll: f32 = (content_h - scroll_view_h).max(0.0);
2109    if max_scroll > 8.0 && cur_y >= max_scroll - 4.0 {
2110        return toc_items
2111            .last()
2112            .map(|it: &DocTocItem| it.get_slug().clone());
2113    }
2114    let positions: Vec<(String, f32)> =
2115        resolve_toc_heading_positions(tree, body_root, scroll_id, toc_items);
2116    let threshold_content_y: f32 = cur_y + 24.0;
2117    let mut active: Option<String> = None;
2118    for (slug, content_y) in positions.into_iter() {
2119        if content_y <= threshold_content_y {
2120            active = Some(slug);
2121        }
2122    }
2123    active.or_else(|| {
2124        toc_items
2125            .first()
2126            .map(|it: &DocTocItem| it.get_slug().clone())
2127    })
2128}
2129
2130/// Attaches a non-destructive scroll observer to every child `NodeKind::ScrollView` inside `outlet_host` so page scrolling pulses `scroll_tick`.
2131///
2132/// # Arguments
2133///
2134/// - `&SceneHandle` - Shared scene handle.
2135/// - `NodeId` - Mounted `EuvRouterOutlet` root container handle.
2136/// - `&Rc<RefCell<Vec<NodeId>>>` - Registry of already-hooked page scroll view handles.
2137/// - `Signal<u64>` - Monotonic scroll tick signal pulsed on every page scroll event.
2138fn hook_outlet_page_scrolls(
2139    scene: &SceneHandle,
2140    outlet_host: NodeId,
2141    hooked: &Rc<RefCell<Vec<NodeId>>>,
2142    scroll_tick: Signal<u64>,
2143) {
2144    if outlet_host == NodeId::default() {
2145        return;
2146    }
2147    scene.with_write(
2148        |tree: &mut SceneTree| {
2149            let kids: Vec<NodeId> = tree.children_vec(outlet_host);
2150            for kid in kids.into_iter() {
2151                let already: bool = hooked
2152                    .try_borrow()
2153                    .ok()
2154                    .map(|list: Ref<'_, Vec<NodeId>>| list.contains(&kid))
2155                    .unwrap_or(false);
2156                if already {
2157                    continue;
2158                }
2159                let is_scroll: bool = tree
2160                    .get_node(kid)
2161                    .map(|scene_node: &SceneNode| {
2162                        matches!(scene_node.get_kind(), NodeKind::ScrollView)
2163                    })
2164                    .unwrap_or(false);
2165                if !is_scroll {
2166                    continue;
2167                }
2168                if let Some(wn) = tree.get_node_mut(kid) {
2169                    let prev_handler: Option<UiEventHandler> = wn
2170                        .get_handlers()
2171                        .handler_for(&UiEventKind::Scroll(Point::default()));
2172                    let wrapped: UiEventHandler =
2173                        Rc::new(RefCell::new(move |ui_event: &UiEvent| {
2174                            if let Some(prev) = prev_handler.as_ref()
2175                                && let Ok(mut factor_val) = prev.try_borrow_mut()
2176                            {
2177                                factor_val(ui_event);
2178                            }
2179                            let _: bool = {
2180                                if let Some(mut updated_value) = scroll_tick.try_get_untracked() {
2181                                    {
2182                                        let item_val: &mut u64 = &mut updated_value;
2183                                        *item_val = item_val.wrapping_add(1);
2184                                    }
2185                                    scroll_tick.set(updated_value)
2186                                } else {
2187                                    false
2188                                }
2189                            };
2190                        }));
2191                    wn.get_mut_handlers().set_on_scroll(Some(wrapped));
2192                    if let Ok(mut list) = hooked.try_borrow_mut() {
2193                        list.push(kid);
2194                    }
2195                }
2196            }
2197        },
2198        (),
2199    );
2200}
2201
2202/// Aligns the left-sidebar active catalog row into viewport bounds and refreshes sticky TOC / ScrollSpy after layout completes.
2203///
2204/// # Arguments
2205///
2206/// - `&DocsViewerState` - Shared documentation viewer state.
2207/// - `&SceneHandle` - Laid-out scene graph handle.
2208pub(crate) fn sync_docs_post_layout_positions(state: &DocsViewerState, scene: &SceneHandle) {
2209    let cur_route: String = state.get_active_route().get_untracked();
2210    let target_row_opt: Option<NodeId> = state.get_catalog_row_nodes().try_borrow().ok().and_then(
2211        |map: Ref<'_, HashMap<String, NodeId>>| {
2212            if let Some(&nid) = map.get(&cur_route) {
2213                return Some(nid);
2214            }
2215            let mut prefix: &str = cur_route.as_str();
2216            while let Some((head, _)) = prefix.rsplit_once('/') {
2217                if head.is_empty() {
2218                    break;
2219                }
2220                if let Some(&nid) = map.get(head) {
2221                    return Some(nid);
2222                }
2223                prefix = head;
2224            }
2225            None
2226        },
2227    );
2228    if let Some(row_id) = target_row_opt {
2229        scene.with_write(
2230            |tree: &mut SceneTree| {
2231                if let Some(scroll_id) = find_enclosing_scroll_view(tree, row_id) {
2232                    let _: bool = scroll_node_into_scroll_view(tree, scroll_id, row_id, 24.0);
2233                }
2234            },
2235            (),
2236        );
2237    }
2238    let _: bool = {
2239        if let Some(mut updated_value) = (state.get_scroll_tick()).try_get_untracked() {
2240            {
2241                let item_val: &mut u64 = &mut updated_value;
2242                *item_val = item_val.wrapping_add(1);
2243            }
2244            (state.get_scroll_tick()).set(updated_value)
2245        } else {
2246            false
2247        }
2248    };
2249}
2250
2251/// Recursively mounts one nested tree-structured TOC branch with vertical guide hairlines, collapsible sub-branches, and active heading accent.
2252///
2253/// # Arguments
2254///
2255/// - `&DocTocTreeNode` - Tree heading node.
2256/// - `usize` - Zero-based nesting depth inside the TOC tree.
2257/// - `Signal<String>` - Active heading anchor slug signal.
2258/// - `DocTocPickCallback` - Callback invoked with `(slug, title)` when a heading entry is clicked.
2259/// - `Option<&Rc<RefCell<HashMap<String, NodeId>>>>` - Optional registry recording `(slug -> row_id)` for auto-scrolling the active TOC entry into view.
2260/// - `ThemeTokens` - Base design tokens.
2261///
2262/// # Returns
2263///
2264/// - `NodeId` - Mounted TOC tree branch node.
2265fn mount_docs_toc_tree_branch(
2266    node: &DocTocTreeNode,
2267    depth: usize,
2268    active_slug: Signal<String>,
2269    on_pick: DocTocPickCallback,
2270    row_registry: Option<&Rc<RefCell<HashMap<String, NodeId>>>>,
2271    tokens: ThemeTokens,
2272) -> NodeId {
2273    let has_children: bool = !node.get_children().is_empty();
2274    let slug_owned: String = node.get_item().get_slug().clone();
2275    let title_owned: String = node.get_item().get_title().clone();
2276    let expanded_sig: Signal<bool> = Signal::new(true);
2277    let hovered_sig: Signal<bool> = Signal::new(false);
2278    let slug_for_style: String = slug_owned.clone();
2279    let row_style = move || -> Style {
2280        let tok: ThemeTokens = use_live_tokens(tokens);
2281        let lp: ThemePalette = tok.get_palette();
2282        let lg: ThemeGeometry = tok.get_geometry();
2283        let is_active: bool = active_slug.get() == slug_for_style;
2284        let is_hov: bool = hovered_sig.get();
2285        let bg: Color = if is_active {
2286            lp.surface(SurfaceRole::Accent).get_bg()
2287        } else if is_hov {
2288            lp.get_muted()
2289        } else {
2290            COLOR_TRANSPARENT
2291        };
2292        style! {
2293            FlexDirection::Row
2294            Width(Length::Percent(100.0))
2295            MinHeight(Length::Px(28.0))
2296            AlignItems::Center
2297            Gap(SPACE_XS)
2298            Padding(Edges::symmetric(4.0, SPACE_SM))
2299            Background(bg)
2300            Radius(lg.get_radius_sm())
2301            Overflow::Hidden
2302            CursorIcon::Pointer
2303        }
2304    };
2305    let slug_for_bar: String = slug_owned.clone();
2306    let bar_style = move || -> Style {
2307        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
2308        let is_active: bool = active_slug.get() == slug_for_bar;
2309        style! {
2310            Width(Length::Px(2.0))
2311            Height(Length::Px(14.0))
2312            FlexShrink(0.0)
2313            Radius(RADIUS_PILL)
2314            Background(if is_active {
2315                lp.get_primary()
2316                } else {
2317                    COLOR_TRANSPARENT
2318            })
2319        }
2320    };
2321    let slug_for_txt: String = slug_owned.clone();
2322    let txt_style = move || -> Style {
2323        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
2324        let is_active: bool = active_slug.get() == slug_for_txt;
2325        let fg: Color = if is_active {
2326            lp.get_primary()
2327        } else if depth == 0 {
2328            lp.get_foreground()
2329        } else {
2330            lp.get_muted_foreground()
2331        };
2332        let mut computed_style: Style = style! {
2333            FlexGrow(1.0)
2334            FlexShrink(1.0)
2335            MinWidth(Length::Px(0.0))
2336            FontSize(if depth == 0 { 12.5 } else { 12.0 })
2337            if is_active {
2338                FontWeight::Medium
2339            } else {
2340                FontWeight::Normal
2341            }
2342            TextColor(fg)
2343            Overflow::Hidden
2344            TextOverflow::Ellipsis
2345        };
2346        computed_style.get_mut_text().set_line_height(1.25);
2347        computed_style
2348    };
2349    let slug_for_click: String = slug_owned.clone();
2350    let title_for_click: String = title_owned.clone();
2351    let pick_cb: DocTocPickCallback = Rc::clone(&on_pick);
2352    let on_row_click = move |_: &UiEvent| {
2353        let _: bool = active_slug.set_if_changed(slug_for_click.clone());
2354        pick_cb(&slug_for_click, &title_for_click);
2355    };
2356    let on_row_enter = move |_: &UiEvent| {
2357        let _: bool = hovered_sig.set_if_changed(true);
2358    };
2359    let on_row_leave = move |_: &UiEvent| {
2360        let _: bool = hovered_sig.set_if_changed(false);
2361    };
2362    let on_toggle_branch = move |_: &UiEvent| {
2363        let _: bool = expanded_sig.set(!expanded_sig.get_untracked());
2364    };
2365    let paint_chev = move |bounds: Rect, display_list: &mut DisplayList| {
2366        let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
2367        draw_docs_tree_chevron(
2368            bounds,
2369            display_list,
2370            lp.get_muted_foreground(),
2371            expanded_sig.get_untracked(),
2372        );
2373    };
2374    let mut row_node: NodeId = NodeId::default();
2375    let mut chev_canvas: NodeId = NodeId::default();
2376    let child_nodes: Vec<NodeId> = node
2377        .get_children()
2378        .iter()
2379        .map(|child: &DocTocTreeNode| {
2380            mount_docs_toc_tree_branch(
2381                child,
2382                depth + 1,
2383                active_slug,
2384                Rc::clone(&on_pick),
2385                row_registry,
2386                tokens,
2387            )
2388        })
2389        .collect();
2390    let child_wrap_style = move || -> Style {
2391        let is_open: bool = expanded_sig.get();
2392        style! {
2393            FlexDirection::Row
2394            if is_open {
2395                Display::Flex
2396            } else {
2397                Display::None
2398            }
2399            Width(Length::Percent(100.0))
2400            Padding(Edges::new(2.0, 0.0, 2.0, 8.0))
2401            Gap(SPACE_SM)
2402            AlignItems::Stretch
2403        }
2404    };
2405    let guide_line_style = move || -> Style {
2406        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
2407        style! {
2408            Width(Length::Px(1.0))
2409            FlexShrink(0.0)
2410            Background(lp.get_border())
2411        }
2412    };
2413    let column_sixteenth_style: Style = style! {
2414        Width(Length::Percent(100.0))
2415        Gap(1.0)
2416    };
2417    let row_tenth_style: Style = style! {
2418        Width(Length::Px(20.0))
2419        Height(Length::Px(20.0))
2420        Padding(Edges::all(SPACE_XS))
2421        Radius(tokens.get_geometry().get_radius_sm())
2422        FlexShrink(0.0)
2423        JustifyContent::Center
2424        AlignItems::Center
2425        CursorIcon::Pointer
2426        StopEventPropagation(true)
2427    };
2428    let canvas_eighth_style: Style = style! {
2429        Width(Length::Px(10.0))
2430        Height(Length::Px(10.0))
2431    };
2432    let column_seventeenth_style: Style = style! {
2433        FlexGrow(1.0)
2434        FlexShrink(1.0)
2435        MinWidth(Length::Px(0.0))
2436        Gap(1.0)
2437    };
2438    let branch: NodeId = view! {
2439        column {
2440            style: column_sixteenth_style
2441            row {
2442                node_ref: row_node
2443                bind_style: row_style
2444                role: A11yRole::Link
2445                a11y_label: title_owned.clone()
2446                on_click: on_row_click
2447                on_pointer_enter: on_row_enter
2448                on_pointer_leave: on_row_leave
2449                view {
2450                    bind_style: bar_style
2451                }
2452                text {
2453                    bind_style: txt_style
2454                    { title_owned }
2455                }
2456                if has_children {
2457                    row {
2458                        style: row_tenth_style
2459                        on_click: on_toggle_branch
2460                        canvas {
2461                            node_ref: chev_canvas
2462                            style: canvas_eighth_style
2463                            painter: paint_chev
2464                        }
2465                    }
2466                }
2467            }
2468            if has_children {
2469                row {
2470                    bind_style: child_wrap_style
2471                    view {
2472                        bind_style: guide_line_style
2473                    }
2474                    column {
2475                        style: column_seventeenth_style
2476                        ..child_nodes
2477                    }
2478                }
2479            }
2480        }
2481    };
2482    if let Some(reg) = row_registry
2483        && let Ok(mut map) = reg.try_borrow_mut()
2484    {
2485        let _: Option<NodeId> = map.insert(slug_owned, row_node);
2486    }
2487    if has_children {
2488        let ctx: Context = current_context();
2489        let scale_factor: SceneHandle = ctx.get_scene().clone();
2490        let (chev_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2491            Effect::new(move || {
2492                let _: bool = expanded_sig.get();
2493                let _: ThemeTokens = use_live_tokens(tokens);
2494                scale_factor.with_write(
2495                    |tree: &mut SceneTree| {
2496                        tree.mark_dirty(chev_canvas, DIRTY_PAINT);
2497                    },
2498                    (),
2499                );
2500            })
2501        });
2502        ctx.get_scene().with_write(
2503            |tree: &mut SceneTree| {
2504                tree.attach_scope(branch, chev_scope);
2505            },
2506            (),
2507        );
2508    }
2509    branch
2510}
2511
2512/// Mounts the tree-structured document TOC widget (`On This Page` / `本页目录`) with nested heading branches and optional collapsible header for compact viewports.
2513///
2514/// # Arguments
2515///
2516/// - `&[DocTocItem]` - Flat page heading items.
2517/// - `&str` - Localized TOC heading title.
2518/// - `Signal<String>` - Reactive active heading slug signal.
2519/// - `DocTocPickCallback` - Callback invoked with `(slug, title)` when a heading is clicked.
2520/// - `Option<&Rc<RefCell<HashMap<String, NodeId>>>>` - Optional registry recording `(slug -> row_id)` for auto-scrolling the active TOC entry into view.
2521/// - `ThemeTokens` - Base design tokens.
2522/// - `bool` - When `true`, renders with an interactive collapsed-by-default disclosure toggle for narrow screens.
2523///
2524/// # Returns
2525///
2526/// - `NodeId` - Mounted tree-structured TOC container.
2527fn mount_docs_tree_toc(
2528    items: &[DocTocItem],
2529    title: &str,
2530    active_slug: Signal<String>,
2531    on_pick: DocTocPickCallback,
2532    row_registry: Option<&Rc<RefCell<HashMap<String, NodeId>>>>,
2533    tokens: ThemeTokens,
2534    collapsible_card: bool,
2535) -> NodeId {
2536    let roots: Vec<DocTocTreeNode> = DocTocTreeNode::from_flat(items);
2537    let branches: Vec<NodeId> = roots
2538        .iter()
2539        .map(|node: &DocTocTreeNode| {
2540            mount_docs_toc_tree_branch(
2541                node,
2542                0,
2543                active_slug,
2544                Rc::clone(&on_pick),
2545                row_registry,
2546                tokens,
2547            )
2548        })
2549        .collect();
2550    let title_owned: String = title.to_string();
2551    let open_sig: Signal<bool> = Signal::new(!collapsible_card);
2552    let container_style = move || -> Style {
2553        let tok: ThemeTokens = use_live_tokens(tokens);
2554        let lp: ThemePalette = tok.get_palette();
2555        let lg: ThemeGeometry = tok.get_geometry();
2556        let card_s: SurfaceColors = lp.surface(SurfaceRole::Card);
2557        style! {
2558            FlexDirection::Column
2559            Width(Length::Percent(100.0))
2560            Padding(Edges::all(SPACE_MD))
2561            Gap(SPACE_XS)
2562            Background(card_s.get_bg())
2563            Border::new(lg.get_border_width(), card_s.get_border())
2564            Radius(lg.get_radius_md())
2565            Overflow::Hidden
2566        }
2567    };
2568    let header_txt_style = move || -> Style {
2569        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
2570        style! {
2571            FlexGrow(1.0)
2572            FlexShrink(1.0)
2573            MinWidth(Length::Px(0.0))
2574            FontSize(12.0)
2575            FontWeight::Medium
2576            TextColor(lp.get_foreground())
2577            Overflow::Hidden
2578            TextOverflow::Ellipsis
2579        }
2580    };
2581    let body_style = move || -> Style {
2582        let is_open: bool = open_sig.get();
2583        style! {
2584            FlexDirection::Column
2585            if is_open {
2586                Display::Flex
2587            } else {
2588                Display::None
2589            }
2590            Width(Length::Percent(100.0))
2591            Gap(2.0)
2592        }
2593    };
2594    let on_toggle_card = move |_: &UiEvent| {
2595        if collapsible_card {
2596            let _: bool = open_sig.set(!open_sig.get_untracked());
2597        }
2598    };
2599    let paint_hdr_chev = move |bounds: Rect, display_list: &mut DisplayList| {
2600        let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
2601        draw_docs_tree_chevron(
2602            bounds,
2603            display_list,
2604            lp.get_muted_foreground(),
2605            open_sig.get_untracked(),
2606        );
2607    };
2608    let mut hdr_chev: NodeId = NodeId::default();
2609    let row_ninth_style: Style = style! {
2610        Width(Length::Percent(100.0))
2611        if collapsible_card {
2612            Padding(Edges::symmetric(SPACE_XS, SPACE_SM))
2613        } else {
2614            Padding(Edges::all(0.0))
2615        }
2616        Radius(tokens.get_geometry().get_radius_sm())
2617        AlignItems::Center
2618        JustifyContent::SpaceBetween
2619        Gap(SPACE_XS)
2620        if collapsible_card { CursorIcon::Pointer } else { CursorIcon::Default }
2621    };
2622    let canvas_seventh_style: Style = style! {
2623        Width(Length::Px(12.0))
2624        Height(Length::Px(12.0))
2625        FlexShrink(0.0)
2626    };
2627    let toc_node: NodeId = view! {
2628        column {
2629            bind_style: container_style
2630            role: A11yRole::Navigation
2631            a11y_label: title_owned.clone()
2632            row {
2633                style: row_ninth_style
2634                on_click: on_toggle_card
2635                text {
2636                    bind_style: header_txt_style
2637                    { title_owned }
2638                }
2639                if collapsible_card {
2640                    canvas {
2641                        node_ref: hdr_chev
2642                        style: canvas_seventh_style
2643                        painter: paint_hdr_chev
2644                    }
2645                }
2646            }
2647            column {
2648                bind_style: body_style
2649                ..branches
2650            }
2651        }
2652    };
2653    if collapsible_card {
2654        let ctx: Context = current_context();
2655        let scale_factor: SceneHandle = ctx.get_scene().clone();
2656        let (hdr_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2657            Effect::new(move || {
2658                let _: bool = open_sig.get();
2659                let _: ThemeTokens = use_live_tokens(tokens);
2660                scale_factor.with_write(
2661                    |tree: &mut SceneTree| {
2662                        tree.mark_dirty(hdr_chev, DIRTY_PAINT);
2663                    },
2664                    (),
2665                );
2666            })
2667        });
2668        ctx.get_scene().with_write(
2669            |tree: &mut SceneTree| {
2670                tree.attach_scope(toc_node, hdr_scope);
2671            },
2672            (),
2673        );
2674    }
2675    toc_node
2676}
2677
2678/// Mounts a centered password unlock gate card for a password-protected documentation page or section.
2679///
2680/// # Arguments
2681///
2682/// - `&DocPage` - Protected documentation page.
2683/// - `&DocsViewerState` - Shared viewer state managing unlocked password secrets.
2684/// - `&str` - Required password string.
2685/// - `ThemeTokens` - Active design tokens.
2686///
2687/// # Returns
2688///
2689/// - `NodeId` - Mounted centered password unlock card.
2690fn mount_docs_password_gate(
2691    page: &DocPage,
2692    state: &DocsViewerState,
2693    secret: &str,
2694    tokens: ThemeTokens,
2695) -> NodeId {
2696    let is_zh: bool = state
2697        .get_site()
2698        .resolved_lang()
2699        .to_ascii_lowercase()
2700        .starts_with(DOCS_LANG_PREFIX_ZH);
2701    let title_str: String = format!(
2702        "{} · {}",
2703        if is_zh {
2704            DOCS_LOCK_TITLE_ZH
2705        } else {
2706            DOCS_LOCK_TITLE_EN
2707        },
2708        page.get_title()
2709    );
2710    let desc_str: &str = if is_zh {
2711        DOCS_LOCK_DESC_ZH
2712    } else {
2713        DOCS_LOCK_DESC_EN
2714    };
2715    let placeholder_str: &str = if is_zh {
2716        DOCS_LOCK_PLACEHOLDER_ZH
2717    } else {
2718        DOCS_LOCK_PLACEHOLDER_EN
2719    };
2720    let btn_str: &str = if is_zh {
2721        DOCS_LOCK_BTN_ZH
2722    } else {
2723        DOCS_LOCK_BTN_EN
2724    };
2725    let err_str: &str = if is_zh {
2726        DOCS_LOCK_ERR_ZH
2727    } else {
2728        DOCS_LOCK_ERR_EN
2729    };
2730    let input_sig: Signal<String> = Signal::new(String::new());
2731    let wrong_sig: Signal<bool> = Signal::new(false);
2732    let secret_owned: String = secret.to_string();
2733    let st_unlock: DocsViewerState = state.clone();
2734    let on_unlock = move |_: &UiEvent| {
2735        let attempt: String = input_sig.get_untracked();
2736        if st_unlock.try_unlock_password(&secret_owned, &attempt) {
2737            let _: bool = wrong_sig.set_if_changed(false);
2738        } else {
2739            let _: bool = wrong_sig.set_if_changed(true);
2740        }
2741    };
2742    let err_style = move || -> Style {
2743        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
2744        style! {
2745            if wrong_sig.get() {
2746                Display::Flex
2747            } else {
2748                Display::None
2749            }
2750            Width(Length::Percent(100.0))
2751            FontSize(12.0)
2752            TextColor(lp.get_destructive())
2753        }
2754    };
2755    let column_fourteenth_style: Style = style! {
2756        Width(Length::Percent(100.0))
2757        AlignItems::Center
2758        Padding(Edges::symmetric(SPACE_2XL, SPACE_MD))
2759    };
2760    let column_fifteenth_style: Style = style! {
2761        Width(Length::Percent(100.0))
2762        MaxWidth(Length::Px(420.0))
2763    };
2764    view! {
2765        column {
2766            style: column_fourteenth_style
2767            column {
2768                style: column_fifteenth_style
2769                EuvCard {
2770                    title: title_str
2771                    subtitle: desc_str
2772                    tokens: tokens
2773                    EuvInput {
2774                        value: input_sig
2775                        placeholder: placeholder_str.to_string()
2776                        tokens: tokens
2777                    }
2778                    text {
2779                        bind_style: err_style
2780                        { err_str }
2781                    }
2782                    EuvButton {
2783                        label: btn_str.to_string()
2784                        variant: EuvButtonVariant::Primary
2785                        tokens: tokens
2786                        on_click: on_unlock
2787                    }
2788                }
2789            }
2790        }
2791    }
2792}
2793
2794/// Renders a standard documentation article page purely from `euv-ui` components (`EuvBreadcrumb`, `EuvDocMetaBar`, `EuvHeader`, tree-structured sticky right `TOC`, `EuvMarkdown`, `EuvDivider`, `EuvDocPager`, centered `mount_docs_footer`), honoring password gates when configured.
2795///
2796/// # Arguments
2797///
2798/// - `&DocPage` - Documentation page to render.
2799/// - `&DocsViewerState` - Shared reactive viewer state for route, TOC, password unlock, and pager interactivity.
2800/// - `ThemeTokens` - Active design tokens.
2801///
2802/// # Returns
2803///
2804/// - `NodeId` - Mounted article page container node.
2805pub fn mount_doc_page_with_context(
2806    page: &DocPage,
2807    state: &DocsViewerState,
2808    tokens: ThemeTokens,
2809) -> NodeId {
2810    if page.get_is_home() {
2811        return mount_doc_home_page(page, state, tokens);
2812    }
2813    if let Some(secret) = page.try_get_password().as_deref()
2814        && !secret.trim().is_empty()
2815    {
2816        let page_owned: DocPage = page.clone();
2817        let state_owned: DocsViewerState = state.clone();
2818        let secret_owned: String = secret.trim().to_string();
2819        let unlocked_sig: Signal<Vec<String>> = state.get_unlocked_passwords();
2820        let build_gated = move || -> Vec<NodeId> {
2821            let live_tok: ThemeTokens = live_tokens_untracked(tokens);
2822            let unlocked: bool = unlocked_sig
2823                .get()
2824                .iter()
2825                .any(|text_value: &String| text_value.as_str() == secret_owned.as_str());
2826            if unlocked {
2827                vec![mount_unlocked_doc_article(
2828                    &page_owned,
2829                    &state_owned,
2830                    live_tok,
2831                )]
2832            } else {
2833                vec![mount_docs_password_gate(
2834                    &page_owned,
2835                    &state_owned,
2836                    &secret_owned,
2837                    live_tok,
2838                )]
2839            }
2840        };
2841        let column_thirteenth_style: Style = style! {
2842            Width(Length::Percent(100.0))
2843        };
2844        return view! {
2845            column {
2846                style: column_thirteenth_style
2847                bind_children: build_gated
2848            }
2849        };
2850    }
2851    mount_unlocked_doc_article(page, state, tokens)
2852}
2853
2854/// Renders the unlocked documentation article layout with sticky right-hand tree TOC (`>= 1024px`) and collapsible inline tree TOC (`< 1024px`).
2855///
2856/// # Arguments
2857///
2858/// - `&DocPage` - Unlocked documentation page to render.
2859/// - `&DocsViewerState` - Shared reactive viewer state.
2860/// - `ThemeTokens` - Active design tokens.
2861///
2862/// # Returns
2863///
2864/// - `NodeId` - Mounted article layout node.
2865fn mount_unlocked_doc_article(
2866    page: &DocPage,
2867    state: &DocsViewerState,
2868    tokens: ThemeTokens,
2869) -> NodeId {
2870    let breadcrumb_segments: Vec<String> = vec![
2871        state.get_site().get_title().clone(),
2872        page.get_section().clone(),
2873        page.get_title().clone(),
2874    ];
2875    let mut meta_bar: EuvDocMetaBar = EuvDocMetaBar::new(
2876        page.get_section().clone(),
2877        page.reading_minutes(),
2878        page.word_count(),
2879        tokens,
2880    )
2881    .source_path(page.get_route().clone());
2882    if let Some(updated) = page.try_get_updated().as_deref() {
2883        meta_bar = meta_bar.updated(updated);
2884    }
2885    let meta_node: NodeId = meta_bar.mount();
2886    let show_subtitle: bool = {
2887        let sum: &str = page.get_summary().trim();
2888        !sum.is_empty() && !sum.eq_ignore_ascii_case(page.get_title().trim())
2889    };
2890    let subtitle_str: String = if show_subtitle {
2891        page.get_summary().clone()
2892    } else {
2893        String::new()
2894    };
2895    let site_for_link: Rc<DocSite> = Rc::clone(state.get_site());
2896    let route_for_link: Signal<String> = state.get_active_route();
2897    let toc_for_link: Signal<String> = state.get_active_toc_slug();
2898    let asset_base: String = state.asset_base();
2899    let body_node: NodeId = if !page.get_markdown_body().trim().is_empty() {
2900        EuvMarkdown::new(page.get_markdown_body().clone(), tokens)
2901            .style(style! {
2902                TextSelectMode::SelectAndCopy
2903            })
2904            .asset_base(asset_base.clone())
2905            .on_link(move |url: &str| {
2906                navigate_doc_href(url, &site_for_link, route_for_link, toc_for_link);
2907            })
2908            .mount()
2909    } else {
2910        mount_fallback_doc_blocks(page, &asset_base, tokens)
2911    };
2912    let (prev_opt, next_opt): (Option<EuvDocPagerLink>, Option<EuvDocPagerLink>) =
2913        state.pager_links_for_route(page.get_route());
2914    let pager_route: Signal<String> = state.get_active_route();
2915    let pager_node: NodeId = EuvDocPager::new(prev_opt, next_opt, pager_route, tokens)
2916        .prev_label(state.get_site().resolved_prev_label())
2917        .next_label(state.get_site().resolved_next_label())
2918        .mount();
2919    let footer_node: NodeId = mount_docs_footer_with_recorder(
2920        state.get_site(),
2921        tokens,
2922        Some(state.get_last_opened_url()),
2923    );
2924    let has_toc: bool = !page.get_toc().is_empty();
2925    let column_twelfth_style: Style = style! {
2926        FlexGrow(1.0)
2927        FlexShrink(1.0)
2928        MinWidth(Length::Px(0.0))
2929        Width(if has_toc { Length::Auto } else { Length::Percent(100.0) })
2930        Gap(SPACE_MD)
2931    };
2932    let doc_main_col: NodeId = view! {
2933        column {
2934            style: column_twelfth_style
2935            EuvBreadcrumb {
2936                segments: breadcrumb_segments
2937                tokens: tokens
2938            }
2939            { meta_node }
2940            EuvHeader {
2941                title: page.get_title().clone()
2942                subtitle: subtitle_str
2943                tokens: tokens
2944            }
2945            { body_node }
2946            EuvDivider {
2947                tokens: tokens
2948            }
2949            { pager_node }
2950            { footer_node }
2951        }
2952    };
2953    if !has_toc {
2954        return doc_main_col;
2955    }
2956    let ctx: Context = current_context();
2957    let toc_slug_sig: Signal<String> = state.get_active_toc_slug();
2958    let scroll_tick_sig: Signal<u64> = state.get_scroll_tick();
2959    let active_route_sig: Signal<String> = state.get_active_route();
2960    let pending_anchor_sig: Signal<Option<String>> = state.get_pending_anchor_scroll();
2961    let pending_restore_sig: Signal<Option<(f32, Option<String>)>> =
2962        state.get_pending_scroll_restore();
2963    let toc_click_lock: Rc<RefCell<Option<(String, String, f32)>>> =
2964        Rc::clone(state.get_toc_click_lock());
2965    let toc_title: &str = state.get_site().resolved_toc_label();
2966    let toc_items_owned: Vec<DocTocItem> = page.get_toc().to_vec();
2967    let page_route_owned: String = page.get_route().clone();
2968    let cur_slug: String = toc_slug_sig.get_untracked();
2969    let cur_matches_page: bool = !cur_slug.is_empty()
2970        && toc_items_owned
2971            .iter()
2972            .any(|it: &DocTocItem| it.get_slug() == &cur_slug);
2973    if !cur_matches_page && let Some(first_it) = toc_items_owned.first() {
2974        let _: bool = toc_slug_sig.set_if_changed(first_it.get_slug().clone());
2975    }
2976    let toc_row_nodes: Rc<RefCell<HashMap<String, NodeId>>> = Rc::new(RefCell::new(HashMap::new()));
2977    let scene_jump: SceneHandle = ctx.get_scene().clone();
2978    let toc_items_click: Vec<DocTocItem> = toc_items_owned.clone();
2979    let route_for_click: String = page_route_owned.clone();
2980    let click_lock_pick: Rc<RefCell<Option<(String, String, f32)>>> = Rc::clone(&toc_click_lock);
2981    let on_toc_pick: DocTocPickCallback = Rc::new(move |slug: &str, _title_txt: &str| {
2982        let mut applied_y_opt: Option<f32> = None;
2983        scene_jump.with_write(
2984            |tree: &mut SceneTree| {
2985                if let Some(scroll_id) = find_enclosing_scroll_view(tree, body_node) {
2986                    applied_y_opt =
2987                        scroll_doc_to_toc_slug(tree, body_node, scroll_id, &toc_items_click, slug);
2988                }
2989            },
2990            (),
2991        );
2992        let applied_y: f32 = applied_y_opt.unwrap_or(0.0);
2993        if let Ok(mut lock_guard) = click_lock_pick.try_borrow_mut() {
2994            *lock_guard = Some((route_for_click.clone(), slug.to_string(), applied_y));
2995        }
2996        let _: bool = toc_slug_sig.set_if_changed(slug.to_string());
2997        sync_docs_browser_hash(&route_for_click, Some(slug));
2998        persist_docs_scroll_state(&route_for_click, applied_y, slug);
2999        let _: bool = {
3000            if let Some(mut updated_value) = scroll_tick_sig.try_get_untracked() {
3001                {
3002                    let item_val: &mut u64 = &mut updated_value;
3003                    *item_val = item_val.wrapping_add(1);
3004                }
3005                scroll_tick_sig.set(updated_value)
3006            } else {
3007                false
3008            }
3009        };
3010        notify_frame_needed();
3011    });
3012    let right_toc_widget: NodeId = mount_docs_tree_toc(
3013        page.get_toc(),
3014        toc_title,
3015        toc_slug_sig,
3016        Rc::clone(&on_toc_pick),
3017        Some(&toc_row_nodes),
3018        tokens,
3019        false,
3020    );
3021    let inline_toc_widget: NodeId = mount_docs_tree_toc(
3022        page.get_toc(),
3023        toc_title,
3024        toc_slug_sig,
3025        on_toc_pick,
3026        None,
3027        tokens,
3028        true,
3029    );
3030    let vp_sig: Signal<Size> = ctx.get_viewport_size();
3031    let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
3032    let init_vp: Size = vp_sig.get_untracked();
3033    let init_safe: SafeAreaInsets = safe_sig.get_untracked();
3034    let init_wide: bool = init_vp.get_width() >= DOCS_WIDE_TOC_BREAKPOINT;
3035    let init_toc_max_h: f32 = (init_vp.get_height()
3036        - SHELL_DESKTOP_HEADER_HEIGHT
3037        - init_safe.get_top().max(0.0)
3038        - init_safe.get_bottom().max(0.0)
3039        - 32.0)
3040        .max(200.0);
3041    let mut wide_row_node: NodeId = NodeId::default();
3042    let mut inline_toc_host: NodeId = NodeId::default();
3043    let mut right_toc_host: NodeId = NodeId::default();
3044    let mut right_toc_scroll: NodeId = NodeId::default();
3045    let column_ninth_style: Style = style! {
3046        Width(Length::Percent(100.0))
3047        Gap(SPACE_MD)
3048    };
3049    let column_tenth_style: Style = style! {
3050        Width(Length::Percent(100.0))
3051        if init_wide { Display::None } else { Display::Flex }
3052    };
3053    let row_eighth_style: Style = style! {
3054        Width(Length::Percent(100.0))
3055        AlignItems::Start
3056        Gap(SPACE_LG)
3057    };
3058    let column_eleventh_style: Style = style! {
3059        Width(Length::Px(DOCS_RIGHT_TOC_WIDTH))
3060        FlexShrink(0.0)
3061        if init_wide { Display::Flex } else { Display::None }
3062    };
3063    let scroll_secondary_style: Style = style! {
3064        FlexDirection::Column
3065        Width(Length::Percent(100.0))
3066        MaxHeight(Length::Px(init_toc_max_h))
3067        Overflow::Scroll
3068        StopScrollPropagation(true)
3069    };
3070    let layout_root: NodeId = view! {
3071        column {
3072            style: column_ninth_style
3073            column {
3074                node_ref: inline_toc_host
3075                style: column_tenth_style
3076                { inline_toc_widget }
3077            }
3078            row {
3079                node_ref: wide_row_node
3080                style: row_eighth_style
3081                { doc_main_col }
3082                column {
3083                    node_ref: right_toc_host
3084                    style: column_eleventh_style
3085                    scroll {
3086                        node_ref: right_toc_scroll
3087                        style: scroll_secondary_style
3088                        { right_toc_widget }
3089                    }
3090                }
3091            }
3092        }
3093    };
3094    let scene_toc: SceneHandle = ctx.get_scene().clone();
3095    let scene_sticky: SceneHandle = ctx.get_scene().clone();
3096    let route_for_entry: String = page_route_owned.clone();
3097    let toc_items_for_entry: Vec<DocTocItem> = toc_items_owned.clone();
3098    let row_nodes_for_spy: Rc<RefCell<HashMap<String, NodeId>>> = Rc::clone(&toc_row_nodes);
3099    let (toc_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
3100        Effect::new(move || {
3101            let box_size: Size = vp_sig.get();
3102            let safe: SafeAreaInsets = safe_sig.get();
3103            let is_wide: bool = box_size.get_width() >= DOCS_WIDE_TOC_BREAKPOINT;
3104            let max_h: f32 = (box_size.get_height()
3105                - SHELL_DESKTOP_HEADER_HEIGHT
3106                - safe.get_top().max(0.0)
3107                - safe.get_bottom().max(0.0)
3108                - 32.0)
3109                .max(200.0);
3110            scene_toc.with_write(
3111                |tree: &mut SceneTree| {
3112                    let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
3113                    let dirty_mask: u16 = dirty_l | DIRTY_PAINT;
3114                    if let Some(item_count) = tree.get_node_mut(right_toc_host) {
3115                        item_count
3116                            .get_mut_style()
3117                            .get_mut_layout()
3118                            .set_display(if is_wide {
3119                                Display::Flex
3120                            } else {
3121                                Display::None
3122                            });
3123                        if !is_wide {
3124                            item_count
3125                                .get_mut_style()
3126                                .get_mut_paint()
3127                                .set_transform(Transform2D::default());
3128                        }
3129                        tree.mark_dirty(right_toc_host, dirty_mask);
3130                    }
3131                    if let Some(node_entry) = tree.get_node_mut(right_toc_scroll) {
3132                        node_entry
3133                            .get_mut_style()
3134                            .get_mut_layout()
3135                            .set_max_height(Length::Px(max_h));
3136                        tree.mark_dirty(right_toc_scroll, dirty_mask);
3137                    }
3138                    if let Some(normal_vec) = tree.get_node_mut(inline_toc_host) {
3139                        normal_vec
3140                            .get_mut_style()
3141                            .get_mut_layout()
3142                            .set_display(if is_wide {
3143                                Display::None
3144                            } else {
3145                                Display::Flex
3146                            });
3147                        tree.mark_dirty(inline_toc_host, dirty_mask);
3148                    }
3149                    tree.mark_dirty(wide_row_node, dirty_mask);
3150                },
3151                (),
3152            );
3153        });
3154        Effect::new(move || {
3155            let cur_r: String = active_route_sig.get();
3156            if cur_r != route_for_entry {
3157                return;
3158            }
3159            let cur_s: String = toc_slug_sig.get_untracked();
3160            let valid: bool = !cur_s.is_empty()
3161                && toc_items_for_entry
3162                    .iter()
3163                    .any(|it: &DocTocItem| it.get_slug() == &cur_s);
3164            if !valid && let Some(first_it) = toc_items_for_entry.first() {
3165                let _: bool = toc_slug_sig.set_if_changed(first_it.get_slug().clone());
3166            }
3167        });
3168        let click_lock_spy: Rc<RefCell<Option<(String, String, f32)>>> = Rc::clone(&toc_click_lock);
3169        Effect::new(move || {
3170            let _: u64 = scroll_tick_sig.get();
3171            let _: Size = vp_sig.get();
3172            let cur_r: String = active_route_sig.get();
3173            let pending_anchor: Option<String> = pending_anchor_sig.get();
3174            let pending_restore: Option<(f32, Option<String>)> = pending_restore_sig.get();
3175            if cur_r != page_route_owned {
3176                return;
3177            }
3178            let mut next_slug: Option<String> = None;
3179            let mut consumed_anchor: bool = false;
3180            let mut consumed_restore: bool = false;
3181            let mut persist_snap: Option<(f32, String)> = None;
3182            scene_sticky.with_write(
3183                |tree: &mut SceneTree| {
3184                    let Some(scroll_id) = find_enclosing_scroll_view(tree, layout_root) else {
3185                        return;
3186                    };
3187                    let Some(scroll_rect) = tree.node_screen_bounds(scroll_id) else {
3188                        return;
3189                    };
3190                    if scroll_rect.get_height() < 2.0 {
3191                        return;
3192                    }
3193                    if let Some(anchor_slug) = pending_anchor.as_deref()
3194                        && let Some(matched) = toc_items_owned
3195                            .iter()
3196                            .find(|it: &&DocTocItem| it.get_slug() == anchor_slug)
3197                    {
3198                        if let Some(applied_y) = scroll_doc_to_toc_slug(
3199                            tree,
3200                            body_node,
3201                            scroll_id,
3202                            &toc_items_owned,
3203                            matched.get_slug().as_str(),
3204                        ) {
3205                            let matched_slug: String = matched.get_slug().clone();
3206                            if let Ok(mut guard) = click_lock_spy.try_borrow_mut() {
3207                                *guard = Some((
3208                                    page_route_owned.clone(),
3209                                    matched_slug.clone(),
3210                                    applied_y,
3211                                ));
3212                            }
3213                            persist_snap = Some((applied_y, matched_slug.clone()));
3214                            next_slug = Some(matched_slug);
3215                            consumed_anchor = true;
3216                        }
3217                    } else if let Some((saved_y, saved_slug_opt)) = pending_restore.as_ref() {
3218                        let (cur_x, content_h): (f32, f32) = tree
3219                            .get_node(scroll_id)
3220                            .map(|scene_node: &SceneNode| {
3221                                (
3222                                    scene_node.get_layout_box().get_scroll_offset().get_x(),
3223                                    scene_node.get_layout_box().get_content_size().get_height(),
3224                                )
3225                            })
3226                            .unwrap_or((0.0, 0.0));
3227                        let max_scroll: f32 = (content_h - scroll_rect.get_height()).max(0.0);
3228                        let clamped_y: f32 = saved_y.clamp(0.0, max_scroll);
3229                        tree.set_scroll_offset(scroll_id, Point::new(cur_x, clamped_y));
3230                        tree.mark_dirty(scroll_id, DIRTY_PAINT);
3231                        let valid_saved: Option<String> =
3232                            saved_slug_opt.clone().filter(|text_value: &String| {
3233                                toc_items_owned
3234                                    .iter()
3235                                    .any(|it: &DocTocItem| it.get_slug() == text_value)
3236                            });
3237                        let resolved: Option<String> = valid_saved.or_else(|| {
3238                            compute_active_toc_slug_for_scroll(
3239                                tree,
3240                                body_node,
3241                                scroll_id,
3242                                &toc_items_owned,
3243                            )
3244                        });
3245                        if let Some(ref slug_str) = resolved {
3246                            if let Ok(mut guard) = click_lock_spy.try_borrow_mut() {
3247                                *guard =
3248                                    Some((page_route_owned.clone(), slug_str.clone(), clamped_y));
3249                            }
3250                            persist_snap = Some((clamped_y, slug_str.clone()));
3251                        }
3252                        next_slug = resolved;
3253                        consumed_restore = true;
3254                    }
3255                    let is_wide: bool =
3256                        tree.get_node(right_toc_host)
3257                            .is_some_and(|target_node: &SceneNode| {
3258                                target_node.style_ref().get_layout().get_display() != Display::None
3259                            });
3260                    if is_wide {
3261                        let avail_h: f32 = (scroll_rect.get_height() - 32.0).max(200.0);
3262                        if let Some(sn) = tree.get_node_mut(right_toc_scroll) {
3263                            let cur_max: Length = sn.style_ref().get_layout().get_max_height();
3264                            let needs_max_update: bool = match cur_max {
3265                                Length::Px(px) => (px - avail_h).abs() > 1.0,
3266                                _ => true,
3267                            };
3268                            if needs_max_update {
3269                                sn.get_mut_style()
3270                                    .get_mut_layout()
3271                                    .set_max_height(Length::Px(avail_h));
3272                                let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
3273                                tree.mark_dirty(right_toc_scroll, dirty_l | DIRTY_PAINT);
3274                            }
3275                        }
3276                        if let Some(wide_rect) = tree.node_screen_bounds(wide_row_node) {
3277                            let toc_h: f32 = tree
3278                                .get_node(right_toc_host)
3279                                .map(|total_len: &SceneNode| {
3280                                    total_len.get_layout_box().get_bounds().get_height()
3281                                })
3282                                .unwrap_or(0.0)
3283                                .min(avail_h);
3284                            let pin_screen_y: f32 = scroll_rect.get_y() + 16.0;
3285                            let max_sticky: f32 = (wide_rect.get_height() - toc_h).max(0.0);
3286                            let sticky_y: f32 =
3287                                (pin_screen_y - wide_rect.get_y()).clamp(0.0, max_sticky);
3288                            if let Some(item_count_primary) = tree.get_node_mut(right_toc_host) {
3289                                let cur_ty: f32 = item_count_primary
3290                                    .style_ref()
3291                                    .get_paint()
3292                                    .get_transform()
3293                                    .get_translate_y();
3294                                if (cur_ty - sticky_y).abs() > 0.25 {
3295                                    item_count_primary
3296                                        .get_mut_style()
3297                                        .get_mut_paint()
3298                                        .set_transform(Transform2D::new(
3299                                            0.0, sticky_y, 1.0, 1.0, 0.0,
3300                                        ));
3301                                    tree.mark_dirty(right_toc_host, DIRTY_PAINT);
3302                                }
3303                            }
3304                        }
3305                    }
3306                    if next_slug.is_none() {
3307                        let cur_scroll_y: f32 = tree
3308                            .get_node(scroll_id)
3309                            .map(|scene_node_primary: &SceneNode| {
3310                                scene_node_primary
3311                                    .get_layout_box()
3312                                    .get_scroll_offset()
3313                                    .get_y()
3314                                    .max(0.0)
3315                            })
3316                            .unwrap_or(0.0);
3317                        let locked_match: Option<String> = click_lock_spy
3318                            .try_borrow_mut()
3319                            .ok()
3320                            .and_then(|mut guard: RefMut<'_, Option<(String, String, f32)>>| {
3321                                let keep: Option<String> = guard.as_ref().and_then(
3322                                    |(lr, lslug, ly): &(String, String, f32)| {
3323                                        if lr == &page_route_owned
3324                                            && (cur_scroll_y - *ly).abs() <= 2.5
3325                                        {
3326                                            Some(lslug.clone())
3327                                        } else {
3328                                            None
3329                                        }
3330                                    },
3331                                );
3332                                if keep.is_none() {
3333                                    *guard = None;
3334                                }
3335                                keep
3336                            });
3337                        if let Some(locked_slug) = locked_match {
3338                            next_slug = Some(locked_slug);
3339                        } else {
3340                            let computed: Option<String> = compute_active_toc_slug_for_scroll(
3341                                tree,
3342                                body_node,
3343                                scroll_id,
3344                                &toc_items_owned,
3345                            );
3346                            if let Some(ref slug_str) = computed {
3347                                persist_snap = Some((cur_scroll_y, slug_str.clone()));
3348                            }
3349                            next_slug = computed;
3350                        }
3351                    }
3352                    let target_slug: String = next_slug
3353                        .clone()
3354                        .unwrap_or_else(|| toc_slug_sig.get_untracked());
3355                    if is_wide
3356                        && !target_slug.is_empty()
3357                        && let Ok(map) = row_nodes_for_spy.try_borrow()
3358                        && let Some(&toc_row_id) = map.get(&target_slug)
3359                    {
3360                        let _: bool =
3361                            scroll_node_into_scroll_view(tree, right_toc_scroll, toc_row_id, 20.0);
3362                    }
3363                },
3364                (),
3365            );
3366            if consumed_anchor {
3367                let _: bool = pending_anchor_sig.set_if_changed(None);
3368            }
3369            if consumed_restore {
3370                let _: bool = pending_restore_sig.set_if_changed(None);
3371            }
3372            if let Some(slug) = next_slug {
3373                let _: bool = toc_slug_sig.set_if_changed(slug);
3374            }
3375            if let Some((sy, sslug)) = persist_snap {
3376                persist_docs_scroll_state(&page_route_owned, sy, &sslug);
3377            }
3378        })
3379    });
3380    ctx.get_scene().with_write(
3381        |tree: &mut SceneTree| {
3382            tree.attach_scope(layout_root, toc_scope);
3383        },
3384        (),
3385    );
3386    layout_root
3387}
3388
3389/// Renders structured `DocBlock` nodes when a `DocPage` has no raw Markdown body text.
3390///
3391/// # Arguments
3392///
3393/// - `&DocPage` - Documentation page holding pre-parsed blocks.
3394/// - `&str` - Relative site-root asset base prefix (`"./"` or `"../"`).
3395/// - `ThemeTokens` - Active design tokens.
3396///
3397/// # Returns
3398///
3399/// - `NodeId` - Mounted fallback block column handle.
3400fn mount_fallback_doc_blocks(page: &DocPage, asset_base: &str, tokens: ThemeTokens) -> NodeId {
3401    let column_eighth_style: Style = style! {
3402        Width(Length::Percent(100.0))
3403        Gap(SPACE_MD)
3404    };
3405    view! {
3406        column {
3407            style: column_eighth_style
3408            for block in page.get_blocks().iter() {
3409                match block {
3410                    DocBlock::Heading { level, text, .. } => {
3411                        EuvMarkdownHeading {
3412                            level: *level
3413                            text: text.clone()
3414                            tokens: tokens
3415                        }
3416                    }
3417                    DocBlock::Paragraph(text) => {
3418                        EuvMarkdownParagraph {
3419                            inlines: parse_markdown_inlines(text)
3420                            tokens: tokens
3421                            asset_base: asset_base
3422                        }
3423                    }
3424                    DocBlock::ListItem(text) => EuvMarkdownList {
3425                        ordered: false
3426                        items: vec![EuvMarkdownListItem::new(text.clone(), 0, None)]
3427                        tokens: tokens
3428                    },
3429                    DocBlock::BlockQuote(text) => EuvMarkdownQuote {
3430                        kind: EuvMarkdownAlertKind::Quote
3431                        lines: vec![text.clone()]
3432                        tokens: tokens
3433                    },
3434                    DocBlock::Table { headers, rows } => EuvMarkdownTable {
3435                        headers: headers.clone()
3436                        alignments: vec![EuvMarkdownAlign::Left; headers.len()]
3437                        rows: rows.clone()
3438                        tokens: tokens
3439                    },
3440                    DocBlock::Image { alt, src } => {
3441                        EuvMarkdownImage {
3442                            alt: alt.clone()
3443                            url: src.clone()
3444                            tokens: tokens
3445                            asset_base: asset_base
3446                        }
3447                    }
3448                    DocBlock::HorizontalRule => EuvMarkdownDivider {
3449                        tokens: tokens
3450                    },
3451                    DocBlock::Code { language, code } => {
3452                        EuvCodeBlock {
3453                            code: code.clone()
3454                            tokens: tokens
3455                            language: language.clone()
3456                            line_numbers: true
3457                            selectable: true
3458                        }
3459                    }
3460                }
3461            }
3462        }
3463    }
3464}
3465
3466/// Renders a single standalone `DocPage` (meta bar, header, interactive TOC, and full `EuvMarkdown`) as native `euv-ui` nodes.
3467///
3468/// # Arguments
3469///
3470/// - `&DocPage` - Documentation page to mount.
3471/// - `ThemeTokens` - Active design tokens.
3472///
3473/// # Returns
3474///
3475/// - `NodeId` - Mounted page container node.
3476pub fn mount_doc_page(page: &DocPage, tokens: ThemeTokens) -> NodeId {
3477    let mut meta_bar: EuvDocMetaBar = EuvDocMetaBar::new(
3478        page.get_section().clone(),
3479        page.reading_minutes(),
3480        page.word_count(),
3481        tokens,
3482    )
3483    .source_path(page.get_route().clone());
3484    if let Some(updated) = page.try_get_updated().as_deref() {
3485        meta_bar = meta_bar.updated(updated);
3486    }
3487    let meta_node: NodeId = meta_bar.mount();
3488    let toc_items: Vec<EuvDocTocItem> = page
3489        .get_toc()
3490        .iter()
3491        .map(|it: &DocTocItem| {
3492            EuvDocTocItem::new(
3493                it.get_level(),
3494                it.get_slug().clone(),
3495                it.get_title().clone(),
3496            )
3497        })
3498        .collect();
3499    let toc_sig: Signal<String> = Signal::new(
3500        toc_items
3501            .first()
3502            .map(|it: &EuvDocTocItem| it.get_slug().clone())
3503            .unwrap_or_default(),
3504    );
3505    let toc_node_opt: Option<NodeId> = if toc_items.is_empty() {
3506        None
3507    } else {
3508        Some(EuvDocToc::new(toc_items, toc_sig, tokens).mount())
3509    };
3510    let body_node: NodeId = if !page.get_markdown_body().trim().is_empty() {
3511        EuvMarkdown::new(page.get_markdown_body().clone(), tokens)
3512            .style(style! {
3513                TextSelectMode::SelectAndCopy
3514            })
3515            .asset_base("./")
3516            .mount()
3517    } else {
3518        mount_fallback_doc_blocks(page, "./", tokens)
3519    };
3520    let column_seventh_style: Style = style! {
3521        Width(Length::Percent(100.0))
3522        Gap(SPACE_MD)
3523    };
3524    view! {
3525        column {
3526            style: column_seventh_style
3527            { meta_node }
3528            EuvHeader {
3529                title: page.get_title().clone()
3530                subtitle: page.get_summary().clone()
3531                tokens: tokens
3532            }
3533            if let Some(toc_node) = toc_node_opt {
3534                { toc_node }
3535            }
3536            { body_node }
3537        }
3538    }
3539}
3540
3541/// Registers every page in `state.site` lazily onto `state.router` with `PageRetention::Freeze`.
3542///
3543/// # Arguments
3544///
3545/// - `&DocsViewerState` - Shared reactive viewer state.
3546fn ensure_docs_routes_registered(state: &DocsViewerState) {
3547    if state.get_router_ready().replace(true) {
3548        return;
3549    }
3550    let mut router: EuvRouter = state.get_router().clone();
3551    for page in state.get_site().get_pages().iter() {
3552        let route_pattern: String = page.get_route().clone();
3553        let route_path: String = route_pattern.clone();
3554        let route_title: String = page.get_title().clone();
3555        let node_style: DocsViewerState = state.clone();
3556        router = router.route_with_retention(
3557            &route_pattern,
3558            &route_title,
3559            PageRetention::Freeze,
3560            move |_: &EuvRouteMatch| {
3561                let tok: ThemeTokens = untracked(|| node_style.get_theme().get_tokens().get());
3562                match node_style.get_site().find_by_route(&route_path) {
3563                    Some(point_val) => mount_doc_page_with_context(point_val, &node_style, tok),
3564                    None => view! {
3565                        EuvEmpty {
3566                            title: EMPTY_PAGE_TITLE.to_string()
3567                            description: EMPTY_PAGE_MSG.to_string()
3568                            tokens: tok
3569                        }
3570                    },
3571                }
3572            },
3573        );
3574    }
3575    let _: EuvRouter = router;
3576}
3577
3578/// Computes the viewport-clamped `(left, top, width, max_height)` anchor frame for a topbar dropdown portal.
3579///
3580/// # Arguments
3581///
3582/// - `&SceneHandle` - Active scene graph handle.
3583/// - `&[NodeId]` - Candidate desktop and mobile trigger node handles.
3584/// - `Size` - Active logical viewport size.
3585/// - `SafeAreaInsets` - Active OS safe-area insets.
3586/// - `f32` - Preferred menu width in logical pixels.
3587/// - `f32` - Preferred menu max height in logical pixels.
3588///
3589/// # Returns
3590///
3591/// - `(f32, f32, f32, f32)` - Clamped `(left, top, width, max_height)` rectangle strictly inside viewport safe bounds.
3592fn docs_dropdown_anchor_rect(
3593    scene: &SceneHandle,
3594    triggers: &[NodeId],
3595    box_size: Size,
3596    safe: SafeAreaInsets,
3597    desired_w: f32,
3598    desired_h: f32,
3599) -> (f32, f32, f32, f32) {
3600    let vp_w: f32 = box_size.get_width().max(320.0);
3601    let vp_h: f32 = box_size.get_height().max(320.0);
3602    let margin: f32 = DOCS_DROPDOWN_EDGE_MARGIN;
3603    let safe_l: f32 = safe.get_left().max(0.0);
3604    let safe_r: f32 = safe.get_right().max(0.0);
3605    let safe_t: f32 = safe.get_top().max(0.0);
3606    let safe_b: f32 = safe.get_bottom().max(0.0);
3607    let max_avail_w: f32 = (vp_w - safe_l - safe_r - margin * 2.0).max(152.0);
3608    let menu_w: f32 = desired_w.min(max_avail_w);
3609    let anchor_opt: Option<Rect> = scene.with_read(
3610        |tree: &SceneTree| {
3611            for &tid in triggers.iter() {
3612                if tree.is_node_visible(tid)
3613                    && let Some(red_val) = tree.node_screen_bounds(tid)
3614                    && red_val.get_width() > 4.0
3615                    && red_val.get_height() > 4.0
3616                {
3617                    return Some(red_val);
3618                }
3619            }
3620            None
3621        },
3622        None,
3623    );
3624    let (raw_left, raw_top): (f32, f32) = match anchor_opt {
3625        Some(radius_val) => (
3626            radius_val.get_x() + radius_val.get_width() - menu_w,
3627            radius_val.get_y() + radius_val.get_height() + 6.0,
3628        ),
3629        None => (
3630            vp_w - safe_r - menu_w - margin,
3631            SHELL_DESKTOP_HEADER_HEIGHT + safe_t + 6.0,
3632        ),
3633    };
3634    let min_left: f32 = safe_l + margin;
3635    let max_left: f32 = (vp_w - safe_r - menu_w - margin).max(min_left);
3636    let left: f32 = raw_left.clamp(min_left, max_left);
3637    let min_top: f32 = safe_t + margin;
3638    let top_clamped: f32 = raw_top.max(min_top);
3639    let avail_below: f32 = (vp_h - safe_b - top_clamped - margin).max(120.0);
3640    let max_h: f32 = desired_h.min(avail_below).max(120.0);
3641    let max_top: f32 = (vp_h - safe_b - max_h - margin).max(min_top);
3642    let top: f32 = top_clamped.min(max_top);
3643    (left, top, menu_w, max_h)
3644}
3645
3646/// Recursively mounts one node in the pure filesystem-mirrored documentation catalog tree with lazy child mounting and exact directory click semantics.
3647///
3648/// # Arguments
3649///
3650/// - `&DocCatalogNode` - Catalog directory or document node.
3651/// - `usize` - Zero-based directory nesting depth.
3652/// - `bool` - Whether small-site default top-level expansion is enabled.
3653/// - `Signal<String>` - Active canonical route signal.
3654/// - `&Rc<RefCell<HashMap<String, NodeId>>>` - Registry recording `(route -> row_node_id)` for scrolling the active item into view.
3655/// - `ThemeTokens` - Base design tokens.
3656///
3657/// # Returns
3658///
3659/// - `NodeId` - Mounted catalog tree branch handle.
3660fn mount_docs_catalog_branch(
3661    node: &DocCatalogNode,
3662    depth: usize,
3663    expand_top_default: bool,
3664    active_route: Signal<String>,
3665    row_registry: &Rc<RefCell<HashMap<String, NodeId>>>,
3666    tokens: ThemeTokens,
3667) -> NodeId {
3668    let is_dir: bool = node.get_is_dir();
3669    let has_children: bool = !node.get_children().is_empty();
3670    let init_route: String = active_route.get_untracked();
3671    let contains_init: bool = node.contains_route(&init_route);
3672    let init_expanded: bool = if !is_dir || !has_children {
3673        false
3674    } else if contains_init {
3675        true
3676    } else if let Some(pref) = node.get_expanded_pref() {
3677        pref
3678    } else if !node.get_collapsible() {
3679        true
3680    } else {
3681        expand_top_default && depth == 0
3682    };
3683    let expanded_sig: Signal<bool> = Signal::new(init_expanded);
3684    let hovered_sig: Signal<bool> = Signal::new(false);
3685    let direct_route: Option<String> = node.try_get_route().clone();
3686    let first_child: Option<String> = node.try_get_first_child_route().clone();
3687    let has_own_content: bool = node.get_has_own_content();
3688    let index_disabled: bool = node.get_index_disabled();
3689    let collapsible: bool = node.get_collapsible();
3690    let locked: bool = node.get_locked();
3691    let title_owned: String = node.get_title().clone();
3692    let node_for_ancestor: DocCatalogNode = node.clone();
3693    let route_for_style: Option<String> = direct_route.clone();
3694    let row_style = move || -> Style {
3695        let tok: ThemeTokens = use_live_tokens(tokens);
3696        let lp: ThemePalette = tok.get_palette();
3697        let lg: ThemeGeometry = tok.get_geometry();
3698        let cur: String = active_route.get();
3699        let is_active: bool = route_for_style.as_deref() == Some(cur.as_str());
3700        let is_hov: bool = hovered_sig.get();
3701        let bg: Color = if is_active {
3702            lp.surface(SurfaceRole::Primary).get_bg()
3703        } else if is_hov {
3704            lp.surface(SurfaceRole::Accent).get_bg()
3705        } else {
3706            COLOR_TRANSPARENT
3707        };
3708        style! {
3709            FlexDirection::Row
3710            Width(Length::Percent(100.0))
3711            MinHeight(Length::Px(32.0))
3712            AlignItems::Center
3713            Gap(SPACE_XS)
3714            Padding(Edges::symmetric(4.0, SPACE_SM))
3715            Background(bg)
3716            Radius(lg.get_radius_sm())
3717            Overflow::Hidden
3718            CursorIcon::Pointer
3719        }
3720    };
3721    let route_for_txt: Option<String> = direct_route.clone();
3722    let txt_style = move || -> Style {
3723        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
3724        let cur: String = active_route.get();
3725        let is_active: bool = route_for_txt.as_deref() == Some(cur.as_str());
3726        let is_hov: bool = hovered_sig.get();
3727        let fg: Color = if is_active {
3728            lp.surface(SurfaceRole::Primary).get_fg()
3729        } else if is_hov {
3730            lp.surface(SurfaceRole::Accent).get_fg()
3731        } else if is_dir {
3732            lp.get_foreground()
3733        } else {
3734            lp.get_muted_foreground()
3735        };
3736        let mut computed_style: Style = style! {
3737            FlexGrow(1.0)
3738            FlexShrink(1.0)
3739            MinWidth(Length::Px(0.0))
3740            FontSize(if is_dir && depth == 0 { 13.0 } else { 12.5 })
3741            if is_active {
3742                FontWeight::Medium
3743            } else {
3744                FontWeight::Normal
3745            }
3746            TextColor(fg)
3747            Overflow::Hidden
3748            TextOverflow::Ellipsis
3749        };
3750        computed_style.get_mut_text().set_line_height(1.25);
3751        computed_style
3752    };
3753    let route_for_click: Option<String> = direct_route.clone();
3754    let first_for_click: Option<String> = first_child;
3755    let on_row_click = move |_: &UiEvent| {
3756        if !is_dir {
3757            if let Some(target) = route_for_click.as_ref() {
3758                let _: bool = active_route.set_if_changed(target.clone());
3759            }
3760            return;
3761        }
3762        if index_disabled {
3763            let was_open: bool = expanded_sig.get_untracked();
3764            if collapsible {
3765                let _: bool = expanded_sig.set_if_changed(!was_open);
3766            }
3767            if !was_open
3768                && has_own_content
3769                && let Some(target) = route_for_click.as_ref()
3770            {
3771                let _: bool = active_route.set_if_changed(target.clone());
3772            }
3773            return;
3774        }
3775        if !has_own_content {
3776            if has_children {
3777                let _: bool = expanded_sig.set_if_changed(true);
3778            }
3779            if let Some(target) = first_for_click.as_ref() {
3780                let _: bool = active_route.set_if_changed(target.clone());
3781            }
3782            return;
3783        }
3784        if has_children {
3785            let cur_route: String = active_route.get_untracked();
3786            let already_active: bool = route_for_click.as_deref() == Some(cur_route.as_str());
3787            if already_active && collapsible {
3788                let _: bool = expanded_sig.set(!expanded_sig.get_untracked());
3789            } else {
3790                let _: bool = expanded_sig.set_if_changed(true);
3791            }
3792        }
3793        if let Some(target) = route_for_click.as_ref() {
3794            let _: bool = active_route.set_if_changed(target.clone());
3795        }
3796    };
3797    let on_chev_click = move |_: &UiEvent| {
3798        if collapsible {
3799            let _: bool = expanded_sig.set(!expanded_sig.get_untracked());
3800        }
3801    };
3802    let on_row_enter = move |_: &UiEvent| {
3803        let _: bool = hovered_sig.set_if_changed(true);
3804    };
3805    let on_row_leave = move |_: &UiEvent| {
3806        let _: bool = hovered_sig.set_if_changed(false);
3807    };
3808    let route_for_chev: Option<String> = direct_route;
3809    let paint_chev = move |bounds: Rect, display_list: &mut DisplayList| {
3810        let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
3811        let cur: String = active_route.get_untracked();
3812        let is_active: bool = route_for_chev.as_deref() == Some(cur.as_str());
3813        let col: Color = if is_active {
3814            lp.surface(SurfaceRole::Primary).get_fg()
3815        } else {
3816            lp.get_muted_foreground()
3817        };
3818        draw_docs_tree_chevron(bounds, display_list, col, expanded_sig.get_untracked());
3819    };
3820    let lock_dot_style = move || -> Style {
3821        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
3822        style! {
3823            Width(Length::Px(6.0))
3824            Height(Length::Px(6.0))
3825            FlexShrink(0.0)
3826            Radius(RADIUS_PILL)
3827            Background(lp.get_warning())
3828        }
3829    };
3830    let children_data: Vec<DocCatalogNode> = node.get_children().clone();
3831    let reg_for_children: Rc<RefCell<HashMap<String, NodeId>>> = Rc::clone(row_registry);
3832    let build_children_lazy = move || -> Vec<NodeId> {
3833        if !expanded_sig.get() {
3834            return Vec::new();
3835        }
3836        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
3837        children_data
3838            .iter()
3839            .map(|child: &DocCatalogNode| {
3840                mount_docs_catalog_branch(
3841                    child,
3842                    depth + 1,
3843                    expand_top_default,
3844                    active_route,
3845                    &reg_for_children,
3846                    live_tok,
3847                )
3848            })
3849            .collect()
3850    };
3851    let child_row_style = move || -> Style {
3852        let is_open: bool = expanded_sig.get();
3853        style! {
3854            FlexDirection::Row
3855            if is_open {
3856                Display::Flex
3857            } else {
3858                Display::None
3859            }
3860            Width(Length::Percent(100.0))
3861            Padding(Edges::new(2.0, 0.0, 2.0, 10.0))
3862            Gap(SPACE_SM)
3863            AlignItems::Stretch
3864        }
3865    };
3866    let tree_guide_style = move || -> Style {
3867        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
3868        style! {
3869            Width(Length::Px(1.0))
3870            FlexShrink(0.0)
3871            Background(lp.get_border())
3872        }
3873    };
3874    let mut row_node: NodeId = NodeId::default();
3875    let mut chev_canvas: NodeId = NodeId::default();
3876    let column_fifth_style: Style = style! {
3877        Width(Length::Percent(100.0))
3878        Gap(2.0)
3879    };
3880    let row_seventh_style: Style = style! {
3881        Width(Length::Px(20.0))
3882        Height(Length::Px(20.0))
3883        Padding(Edges::all(SPACE_XS))
3884        Radius(tokens.get_geometry().get_radius_sm())
3885        FlexShrink(0.0)
3886        JustifyContent::Center
3887        AlignItems::Center
3888        CursorIcon::Pointer
3889        StopEventPropagation(true)
3890    };
3891    let canvas_sixth_style: Style = style! {
3892        Width(Length::Px(10.0))
3893        Height(Length::Px(10.0))
3894    };
3895    let column_sixth_style: Style = style! {
3896        FlexGrow(1.0)
3897        FlexShrink(1.0)
3898        MinWidth(Length::Px(0.0))
3899        Gap(2.0)
3900    };
3901    let branch_node: NodeId = view! {
3902        column {
3903            style: column_fifth_style
3904            row {
3905                node_ref: row_node
3906                bind_style: row_style
3907                role: if is_dir { A11yRole::Button } else { A11yRole::Link }
3908                a11y_label: title_owned.clone()
3909                on_click: on_row_click
3910                on_pointer_enter: on_row_enter
3911                on_pointer_leave: on_row_leave
3912                if is_dir && has_children {
3913                    row {
3914                        style: row_seventh_style
3915                        on_click: on_chev_click
3916                        canvas {
3917                            node_ref: chev_canvas
3918                            style: canvas_sixth_style
3919                            painter: paint_chev
3920                        }
3921                    }
3922                }
3923                text {
3924                    bind_style: txt_style
3925                    { title_owned }
3926                }
3927                if locked {
3928                    view {
3929                        bind_style: lock_dot_style
3930                    }
3931                }
3932            }
3933            if is_dir && has_children {
3934                row {
3935                    bind_style: child_row_style
3936                    view {
3937                        bind_style: tree_guide_style
3938                    }
3939                    column {
3940                        style: column_sixth_style
3941                        bind_children: build_children_lazy
3942                    }
3943                }
3944            }
3945        }
3946    };
3947    if let Some(route_key) = node.try_get_route().as_deref()
3948        && let Ok(mut map) = row_registry.try_borrow_mut()
3949    {
3950        let _: Option<NodeId> = map.insert(route_key.to_string(), row_node);
3951    }
3952    if is_dir && has_children {
3953        let ctx: Context = current_context();
3954        let scale_factor: SceneHandle = ctx.get_scene().clone();
3955        let (branch_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
3956            let _: Effect = Effect::new(move || {
3957                let cur: String = active_route.get();
3958                if node_for_ancestor.contains_route(&cur) {
3959                    let _: bool = expanded_sig.set_if_changed(true);
3960                }
3961            });
3962            Effect::new(move || {
3963                let _: bool = expanded_sig.get();
3964                let _: String = active_route.get();
3965                let _: ThemeTokens = use_live_tokens(tokens);
3966                scale_factor.with_write(
3967                    |tree: &mut SceneTree| {
3968                        tree.mark_dirty(chev_canvas, DIRTY_PAINT);
3969                    },
3970                    (),
3971                );
3972            })
3973        });
3974        ctx.get_scene().with_write(
3975            |tree: &mut SceneTree| {
3976                tree.attach_scope(branch_node, branch_scope);
3977            },
3978            (),
3979        );
3980    }
3981    branch_node
3982}
3983
3984/// Mounts the pure filesystem-mirrored documentation left sidebar tree (without any sidebar search input).
3985///
3986/// # Arguments
3987///
3988/// - `&DocsViewerState` - Shared documentation viewer state.
3989/// - `ThemeTokens` - Base design tokens.
3990///
3991/// # Returns
3992///
3993/// - `NodeId` - Mounted recursive directory catalog tree container.
3994fn mount_docs_catalog_tree(state: &DocsViewerState, tokens: ThemeTokens) -> NodeId {
3995    let active_route: Signal<String> = state.get_active_route();
3996    let row_registry: &Rc<RefCell<HashMap<String, NodeId>>> = state.get_catalog_row_nodes();
3997    if let Ok(mut map) = row_registry.try_borrow_mut() {
3998        map.clear();
3999    }
4000    let total_pages: usize = state.get_site().get_pages().len();
4001    let expand_top_default: bool = total_pages <= 24;
4002    let nodes: Vec<NodeId> = state
4003        .get_catalog_tree()
4004        .iter()
4005        .map(|entry: &DocCatalogNode| {
4006            mount_docs_catalog_branch(
4007                entry,
4008                0,
4009                expand_top_default,
4010                active_route,
4011                row_registry,
4012                tokens,
4013            )
4014        })
4015        .collect();
4016    let column_quaternary_style: Style = style! {
4017        Width(Length::Percent(100.0))
4018        Gap(2.0)
4019    };
4020    let root: NodeId = view! {
4021        column {
4022            style: column_quaternary_style
4023            role: A11yRole::Navigation
4024            ..nodes
4025        }
4026    };
4027    state.get_sidebar_root().set(root);
4028    root
4029}
4030
4031/// Mounts the viewport-clamped floating Locale Dropdown portal anchored beneath the topbar Globe icon button.
4032///
4033/// # Arguments
4034///
4035/// - `&DocsViewerState` - Shared documentation viewer state.
4036/// - `ThemeTokens` - Base design tokens.
4037/// - `Vec<NodeId>` - Desktop and Mobile Globe trigger node handles.
4038///
4039/// # Returns
4040///
4041/// - `NodeId` - Mounted floating locale dropdown portal handle.
4042fn mount_docs_locale_dropdown_portal(
4043    state: &DocsViewerState,
4044    tokens: ThemeTokens,
4045    triggers: Vec<NodeId>,
4046) -> NodeId {
4047    let mut ctx: Context = current_context();
4048    let open_sig: Signal<bool> = state.get_locale_menu_open();
4049    let last_href_sig: Signal<String> = state.get_last_locale_href();
4050    let active_route_sig: Signal<String> = state.get_active_route();
4051    let active_toc_sig: Signal<String> = state.get_active_toc_slug();
4052    let vp_sig: Signal<Size> = ctx.get_viewport_size();
4053    let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
4054    let init_tok: ThemeTokens = live_tokens_untracked(tokens);
4055    let palette: ThemePalette = init_tok.get_palette();
4056    let geometry: ThemeGeometry = init_tok.get_geometry();
4057    let card_s: SurfaceColors = palette.surface(SurfaceRole::Card);
4058    let menu_r: f32 = geometry.get_radius_lg();
4059    let item_r: f32 = concentric_radius(menu_r, CONTROL_INSET);
4060    let active_prefix: String = state.get_site().get_locale_prefix().clone();
4061    let locales: Vec<DocLocaleConfig> = state.get_site().get_locales().clone();
4062    let hovered_idx: Signal<Option<usize>> = Signal::new(None);
4063    let mut item_rows: Vec<(NodeId, NodeId, NodeId, bool)> = Vec::with_capacity(locales.len());
4064    let mut item_nodes: Vec<NodeId> = Vec::with_capacity(locales.len());
4065    for (idx, loc) in locales.iter().enumerate() {
4066        let is_cur: bool = loc.get_prefix().as_str() == active_prefix.as_str();
4067        let display_lbl: String = if !loc.get_label().trim().is_empty() {
4068            loc.get_label().trim().to_string()
4069        } else {
4070            loc.get_dir().to_ascii_uppercase()
4071        };
4072        let active_prefix_pick: String = active_prefix.clone();
4073        let target_prefix_pick: String = loc.get_prefix().clone();
4074        let (init_bg, init_fg): (Color, Color) = if is_cur {
4075            let color_value: SurfaceColors = palette.surface(SurfaceRole::Primary);
4076            (color_value.get_bg(), color_value.get_fg())
4077        } else {
4078            (COLOR_TRANSPARENT, card_s.get_fg())
4079        };
4080        let on_pick_locale = move |_: &UiEvent| {
4081            let cur_route: String = active_route_sig.get_untracked();
4082            let cur_anchor: String = active_toc_sig.get_untracked();
4083            #[cfg(target_arch = "wasm32")]
4084            let base_dir: String = window()
4085                .and_then(|win: Window| win.location().pathname().ok())
4086                .map(|pn: String| {
4087                    resolve_site_root_from_pathname(pn.as_str(), active_prefix_pick.as_str())
4088                })
4089                .unwrap_or_else(|| asset_base_for_locale_prefix(active_prefix_pick.as_str()));
4090            #[cfg(not(target_arch = "wasm32"))]
4091            let base_dir: String = asset_base_for_locale_prefix(active_prefix_pick.as_str());
4092            let target_href: String = build_locale_switch_url(
4093                base_dir.as_str(),
4094                target_prefix_pick.as_str(),
4095                cur_route.as_str(),
4096                (!cur_anchor.is_empty()).then_some(cur_anchor.as_str()),
4097            );
4098            let _: bool = last_href_sig.set_if_changed(target_href.clone());
4099            let _: bool = open_sig.set_if_changed(false);
4100            #[cfg(target_arch = "wasm32")]
4101            if !is_cur {
4102                open_browser_url(&target_href, false);
4103            }
4104        };
4105        let paint_check = move |bounds: Rect, display_list: &mut DisplayList| {
4106            if is_cur {
4107                let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
4108                let fg: Color = lp.surface(SurfaceRole::Primary).get_fg();
4109                draw_euv_icon(EuvIconName::Check, bounds, display_list, fg);
4110            }
4111        };
4112        let mut txt_id: NodeId = NodeId::default();
4113        let mut chk_id: NodeId = NodeId::default();
4114        let row_sixth_style: Style = style! {
4115            Width(Length::Percent(100.0))
4116            Height(Length::Px(DOCS_DROPDOWN_ITEM_HEIGHT))
4117            Padding(Edges::symmetric(0.0, SPACE_SM))
4118            AlignItems::Center
4119            Gap(SPACE_SM)
4120            Background(init_bg)
4121            Radius(item_r)
4122            Overflow::Hidden
4123            CursorIcon::Pointer
4124            StopEventPropagation(true)
4125        };
4126        let text_secondary_style: Style = style! {
4127            FlexGrow(1.0)
4128            FlexShrink(1.0)
4129            MinWidth(Length::Px(0.0))
4130            FontSize(13.0)
4131            if is_cur { FontWeight::SemiBold } else { FontWeight::Normal }
4132            TextColor(init_fg)
4133            Overflow::Hidden
4134            TextOverflow::Ellipsis
4135        };
4136        let canvas_fifth_style: Style = style! {
4137            Width(Length::Px(13.0))
4138            Height(Length::Px(13.0))
4139            FlexShrink(0.0)
4140        };
4141        let row_id: NodeId = view! {
4142            row {
4143                style: row_sixth_style
4144                role: A11yRole::MenuItem
4145                a11y_label: display_lbl.clone()
4146                on_click: on_pick_locale
4147                text {
4148                    node_ref: txt_id
4149                    style: text_secondary_style
4150                    { display_lbl }
4151                }
4152                canvas {
4153                    node_ref: chk_id
4154                    style: canvas_fifth_style
4155                    painter: paint_check
4156                }
4157            }
4158        };
4159        ctx.on_pointer_enter(row_id, move |_: &UiEvent| {
4160            let _: bool = hovered_idx.set_if_changed(Some(idx));
4161        });
4162        ctx.on_pointer_leave(row_id, move |_: &UiEvent| {
4163            if hovered_idx.get_untracked() == Some(idx) {
4164                let _: bool = hovered_idx.set_if_changed(None);
4165            }
4166        });
4167        item_rows.push((row_id, txt_id, chk_id, is_cur));
4168        item_nodes.push(row_id);
4169    }
4170    let est_h: f32 =
4171        (locales.len() as f32) * (DOCS_DROPDOWN_ITEM_HEIGHT + CONTROL_INSET) + CONTROL_INSET * 2.0;
4172    let mut card: NodeId = NodeId::default();
4173    let portal_secondary_style: Style = style! {
4174        Display::None
4175        Position::Fixed
4176        Inset(Some(0.0), Some(0.0), Some(0.0), Some(0.0))
4177        Width(Length::Percent(100.0))
4178        Height(Length::Percent(100.0))
4179        Background(COLOR_TRANSPARENT)
4180        PointerEvents::None
4181        StopScrollPropagation(true)
4182        ZIndex(DOCS_DROPDOWN_Z_INDEX)
4183    };
4184    let column_tertiary_style: Style = style! {
4185        Position::Absolute
4186        Inset(Some(SHELL_DESKTOP_HEADER_HEIGHT + 6.0), None, None, Some(8.0))
4187        Width(Length::Px(DOCS_LOCALE_MENU_WIDTH))
4188        Padding(Edges::all(CONTROL_INSET))
4189        Gap(CONTROL_INSET)
4190        Background(card_s.get_bg())
4191        Border::new(geometry.get_border_width(), card_s.get_border())
4192        Radius(menu_r)
4193        geometry.get_shadow_lg()
4194        Overflow::Hidden
4195        StopEventPropagation(true)
4196    };
4197    let portal: NodeId = view! {
4198        portal {
4199            style: portal_secondary_style
4200            column {
4201                node_ref: card
4202                style: column_tertiary_style
4203                role: A11yRole::Menu
4204                a11y_label: BTN_LOCALE_A11Y.to_string()
4205                ..item_nodes
4206            }
4207        }
4208    };
4209    ctx.on_click(portal, move |ui_event: &UiEvent| {
4210        if ui_event.get_target() == portal {
4211            let _: bool = open_sig.set_if_changed(false);
4212        }
4213    });
4214    for key_target in [portal, card].into_iter() {
4215        ctx.on_key(key_target, move |interaction_event: &UiEvent| {
4216            let is_esc: bool = matches!(
4217                interaction_event.get_kind(),
4218                UiEventKind::KeyDown(KeyCode::Escape, _)
4219            ) || matches!(
4220                interaction_event.get_kind(),
4221                UiEventKind::KeyDown(KeyCode::Back, _)
4222            );
4223            if is_esc && open_sig.get_untracked() {
4224                let _: bool = open_sig.set_if_changed(false);
4225            }
4226        });
4227    }
4228    let sc_pos: SceneHandle = ctx.get_scene().clone();
4229    let sc_paint: SceneHandle = sc_pos.clone();
4230    let owned_nodes: Vec<NodeId> = {
4231        let mut target_node_id: Vec<NodeId> = Vec::with_capacity(item_rows.len() * 3 + 2);
4232        target_node_id.push(portal);
4233        target_node_id.push(card);
4234        for &(rid, tid, cid, _) in item_rows.iter() {
4235            target_node_id.push(rid);
4236            target_node_id.push(tid);
4237            target_node_id.push(cid);
4238        }
4239        target_node_id
4240    };
4241    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4242        let _: Effect =
4243            EuvOverlayStack::bind_signal(open_sig, DOCS_LOCALE_OVERLAY_NAME, DOCS_DROPDOWN_Z_INDEX);
4244        let _: Effect = Effect::new(move || {
4245            let is_open: bool = open_sig.get();
4246            let box_size: Size = vp_sig.get();
4247            let safe: SafeAreaInsets = safe_sig.get();
4248            let (left, top, width, _): (f32, f32, f32, f32) = docs_dropdown_anchor_rect(
4249                &sc_pos,
4250                &triggers,
4251                box_size,
4252                safe,
4253                DOCS_LOCALE_MENU_WIDTH,
4254                est_h.min(DOCS_DROPDOWN_MAX_HEIGHT),
4255            );
4256            if !is_open {
4257                let _: bool = hovered_idx.set_if_changed(None);
4258            }
4259            sc_pos.with_write(
4260                |tree: &mut SceneTree| {
4261                    let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4262                    let dirty_all: u16 = dirty_l | DIRTY_PAINT;
4263                    if let Some(item_count) = tree.get_node_mut(card) {
4264                        let lay: &mut LayoutStyle = item_count.get_mut_style().get_mut_layout();
4265                        lay.set_left(Some(left))
4266                            .set_top(Some(top))
4267                            .set_width(Length::Px(width));
4268                        tree.mark_dirty(card, dirty_all);
4269                    }
4270                    if let Some(node_entry) = tree.get_node_mut(portal) {
4271                        let computed_style: &mut Style = node_entry.get_mut_style();
4272                        computed_style.get_mut_layout().set_display(if is_open {
4273                            Display::Flex
4274                        } else {
4275                            Display::None
4276                        });
4277                        computed_style
4278                            .get_mut_paint()
4279                            .set_pointer_events(if is_open {
4280                                PointerEvents::Auto
4281                            } else {
4282                                PointerEvents::None
4283                            });
4284                        tree.mark_dirty(portal, dirty_all);
4285                    }
4286                },
4287                (),
4288            );
4289        });
4290        Effect::new(move || {
4291            let hov: Option<usize> = hovered_idx.get();
4292            let tok: ThemeTokens = use_live_tokens(tokens);
4293            let lp: ThemePalette = tok.get_palette();
4294            let lg: ThemeGeometry = tok.get_geometry();
4295            let cs: SurfaceColors = lp.surface(SurfaceRole::Card);
4296            let ps: SurfaceColors = lp.surface(SurfaceRole::Primary);
4297            let ac: SurfaceColors = lp.surface(SurfaceRole::Accent);
4298            sc_paint.with_write(
4299                |tree: &mut SceneTree| {
4300                    if let Some(normal_vec) = tree.get_node_mut(card) {
4301                        normal_vec
4302                            .get_mut_style()
4303                            .get_mut_paint()
4304                            .set_background(Some(cs.get_bg()))
4305                            .set_border(Border::new(lg.get_border_width(), cs.get_border()))
4306                            .set_shadow(Some(lg.get_shadow_lg()));
4307                        tree.mark_dirty(card, DIRTY_PAINT);
4308                    }
4309                    for (idx, &(rid, tid, cid, is_cur)) in item_rows.iter().enumerate() {
4310                        let is_hov: bool = hov == Some(idx);
4311                        let (bg, fg): (Color, Color) = if is_cur {
4312                            (ps.get_bg(), ps.get_fg())
4313                        } else if is_hov {
4314                            (ac.get_bg(), ac.get_fg())
4315                        } else {
4316                            (COLOR_TRANSPARENT, cs.get_fg())
4317                        };
4318                        if let Some(total_len) = tree.get_node_mut(rid) {
4319                            total_len
4320                                .get_mut_style()
4321                                .get_mut_paint()
4322                                .set_background(Some(bg));
4323                            tree.mark_dirty(rid, DIRTY_PAINT);
4324                        }
4325                        if let Some(item_count_primary) = tree.get_node_mut(tid) {
4326                            item_count_primary
4327                                .get_mut_style()
4328                                .get_mut_text()
4329                                .set_color(fg);
4330                            tree.mark_dirty(tid, DIRTY_PAINT);
4331                        }
4332                        tree.mark_dirty(cid, DIRTY_PAINT);
4333                    }
4334                },
4335                (),
4336            );
4337        })
4338    });
4339    ctx.get_scene().with_write(
4340        |tree: &mut SceneTree| {
4341            mark_theme_owned(tree, owned_nodes.as_slice());
4342            tree.attach_scope(portal, scope);
4343        },
4344        (),
4345    );
4346    portal
4347}
4348
4349/// Mounts the viewport-clamped scrollable floating 17-Scheme Theme Color Dropdown portal anchored beneath the topbar Palette icon button.
4350///
4351/// # Arguments
4352///
4353/// - `&DocsViewerState` - Shared documentation viewer state.
4354/// - `ThemeTokens` - Base design tokens.
4355/// - `Vec<NodeId>` - Desktop and Mobile Palette trigger node handles.
4356///
4357/// # Returns
4358///
4359/// - `NodeId` - Mounted floating 17-scheme dropdown portal handle.
4360fn mount_docs_scheme_dropdown_portal(
4361    state: &DocsViewerState,
4362    tokens: ThemeTokens,
4363    triggers: Vec<NodeId>,
4364) -> NodeId {
4365    let mut ctx: Context = current_context();
4366    let open_sig: Signal<bool> = state.get_scheme_menu_open();
4367    let scheme_sig: Signal<DesignScheme> = state.get_theme().get_scheme();
4368    let mode_sig: Signal<ThemeMode> = state.get_theme().get_mode();
4369    let vp_sig: Signal<Size> = ctx.get_viewport_size();
4370    let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
4371    let init_tok: ThemeTokens = live_tokens_untracked(tokens);
4372    let palette: ThemePalette = init_tok.get_palette();
4373    let geometry: ThemeGeometry = init_tok.get_geometry();
4374    let card_s: SurfaceColors = palette.surface(SurfaceRole::Card);
4375    let menu_r: f32 = geometry.get_radius_lg();
4376    let item_r: f32 = concentric_radius(menu_r, CONTROL_INSET);
4377    let all_schemes: [DesignScheme; 17] = DesignScheme::all();
4378    let init_scheme: DesignScheme = scheme_sig.get_untracked();
4379    let init_mode: ThemeMode = mode_sig.get_untracked();
4380    let hovered_idx: Signal<Option<usize>> = Signal::new(None);
4381    let mut item_handles: Vec<(DesignScheme, NodeId, NodeId, NodeId, NodeId)> =
4382        Vec::with_capacity(all_schemes.len());
4383    let mut item_nodes: Vec<NodeId> = Vec::with_capacity(all_schemes.len());
4384    for (idx, scheme) in all_schemes.into_iter().enumerate() {
4385        let is_sel: bool = scheme == init_scheme;
4386        let (init_bg, init_fg): (Color, Color) = if is_sel {
4387            let ps: SurfaceColors = palette.surface(SurfaceRole::Primary);
4388            (ps.get_bg(), ps.get_fg())
4389        } else {
4390            (COLOR_TRANSPARENT, card_s.get_fg())
4391        };
4392        let init_swatch: Color = ThemeTokens::resolve(scheme, init_mode)
4393            .get_palette()
4394            .get_primary();
4395        let lbl_str: &'static str = docs_scheme_display_label(scheme);
4396        let on_pick_scheme = move |_: &UiEvent| {
4397            let _: bool = scheme_sig.set_if_changed(scheme);
4398            let _: bool = open_sig.set_if_changed(false);
4399        };
4400        let paint_check = move |bounds: Rect, display_list: &mut DisplayList| {
4401            if scheme_sig.get_untracked() == scheme {
4402                let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
4403                let fg: Color = lp.surface(SurfaceRole::Primary).get_fg();
4404                draw_euv_icon(EuvIconName::Check, bounds, display_list, fg);
4405            }
4406        };
4407        let mut dot_id: NodeId = NodeId::default();
4408        let mut txt_id: NodeId = NodeId::default();
4409        let mut chk_id: NodeId = NodeId::default();
4410        let row_fifth_style: Style = style! {
4411            Width(Length::Percent(100.0))
4412            Height(Length::Px(DOCS_DROPDOWN_ITEM_HEIGHT))
4413            Padding(Edges::symmetric(0.0, SPACE_SM))
4414            AlignItems::Center
4415            Gap(SPACE_SM)
4416            Background(init_bg)
4417            Radius(item_r)
4418            Overflow::Hidden
4419            CursorIcon::Pointer
4420            StopEventPropagation(true)
4421        };
4422        let view_style: Style = style! {
4423            Width(Length::Px(12.0))
4424            Height(Length::Px(12.0))
4425            FlexShrink(0.0)
4426            Background(init_swatch)
4427            Border::new(1.0, palette.get_border())
4428            Radius(RADIUS_PILL)
4429        };
4430        let text_style: Style = style! {
4431            FlexGrow(1.0)
4432            FlexShrink(1.0)
4433            MinWidth(Length::Px(0.0))
4434            FontSize(13.0)
4435            if is_sel { FontWeight::SemiBold } else { FontWeight::Normal }
4436            TextColor(init_fg)
4437            Overflow::Hidden
4438            TextOverflow::Ellipsis
4439        };
4440        let canvas_quaternary_style: Style = style! {
4441            Width(Length::Px(13.0))
4442            Height(Length::Px(13.0))
4443            FlexShrink(0.0)
4444        };
4445        let row_id: NodeId = view! {
4446            row {
4447                style: row_fifth_style
4448                role: A11yRole::MenuItem
4449                a11y_label: lbl_str.to_string()
4450                on_click: on_pick_scheme
4451                view {
4452                    node_ref: dot_id
4453                    style: view_style
4454                }
4455                text {
4456                    node_ref: txt_id
4457                    style: text_style
4458                    { lbl_str }
4459                }
4460                canvas {
4461                    node_ref: chk_id
4462                    style: canvas_quaternary_style
4463                    painter: paint_check
4464                }
4465            }
4466        };
4467        ctx.on_pointer_enter(row_id, move |_: &UiEvent| {
4468            let _: bool = hovered_idx.set_if_changed(Some(idx));
4469        });
4470        ctx.on_pointer_leave(row_id, move |_: &UiEvent| {
4471            if hovered_idx.get_untracked() == Some(idx) {
4472                let _: bool = hovered_idx.set_if_changed(None);
4473            }
4474        });
4475        item_handles.push((scheme, row_id, dot_id, txt_id, chk_id));
4476        item_nodes.push(row_id);
4477    }
4478    let mut card: NodeId = NodeId::default();
4479    let mut scroll_list: NodeId = NodeId::default();
4480    let portal_style: Style = style! {
4481        Display::None
4482        Position::Fixed
4483        Inset(Some(0.0), Some(0.0), Some(0.0), Some(0.0))
4484        Width(Length::Percent(100.0))
4485        Height(Length::Percent(100.0))
4486        Background(COLOR_TRANSPARENT)
4487        PointerEvents::None
4488        StopScrollPropagation(true)
4489        ZIndex(DOCS_DROPDOWN_Z_INDEX)
4490    };
4491    let column_secondary_style: Style = style! {
4492        Position::Absolute
4493        Inset(Some(SHELL_DESKTOP_HEADER_HEIGHT + 6.0), None, None, Some(8.0))
4494        Width(Length::Px(DOCS_SCHEME_MENU_WIDTH))
4495        Padding(Edges::all(CONTROL_INSET))
4496        Background(card_s.get_bg())
4497        Border::new(geometry.get_border_width(), card_s.get_border())
4498        Radius(menu_r)
4499        geometry.get_shadow_lg()
4500        Overflow::Hidden
4501        StopEventPropagation(true)
4502    };
4503    let scroll_style: Style = style! {
4504        FlexDirection::Column
4505        Width(Length::Percent(100.0))
4506        MaxHeight(Length::Px(DOCS_DROPDOWN_MAX_HEIGHT))
4507        Gap(CONTROL_INSET)
4508    };
4509    let portal: NodeId = view! {
4510        portal {
4511            style: portal_style
4512            column {
4513                node_ref: card
4514                style: column_secondary_style
4515                role: A11yRole::Menu
4516                a11y_label: BTN_SCHEME_A11Y.to_string()
4517                scroll {
4518                    node_ref: scroll_list
4519                    style: scroll_style
4520                    ..item_nodes
4521                }
4522            }
4523        }
4524    };
4525    ctx.on_click(portal, move |ui_event: &UiEvent| {
4526        if ui_event.get_target() == portal {
4527            let _: bool = open_sig.set_if_changed(false);
4528        }
4529    });
4530    for key_target in [portal, card].into_iter() {
4531        ctx.on_key(key_target, move |interaction_event: &UiEvent| {
4532            let is_esc: bool = matches!(
4533                interaction_event.get_kind(),
4534                UiEventKind::KeyDown(KeyCode::Escape, _)
4535            ) || matches!(
4536                interaction_event.get_kind(),
4537                UiEventKind::KeyDown(KeyCode::Back, _)
4538            );
4539            if is_esc && open_sig.get_untracked() {
4540                let _: bool = open_sig.set_if_changed(false);
4541            }
4542        });
4543    }
4544    let sc_pos: SceneHandle = ctx.get_scene().clone();
4545    let sc_paint: SceneHandle = sc_pos.clone();
4546    let owned_nodes: Vec<NodeId> = {
4547        let mut target_node_id: Vec<NodeId> = Vec::with_capacity(item_handles.len() * 4 + 3);
4548        target_node_id.push(portal);
4549        target_node_id.push(card);
4550        target_node_id.push(scroll_list);
4551        for &(_, rid, did, tid, cid) in item_handles.iter() {
4552            target_node_id.push(rid);
4553            target_node_id.push(did);
4554            target_node_id.push(tid);
4555            target_node_id.push(cid);
4556        }
4557        target_node_id
4558    };
4559    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4560        let _: Effect =
4561            EuvOverlayStack::bind_signal(open_sig, DOCS_SCHEME_OVERLAY_NAME, DOCS_DROPDOWN_Z_INDEX);
4562        let _: Effect = Effect::new(move || {
4563            let is_open: bool = open_sig.get();
4564            let box_size: Size = vp_sig.get();
4565            let safe: SafeAreaInsets = safe_sig.get();
4566            let (left, top, width, max_h): (f32, f32, f32, f32) = docs_dropdown_anchor_rect(
4567                &sc_pos,
4568                &triggers,
4569                box_size,
4570                safe,
4571                DOCS_SCHEME_MENU_WIDTH,
4572                DOCS_DROPDOWN_MAX_HEIGHT,
4573            );
4574            if !is_open {
4575                let _: bool = hovered_idx.set_if_changed(None);
4576            }
4577            let inner_max_h: f32 = (max_h - CONTROL_INSET * 2.0).max(96.0);
4578            sc_pos.with_write(
4579                |tree: &mut SceneTree| {
4580                    let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4581                    let dirty_all: u16 = dirty_l | DIRTY_PAINT;
4582                    if let Some(item_count) = tree.get_node_mut(scroll_list) {
4583                        item_count
4584                            .get_mut_style()
4585                            .get_mut_layout()
4586                            .set_max_height(Length::Px(inner_max_h));
4587                        tree.mark_dirty(scroll_list, dirty_all);
4588                    }
4589                    if let Some(node_entry) = tree.get_node_mut(card) {
4590                        let lay: &mut LayoutStyle = node_entry.get_mut_style().get_mut_layout();
4591                        lay.set_left(Some(left))
4592                            .set_top(Some(top))
4593                            .set_width(Length::Px(width));
4594                        tree.mark_dirty(card, dirty_all);
4595                    }
4596                    if let Some(normal_vec) = tree.get_node_mut(portal) {
4597                        let computed_style: &mut Style = normal_vec.get_mut_style();
4598                        computed_style.get_mut_layout().set_display(if is_open {
4599                            Display::Flex
4600                        } else {
4601                            Display::None
4602                        });
4603                        computed_style
4604                            .get_mut_paint()
4605                            .set_pointer_events(if is_open {
4606                                PointerEvents::Auto
4607                            } else {
4608                                PointerEvents::None
4609                            });
4610                        tree.mark_dirty(portal, dirty_all);
4611                    }
4612                },
4613                (),
4614            );
4615        });
4616        Effect::new(move || {
4617            let cur_scheme: DesignScheme = scheme_sig.get();
4618            let cur_mode: ThemeMode = mode_sig.get();
4619            let hov: Option<usize> = hovered_idx.get();
4620            let tok: ThemeTokens = use_live_tokens(tokens);
4621            let lp: ThemePalette = tok.get_palette();
4622            let lg: ThemeGeometry = tok.get_geometry();
4623            let cs: SurfaceColors = lp.surface(SurfaceRole::Card);
4624            let ps: SurfaceColors = lp.surface(SurfaceRole::Primary);
4625            let ac: SurfaceColors = lp.surface(SurfaceRole::Accent);
4626            sc_paint.with_write(
4627                |tree: &mut SceneTree| {
4628                    if let Some(total_len) = tree.get_node_mut(card) {
4629                        total_len
4630                            .get_mut_style()
4631                            .get_mut_paint()
4632                            .set_background(Some(cs.get_bg()))
4633                            .set_border(Border::new(lg.get_border_width(), cs.get_border()))
4634                            .set_shadow(Some(lg.get_shadow_lg()));
4635                        tree.mark_dirty(card, DIRTY_PAINT);
4636                    }
4637                    for (idx, &(sc_item, rid, did, tid, cid)) in item_handles.iter().enumerate() {
4638                        let is_sel: bool = sc_item == cur_scheme;
4639                        let is_hov: bool = hov == Some(idx);
4640                        let (bg, fg): (Color, Color) = if is_sel {
4641                            (ps.get_bg(), ps.get_fg())
4642                        } else if is_hov {
4643                            (ac.get_bg(), ac.get_fg())
4644                        } else {
4645                            (COLOR_TRANSPARENT, cs.get_fg())
4646                        };
4647                        let sw_col: Color = ThemeTokens::resolve(sc_item, cur_mode)
4648                            .get_palette()
4649                            .get_primary();
4650                        let sw_border: Color = if is_sel {
4651                            ps.get_fg().with_alpha(160)
4652                        } else {
4653                            lp.get_border()
4654                        };
4655                        if let Some(item_count_primary) = tree.get_node_mut(rid) {
4656                            item_count_primary
4657                                .get_mut_style()
4658                                .get_mut_paint()
4659                                .set_background(Some(bg));
4660                            tree.mark_dirty(rid, DIRTY_PAINT);
4661                        }
4662                        if let Some(item_count_secondary) = tree.get_node_mut(did) {
4663                            item_count_secondary
4664                                .get_mut_style()
4665                                .get_mut_paint()
4666                                .set_background(Some(sw_col))
4667                                .set_border(Border::new(1.0, sw_border));
4668                            tree.mark_dirty(did, DIRTY_PAINT);
4669                        }
4670                        if let Some(item_count_next) = tree.get_node_mut(tid) {
4671                            item_count_next
4672                                .get_mut_style()
4673                                .get_mut_text()
4674                                .set_color(fg)
4675                                .set_weight(if is_sel {
4676                                    FontWeight::SemiBold
4677                                } else {
4678                                    FontWeight::Normal
4679                                });
4680                            tree.mark_dirty(tid, DIRTY_PAINT);
4681                        }
4682                        tree.mark_dirty(cid, DIRTY_PAINT);
4683                    }
4684                },
4685                (),
4686            );
4687        })
4688    });
4689    ctx.get_scene().with_write(
4690        |tree: &mut SceneTree| {
4691            mark_theme_owned(tree, owned_nodes.as_slice());
4692            tree.attach_scope(portal, scope);
4693        },
4694        (),
4695    );
4696    portal
4697}
4698
4699/// Mounts the full showcase-parity reactive documentation shell (`EuvAppShell`, `EuvRouter` `PageRetention::Freeze`, pure recursive filesystem catalog tree sidebar, topbar live Search + Locale Globe dropdown + 17-Scheme Palette dropdown + Light/Dark toggle, sticky right tree TOC, and mobile 2-item `EuvBottomNav`).
4700///
4701/// # Arguments
4702///
4703/// - `&DocsViewerState` - Shared reactive documentation viewer state.
4704///
4705/// # Returns
4706///
4707/// - `NodeId` - Mounted documentation application root handle.
4708pub fn mount_docs_viewer_with_state(state: &DocsViewerState) -> NodeId {
4709    provide_theme(state.get_theme().clone());
4710    ensure_docs_routes_registered(state);
4711    let tokens: ThemeTokens = untracked(|| state.get_theme().get_tokens().get());
4712    let active_route: Signal<String> = state.get_active_route();
4713    let cmd_open: Signal<bool> = state.get_cmd_open();
4714    let cmd_query: Signal<String> = state.get_cmd_query();
4715    let locale_open: Signal<bool> = state.get_locale_menu_open();
4716    let scheme_open: Signal<bool> = state.get_scheme_menu_open();
4717    let all_pages: &[DocPage] = state.get_site().get_pages().as_slice();
4718    let mut cmd_routes: Vec<String> = Vec::with_capacity(all_pages.len());
4719    let mut cmd_items: Vec<String> = Vec::with_capacity(all_pages.len() + 2);
4720    for page in all_pages.iter() {
4721        if !page.has_readable_content() {
4722            continue;
4723        }
4724        cmd_routes.push(page.get_route().clone());
4725        cmd_items.push(format!("{} — {}", page.get_title(), page.get_section()));
4726    }
4727    let toggle_idx: usize = cmd_items.len();
4728    cmd_items.push(CMD_ACTION_TOGGLE_MODE.to_string());
4729    let scheme_idx: usize = cmd_items.len();
4730    cmd_items.push(CMD_ACTION_NEXT_SCHEME.to_string());
4731    let cmd_sel: Signal<Option<usize>> = Signal::new(None);
4732    let cmd_list: NodeId = view! {
4733        EuvCommand {
4734            items: cmd_items
4735            selected: cmd_sel
4736            tokens: tokens
4737            query: cmd_query
4738            placeholder: CMD_PLACEHOLDER
4739            frameless: true
4740        }
4741    };
4742    let cmd_state: DocsViewerState = state.clone();
4743    let (cmd_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4744        Effect::new(move || {
4745            if let Some(idx) = cmd_sel.get() {
4746                if let Some(target) = cmd_routes.get(idx) {
4747                    let _: bool = active_route.set_if_changed(target.clone());
4748                } else if idx == toggle_idx {
4749                    cmd_state.toggle_theme_mode();
4750                } else if idx == scheme_idx {
4751                    cmd_state.next_scheme();
4752                }
4753                let _: bool = cmd_sel.set_if_changed(None);
4754                let _: bool = cmd_open.set_if_changed(false);
4755            }
4756        })
4757    });
4758    let cmd_modal: NodeId = view! {
4759        EuvModal {
4760            open: cmd_open
4761            title: CMD_MODAL_TITLE.to_string()
4762            body: cmd_list
4763            tokens: tokens
4764        }
4765    };
4766    let mut rctx: Context = current_context();
4767    let theme_memo: Memo<ThemeTokens> = state.get_theme().get_tokens();
4768    let prev_modal_tok: Rc<Cell<ThemeTokens>> = Rc::new(Cell::new(tokens));
4769    let modal_theme_ctx: Context = rctx.clone();
4770    let (modal_theme_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4771        Effect::new(move || {
4772            let next_tok: ThemeTokens = theme_memo.get();
4773            let old_tok: ThemeTokens = prev_modal_tok.replace(next_tok);
4774            if old_tok == next_tok {
4775                return;
4776            }
4777            modal_theme_ctx.get_scene().with_write(
4778                |tree: &mut SceneTree| {
4779                    remap_subtree_theme_in_place(tree, cmd_modal, old_tok, next_tok);
4780                },
4781                (),
4782            );
4783        })
4784    });
4785    rctx.get_scene().with_write(
4786        |tree: &mut SceneTree| {
4787            tree.attach_scope(cmd_modal, cmd_scope);
4788            tree.attach_scope(cmd_modal, modal_theme_scope);
4789        },
4790        (),
4791    );
4792    let router: EuvRouter = state.get_router().clone();
4793    let cur_route: String = active_route.get_untracked();
4794    if router.get_current_path().get_untracked() != cur_route {
4795        router.replace(&cur_route);
4796    }
4797    let breadcrumb_sig: Signal<String> = Signal::new(state.breadcrumb_for_route(&cur_route));
4798    let page_pad_sig: Signal<Edges> = Signal::new(Edges::all(SPACE_LG));
4799    let swipe_routes: Vec<String> = state.ordered_routes();
4800    let state_sync: DocsViewerState = state.clone();
4801    let router_sync_in: EuvRouter = router.clone();
4802    let router_path_sig: Signal<String> = router.get_current_path();
4803    let (sync_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4804        let _: Effect = Effect::new(move || {
4805            let target: String = active_route.get();
4806            let _: bool = breadcrumb_sig.set_if_changed(state_sync.breadcrumb_for_route(&target));
4807            if router_sync_in.get_current_path().get_untracked() != target {
4808                router_sync_in.push(&target);
4809            }
4810        });
4811        Effect::new(move || {
4812            let rp: String = router_path_sig.get();
4813            if active_route.get_untracked() != rp {
4814                let _: bool = active_route.set_if_changed(rp);
4815            }
4816        })
4817    });
4818    let state_fallback: DocsViewerState = state.clone();
4819    let outlet_node: NodeId = router
4820        .outlet(move |matched: &EuvRouteMatch| {
4821            let tok: ThemeTokens = untracked(|| state_fallback.get_theme().get_tokens().get());
4822            match state_fallback
4823                .get_site()
4824                .find_by_route(matched.get_path())
4825                .or_else(|| state_fallback.get_site().get_pages().first())
4826            {
4827                Some(point_val) => mount_doc_page_with_context(point_val, &state_fallback, tok),
4828                None => view! {
4829                    EuvEmpty {
4830                        title: EMPTY_PAGE_TITLE.to_string()
4831                        description: EMPTY_PAGE_MSG.to_string()
4832                        tokens: tok
4833                    }
4834                },
4835            }
4836        })
4837        .with_theme(state.get_theme().clone())
4838        .with_page_padding(page_pad_sig)
4839        .with_route_order(swipe_routes.clone())
4840        .mount();
4841    rctx.get_scene().with_write(
4842        |tree: &mut SceneTree| {
4843            tree.attach_scope(outlet_node, sync_scope);
4844        },
4845        (),
4846    );
4847    let sidebar_node: NodeId = mount_docs_catalog_tree(state, tokens);
4848    let theme_mode_sig: Signal<ThemeMode> = state.get_theme().get_mode();
4849    let has_multi_locales: bool = state.get_site().get_locales().len() > 1;
4850    let search_pill_lbl: &'static str = state.search_button_label();
4851    let icon_btn_style_desk = move || -> Style {
4852        let live_tok: ThemeTokens = use_live_tokens(tokens);
4853        let live_p: ThemePalette = live_tok.get_palette();
4854        let live_g: ThemeGeometry = live_tok.get_geometry();
4855        style! {
4856            FlexDirection::Row
4857            Width(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4858            Height(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4859            FlexShrink(0.0)
4860            JustifyContent::Center
4861            AlignItems::Center
4862            Background(live_p.get_background())
4863            Border::new(live_g.get_border_width(), live_p.get_border())
4864            Radius(live_g.get_radius_md())
4865            CursorIcon::Pointer
4866        }
4867    };
4868    let icon_btn_style_mob = move || -> Style {
4869        let live_tok: ThemeTokens = use_live_tokens(tokens);
4870        let live_p: ThemePalette = live_tok.get_palette();
4871        let live_g: ThemeGeometry = live_tok.get_geometry();
4872        style! {
4873            FlexDirection::Row
4874            Width(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4875            Height(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4876            FlexShrink(0.0)
4877            JustifyContent::Center
4878            AlignItems::Center
4879            Background(live_p.get_background())
4880            Border::new(live_g.get_border_width(), live_p.get_border())
4881            Radius(live_g.get_radius_md())
4882            CursorIcon::Pointer
4883        }
4884    };
4885    let search_pill_style = move || -> Style {
4886        let live_tok: ThemeTokens = use_live_tokens(tokens);
4887        let live_p: ThemePalette = live_tok.get_palette();
4888        let live_g: ThemeGeometry = live_tok.get_geometry();
4889        style! {
4890            FlexDirection::Row
4891            MinWidth(Length::Px(136.0))
4892            Height(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4893            FlexShrink(0.0)
4894            Padding(Edges::symmetric(0.0, 10.0))
4895            JustifyContent::SpaceBetween
4896            AlignItems::Center
4897            Gap(SPACE_SM)
4898            Background(live_p.get_background())
4899            Border::new(live_g.get_border_width(), live_p.get_border())
4900            Radius(live_g.get_radius_md())
4901            CursorIcon::Pointer
4902        }
4903    };
4904    let search_lbl_style = move || -> Style {
4905        let live_p: ThemePalette = use_live_tokens(tokens).get_palette();
4906        style! {
4907            FontSize(12.5)
4908            TextColor(live_p.get_muted_foreground())
4909        }
4910    };
4911    let kbd_badge_style = move || -> Style {
4912        let live_tok: ThemeTokens = use_live_tokens(tokens);
4913        let live_p: ThemePalette = live_tok.get_palette();
4914        let live_g: ThemeGeometry = live_tok.get_geometry();
4915        style! {
4916            Padding(Edges::symmetric(1.0, 5.0))
4917            Background(live_p.get_muted())
4918            Border::new(live_g.get_border_width(), live_p.get_border())
4919            Radius(live_g.get_radius_sm())
4920            FontSize(11.0)
4921            TextColor(live_p.get_muted_foreground())
4922        }
4923    };
4924    let paint_search_desk = move |bounds: Rect, display_list: &mut DisplayList| {
4925        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4926        draw_docs_search_icon(bounds, display_list, live_p.get_muted_foreground());
4927    };
4928    let paint_search_mob = move |bounds: Rect, draw_commands: &mut DisplayList| {
4929        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4930        draw_docs_search_icon(bounds, draw_commands, live_p.get_foreground());
4931    };
4932    let paint_globe_desk = move |bounds: Rect, command_list: &mut DisplayList| {
4933        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4934        draw_docs_globe_icon(bounds, command_list, live_p.get_foreground());
4935    };
4936    let paint_globe_mob = move |bounds: Rect, display_list_primary: &mut DisplayList| {
4937        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4938        draw_docs_globe_icon(bounds, display_list_primary, live_p.get_foreground());
4939    };
4940    let paint_scheme_desk = move |bounds: Rect, display_list_secondary: &mut DisplayList| {
4941        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4942        draw_docs_palette_icon(
4943            bounds,
4944            display_list_secondary,
4945            live_p.get_foreground(),
4946            live_p.get_primary(),
4947        );
4948    };
4949    let paint_scheme_mob = move |bounds: Rect, display_list_next: &mut DisplayList| {
4950        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4951        draw_docs_palette_icon(
4952            bounds,
4953            display_list_next,
4954            live_p.get_foreground(),
4955            live_p.get_primary(),
4956        );
4957    };
4958    let paint_mode_desk = move |bounds: Rect, display_list_alt: &mut DisplayList| {
4959        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4960        match theme_mode_sig.get_untracked() {
4961            ThemeMode::Dark => {
4962                draw_docs_sun_icon(bounds, display_list_alt, live_p.get_foreground())
4963            }
4964            ThemeMode::Light => {
4965                draw_docs_moon_star_icon(bounds, display_list_alt, live_p.get_foreground())
4966            }
4967        }
4968    };
4969    let paint_mode_mob = move |bounds: Rect, display_list_inner: &mut DisplayList| {
4970        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4971        match theme_mode_sig.get_untracked() {
4972            ThemeMode::Dark => {
4973                draw_docs_sun_icon(bounds, display_list_inner, live_p.get_foreground())
4974            }
4975            ThemeMode::Light => {
4976                draw_docs_moon_star_icon(bounds, display_list_inner, live_p.get_foreground())
4977            }
4978        }
4979    };
4980    let st_mode_desk: DocsViewerState = state.clone();
4981    let st_mode_mob: DocsViewerState = state.clone();
4982    let on_open_cmd_desk = move |_: &UiEvent| {
4983        let _: bool = locale_open.set_if_changed(false);
4984        let _: bool = scheme_open.set_if_changed(false);
4985        let _: bool = cmd_open.set_if_changed(true);
4986    };
4987    let on_open_cmd_mob = move |_: &UiEvent| {
4988        let _: bool = locale_open.set_if_changed(false);
4989        let _: bool = scheme_open.set_if_changed(false);
4990        let _: bool = cmd_open.set_if_changed(true);
4991    };
4992    let on_toggle_locale_desk = move |_: &UiEvent| {
4993        let next: bool = !locale_open.get_untracked();
4994        let _: bool = scheme_open.set_if_changed(false);
4995        let _: bool = locale_open.set_if_changed(next);
4996    };
4997    let on_toggle_locale_mob = move |_: &UiEvent| {
4998        let next: bool = !locale_open.get_untracked();
4999        let _: bool = scheme_open.set_if_changed(false);
5000        let _: bool = locale_open.set_if_changed(next);
5001    };
5002    let on_toggle_scheme_desk = move |_: &UiEvent| {
5003        let next: bool = !scheme_open.get_untracked();
5004        let _: bool = locale_open.set_if_changed(false);
5005        let _: bool = scheme_open.set_if_changed(next);
5006    };
5007    let on_toggle_scheme_mob = move |_: &UiEvent| {
5008        let next: bool = !scheme_open.get_untracked();
5009        let _: bool = locale_open.set_if_changed(false);
5010        let _: bool = scheme_open.set_if_changed(next);
5011    };
5012    let on_toggle_mode_desk = move |_: &UiEvent| {
5013        st_mode_desk.toggle_theme_mode();
5014    };
5015    let on_toggle_mode_mob = move |_: &UiEvent| {
5016        st_mode_mob.toggle_theme_mode();
5017    };
5018    let mut locale_btn_desk: NodeId = NodeId::default();
5019    let mut locale_btn_mob: NodeId = NodeId::default();
5020    let mut scheme_btn_desk: NodeId = NodeId::default();
5021    let mut scheme_btn_mob: NodeId = NodeId::default();
5022    let row_tertiary_style: Style = style! {
5023        Gap(SPACE_XS)
5024        AlignItems::Center
5025    };
5026    let row_quaternary_style: Style = style! {
5027        AlignItems::Center
5028        Gap(6.0)
5029    };
5030    let canvas_secondary_style: Style = style! {
5031        Width(Length::Px(15.0))
5032        Height(Length::Px(15.0))
5033        FlexShrink(0.0)
5034    };
5035    let canvas_tertiary_style: Style = style! {
5036        Width(Length::Px(DOCS_TOPBAR_ICON_SIZE))
5037        Height(Length::Px(DOCS_TOPBAR_ICON_SIZE))
5038    };
5039    let top_actions: NodeId = view! {
5040        row {
5041            style: row_tertiary_style
5042            row {
5043                bind_style: search_pill_style
5044                role: A11yRole::Button
5045                a11y_label: BTN_SEARCH_A11Y.to_string()
5046                on_click: on_open_cmd_desk
5047                row {
5048                    style: row_quaternary_style
5049                    canvas {
5050                        style: canvas_secondary_style
5051                        caching: CanvasCaching::RetainedStatic
5052                        painter: paint_search_desk
5053                    }
5054                    text {
5055                        bind_style: search_lbl_style
5056                        { search_pill_lbl }
5057                    }
5058                }
5059                text {
5060                    bind_style: kbd_badge_style
5061                    { DOCS_SEARCH_SHORTCUT_HINT }
5062                }
5063            }
5064            if has_multi_locales {
5065                row {
5066                    node_ref: locale_btn_desk
5067                    bind_style: icon_btn_style_desk
5068                    role: A11yRole::Button
5069                    a11y_label: BTN_LOCALE_A11Y.to_string()
5070                    on_click: on_toggle_locale_desk
5071                    canvas {
5072                        style: canvas_tertiary_style
5073                        caching: CanvasCaching::RetainedStatic
5074                        painter: paint_globe_desk
5075                    }
5076                }
5077            }
5078            row {
5079                node_ref: scheme_btn_desk
5080                bind_style: icon_btn_style_desk
5081                role: A11yRole::Button
5082                a11y_label: BTN_SCHEME_A11Y.to_string()
5083                on_click: on_toggle_scheme_desk
5084                canvas {
5085                    style: canvas_tertiary_style
5086                    caching: CanvasCaching::RetainedStatic
5087                    painter: paint_scheme_desk
5088                }
5089            }
5090            row {
5091                bind_style: icon_btn_style_desk
5092                role: A11yRole::Button
5093                a11y_label: BTN_MODE_A11Y.to_string()
5094                on_click: on_toggle_mode_desk
5095                canvas {
5096                    style: canvas_tertiary_style
5097                    caching: CanvasCaching::RetainedStatic
5098                    painter: paint_mode_desk
5099                }
5100            }
5101        }
5102    };
5103    let row_secondary_style: Style = style! {
5104        Gap(SPACE_XS)
5105        AlignItems::Center
5106    };
5107    let canvas_style: Style = style! {
5108        Width(Length::Px(DOCS_TOPBAR_ICON_SIZE))
5109        Height(Length::Px(DOCS_TOPBAR_ICON_SIZE))
5110    };
5111    let mobile_actions: NodeId = view! {
5112        row {
5113            style: row_secondary_style
5114            row {
5115                bind_style: icon_btn_style_mob
5116                role: A11yRole::Button
5117                a11y_label: BTN_SEARCH_A11Y.to_string()
5118                on_click: on_open_cmd_mob
5119                canvas {
5120                    style: canvas_style
5121                    caching: CanvasCaching::RetainedStatic
5122                    painter: paint_search_mob
5123                }
5124            }
5125            if has_multi_locales {
5126                row {
5127                    node_ref: locale_btn_mob
5128                    bind_style: icon_btn_style_mob
5129                    role: A11yRole::Button
5130                    a11y_label: BTN_LOCALE_A11Y.to_string()
5131                    on_click: on_toggle_locale_mob
5132                    canvas {
5133                        style: canvas_style
5134                        caching: CanvasCaching::RetainedStatic
5135                        painter: paint_globe_mob
5136                    }
5137                }
5138            }
5139            row {
5140                node_ref: scheme_btn_mob
5141                bind_style: icon_btn_style_mob
5142                role: A11yRole::Button
5143                a11y_label: BTN_SCHEME_A11Y.to_string()
5144                on_click: on_toggle_scheme_mob
5145                canvas {
5146                    style: canvas_style
5147                    caching: CanvasCaching::RetainedStatic
5148                    painter: paint_scheme_mob
5149                }
5150            }
5151            row {
5152                bind_style: icon_btn_style_mob
5153                role: A11yRole::Button
5154                a11y_label: BTN_MODE_A11Y.to_string()
5155                on_click: on_toggle_mode_mob
5156                canvas {
5157                    style: canvas_style
5158                    caching: CanvasCaching::RetainedStatic
5159                    painter: paint_mode_mob
5160                }
5161            }
5162        }
5163    };
5164    let bottom_items: Vec<EuvNavItem> = state.bottom_nav_items();
5165    let home_route_path: String = state.home_route();
5166    let catalog_open: Signal<bool> = state.get_catalog_drawer_open();
5167    let bnav_route: Signal<String> =
5168        Signal::new(if active_route.get_untracked() == home_route_path {
5169            home_route_path.clone()
5170        } else {
5171            DOCS_BNAV_CATALOG_ROUTE.to_string()
5172        });
5173    let home_for_bnav: String = home_route_path.clone();
5174    let home_for_sync: String = home_route_path.clone();
5175    let home_for_brand: String = home_route_path;
5176    let vp_for_drawer: Signal<Size> = rctx.get_viewport_size();
5177    let (bnav_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
5178        let _: Effect = Effect::new(move || {
5179            let picked: String = bnav_route.get();
5180            if picked == DOCS_BNAV_CATALOG_ROUTE {
5181                let _: bool = catalog_open.set_if_changed(true);
5182            } else if picked == home_for_bnav {
5183                let _: bool = catalog_open.set_if_changed(false);
5184                if active_route.get_untracked() != home_for_bnav {
5185                    let _: bool = active_route.set_if_changed(home_for_bnav.clone());
5186                }
5187            }
5188        });
5189        let _: Effect = Effect::new(move || {
5190            let cur: String = active_route.get();
5191            let _: bool = catalog_open.set_if_changed(false);
5192            let next_tab: String = if cur == home_for_sync {
5193                home_for_sync.clone()
5194            } else {
5195                String::new()
5196            };
5197            if bnav_route.get_untracked() != next_tab {
5198                let _: bool = bnav_route.set_if_changed(next_tab);
5199            }
5200        });
5201        let _: Effect = Effect::new(move || {
5202            let open_now: bool = catalog_open.get();
5203            if !open_now && bnav_route.get_untracked() == DOCS_BNAV_CATALOG_ROUTE {
5204                let cur: String = active_route.get_untracked();
5205                let _: bool = bnav_route.set_if_changed(cur);
5206            }
5207        });
5208        Effect::new(move || {
5209            let box_size: Size = vp_for_drawer.get();
5210            if box_size.get_width() >= DESKTOP_LAYOUT_BREAKPOINT {
5211                let _: bool = catalog_open.set_if_changed(false);
5212            }
5213        })
5214    });
5215    let bottom_nav_opt: Option<NodeId> = if bottom_items.len() >= 2 {
5216        Some(view! {
5217            EuvBottomNav {
5218                items: bottom_items
5219                active_route: bnav_route
5220                tokens: tokens
5221            }
5222        })
5223    } else {
5224        None
5225    };
5226    let brand_scene: SceneHandle = rctx.get_scene().clone();
5227    let on_brand_home = move |_: &UiEvent| {
5228        let _: bool = catalog_open.set_if_changed(false);
5229        let _: bool = locale_open.set_if_changed(false);
5230        let _: bool = scheme_open.set_if_changed(false);
5231        let _: bool = active_route.set_if_changed(home_for_brand.clone());
5232        brand_scene.with_write(
5233            |tree: &mut SceneTree| {
5234                reset_active_scroll_in_subtree(tree, outlet_node);
5235            },
5236            (),
5237        );
5238    };
5239    let mut shell: EuvAppShell = EuvAppShell::new(
5240        state.get_site().get_title().clone(),
5241        sidebar_node,
5242        outlet_node,
5243        tokens,
5244    )
5245    .route(active_route)
5246    .drawer_open(catalog_open)
5247    .brand_logo(euv_brand_logo_image())
5248    .auto_hide_chrome_on_scroll(true)
5249    .on_brand_click(on_brand_home)
5250    .top_bar_actions(top_actions)
5251    .mobile_header_actions(mobile_actions)
5252    .breadcrumb(breadcrumb_sig)
5253    .swipe_routes(swipe_routes)
5254    .theme(state.get_theme().clone())
5255    .page_padding(page_pad_sig);
5256    if let Some(bnav) = bottom_nav_opt {
5257        shell = shell.bottom_nav(bnav);
5258    }
5259    state.get_outlet_root().set(outlet_node);
5260    let scroll_tick_sig: Signal<u64> = state.get_scroll_tick();
5261    let shell_node: NodeId = shell.mount();
5262    let hooked_page_scrolls: Rc<RefCell<Vec<NodeId>>> = Rc::new(RefCell::new(Vec::new()));
5263    let hook_scene: SceneHandle = rctx.get_scene().clone();
5264    let sync_state: DocsViewerState = state.clone();
5265    let sync_scene: SceneHandle = rctx.get_scene().clone();
5266    hook_outlet_page_scrolls(
5267        &hook_scene,
5268        outlet_node,
5269        &hooked_page_scrolls,
5270        scroll_tick_sig,
5271    );
5272    let (scroll_hook_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
5273        Effect::new(move || {
5274            let _: String = active_route.get();
5275            let _: bool = catalog_open.get();
5276            hook_outlet_page_scrolls(
5277                &hook_scene,
5278                outlet_node,
5279                &hooked_page_scrolls,
5280                scroll_tick_sig,
5281            );
5282            sync_state.get_pending_post_layout_sync().set(true);
5283            sync_docs_post_layout_positions(&sync_state, &sync_scene);
5284            notify_frame_needed();
5285        })
5286    });
5287    let locale_portal_opt: Option<NodeId> = if has_multi_locales {
5288        Some(mount_docs_locale_dropdown_portal(
5289            state,
5290            tokens,
5291            vec![locale_btn_desk, locale_btn_mob],
5292        ))
5293    } else {
5294        None
5295    };
5296    let scheme_portal: NodeId =
5297        mount_docs_scheme_dropdown_portal(state, tokens, vec![scheme_btn_desk, scheme_btn_mob]);
5298    rctx.get_scene().with_write(
5299        |tree: &mut SceneTree| {
5300            tree.attach_scope(shell_node, bnav_scope);
5301            tree.attach_scope(shell_node, scroll_hook_scope);
5302        },
5303        (),
5304    );
5305    let column_style: Style = style! {
5306        Width(Length::Percent(100.0))
5307        Height(Length::Percent(100.0))
5308    };
5309    let viewer_root: NodeId = view! {
5310        column {
5311            style: column_style
5312            { shell_node }
5313            { cmd_modal }
5314            if let Some(lp) = locale_portal_opt {
5315                { lp }
5316            }
5317            { scheme_portal }
5318        }
5319    };
5320    rctx.on_key(viewer_root, move |ui_event: &UiEvent| {
5321        if let UiEventKind::KeyDown(KeyCode::Character(ch), mods) = ui_event.get_kind()
5322            && (mods.get_meta() || mods.get_ctrl())
5323            && (*ch == 'k' || *ch == 'K')
5324        {
5325            let _: bool = locale_open.set_if_changed(false);
5326            let _: bool = scheme_open.set_if_changed(false);
5327            let _: bool = cmd_open.set_if_changed(true);
5328        }
5329    });
5330    viewer_root
5331}
5332
5333/// Mounts the cross-platform reactive showcase-parity documentation viewer for `site` using `euv-ui`.
5334///
5335/// # Arguments
5336///
5337/// - `&DocSite` - Parsed documentation site.
5338/// - `Signal<String>` - Active route path signal.
5339/// - `Signal<String>` - Search query input signal.
5340/// - `ThemeTokens` - Active design tokens.
5341///
5342/// # Returns
5343///
5344/// - `NodeId` - Mounted reactive documentation shell node.
5345pub fn mount_docs_viewer(
5346    site: &DocSite,
5347    active_route: Signal<String>,
5348    search_query: Signal<String>,
5349    tokens: ThemeTokens,
5350) -> NodeId {
5351    let state: DocsViewerState =
5352        DocsViewerState::new(site.clone(), active_route, search_query, tokens);
5353    mount_docs_viewer_with_state(&state)
5354}
5355
5356/// Launches the documentation viewer app and steps one headless or native frame.
5357///
5358/// # Arguments
5359///
5360/// - `&DocSite` - Loaded documentation site.
5361/// - `bool` - When `true`, renders headlessly via `HeadlessPlatform`.
5362///
5363/// # Returns
5364///
5365/// - `Result<FrameStats, PlatformError>` - Frame render telemetry.
5366pub fn render_docs_smoke(site: &DocSite, headless: bool) -> Result<FrameStats, PlatformError> {
5367    render_docs_app(site, headless, false)
5368}
5369
5370/// Launches the documentation viewer app in either single-frame or interactive event-loop mode.
5371///
5372/// # Arguments
5373///
5374/// - `&DocSite` - Loaded documentation site.
5375/// - `bool` - When `true`, renders headlessly via `HeadlessPlatform`.
5376/// - `bool` - When `true` and not headless, runs the interactive frame loop until window close.
5377///
5378/// # Returns
5379///
5380/// - `Result<FrameStats, PlatformError>` - Final rendered frame telemetry.
5381pub fn render_docs_app(
5382    site: &DocSite,
5383    headless: bool,
5384    interactive: bool,
5385) -> Result<FrameStats, PlatformError> {
5386    EuvOverlayStack::clear();
5387    reset_fullscreen_state();
5388    clear_provided_theme();
5389    let mut window_cfg: WindowConfig = WindowConfig::default();
5390    window_cfg
5391        .set_title(DOCS_WINDOW_TITLE.to_string())
5392        .set_size(DOCS_WINDOW_WIDTH, DOCS_WINDOW_HEIGHT)
5393        .set_render(RenderConfig::software())
5394        .set_icon(Some(euv_brand_logo_image()));
5395    let mut app_cfg: AppConfig = AppConfig::default();
5396    app_cfg.set_window(window_cfg);
5397    let mut app: App = if headless {
5398        App::headless(app_cfg)?
5399    } else {
5400        App::new(app_cfg)?
5401    };
5402    let initial_route: String = site
5403        .get_pages()
5404        .first()
5405        .map(|point_val: &DocPage| point_val.get_route().clone())
5406        .unwrap_or_else(|| "/".to_string());
5407    let active_route: Signal<String> = Signal::new(initial_route);
5408    let search_query: Signal<String> = Signal::new(String::new());
5409    let tokens: ThemeTokens = ThemeTokens::resolve(active_feature_scheme(), ThemeMode::Light);
5410    let state: DocsViewerState =
5411        DocsViewerState::new(site.clone(), active_route, search_query, tokens);
5412    let mount_state: DocsViewerState = state.clone();
5413    let _: NodeId = app.mount(move || mount_docs_viewer_with_state(&mount_state));
5414    let limit: Option<u64> = if interactive && !headless {
5415        None
5416    } else {
5417        Some(1)
5418    };
5419    app.run_frames(limit)
5420}
5421
5422/// Resolves a candidate path or locale-prefixed path against `site` pages, normalizing duplicate slashes and `.html` suffixes.
5423///
5424/// # Arguments
5425///
5426/// - `&DocSite` - Loaded documentation site.
5427/// - `&str` - Raw path fragment or URL pathname candidate.
5428///
5429/// # Returns
5430///
5431/// - `Option<String>` - Matching canonical page route when found.
5432fn resolve_docs_candidate_path(site: &DocSite, raw_path: &str) -> Option<String> {
5433    let without_query: &str = raw_path.split(['?', '#']).next().unwrap_or("").trim();
5434    let mut segments: Vec<&str> = without_query
5435        .split('/')
5436        .filter(|seg: &&str| !seg.is_empty())
5437        .collect();
5438    if segments
5439        .last()
5440        .is_some_and(|last: &&str| last.eq_ignore_ascii_case(DOCS_SUFFIX_INDEX_HTML))
5441    {
5442        let _: Option<&str> = segments.pop();
5443    }
5444    let normalized_segments: Vec<String> = segments
5445        .into_iter()
5446        .map(|seg: &str| {
5447            seg.strip_suffix(DOCS_SUFFIX_HTML)
5448                .unwrap_or(seg)
5449                .to_string()
5450        })
5451        .filter(|seg: &String| !seg.is_empty())
5452        .collect();
5453    let candidate: String = if normalized_segments.is_empty() {
5454        "/".to_string()
5455    } else {
5456        format!("/{}", normalized_segments.join("/"))
5457    };
5458    if let Some(found) = site.resolve_readable_route(&candidate) {
5459        return Some(found);
5460    }
5461    if let Some(first_seg) = normalized_segments.first() {
5462        let active_locale: &str = site.get_locale_prefix().trim_matches('/');
5463        let matches_builtin: bool = DOCS_KNOWN_LOCALE_SEGMENTS
5464            .iter()
5465            .any(|loc: &&str| loc.eq_ignore_ascii_case(first_seg));
5466        let matches_active: bool =
5467            !active_locale.is_empty() && active_locale.eq_ignore_ascii_case(first_seg);
5468        let matches_configured: bool = site.get_locales().iter().any(|loc: &DocLocaleConfig| {
5469            let dir_match: bool = loc.get_dir().eq_ignore_ascii_case(first_seg);
5470            let pref_match: bool = loc
5471                .get_prefix()
5472                .trim_matches('/')
5473                .eq_ignore_ascii_case(first_seg);
5474            dir_match || pref_match
5475        });
5476        let is_known_locale: bool = [matches_builtin, matches_active, matches_configured]
5477            .into_iter()
5478            .any(|matched: bool| matched);
5479        if is_known_locale {
5480            let rest: &[String] = &normalized_segments[1..];
5481            let stripped: String = if rest.is_empty() {
5482                "/".to_string()
5483            } else {
5484                format!("/{}", rest.join("/"))
5485            };
5486            if let Some(found) = site.resolve_readable_route(&stripped) {
5487                return Some(found);
5488            }
5489        }
5490    }
5491    None
5492}
5493
5494/// Normalizes browser `location.hash` and `location.pathname` into a valid `DocSite` route and optional heading anchor slug.
5495///
5496/// # Arguments
5497///
5498/// - `&DocSite` - Loaded documentation site.
5499/// - `&str` - Raw `window.location.hash` value.
5500/// - `&str` - Raw `window.location.pathname` value.
5501///
5502/// # Returns
5503///
5504/// - `(String, Option<String>)` - Resolved canonical route path and optional heading anchor slug.
5505#[must_use]
5506pub fn normalize_docs_history_target(
5507    site: &DocSite,
5508    raw_hash: &str,
5509    raw_pathname: &str,
5510) -> (String, Option<String>) {
5511    let default_route: String = site
5512        .find_by_route("/")
5513        .or_else(|| site.get_pages().first())
5514        .map(|point_val: &DocPage| point_val.get_route().clone())
5515        .unwrap_or_else(|| "/".to_string());
5516    let path_fallback: String =
5517        resolve_docs_candidate_path(site, raw_pathname).unwrap_or_else(|| default_route.clone());
5518    let trimmed_hash: &str = raw_hash.trim().trim_start_matches('#').trim();
5519    if trimmed_hash.is_empty() {
5520        return (path_fallback, None);
5521    }
5522    if trimmed_hash.starts_with('/') {
5523        let (route_part, anchor_raw): (&str, Option<&str>) = match trimmed_hash.split_once('#') {
5524            Some((red_val, alpha_val)) => (red_val, Some(alpha_val)),
5525            None => (trimmed_hash, None),
5526        };
5527        let anchor: Option<String> = anchor_raw
5528            .map(str::trim)
5529            .filter(|first_val: &&str| !first_val.is_empty())
5530            .map(str::to_string);
5531        if route_part.trim_matches('/').is_empty() {
5532            return (path_fallback, anchor);
5533        }
5534        if let Some(found) = resolve_docs_candidate_path(site, route_part) {
5535            return (found, anchor);
5536        }
5537        return (default_route, None);
5538    }
5539    let (head_part, anchor_raw): (&str, Option<&str>) = match trimmed_hash.split_once('#') {
5540        Some((height_val, area_val)) => (height_val, Some(area_val)),
5541        None => (trimmed_hash, None),
5542    };
5543    let tail_anchor: Option<String> = anchor_raw
5544        .map(str::trim)
5545        .filter(|alpha_val_primary: &&str| !alpha_val_primary.is_empty())
5546        .map(str::to_string);
5547    if head_part.contains('/') {
5548        if let Some(found) = resolve_docs_candidate_path(site, head_part) {
5549            return (found, tail_anchor);
5550        }
5551        return (default_route, None);
5552    }
5553    (path_fallback, Some(head_part.to_string()))
5554}
5555
5556/// Applies an incoming browser history location (`popstate` / `hashchange`) to `app` and `state`, dismissing overlays and exiting fullscreen first.
5557///
5558/// # Arguments
5559///
5560/// - `&mut App` - Running documentation viewer application instance.
5561/// - `&DocsViewerState` - Shared reactive documentation viewer state.
5562/// - `&str` - Raw `window.location.hash` value.
5563/// - `&str` - Raw `window.location.pathname` value.
5564///
5565/// # Returns
5566///
5567/// - `String` - Normalized canonical documentation route applied to `state`.
5568pub fn apply_docs_history_navigation(
5569    app: &mut App,
5570    state: &DocsViewerState,
5571    raw_hash: &str,
5572    raw_pathname: &str,
5573) -> String {
5574    let (target_route, anchor): (String, Option<String>) =
5575        normalize_docs_history_target(state.get_site(), raw_hash, raw_pathname);
5576    let _: usize = EuvOverlayStack::dismiss_all();
5577    let _: bool = state.get_cmd_open().set_if_changed(false);
5578    if app.is_immersive_fullscreen() || is_fullscreen_active() || EuvOverlayStack::has_fullscreen()
5579    {
5580        let _: usize = sync_external_fullscreen_exit();
5581        app.set_immersive_fullscreen(false);
5582    }
5583    let _: bool = state
5584        .get_active_route()
5585        .set_if_changed(target_route.clone());
5586    let resolved_slug: String = anchor.clone().unwrap_or_else(|| {
5587        state
5588            .get_site()
5589            .find_by_route(&target_route)
5590            .and_then(|point_val: &DocPage| point_val.get_toc().first())
5591            .map(|it: &DocTocItem| it.get_slug().clone())
5592            .unwrap_or_default()
5593    });
5594    if let Ok(mut guard) = state.get_toc_click_lock().try_borrow_mut() {
5595        *guard = None;
5596    }
5597    let _: bool = state.get_active_toc_slug().set_if_changed(resolved_slug);
5598    let _: bool = state.get_pending_anchor_scroll().set_if_changed(anchor);
5599    let _: bool = state.get_pending_scroll_restore().set_if_changed(None);
5600    state.get_pending_post_layout_sync().set(true);
5601    target_route
5602}
5603
5604/// Synchronizes browser URL hash (`#<route>` or `#<route>#<anchor>`) without pushing redundant history entries or triggering reload loops.
5605///
5606/// # Arguments
5607///
5608/// - `&str` - Active canonical documentation route path.
5609/// - `Option<&str>` - Optional active TOC heading anchor slug.
5610pub(crate) fn sync_docs_browser_hash(route: &str, anchor: Option<&str>) {
5611    #[cfg(target_arch = "wasm32")]
5612    {
5613        if WEB_DOCS_SYNCING_FROM_HISTORY.with(Cell::get) {
5614            return;
5615        }
5616        let Some(win) = window() else {
5617            return;
5618        };
5619        let norm_route: String = if route.is_empty() || route == "/" {
5620            "/".to_string()
5621        } else if route.starts_with('/') {
5622            route.to_string()
5623        } else {
5624            format!("/{route}")
5625        };
5626        let clean_anchor: Option<&str> = anchor
5627            .map(|text_value: &str| text_value.trim().trim_start_matches('#').trim())
5628            .filter(|alpha_val: &&str| !alpha_val.is_empty());
5629        let target_hash: String = match clean_anchor {
5630            Some(slug) => format!("#{norm_route}#{slug}"),
5631            None => format!("#{norm_route}"),
5632        };
5633        if win.location().hash().ok().as_deref() == Some(target_hash.as_str()) {
5634            return;
5635        }
5636        let replaced: bool = win
5637            .history()
5638            .ok()
5639            .and_then(|hist: History| {
5640                hist.replace_state_with_url(&JsValue::NULL, "", Some(&target_hash))
5641                    .ok()
5642            })
5643            .is_some();
5644        if !replaced {
5645            let prev: bool =
5646                WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
5647            let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
5648            WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev));
5649        }
5650    }
5651    #[cfg(not(target_arch = "wasm32"))]
5652    let _: (&str, Option<&str>) = (route, anchor);
5653}
5654
5655/// Persists `(route, scroll_y, active_slug)` into browser `sessionStorage` (`DOCS_SCROLL_STORAGE_KEY`) so refreshing preserves reading position.
5656///
5657/// # Arguments
5658///
5659/// - `&str` - Active canonical route path.
5660/// - `f32` - Current vertical scroll offset in logical pixels.
5661/// - `&str` - Active TOC heading anchor slug.
5662pub(crate) fn persist_docs_scroll_state(route: &str, scroll_y: f32, active_slug: &str) {
5663    #[cfg(target_arch = "wasm32")]
5664    {
5665        if let Some(win) = window()
5666            && let Ok(Some(storage)) = win.session_storage()
5667        {
5668            let payload: String = format_docs_scroll_snapshot(route, scroll_y, active_slug);
5669            let _: Result<(), JsValue> = storage.set_item(DOCS_SCROLL_STORAGE_KEY, &payload);
5670        }
5671    }
5672    #[cfg(not(target_arch = "wasm32"))]
5673    let _: (&str, f32, &str) = (route, scroll_y, active_slug);
5674}
5675
5676/// Loads a previously persisted `(scroll_y, slug)` snapshot for `expected_route` from browser `sessionStorage`.
5677///
5678/// # Arguments
5679///
5680/// - `&str` - Canonical documentation route being restored.
5681///
5682/// # Returns
5683///
5684/// - `Option<(f32, Option<String>)>` - Saved scroll position and optional TOC slug when available.
5685#[cfg(target_arch = "wasm32")]
5686pub(crate) fn load_persisted_docs_scroll_state(
5687    expected_route: &str,
5688) -> Option<(f32, Option<String>)> {
5689    let win: Window = window()?;
5690    let storage: Storage = win.session_storage().ok()??;
5691    let raw: String = storage.get_item(DOCS_SCROLL_STORAGE_KEY).ok()??;
5692    parse_docs_scroll_snapshot(&raw, expected_route)
5693}
5694
5695/// Loads persisted unlocked documentation password secrets from browser `localStorage` (`"euv_docs_unlocked_v1"`).
5696///
5697/// # Returns
5698///
5699/// - `Vec<String>` - Previously unlocked password secrets, or an empty vector when unavailable.
5700pub(crate) fn load_persisted_unlocked_passwords() -> Vec<String> {
5701    #[cfg(target_arch = "wasm32")]
5702    {
5703        if let Some(win) = window()
5704            && let Ok(Some(storage)) = win.local_storage()
5705            && let Ok(Some(raw)) = storage.get_item(DOCS_UNLOCKED_STORAGE_KEY)
5706            && let Ok(parsed) = serde_json::from_str::<Vec<String>>(&raw)
5707        {
5708            return parsed;
5709        }
5710    }
5711    Vec::new()
5712}
5713
5714/// Persists unlocked documentation password secrets into browser `localStorage` (`"euv_docs_unlocked_v1"`).
5715///
5716/// # Arguments
5717///
5718/// - `&[String]` - Active list of unlocked password secrets.
5719pub(crate) fn persist_unlocked_passwords(list: &[String]) {
5720    #[cfg(target_arch = "wasm32")]
5721    {
5722        if let Some(win) = window()
5723            && let Ok(Some(storage)) = win.local_storage()
5724            && let Ok(encoded) = serde_json::to_string(list)
5725        {
5726            let _: Result<(), JsValue> = storage.set_item(DOCS_UNLOCKED_STORAGE_KEY, &encoded);
5727        }
5728    }
5729    #[cfg(not(target_arch = "wasm32"))]
5730    let _: usize = list.len();
5731}
5732
5733/// Synchronizes the running WebAssembly documentation viewer from browser `popstate` or `hashchange` and immediately repaints.
5734///
5735/// # Arguments
5736///
5737/// - `&Window` - Active browser `Window`.
5738#[cfg(target_arch = "wasm32")]
5739fn web_docs_sync_from_browser_history(win: &Window) {
5740    let raw_hash: String = win.location().hash().unwrap_or_default();
5741    let raw_pathname: String = win.location().pathname().unwrap_or_default();
5742    let prev_guard: bool =
5743        WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
5744    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5745        if let Ok(mut borrow) = slot.try_borrow_mut()
5746            && let Some((app, state)) = borrow.as_mut()
5747        {
5748            let _: String = apply_docs_history_navigation(app, state, &raw_hash, &raw_pathname);
5749            let _: Result<FrameStats, PlatformError> = app.step_frame();
5750            state.get_pending_post_layout_sync().set(false);
5751            state.sync_post_layout_positions(app.get_scene());
5752            let _: Result<FrameStats, PlatformError> = app.step_frame();
5753        }
5754    });
5755    WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
5756}
5757
5758/// Extracts plain UTF-8 clipboard text from a browser `paste` DOM event.
5759///
5760/// # Arguments
5761///
5762/// - `&web_sys::Event` - Browser DOM `paste` event.
5763///
5764/// # Returns
5765///
5766/// - `Option<String>` - Non-empty pasted text when available.
5767#[cfg(target_arch = "wasm32")]
5768fn web_docs_extract_paste_text(ui_event: &web_sys::Event) -> Option<String> {
5769    let data: JsValue = Reflect::get(
5770        ui_event.as_ref(),
5771        &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA),
5772    )
5773    .ok()?;
5774    if data.is_null() || data.is_undefined() {
5775        return None;
5776    }
5777    let get_fn_val: JsValue = Reflect::get(&data, &JsValue::from_str(WEB_PROP_GET_DATA)).ok()?;
5778    let get_fn: Function = get_fn_val.dyn_into::<Function>().ok()?;
5779    let result: JsValue = get_fn
5780        .call1(&data, &JsValue::from_str(WEB_MIME_TEXT_PLAIN))
5781        .ok()?;
5782    result
5783        .as_string()
5784        .filter(|text_value: &String| !text_value.is_empty())
5785}
5786
5787/// Returns `true` when the browser document currently has a standard or WebKit fullscreen element active.
5788///
5789/// # Arguments
5790///
5791/// - `&Document` - Active browser `Document`.
5792///
5793/// # Returns
5794///
5795/// - `bool` - `true` while browser fullscreen mode is active.
5796#[cfg(target_arch = "wasm32")]
5797fn web_docs_doc_is_fullscreen(doc: &Document) -> bool {
5798    if doc.fullscreen_element().is_some() {
5799        return true;
5800    }
5801    Reflect::get(
5802        doc.as_ref(),
5803        &JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
5804    )
5805    .ok()
5806    .map(|item_val: JsValue| !item_val.is_null() && !item_val.is_undefined())
5807    .unwrap_or(false)
5808}
5809
5810/// Attaches browser `popstate`, `hashchange`, `pageshow`, `blur`, `touchcancel`, `paste`, `fullscreenchange`, and color-scheme listeners once for the docs viewer.
5811///
5812/// # Arguments
5813///
5814/// - `&Window` - Active browser `Window`.
5815#[cfg(target_arch = "wasm32")]
5816fn web_docs_attach_browser_listeners(win: &Window) {
5817    let already_attached: bool =
5818        WEB_DOCS_LISTENERS_ATTACHED.with(|flag: &Cell<bool>| flag.replace(true));
5819    if already_attached {
5820        return;
5821    }
5822    let win_hist: Window = win.clone();
5823    let on_history: Closure<dyn FnMut(web_sys::Event)> =
5824        Closure::wrap(Box::new(move |_: web_sys::Event| {
5825            web_docs_sync_from_browser_history(&win_hist);
5826        }) as Box<dyn FnMut(web_sys::Event)>);
5827    drop(win.add_event_listener_with_callback(
5828        WEB_EVENT_POP_STATE,
5829        on_history.as_ref().unchecked_ref(),
5830    ));
5831    drop(win.add_event_listener_with_callback(
5832        WEB_EVENT_HASH_CHANGE,
5833        on_history.as_ref().unchecked_ref(),
5834    ));
5835    drop(win.add_event_listener_with_callback(
5836        WEB_EVENT_PAGE_SHOW,
5837        on_history.as_ref().unchecked_ref(),
5838    ));
5839    on_history.forget();
5840    let on_cancel: Closure<dyn FnMut(web_sys::Event)> =
5841        Closure::wrap(Box::new(move |_: web_sys::Event| {
5842            WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5843                if let Ok(mut borrow) = slot.try_borrow_mut()
5844                    && let Some((app, _)) = borrow.as_mut()
5845                {
5846                    let wid: WindowId = app.get_window_state().get_id();
5847                    app.dispatch_window_event(WindowEvent::PointerCancel(wid, 0));
5848                    let _: Result<FrameStats, PlatformError> = app.step_frame();
5849                }
5850            });
5851        }) as Box<dyn FnMut(web_sys::Event)>);
5852    drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_cancel.as_ref().unchecked_ref()));
5853    drop(win.add_event_listener_with_callback(
5854        WEB_EVENT_TOUCH_CANCEL,
5855        on_cancel.as_ref().unchecked_ref(),
5856    ));
5857    on_cancel.forget();
5858    let on_paste: Closure<dyn FnMut(web_sys::Event)> =
5859        Closure::wrap(Box::new(move |ui_event: web_sys::Event| {
5860            if let Some(pasted) = web_docs_extract_paste_text(&ui_event) {
5861                ui_event.prevent_default();
5862                WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5863                    if let Ok(mut borrow) = slot.try_borrow_mut()
5864                        && let Some((app, _)) = borrow.as_mut()
5865                    {
5866                        let wid: WindowId = app.get_window_state().get_id();
5867                        app.dispatch_window_event(WindowEvent::TextInput(wid, pasted));
5868                        let _: Result<FrameStats, PlatformError> = app.step_frame();
5869                    }
5870                });
5871            }
5872        }) as Box<dyn FnMut(web_sys::Event)>);
5873    drop(win.add_event_listener_with_callback(WEB_EVENT_PASTE, on_paste.as_ref().unchecked_ref()));
5874    on_paste.forget();
5875    if let Some(doc) = win.document() {
5876        let doc_fs: Document = doc.clone();
5877        let on_fs: Closure<dyn FnMut(web_sys::Event)> =
5878            Closure::wrap(Box::new(move |_: web_sys::Event| {
5879                if !web_docs_doc_is_fullscreen(&doc_fs) {
5880                    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5881                        if let Ok(mut borrow) = slot.try_borrow_mut()
5882                            && let Some((app, _)) = borrow.as_mut()
5883                            && (app.is_immersive_fullscreen()
5884                                || is_fullscreen_active()
5885                                || EuvOverlayStack::has_fullscreen())
5886                        {
5887                            let _: usize = sync_external_fullscreen_exit();
5888                            app.set_immersive_fullscreen(false);
5889                            let wid: WindowId = app.get_window_state().get_id();
5890                            let measured: SafeAreaInsets = web_query_safe_area_insets();
5891                            app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, measured));
5892                            let _: Result<FrameStats, PlatformError> = app.step_frame();
5893                        }
5894                    });
5895                }
5896            }) as Box<dyn FnMut(web_sys::Event)>);
5897        drop(doc.add_event_listener_with_callback(
5898            WEB_EVENT_FULLSCREEN_CHANGE,
5899            on_fs.as_ref().unchecked_ref(),
5900        ));
5901        drop(doc.add_event_listener_with_callback(
5902            WEB_EVENT_WEBKIT_FULLSCREEN_CHANGE,
5903            on_fs.as_ref().unchecked_ref(),
5904        ));
5905        on_fs.forget();
5906    }
5907    if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
5908        let mql_cb: MediaQueryList = mql.clone();
5909        let on_theme: Closure<dyn FnMut(web_sys::Event)> =
5910            Closure::wrap(Box::new(move |_: web_sys::Event| {
5911                let next_theme: ThemeMode = if mql_cb.matches() {
5912                    ThemeMode::Dark
5913                } else {
5914                    ThemeMode::Light
5915                };
5916                WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5917                    if let Ok(mut borrow) = slot.try_borrow_mut()
5918                        && let Some((app, _)) = borrow.as_mut()
5919                    {
5920                        let wid: WindowId = app.get_window_state().get_id();
5921                        app.dispatch_window_event(WindowEvent::ThemeChanged(wid, next_theme));
5922                        let _: Result<FrameStats, PlatformError> = app.step_frame();
5923                    }
5924                });
5925            }) as Box<dyn FnMut(web_sys::Event)>);
5926        drop(
5927            mql.add_event_listener_with_callback(
5928                WEB_EVENT_CHANGE,
5929                on_theme.as_ref().unchecked_ref(),
5930            ),
5931        );
5932        on_theme.forget();
5933    }
5934}
5935
5936/// Boots the persistent WebAssembly showcase-parity documentation viewer from a serialized `DocSite` JSON bundle.
5937///
5938/// # Arguments
5939///
5940/// - `&str` - Compact UTF-8 JSON payload produced for the active locale bundle.
5941///
5942/// # Returns
5943///
5944/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
5945#[cfg(target_arch = "wasm32")]
5946pub fn boot_wasm_docs_bundle(bundle_json: &str) -> u64 {
5947    let site: DocSite = serde_json::from_str::<DocSite>(bundle_json).unwrap_or_else(|_| {
5948        DocSite::new(
5949            DOCS_SITE_TITLE.to_string(),
5950            DOCS_SITE_TAGLINE.to_string(),
5951            Vec::new(),
5952        )
5953    });
5954    boot_wasm_docs_site(site)
5955}
5956
5957/// Boots the persistent WebAssembly showcase-parity documentation viewer from a split plaintext shell and `EUVZ`-compressed bodies.
5958///
5959/// # Arguments
5960///
5961/// - `&str` - Compact plaintext `DocSite` shell JSON carrying metadata and TOC headings.
5962/// - `&[u8]` - `EUVZ`-compressed page body payload bytes.
5963///
5964/// # Returns
5965///
5966/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
5967#[cfg(target_arch = "wasm32")]
5968pub fn boot_wasm_docs_compressed_bundle(shell_json: &str, compressed_bodies: &[u8]) -> u64 {
5969    let site: DocSite = unpack_site_bundle(shell_json, compressed_bodies).unwrap_or_else(|_| {
5970        DocSite::new(
5971            DOCS_SITE_TITLE.to_string(),
5972            DOCS_SITE_TAGLINE.to_string(),
5973            Vec::new(),
5974        )
5975    });
5976    boot_wasm_docs_site(site)
5977}
5978
5979/// Mounts the hydrated `DocSite` into the persistent WebAssembly viewer runtime and renders the initial frame.
5980///
5981/// # Arguments
5982///
5983/// - `DocSite` - Hydrated documentation site for the active locale.
5984///
5985/// # Returns
5986///
5987/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
5988#[cfg(target_arch = "wasm32")]
5989fn boot_wasm_docs_site(site: DocSite) -> u64 {
5990    console_error_panic_hook::set_once();
5991    reset_reactive_runtime();
5992    EuvOverlayStack::clear();
5993    reset_fullscreen_state();
5994    clear_provided_theme();
5995    let mut window_cfg: WindowConfig = WindowConfig::default();
5996    window_cfg
5997        .set_title(format!("{} · {EUV_DOCS_RELEASE_MARKER}", site.get_title()))
5998        .set_size(DOCS_WINDOW_WIDTH, DOCS_WINDOW_HEIGHT)
5999        .set_render(RenderConfig::software());
6000    let mut app_cfg: AppConfig = AppConfig::default();
6001    app_cfg.set_window(window_cfg);
6002    let mut app: App = match App::new(app_cfg) {
6003        Ok(alpha_val) => alpha_val,
6004        Err(_) => return 0,
6005    };
6006    let (initial_route, initial_anchor): (String, Option<String>) = if let Some(win) = window() {
6007        let raw_hash: String = win.location().hash().unwrap_or_default();
6008        let raw_pathname: String = win.location().pathname().unwrap_or_default();
6009        normalize_docs_history_target(&site, &raw_hash, &raw_pathname)
6010    } else {
6011        let fallback: String = site
6012            .get_pages()
6013            .first()
6014            .map(|point_val: &DocPage| point_val.get_route().clone())
6015            .unwrap_or_else(|| "/".to_string());
6016        (fallback, None)
6017    };
6018    let active_route: Signal<String> = Signal::new(initial_route.clone());
6019    let search_query: Signal<String> = Signal::new(String::new());
6020    let tokens: ThemeTokens = ThemeTokens::resolve(active_feature_scheme(), ThemeMode::Light);
6021    let state: DocsViewerState = DocsViewerState::new(site, active_route, search_query, tokens);
6022    if let Some(anchor) = initial_anchor {
6023        let _: bool = state.get_active_toc_slug().set_if_changed(anchor.clone());
6024        let _: bool = state
6025            .get_pending_anchor_scroll()
6026            .set_if_changed(Some(anchor));
6027    } else if let Some((saved_y, saved_slug)) =
6028        load_persisted_docs_scroll_state(initial_route.as_str())
6029    {
6030        if let Some(ref slug) = saved_slug {
6031            let _: bool = state.get_active_toc_slug().set_if_changed(slug.clone());
6032        }
6033        let _: bool = state
6034            .get_pending_scroll_restore()
6035            .set_if_changed(Some((saved_y, saved_slug)));
6036    }
6037    let has_home: bool = state
6038        .get_site()
6039        .get_pages()
6040        .iter()
6041        .any(|palette_val: &DocPage| palette_val.get_is_home());
6042    let mount_state: DocsViewerState = state.clone();
6043    let _: NodeId = app.mount(move || mount_docs_viewer_with_state(&mount_state));
6044    let route_watch: Signal<String> = state.get_active_route();
6045    let site_watch: Rc<DocSite> = state.get_site().clone();
6046    let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
6047        Effect::new(move || {
6048            let text_value: String = route_watch.get();
6049            if WEB_DOCS_SYNCING_FROM_HISTORY.with(Cell::get) {
6050                return;
6051            }
6052            if let Some(win) = window() {
6053                let raw_hash: String = win.location().hash().unwrap_or_default();
6054                let raw_pathname: String = win.location().pathname().unwrap_or_default();
6055                let (cur_route, _): (String, Option<String>) =
6056                    normalize_docs_history_target(&site_watch, &raw_hash, &raw_pathname);
6057                if cur_route != text_value {
6058                    let target_hash: String = format!("#{text_value}");
6059                    let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
6060                }
6061            }
6062        })
6063    });
6064    let root_id: NodeId = app
6065        .get_scene()
6066        .with_read(SceneTree::get_root, NodeId::default());
6067    app.get_scene().with_write(
6068        |tree: &mut SceneTree| {
6069            tree.attach_scope(root_id, hash_scope);
6070        },
6071        (),
6072    );
6073    let first_hash: u64 = app
6074        .step_frame()
6075        .map(|stats: FrameStats| stats.get_frame_hash())
6076        .unwrap_or(0);
6077    state.get_pending_post_layout_sync().set(false);
6078    state.sync_post_layout_positions(app.get_scene());
6079    let hash: u64 = app
6080        .step_frame()
6081        .map(|stats: FrameStats| stats.get_frame_hash())
6082        .unwrap_or(first_hash);
6083    let fetch_state: DocsViewerState = state.clone();
6084    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6085        if let Ok(mut borrow) = slot.try_borrow_mut() {
6086            *borrow = Some((app, state));
6087        }
6088    });
6089    if let Some(win) = window() {
6090        web_docs_attach_browser_listeners(&win);
6091    }
6092    if has_home {
6093        trigger_wasm_catalog_fetch(&fetch_state);
6094    }
6095    hash
6096}
6097
6098/// Switches the active route in the running WebAssembly documentation viewer and renders immediately.
6099///
6100/// # Arguments
6101///
6102/// - `&str` - Canonical route path.
6103///
6104/// # Returns
6105///
6106/// - `u64` - Rendered frame hash.
6107#[cfg(target_arch = "wasm32")]
6108pub fn wasm_docs_render_route(route: &str) -> u64 {
6109    let prev_guard: bool =
6110        WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
6111    let raw_pathname: String = window()
6112        .and_then(|win: Window| win.location().pathname().ok())
6113        .unwrap_or_default();
6114    let frame_hash: u64 =
6115        WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6116            let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut()
6117            {
6118                Ok(guard) => guard,
6119                Err(_) => return 0,
6120            };
6121            let Some((app, state)) = borrow.as_mut() else {
6122                return 0;
6123            };
6124            let _: String = apply_docs_history_navigation(app, state, route, &raw_pathname);
6125            let _: Result<FrameStats, PlatformError> = app.step_frame();
6126            state.get_pending_post_layout_sync().set(false);
6127            state.sync_post_layout_positions(app.get_scene());
6128            app.step_frame()
6129                .map(|stats: FrameStats| stats.get_frame_hash())
6130                .unwrap_or(0)
6131        });
6132    WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
6133    frame_hash
6134}
6135
6136/// Dispatches a browser pointer move event into the running WebAssembly documentation viewer.
6137///
6138/// # Arguments
6139///
6140/// - `f32` - Logical X coordinate inside the canvas.
6141/// - `f32` - Logical Y coordinate inside the canvas.
6142///
6143/// # Returns
6144///
6145/// - `u64` - Rendered frame hash.
6146#[cfg(target_arch = "wasm32")]
6147pub fn wasm_docs_pointer_move(pos_x: f32, pos_y: f32) -> u64 {
6148    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6149        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6150            Ok(guard) => guard,
6151            Err(_) => return 0,
6152        };
6153        let Some((app, _)) = borrow.as_mut() else {
6154            return 0;
6155        };
6156        let wid: WindowId = app.get_window_state().get_id();
6157        app.dispatch_window_event(WindowEvent::PointerMove(
6158            wid,
6159            PointerEvent::mouse(pos_x, pos_y),
6160        ));
6161        app.step_frame()
6162            .map(|stats: FrameStats| stats.get_frame_hash())
6163            .unwrap_or(0)
6164    })
6165}
6166
6167/// Dispatches a browser pointer press event into the running WebAssembly documentation viewer.
6168///
6169/// # Arguments
6170///
6171/// - `f32` - Logical X coordinate inside the canvas.
6172/// - `f32` - Logical Y coordinate inside the canvas.
6173///
6174/// # Returns
6175///
6176/// - `u64` - Rendered frame hash.
6177#[cfg(target_arch = "wasm32")]
6178pub fn wasm_docs_pointer_down(pos_x: f32, pos_y: f32) -> u64 {
6179    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6180        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6181            Ok(guard) => guard,
6182            Err(_) => return 0,
6183        };
6184        let Some((app, _)) = borrow.as_mut() else {
6185            return 0;
6186        };
6187        let wid: WindowId = app.get_window_state().get_id();
6188        app.dispatch_window_event(WindowEvent::PointerDown(
6189            wid,
6190            PointerEvent::mouse(pos_x, pos_y),
6191        ));
6192        app.step_frame()
6193            .map(|stats: FrameStats| stats.get_frame_hash())
6194            .unwrap_or(0)
6195    })
6196}
6197
6198/// Dispatches a browser pointer release event into the running WebAssembly documentation viewer.
6199///
6200/// # Arguments
6201///
6202/// - `f32` - Logical X coordinate inside the canvas.
6203/// - `f32` - Logical Y coordinate inside the canvas.
6204///
6205/// # Returns
6206///
6207/// - `u64` - Rendered frame hash.
6208#[cfg(target_arch = "wasm32")]
6209pub fn wasm_docs_pointer_up(pos_x: f32, pos_y: f32) -> u64 {
6210    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6211        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6212            Ok(guard) => guard,
6213            Err(_) => return 0,
6214        };
6215        let Some((app, _)) = borrow.as_mut() else {
6216            return 0;
6217        };
6218        let wid: WindowId = app.get_window_state().get_id();
6219        app.dispatch_window_event(WindowEvent::PointerUp(
6220            wid,
6221            PointerEvent::mouse(pos_x, pos_y),
6222        ));
6223        app.step_frame()
6224            .map(|stats: FrameStats| stats.get_frame_hash())
6225            .unwrap_or(0)
6226    })
6227}
6228
6229/// 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.
6230///
6231/// # Arguments
6232///
6233/// - `u8` - Event kind (`0` move, `1` down, `2` up, `3` cancel).
6234/// - `u32` - Browser DOM `PointerEvent.pointerId`.
6235/// - `bool` - Whether the source pointer is a touch contact (`PointerDevice::Touch`).
6236/// - `f32` - Logical X coordinate inside the canvas.
6237/// - `f32` - Logical Y coordinate inside the canvas.
6238/// - `f32` - Normalized contact pressure (`0.0..=1.0`).
6239///
6240/// # Returns
6241///
6242/// - `u64` - Rendered frame hash.
6243#[cfg(target_arch = "wasm32")]
6244pub fn wasm_docs_pointer_event(
6245    kind: u8,
6246    pointer_id: u32,
6247    is_touch: bool,
6248    pos_x: f32,
6249    pos_y: f32,
6250    pressure: f32,
6251) -> u64 {
6252    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6253        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6254            Ok(guard) => guard,
6255            Err(_) => return 0,
6256        };
6257        let Some((app, _)) = borrow.as_mut() else {
6258            return 0;
6259        };
6260        let wid: WindowId = app.get_window_state().get_id();
6261        let pid: u64 = u64::from(pointer_id);
6262        let device: PointerDevice = if is_touch {
6263            PointerDevice::Touch
6264        } else {
6265            PointerDevice::Mouse
6266        };
6267        let ptr: PointerEvent = PointerEvent::new(
6268            pid,
6269            device,
6270            Point::new(pos_x, pos_y),
6271            PointerButton::Primary,
6272            pressure.clamp(0.0, 1.0),
6273            Modifiers::default(),
6274        );
6275        match kind {
6276            1 => app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr)),
6277            2 => app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr)),
6278            3 => app.dispatch_window_event(WindowEvent::PointerCancel(wid, pid)),
6279            _ => app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr)),
6280        }
6281        app.step_frame()
6282            .map(|stats: FrameStats| stats.get_frame_hash())
6283            .unwrap_or(0)
6284    })
6285}
6286
6287/// Dispatches a browser wheel scroll delta into the running WebAssembly documentation viewer.
6288///
6289/// # Arguments
6290///
6291/// - `f32` - Horizontal scroll delta.
6292/// - `f32` - Vertical scroll delta.
6293///
6294/// # Returns
6295///
6296/// - `u64` - Rendered frame hash.
6297#[cfg(target_arch = "wasm32")]
6298pub fn wasm_docs_scroll(dx: f32, dy: f32) -> u64 {
6299    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6300        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6301            Ok(guard) => guard,
6302            Err(_) => return 0,
6303        };
6304        let Some((app, _)) = borrow.as_mut() else {
6305            return 0;
6306        };
6307        let wid: WindowId = app.get_window_state().get_id();
6308        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
6309        app.step_frame()
6310            .map(|stats: FrameStats| stats.get_frame_hash())
6311            .unwrap_or(0)
6312    })
6313}
6314
6315/// Dispatches a browser wheel scroll delta anchored at logical pointer `(x, y)` so scrolling over any container works immediately.
6316///
6317/// # Arguments
6318///
6319/// - `f32` - Logical pointer X coordinate inside the canvas.
6320/// - `f32` - Logical pointer Y coordinate inside the canvas.
6321/// - `f32` - Horizontal scroll delta in CSS pixels.
6322/// - `f32` - Vertical scroll delta in CSS pixels.
6323///
6324/// # Returns
6325///
6326/// - `u64` - Rendered frame hash.
6327#[cfg(target_arch = "wasm32")]
6328pub fn wasm_docs_scroll_at(pos_x: f32, pos_y: f32, dx: f32, dy: f32) -> u64 {
6329    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6330        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6331            Ok(guard) => guard,
6332            Err(_) => return 0,
6333        };
6334        let Some((app, _)) = borrow.as_mut() else {
6335            return 0;
6336        };
6337        let wid: WindowId = app.get_window_state().get_id();
6338        app.dispatch_window_event(WindowEvent::PointerMove(
6339            wid,
6340            PointerEvent::mouse(pos_x, pos_y),
6341        ));
6342        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
6343        app.step_frame()
6344            .map(|stats: FrameStats| stats.get_frame_hash())
6345            .unwrap_or(0)
6346    })
6347}
6348
6349/// Re-queries real browser CSS `env(safe-area-inset-*)` values and dispatches `WindowEvent::SafeAreaChanged` only when insets actually change.
6350///
6351/// # Returns
6352///
6353/// - `u64` - Rendered frame hash.
6354#[cfg(target_arch = "wasm32")]
6355pub fn wasm_docs_sync_safe_area() -> u64 {
6356    let measured: SafeAreaInsets = web_query_safe_area_insets();
6357    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6358        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6359            Ok(guard) => guard,
6360            Err(_) => return 0,
6361        };
6362        let Some((app, _)) = borrow.as_mut() else {
6363            return 0;
6364        };
6365        let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
6366            SafeAreaInsets::default()
6367        } else {
6368            measured
6369        };
6370        let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
6371        if current == effective {
6372            return app.get_renderer().get_last_stats().get_frame_hash();
6373        }
6374        let wid: WindowId = app.get_window_state().get_id();
6375        app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
6376        app.step_frame()
6377            .map(|stats: FrameStats| stats.get_frame_hash())
6378            .unwrap_or(0)
6379    })
6380}
6381
6382/// Dispatches a browser keyboard event with full modifier flags into the running WebAssembly documentation viewer.
6383///
6384/// # Arguments
6385///
6386/// - `&str` - DOM `KeyboardEvent.key` string.
6387/// - `bool` - Whether Control is pressed.
6388/// - `bool` - Whether Shift is pressed.
6389/// - `bool` - Whether Alt / Option is pressed.
6390/// - `bool` - Whether Meta / Command is pressed.
6391///
6392/// # Returns
6393///
6394/// - `u64` - Rendered frame hash.
6395#[cfg(target_arch = "wasm32")]
6396pub fn wasm_docs_key_down_mods(key: &str, ctrl: bool, shift: bool, alt: bool, meta: bool) -> u64 {
6397    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6398        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6399            Ok(guard) => guard,
6400            Err(_) => return 0,
6401        };
6402        let Some((app, _)) = borrow.as_mut() else {
6403            return 0;
6404        };
6405        let wid: WindowId = app.get_window_state().get_id();
6406        let code: KeyCode = match key {
6407            WEB_KEY_ENTER => KeyCode::Enter,
6408            WEB_KEY_BACKSPACE => KeyCode::Backspace,
6409            WEB_KEY_DELETE => KeyCode::Delete,
6410            WEB_KEY_ESCAPE => KeyCode::Escape,
6411            WEB_KEY_TAB => KeyCode::Tab,
6412            WEB_KEY_SPACE => KeyCode::Space,
6413            WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
6414            WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
6415            WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
6416            WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
6417            WEB_KEY_PAGE_UP => KeyCode::PageUp,
6418            WEB_KEY_PAGE_DOWN => KeyCode::PageDown,
6419            WEB_KEY_HOME => KeyCode::Home,
6420            WEB_KEY_END => KeyCode::End,
6421            other => other
6422                .chars()
6423                .next()
6424                .map(KeyCode::Character)
6425                .unwrap_or(KeyCode::Unknown),
6426        };
6427        let mods: Modifiers = Modifiers::new(shift, ctrl, alt, meta);
6428        app.dispatch_window_event(WindowEvent::KeyDown(wid, KeyEvent::new(code, mods, false)));
6429        if !ctrl && !alt && !meta && key.chars().count() == 1 {
6430            app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
6431        }
6432        app.step_frame()
6433            .map(|stats: FrameStats| stats.get_frame_hash())
6434            .unwrap_or(0)
6435    })
6436}
6437
6438/// Copies and returns the currently selected text from the running WebAssembly documentation viewer (`""` when nothing is selected).
6439///
6440/// # Returns
6441///
6442/// - `String` - Selected UTF-8 text copied to the clipboard, or empty string.
6443#[cfg(target_arch = "wasm32")]
6444pub fn wasm_docs_copy_selected() -> String {
6445    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6446        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6447            Ok(guard) => guard,
6448            Err(_) => return String::new(),
6449        };
6450        let Some((app, _)) = borrow.as_mut() else {
6451            return String::new();
6452        };
6453        app.copy_selection()
6454            .or_else(|| app.get_scene().get_selected_text())
6455            .unwrap_or_default()
6456    })
6457}
6458
6459/// Dispatches UTF-8 text input (including composed IME/CJK text) into the running WebAssembly documentation viewer and renders immediately.
6460///
6461/// # Arguments
6462///
6463/// - `&str` - Composed or typed UTF-8 text string.
6464///
6465/// # Returns
6466///
6467/// - `u64` - Rendered frame hash.
6468#[cfg(target_arch = "wasm32")]
6469pub fn wasm_docs_text_input(text: &str) -> u64 {
6470    if text.is_empty() {
6471        return 0;
6472    }
6473    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6474        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6475            Ok(guard) => guard,
6476            Err(_) => return 0,
6477        };
6478        let Some((app, _)) = borrow.as_mut() else {
6479            return 0;
6480        };
6481        let wid: WindowId = app.get_window_state().get_id();
6482        app.dispatch_window_event(WindowEvent::TextInput(wid, text.to_string()));
6483        app.step_frame()
6484            .map(|stats: FrameStats| stats.get_frame_hash())
6485            .unwrap_or(0)
6486    })
6487}
6488
6489/// Returns `true` when the running WebAssembly documentation viewer currently has a focused `NodeKind::Input` text field.
6490///
6491/// # Returns
6492///
6493/// - `bool` - Whether an interactive text input (for example Search modal or Password gate) currently holds focus.
6494#[cfg(target_arch = "wasm32")]
6495#[must_use]
6496pub fn wasm_docs_has_focused_input() -> bool {
6497    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6498        let borrow: Ref<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow() {
6499            Ok(guard) => guard,
6500            Err(_) => return false,
6501        };
6502        let Some((app, _)) = borrow.as_ref() else {
6503            return false;
6504        };
6505        app.get_scene().with_read(
6506            |tree: &SceneTree| {
6507                tree.get_focus()
6508                    .focused_node()
6509                    .and_then(|id: NodeId| tree.get_node(id))
6510                    .is_some_and(|scene_node: &SceneNode| {
6511                        matches!(scene_node.get_kind(), NodeKind::Input(_))
6512                    })
6513            },
6514            false,
6515        )
6516    })
6517}
6518
6519/// Dispatches a browser keyboard event into the running WebAssembly documentation viewer.
6520///
6521/// # Arguments
6522///
6523/// - `&str` - DOM `KeyboardEvent.key` string.
6524///
6525/// # Returns
6526///
6527/// - `u64` - Rendered frame hash.
6528#[cfg(target_arch = "wasm32")]
6529pub fn wasm_docs_key_down(key: &str) -> u64 {
6530    wasm_docs_key_down_mods(key, false, false, false, false)
6531}
6532
6533/// Advances animations or repaints the running WebAssembly documentation viewer whenever animations or async image/data loads dirty the scene.
6534///
6535/// # Arguments
6536///
6537/// - `f32` - Elapsed seconds since the previous animation frame.
6538///
6539/// # Returns
6540///
6541/// - `u64` - Rendered frame hash.
6542#[cfg(target_arch = "wasm32")]
6543pub fn wasm_docs_tick(dt_secs: f32) -> u64 {
6544    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6545        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6546            Ok(guard) => guard,
6547            Err(_) => return 0,
6548        };
6549        let Some((app, state)) = borrow.as_mut() else {
6550            return 0;
6551        };
6552        let needs_post_sync: bool = state.get_pending_post_layout_sync().replace(false);
6553        if needs_post_sync {
6554            let _: Result<FrameStats, PlatformError> = app.step_game_frame(dt_secs.max(0.0));
6555            state.sync_post_layout_positions(app.get_scene());
6556            return app
6557                .step_game_frame(0.0)
6558                .map(|stats: FrameStats| stats.get_frame_hash())
6559                .unwrap_or(0);
6560        }
6561        if dt_secs <= 0.0 || app.has_active_animations() || take_frame_needed() {
6562            return app
6563                .step_game_frame(dt_secs.max(0.0))
6564                .map(|stats: FrameStats| stats.get_frame_hash())
6565                .unwrap_or(0);
6566        }
6567        app.get_renderer().get_last_stats().get_frame_hash()
6568    })
6569}
6570
6571/// Resizes the WebAssembly documentation viewer canvas and logical viewport immediately from CSS pixels and `dpr`, delegating to exact physical pixel synchronization.
6572///
6573/// # Arguments
6574///
6575/// - `u32` - Logical viewport width in CSS pixels.
6576/// - `u32` - Logical viewport height in CSS pixels.
6577/// - `f32` - Active browser `window.devicePixelRatio`.
6578///
6579/// # Returns
6580///
6581/// - `u64` - Rendered frame hash.
6582#[cfg(target_arch = "wasm32")]
6583pub fn wasm_docs_resize(width: u32, height: u32, dpr: f32) -> u64 {
6584    let width_val: u32 = width.max(64);
6585    let height_val: u32 = height.max(64);
6586    let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
6587        dpr.clamp(0.5, 6.0)
6588    } else {
6589        1.0
6590    };
6591    let phys_w: u32 = ((width_val as f64) * (scale as f64))
6592        .round()
6593        .clamp(64.0, 8192.0) as u32;
6594    let phys_h: u32 = ((height_val as f64) * (scale as f64))
6595        .round()
6596        .clamp(64.0, 8192.0) as u32;
6597    wasm_docs_resize_physical(phys_w, phys_h, scale)
6598}
6599
6600/// Resizes the active WebAssembly documentation canvas and `App` to exact compositor physical pixels `(phys_w, phys_h)` at `dpr` and re-renders.
6601///
6602/// # Arguments
6603///
6604/// - `u32` - Exact physical surface width in device pixels.
6605/// - `u32` - Exact physical surface height in device pixels.
6606/// - `f32` - Active browser `window.devicePixelRatio`.
6607///
6608/// # Returns
6609///
6610/// - `u64` - Rendered frame hash.
6611#[cfg(target_arch = "wasm32")]
6612pub fn wasm_docs_resize_physical(phys_w: u32, phys_h: u32, dpr: f32) -> u64 {
6613    let measured_safe: SafeAreaInsets = web_query_safe_area_insets();
6614    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6615        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6616            Ok(guard) => guard,
6617            Err(_) => return 0,
6618        };
6619        let Some((app, state)) = borrow.as_mut() else {
6620            return 0;
6621        };
6622        let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
6623            dpr.clamp(0.5, 6.0)
6624        } else {
6625            1.0
6626        };
6627        let pw: u32 = phys_w.clamp(64, 8192);
6628        let ph: u32 = phys_h.clamp(64, 8192);
6629        if let Some(win) = window()
6630            && let Some(doc) = win.document()
6631            && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
6632            && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
6633        {
6634            if canvas.width() != pw {
6635                canvas.set_width(pw);
6636            }
6637            if canvas.height() != ph {
6638                canvas.set_height(ph);
6639            }
6640        }
6641        app.set_exact_physical_viewport(pw, ph, scale);
6642        app.get_scene().with_write(
6643            |tree: &mut SceneTree| {
6644                let root: NodeId = tree.get_root();
6645                let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
6646                tree.mark_dirty(root, dirty_l | DIRTY_PAINT);
6647            },
6648            (),
6649        );
6650        let effective_safe: SafeAreaInsets = if app.is_immersive_fullscreen() {
6651            SafeAreaInsets::default()
6652        } else {
6653            measured_safe
6654        };
6655        let current_safe: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
6656        if current_safe != effective_safe {
6657            let wid: WindowId = app.get_window_state().get_id();
6658            app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective_safe));
6659        }
6660        let first_hash: u64 = app
6661            .step_frame()
6662            .map(|stats: FrameStats| stats.get_frame_hash())
6663            .unwrap_or(0);
6664        state.get_pending_post_layout_sync().set(false);
6665        state.sync_post_layout_positions(app.get_scene());
6666        let final_hash: u64 = app
6667            .step_frame()
6668            .map(|stats: FrameStats| stats.get_frame_hash())
6669            .unwrap_or(first_hash);
6670        notify_frame_needed();
6671        final_hash
6672    })
6673}