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        Padding(Edges::new(0.0, 0.0, SPACE_LG, 0.0))
4019        Gap(2.0)
4020    };
4021    let root: NodeId = view! {
4022        column {
4023            style: column_quaternary_style
4024            role: A11yRole::Navigation
4025            ..nodes
4026        }
4027    };
4028    state.get_sidebar_root().set(root);
4029    root
4030}
4031
4032/// Mounts the viewport-clamped floating Locale Dropdown portal anchored beneath the topbar Globe icon button.
4033///
4034/// # Arguments
4035///
4036/// - `&DocsViewerState` - Shared documentation viewer state.
4037/// - `ThemeTokens` - Base design tokens.
4038/// - `Vec<NodeId>` - Desktop and Mobile Globe trigger node handles.
4039///
4040/// # Returns
4041///
4042/// - `NodeId` - Mounted floating locale dropdown portal handle.
4043fn mount_docs_locale_dropdown_portal(
4044    state: &DocsViewerState,
4045    tokens: ThemeTokens,
4046    triggers: Vec<NodeId>,
4047) -> NodeId {
4048    let mut ctx: Context = current_context();
4049    let open_sig: Signal<bool> = state.get_locale_menu_open();
4050    let last_href_sig: Signal<String> = state.get_last_locale_href();
4051    let active_route_sig: Signal<String> = state.get_active_route();
4052    let active_toc_sig: Signal<String> = state.get_active_toc_slug();
4053    let vp_sig: Signal<Size> = ctx.get_viewport_size();
4054    let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
4055    let init_tok: ThemeTokens = live_tokens_untracked(tokens);
4056    let palette: ThemePalette = init_tok.get_palette();
4057    let geometry: ThemeGeometry = init_tok.get_geometry();
4058    let card_s: SurfaceColors = palette.surface(SurfaceRole::Card);
4059    let menu_r: f32 = geometry.get_radius_lg();
4060    let item_r: f32 = concentric_radius(menu_r, CONTROL_INSET);
4061    let active_prefix: String = state.get_site().get_locale_prefix().clone();
4062    let locales: Vec<DocLocaleConfig> = state.get_site().get_locales().clone();
4063    let hovered_idx: Signal<Option<usize>> = Signal::new(None);
4064    let mut item_rows: Vec<(NodeId, NodeId, NodeId, bool)> = Vec::with_capacity(locales.len());
4065    let mut item_nodes: Vec<NodeId> = Vec::with_capacity(locales.len());
4066    for (idx, loc) in locales.iter().enumerate() {
4067        let is_cur: bool = loc.get_prefix().as_str() == active_prefix.as_str();
4068        let display_lbl: String = if !loc.get_label().trim().is_empty() {
4069            loc.get_label().trim().to_string()
4070        } else {
4071            loc.get_dir().to_ascii_uppercase()
4072        };
4073        let active_prefix_pick: String = active_prefix.clone();
4074        let target_prefix_pick: String = loc.get_prefix().clone();
4075        let (init_bg, init_fg): (Color, Color) = if is_cur {
4076            let color_value: SurfaceColors = palette.surface(SurfaceRole::Primary);
4077            (color_value.get_bg(), color_value.get_fg())
4078        } else {
4079            (COLOR_TRANSPARENT, card_s.get_fg())
4080        };
4081        let on_pick_locale = move |_: &UiEvent| {
4082            let cur_route: String = active_route_sig.get_untracked();
4083            let cur_anchor: String = active_toc_sig.get_untracked();
4084            #[cfg(target_arch = "wasm32")]
4085            let base_dir: String = window()
4086                .and_then(|win: Window| win.location().pathname().ok())
4087                .map(|pn: String| {
4088                    resolve_site_root_from_pathname(pn.as_str(), active_prefix_pick.as_str())
4089                })
4090                .unwrap_or_else(|| asset_base_for_locale_prefix(active_prefix_pick.as_str()));
4091            #[cfg(not(target_arch = "wasm32"))]
4092            let base_dir: String = asset_base_for_locale_prefix(active_prefix_pick.as_str());
4093            let target_href: String = build_locale_switch_url(
4094                base_dir.as_str(),
4095                target_prefix_pick.as_str(),
4096                cur_route.as_str(),
4097                (!cur_anchor.is_empty()).then_some(cur_anchor.as_str()),
4098            );
4099            let _: bool = last_href_sig.set_if_changed(target_href.clone());
4100            let _: bool = open_sig.set_if_changed(false);
4101            #[cfg(target_arch = "wasm32")]
4102            if !is_cur {
4103                open_browser_url(&target_href, false);
4104            }
4105        };
4106        let paint_check = move |bounds: Rect, display_list: &mut DisplayList| {
4107            if is_cur {
4108                let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
4109                let fg: Color = lp.surface(SurfaceRole::Primary).get_fg();
4110                draw_euv_icon(EuvIconName::Check, bounds, display_list, fg);
4111            }
4112        };
4113        let mut txt_id: NodeId = NodeId::default();
4114        let mut chk_id: NodeId = NodeId::default();
4115        let row_sixth_style: Style = style! {
4116            Width(Length::Percent(100.0))
4117            Height(Length::Px(DOCS_DROPDOWN_ITEM_HEIGHT))
4118            Padding(Edges::symmetric(0.0, SPACE_SM))
4119            AlignItems::Center
4120            Gap(SPACE_SM)
4121            Background(init_bg)
4122            Radius(item_r)
4123            Overflow::Hidden
4124            CursorIcon::Pointer
4125            StopEventPropagation(true)
4126        };
4127        let text_secondary_style: Style = style! {
4128            FlexGrow(1.0)
4129            FlexShrink(1.0)
4130            MinWidth(Length::Px(0.0))
4131            FontSize(13.0)
4132            if is_cur { FontWeight::SemiBold } else { FontWeight::Normal }
4133            TextColor(init_fg)
4134            Overflow::Hidden
4135            TextOverflow::Ellipsis
4136        };
4137        let canvas_fifth_style: Style = style! {
4138            Width(Length::Px(13.0))
4139            Height(Length::Px(13.0))
4140            FlexShrink(0.0)
4141        };
4142        let row_id: NodeId = view! {
4143            row {
4144                style: row_sixth_style
4145                role: A11yRole::MenuItem
4146                a11y_label: display_lbl.clone()
4147                on_click: on_pick_locale
4148                text {
4149                    node_ref: txt_id
4150                    style: text_secondary_style
4151                    { display_lbl }
4152                }
4153                canvas {
4154                    node_ref: chk_id
4155                    style: canvas_fifth_style
4156                    painter: paint_check
4157                }
4158            }
4159        };
4160        ctx.on_pointer_enter(row_id, move |_: &UiEvent| {
4161            let _: bool = hovered_idx.set_if_changed(Some(idx));
4162        });
4163        ctx.on_pointer_leave(row_id, move |_: &UiEvent| {
4164            if hovered_idx.get_untracked() == Some(idx) {
4165                let _: bool = hovered_idx.set_if_changed(None);
4166            }
4167        });
4168        item_rows.push((row_id, txt_id, chk_id, is_cur));
4169        item_nodes.push(row_id);
4170    }
4171    let est_h: f32 =
4172        (locales.len() as f32) * (DOCS_DROPDOWN_ITEM_HEIGHT + CONTROL_INSET) + CONTROL_INSET * 2.0;
4173    let mut card: NodeId = NodeId::default();
4174    let portal_secondary_style: Style = style! {
4175        Display::None
4176        Position::Fixed
4177        Inset(Some(0.0), Some(0.0), Some(0.0), Some(0.0))
4178        Width(Length::Percent(100.0))
4179        Height(Length::Percent(100.0))
4180        Background(COLOR_TRANSPARENT)
4181        PointerEvents::None
4182        StopScrollPropagation(true)
4183        ZIndex(DOCS_DROPDOWN_Z_INDEX)
4184    };
4185    let column_tertiary_style: Style = style! {
4186        Position::Absolute
4187        Inset(Some(SHELL_DESKTOP_HEADER_HEIGHT + 6.0), None, None, Some(8.0))
4188        Width(Length::Px(DOCS_LOCALE_MENU_WIDTH))
4189        Padding(Edges::all(CONTROL_INSET))
4190        Gap(CONTROL_INSET)
4191        Background(card_s.get_bg())
4192        Border::new(geometry.get_border_width(), card_s.get_border())
4193        Radius(menu_r)
4194        geometry.get_shadow_lg()
4195        Overflow::Hidden
4196        StopEventPropagation(true)
4197    };
4198    let portal: NodeId = view! {
4199        portal {
4200            style: portal_secondary_style
4201            column {
4202                node_ref: card
4203                style: column_tertiary_style
4204                role: A11yRole::Menu
4205                a11y_label: BTN_LOCALE_A11Y.to_string()
4206                ..item_nodes
4207            }
4208        }
4209    };
4210    ctx.on_click(portal, move |ui_event: &UiEvent| {
4211        if ui_event.get_target() == portal {
4212            let _: bool = open_sig.set_if_changed(false);
4213        }
4214    });
4215    for key_target in [portal, card].into_iter() {
4216        ctx.on_key(key_target, move |interaction_event: &UiEvent| {
4217            let is_esc: bool = matches!(
4218                interaction_event.get_kind(),
4219                UiEventKind::KeyDown(KeyCode::Escape, _)
4220            ) || matches!(
4221                interaction_event.get_kind(),
4222                UiEventKind::KeyDown(KeyCode::Back, _)
4223            );
4224            if is_esc && open_sig.get_untracked() {
4225                let _: bool = open_sig.set_if_changed(false);
4226            }
4227        });
4228    }
4229    let sc_pos: SceneHandle = ctx.get_scene().clone();
4230    let sc_paint: SceneHandle = sc_pos.clone();
4231    let owned_nodes: Vec<NodeId> = {
4232        let mut target_node_id: Vec<NodeId> = Vec::with_capacity(item_rows.len() * 3 + 2);
4233        target_node_id.push(portal);
4234        target_node_id.push(card);
4235        for &(rid, tid, cid, _) in item_rows.iter() {
4236            target_node_id.push(rid);
4237            target_node_id.push(tid);
4238            target_node_id.push(cid);
4239        }
4240        target_node_id
4241    };
4242    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4243        let _: Effect =
4244            EuvOverlayStack::bind_signal(open_sig, DOCS_LOCALE_OVERLAY_NAME, DOCS_DROPDOWN_Z_INDEX);
4245        let _: Effect = Effect::new(move || {
4246            let is_open: bool = open_sig.get();
4247            let box_size: Size = vp_sig.get();
4248            let safe: SafeAreaInsets = safe_sig.get();
4249            let (left, top, width, _): (f32, f32, f32, f32) = docs_dropdown_anchor_rect(
4250                &sc_pos,
4251                &triggers,
4252                box_size,
4253                safe,
4254                DOCS_LOCALE_MENU_WIDTH,
4255                est_h.min(DOCS_DROPDOWN_MAX_HEIGHT),
4256            );
4257            if !is_open {
4258                let _: bool = hovered_idx.set_if_changed(None);
4259            }
4260            sc_pos.with_write(
4261                |tree: &mut SceneTree| {
4262                    let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4263                    let dirty_all: u16 = dirty_l | DIRTY_PAINT;
4264                    if let Some(item_count) = tree.get_node_mut(card) {
4265                        let lay: &mut LayoutStyle = item_count.get_mut_style().get_mut_layout();
4266                        lay.set_left(Some(left))
4267                            .set_top(Some(top))
4268                            .set_width(Length::Px(width));
4269                        tree.mark_dirty(card, dirty_all);
4270                    }
4271                    if let Some(node_entry) = tree.get_node_mut(portal) {
4272                        let computed_style: &mut Style = node_entry.get_mut_style();
4273                        computed_style.get_mut_layout().set_display(if is_open {
4274                            Display::Flex
4275                        } else {
4276                            Display::None
4277                        });
4278                        computed_style
4279                            .get_mut_paint()
4280                            .set_pointer_events(if is_open {
4281                                PointerEvents::Auto
4282                            } else {
4283                                PointerEvents::None
4284                            });
4285                        tree.mark_dirty(portal, dirty_all);
4286                    }
4287                },
4288                (),
4289            );
4290        });
4291        Effect::new(move || {
4292            let hov: Option<usize> = hovered_idx.get();
4293            let tok: ThemeTokens = use_live_tokens(tokens);
4294            let lp: ThemePalette = tok.get_palette();
4295            let lg: ThemeGeometry = tok.get_geometry();
4296            let cs: SurfaceColors = lp.surface(SurfaceRole::Card);
4297            let ps: SurfaceColors = lp.surface(SurfaceRole::Primary);
4298            let ac: SurfaceColors = lp.surface(SurfaceRole::Accent);
4299            sc_paint.with_write(
4300                |tree: &mut SceneTree| {
4301                    if let Some(normal_vec) = tree.get_node_mut(card) {
4302                        normal_vec
4303                            .get_mut_style()
4304                            .get_mut_paint()
4305                            .set_background(Some(cs.get_bg()))
4306                            .set_border(Border::new(lg.get_border_width(), cs.get_border()))
4307                            .set_shadow(Some(lg.get_shadow_lg()));
4308                        tree.mark_dirty(card, DIRTY_PAINT);
4309                    }
4310                    for (idx, &(rid, tid, cid, is_cur)) in item_rows.iter().enumerate() {
4311                        let is_hov: bool = hov == Some(idx);
4312                        let (bg, fg): (Color, Color) = if is_cur {
4313                            (ps.get_bg(), ps.get_fg())
4314                        } else if is_hov {
4315                            (ac.get_bg(), ac.get_fg())
4316                        } else {
4317                            (COLOR_TRANSPARENT, cs.get_fg())
4318                        };
4319                        if let Some(total_len) = tree.get_node_mut(rid) {
4320                            total_len
4321                                .get_mut_style()
4322                                .get_mut_paint()
4323                                .set_background(Some(bg));
4324                            tree.mark_dirty(rid, DIRTY_PAINT);
4325                        }
4326                        if let Some(item_count_primary) = tree.get_node_mut(tid) {
4327                            item_count_primary
4328                                .get_mut_style()
4329                                .get_mut_text()
4330                                .set_color(fg);
4331                            tree.mark_dirty(tid, DIRTY_PAINT);
4332                        }
4333                        tree.mark_dirty(cid, DIRTY_PAINT);
4334                    }
4335                },
4336                (),
4337            );
4338        })
4339    });
4340    ctx.get_scene().with_write(
4341        |tree: &mut SceneTree| {
4342            mark_theme_owned(tree, owned_nodes.as_slice());
4343            tree.attach_scope(portal, scope);
4344        },
4345        (),
4346    );
4347    portal
4348}
4349
4350/// Mounts the viewport-clamped scrollable floating 17-Scheme Theme Color Dropdown portal anchored beneath the topbar Palette icon button.
4351///
4352/// # Arguments
4353///
4354/// - `&DocsViewerState` - Shared documentation viewer state.
4355/// - `ThemeTokens` - Base design tokens.
4356/// - `Vec<NodeId>` - Desktop and Mobile Palette trigger node handles.
4357///
4358/// # Returns
4359///
4360/// - `NodeId` - Mounted floating 17-scheme dropdown portal handle.
4361fn mount_docs_scheme_dropdown_portal(
4362    state: &DocsViewerState,
4363    tokens: ThemeTokens,
4364    triggers: Vec<NodeId>,
4365) -> NodeId {
4366    let mut ctx: Context = current_context();
4367    let open_sig: Signal<bool> = state.get_scheme_menu_open();
4368    let scheme_sig: Signal<DesignScheme> = state.get_theme().get_scheme();
4369    let mode_sig: Signal<ThemeMode> = state.get_theme().get_mode();
4370    let vp_sig: Signal<Size> = ctx.get_viewport_size();
4371    let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
4372    let init_tok: ThemeTokens = live_tokens_untracked(tokens);
4373    let palette: ThemePalette = init_tok.get_palette();
4374    let geometry: ThemeGeometry = init_tok.get_geometry();
4375    let card_s: SurfaceColors = palette.surface(SurfaceRole::Card);
4376    let menu_r: f32 = geometry.get_radius_lg();
4377    let item_r: f32 = concentric_radius(menu_r, CONTROL_INSET);
4378    let all_schemes: [DesignScheme; 17] = DesignScheme::all();
4379    let init_scheme: DesignScheme = scheme_sig.get_untracked();
4380    let init_mode: ThemeMode = mode_sig.get_untracked();
4381    let hovered_idx: Signal<Option<usize>> = Signal::new(None);
4382    let mut item_handles: Vec<(DesignScheme, NodeId, NodeId, NodeId, NodeId)> =
4383        Vec::with_capacity(all_schemes.len());
4384    let mut item_nodes: Vec<NodeId> = Vec::with_capacity(all_schemes.len());
4385    for (idx, scheme) in all_schemes.into_iter().enumerate() {
4386        let is_sel: bool = scheme == init_scheme;
4387        let (init_bg, init_fg): (Color, Color) = if is_sel {
4388            let ps: SurfaceColors = palette.surface(SurfaceRole::Primary);
4389            (ps.get_bg(), ps.get_fg())
4390        } else {
4391            (COLOR_TRANSPARENT, card_s.get_fg())
4392        };
4393        let init_swatch: Color = ThemeTokens::resolve(scheme, init_mode)
4394            .get_palette()
4395            .get_primary();
4396        let lbl_str: &'static str = docs_scheme_display_label(scheme);
4397        let on_pick_scheme = move |_: &UiEvent| {
4398            let _: bool = scheme_sig.set_if_changed(scheme);
4399            let _: bool = open_sig.set_if_changed(false);
4400        };
4401        let paint_check = move |bounds: Rect, display_list: &mut DisplayList| {
4402            if scheme_sig.get_untracked() == scheme {
4403                let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
4404                let fg: Color = lp.surface(SurfaceRole::Primary).get_fg();
4405                draw_euv_icon(EuvIconName::Check, bounds, display_list, fg);
4406            }
4407        };
4408        let mut dot_id: NodeId = NodeId::default();
4409        let mut txt_id: NodeId = NodeId::default();
4410        let mut chk_id: NodeId = NodeId::default();
4411        let row_fifth_style: Style = style! {
4412            Width(Length::Percent(100.0))
4413            Height(Length::Px(DOCS_DROPDOWN_ITEM_HEIGHT))
4414            Padding(Edges::symmetric(0.0, SPACE_SM))
4415            AlignItems::Center
4416            Gap(SPACE_SM)
4417            Background(init_bg)
4418            Radius(item_r)
4419            Overflow::Hidden
4420            CursorIcon::Pointer
4421            StopEventPropagation(true)
4422        };
4423        let view_style: Style = style! {
4424            Width(Length::Px(12.0))
4425            Height(Length::Px(12.0))
4426            FlexShrink(0.0)
4427            Background(init_swatch)
4428            Border::new(1.0, palette.get_border())
4429            Radius(RADIUS_PILL)
4430        };
4431        let text_style: Style = style! {
4432            FlexGrow(1.0)
4433            FlexShrink(1.0)
4434            MinWidth(Length::Px(0.0))
4435            FontSize(13.0)
4436            if is_sel { FontWeight::SemiBold } else { FontWeight::Normal }
4437            TextColor(init_fg)
4438            Overflow::Hidden
4439            TextOverflow::Ellipsis
4440        };
4441        let canvas_quaternary_style: Style = style! {
4442            Width(Length::Px(13.0))
4443            Height(Length::Px(13.0))
4444            FlexShrink(0.0)
4445        };
4446        let row_id: NodeId = view! {
4447            row {
4448                style: row_fifth_style
4449                role: A11yRole::MenuItem
4450                a11y_label: lbl_str.to_string()
4451                on_click: on_pick_scheme
4452                view {
4453                    node_ref: dot_id
4454                    style: view_style
4455                }
4456                text {
4457                    node_ref: txt_id
4458                    style: text_style
4459                    { lbl_str }
4460                }
4461                canvas {
4462                    node_ref: chk_id
4463                    style: canvas_quaternary_style
4464                    painter: paint_check
4465                }
4466            }
4467        };
4468        ctx.on_pointer_enter(row_id, move |_: &UiEvent| {
4469            let _: bool = hovered_idx.set_if_changed(Some(idx));
4470        });
4471        ctx.on_pointer_leave(row_id, move |_: &UiEvent| {
4472            if hovered_idx.get_untracked() == Some(idx) {
4473                let _: bool = hovered_idx.set_if_changed(None);
4474            }
4475        });
4476        item_handles.push((scheme, row_id, dot_id, txt_id, chk_id));
4477        item_nodes.push(row_id);
4478    }
4479    let mut card: NodeId = NodeId::default();
4480    let mut scroll_list: NodeId = NodeId::default();
4481    let portal_style: Style = style! {
4482        Display::None
4483        Position::Fixed
4484        Inset(Some(0.0), Some(0.0), Some(0.0), Some(0.0))
4485        Width(Length::Percent(100.0))
4486        Height(Length::Percent(100.0))
4487        Background(COLOR_TRANSPARENT)
4488        PointerEvents::None
4489        StopScrollPropagation(true)
4490        ZIndex(DOCS_DROPDOWN_Z_INDEX)
4491    };
4492    let column_secondary_style: Style = style! {
4493        Position::Absolute
4494        Inset(Some(SHELL_DESKTOP_HEADER_HEIGHT + 6.0), None, None, Some(8.0))
4495        Width(Length::Px(DOCS_SCHEME_MENU_WIDTH))
4496        Padding(Edges::all(CONTROL_INSET))
4497        Background(card_s.get_bg())
4498        Border::new(geometry.get_border_width(), card_s.get_border())
4499        Radius(menu_r)
4500        geometry.get_shadow_lg()
4501        Overflow::Hidden
4502        StopEventPropagation(true)
4503    };
4504    let scroll_style: Style = style! {
4505        FlexDirection::Column
4506        Width(Length::Percent(100.0))
4507        MaxHeight(Length::Px(DOCS_DROPDOWN_MAX_HEIGHT))
4508        Gap(CONTROL_INSET)
4509    };
4510    let portal: NodeId = view! {
4511        portal {
4512            style: portal_style
4513            column {
4514                node_ref: card
4515                style: column_secondary_style
4516                role: A11yRole::Menu
4517                a11y_label: BTN_SCHEME_A11Y.to_string()
4518                scroll {
4519                    node_ref: scroll_list
4520                    style: scroll_style
4521                    ..item_nodes
4522                }
4523            }
4524        }
4525    };
4526    ctx.on_click(portal, move |ui_event: &UiEvent| {
4527        if ui_event.get_target() == portal {
4528            let _: bool = open_sig.set_if_changed(false);
4529        }
4530    });
4531    for key_target in [portal, card].into_iter() {
4532        ctx.on_key(key_target, move |interaction_event: &UiEvent| {
4533            let is_esc: bool = matches!(
4534                interaction_event.get_kind(),
4535                UiEventKind::KeyDown(KeyCode::Escape, _)
4536            ) || matches!(
4537                interaction_event.get_kind(),
4538                UiEventKind::KeyDown(KeyCode::Back, _)
4539            );
4540            if is_esc && open_sig.get_untracked() {
4541                let _: bool = open_sig.set_if_changed(false);
4542            }
4543        });
4544    }
4545    let sc_pos: SceneHandle = ctx.get_scene().clone();
4546    let sc_paint: SceneHandle = sc_pos.clone();
4547    let owned_nodes: Vec<NodeId> = {
4548        let mut target_node_id: Vec<NodeId> = Vec::with_capacity(item_handles.len() * 4 + 3);
4549        target_node_id.push(portal);
4550        target_node_id.push(card);
4551        target_node_id.push(scroll_list);
4552        for &(_, rid, did, tid, cid) in item_handles.iter() {
4553            target_node_id.push(rid);
4554            target_node_id.push(did);
4555            target_node_id.push(tid);
4556            target_node_id.push(cid);
4557        }
4558        target_node_id
4559    };
4560    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4561        let _: Effect =
4562            EuvOverlayStack::bind_signal(open_sig, DOCS_SCHEME_OVERLAY_NAME, DOCS_DROPDOWN_Z_INDEX);
4563        let _: Effect = Effect::new(move || {
4564            let is_open: bool = open_sig.get();
4565            let box_size: Size = vp_sig.get();
4566            let safe: SafeAreaInsets = safe_sig.get();
4567            let (left, top, width, max_h): (f32, f32, f32, f32) = docs_dropdown_anchor_rect(
4568                &sc_pos,
4569                &triggers,
4570                box_size,
4571                safe,
4572                DOCS_SCHEME_MENU_WIDTH,
4573                DOCS_DROPDOWN_MAX_HEIGHT,
4574            );
4575            if !is_open {
4576                let _: bool = hovered_idx.set_if_changed(None);
4577            }
4578            let inner_max_h: f32 = (max_h - CONTROL_INSET * 2.0).max(96.0);
4579            sc_pos.with_write(
4580                |tree: &mut SceneTree| {
4581                    let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4582                    let dirty_all: u16 = dirty_l | DIRTY_PAINT;
4583                    if let Some(item_count) = tree.get_node_mut(scroll_list) {
4584                        item_count
4585                            .get_mut_style()
4586                            .get_mut_layout()
4587                            .set_max_height(Length::Px(inner_max_h));
4588                        tree.mark_dirty(scroll_list, dirty_all);
4589                    }
4590                    if let Some(node_entry) = tree.get_node_mut(card) {
4591                        let lay: &mut LayoutStyle = node_entry.get_mut_style().get_mut_layout();
4592                        lay.set_left(Some(left))
4593                            .set_top(Some(top))
4594                            .set_width(Length::Px(width));
4595                        tree.mark_dirty(card, dirty_all);
4596                    }
4597                    if let Some(normal_vec) = tree.get_node_mut(portal) {
4598                        let computed_style: &mut Style = normal_vec.get_mut_style();
4599                        computed_style.get_mut_layout().set_display(if is_open {
4600                            Display::Flex
4601                        } else {
4602                            Display::None
4603                        });
4604                        computed_style
4605                            .get_mut_paint()
4606                            .set_pointer_events(if is_open {
4607                                PointerEvents::Auto
4608                            } else {
4609                                PointerEvents::None
4610                            });
4611                        tree.mark_dirty(portal, dirty_all);
4612                    }
4613                },
4614                (),
4615            );
4616        });
4617        Effect::new(move || {
4618            let cur_scheme: DesignScheme = scheme_sig.get();
4619            let cur_mode: ThemeMode = mode_sig.get();
4620            let hov: Option<usize> = hovered_idx.get();
4621            let tok: ThemeTokens = use_live_tokens(tokens);
4622            let lp: ThemePalette = tok.get_palette();
4623            let lg: ThemeGeometry = tok.get_geometry();
4624            let cs: SurfaceColors = lp.surface(SurfaceRole::Card);
4625            let ps: SurfaceColors = lp.surface(SurfaceRole::Primary);
4626            let ac: SurfaceColors = lp.surface(SurfaceRole::Accent);
4627            sc_paint.with_write(
4628                |tree: &mut SceneTree| {
4629                    if let Some(total_len) = tree.get_node_mut(card) {
4630                        total_len
4631                            .get_mut_style()
4632                            .get_mut_paint()
4633                            .set_background(Some(cs.get_bg()))
4634                            .set_border(Border::new(lg.get_border_width(), cs.get_border()))
4635                            .set_shadow(Some(lg.get_shadow_lg()));
4636                        tree.mark_dirty(card, DIRTY_PAINT);
4637                    }
4638                    for (idx, &(sc_item, rid, did, tid, cid)) in item_handles.iter().enumerate() {
4639                        let is_sel: bool = sc_item == cur_scheme;
4640                        let is_hov: bool = hov == Some(idx);
4641                        let (bg, fg): (Color, Color) = if is_sel {
4642                            (ps.get_bg(), ps.get_fg())
4643                        } else if is_hov {
4644                            (ac.get_bg(), ac.get_fg())
4645                        } else {
4646                            (COLOR_TRANSPARENT, cs.get_fg())
4647                        };
4648                        let sw_col: Color = ThemeTokens::resolve(sc_item, cur_mode)
4649                            .get_palette()
4650                            .get_primary();
4651                        let sw_border: Color = if is_sel {
4652                            ps.get_fg().with_alpha(160)
4653                        } else {
4654                            lp.get_border()
4655                        };
4656                        if let Some(item_count_primary) = tree.get_node_mut(rid) {
4657                            item_count_primary
4658                                .get_mut_style()
4659                                .get_mut_paint()
4660                                .set_background(Some(bg));
4661                            tree.mark_dirty(rid, DIRTY_PAINT);
4662                        }
4663                        if let Some(item_count_secondary) = tree.get_node_mut(did) {
4664                            item_count_secondary
4665                                .get_mut_style()
4666                                .get_mut_paint()
4667                                .set_background(Some(sw_col))
4668                                .set_border(Border::new(1.0, sw_border));
4669                            tree.mark_dirty(did, DIRTY_PAINT);
4670                        }
4671                        if let Some(item_count_next) = tree.get_node_mut(tid) {
4672                            item_count_next
4673                                .get_mut_style()
4674                                .get_mut_text()
4675                                .set_color(fg)
4676                                .set_weight(if is_sel {
4677                                    FontWeight::SemiBold
4678                                } else {
4679                                    FontWeight::Normal
4680                                });
4681                            tree.mark_dirty(tid, DIRTY_PAINT);
4682                        }
4683                        tree.mark_dirty(cid, DIRTY_PAINT);
4684                    }
4685                },
4686                (),
4687            );
4688        })
4689    });
4690    ctx.get_scene().with_write(
4691        |tree: &mut SceneTree| {
4692            mark_theme_owned(tree, owned_nodes.as_slice());
4693            tree.attach_scope(portal, scope);
4694        },
4695        (),
4696    );
4697    portal
4698}
4699
4700/// 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`).
4701///
4702/// # Arguments
4703///
4704/// - `&DocsViewerState` - Shared reactive documentation viewer state.
4705///
4706/// # Returns
4707///
4708/// - `NodeId` - Mounted documentation application root handle.
4709pub fn mount_docs_viewer_with_state(state: &DocsViewerState) -> NodeId {
4710    provide_theme(state.get_theme().clone());
4711    ensure_docs_routes_registered(state);
4712    let tokens: ThemeTokens = untracked(|| state.get_theme().get_tokens().get());
4713    let active_route: Signal<String> = state.get_active_route();
4714    let cmd_open: Signal<bool> = state.get_cmd_open();
4715    let cmd_query: Signal<String> = state.get_cmd_query();
4716    let locale_open: Signal<bool> = state.get_locale_menu_open();
4717    let scheme_open: Signal<bool> = state.get_scheme_menu_open();
4718    let all_pages: &[DocPage] = state.get_site().get_pages().as_slice();
4719    let mut cmd_routes: Vec<String> = Vec::with_capacity(all_pages.len());
4720    let mut cmd_items: Vec<String> = Vec::with_capacity(all_pages.len() + 2);
4721    for page in all_pages.iter() {
4722        if !page.has_readable_content() {
4723            continue;
4724        }
4725        cmd_routes.push(page.get_route().clone());
4726        cmd_items.push(format!("{} — {}", page.get_title(), page.get_section()));
4727    }
4728    let toggle_idx: usize = cmd_items.len();
4729    cmd_items.push(CMD_ACTION_TOGGLE_MODE.to_string());
4730    let scheme_idx: usize = cmd_items.len();
4731    cmd_items.push(CMD_ACTION_NEXT_SCHEME.to_string());
4732    let cmd_sel: Signal<Option<usize>> = Signal::new(None);
4733    let cmd_list: NodeId = view! {
4734        EuvCommand {
4735            items: cmd_items
4736            selected: cmd_sel
4737            tokens: tokens
4738            query: cmd_query
4739            placeholder: CMD_PLACEHOLDER
4740            frameless: true
4741        }
4742    };
4743    let cmd_state: DocsViewerState = state.clone();
4744    let (cmd_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4745        Effect::new(move || {
4746            if let Some(idx) = cmd_sel.get() {
4747                if let Some(target) = cmd_routes.get(idx) {
4748                    let _: bool = active_route.set_if_changed(target.clone());
4749                } else if idx == toggle_idx {
4750                    cmd_state.toggle_theme_mode();
4751                } else if idx == scheme_idx {
4752                    cmd_state.next_scheme();
4753                }
4754                let _: bool = cmd_sel.set_if_changed(None);
4755                let _: bool = cmd_open.set_if_changed(false);
4756            }
4757        })
4758    });
4759    let cmd_modal: NodeId = view! {
4760        EuvModal {
4761            open: cmd_open
4762            title: CMD_MODAL_TITLE.to_string()
4763            body: cmd_list
4764            tokens: tokens
4765        }
4766    };
4767    let mut rctx: Context = current_context();
4768    let theme_memo: Memo<ThemeTokens> = state.get_theme().get_tokens();
4769    let prev_modal_tok: Rc<Cell<ThemeTokens>> = Rc::new(Cell::new(tokens));
4770    let modal_theme_ctx: Context = rctx.clone();
4771    let (modal_theme_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4772        Effect::new(move || {
4773            let next_tok: ThemeTokens = theme_memo.get();
4774            let old_tok: ThemeTokens = prev_modal_tok.replace(next_tok);
4775            if old_tok == next_tok {
4776                return;
4777            }
4778            modal_theme_ctx.get_scene().with_write(
4779                |tree: &mut SceneTree| {
4780                    remap_subtree_theme_in_place(tree, cmd_modal, old_tok, next_tok);
4781                },
4782                (),
4783            );
4784        })
4785    });
4786    rctx.get_scene().with_write(
4787        |tree: &mut SceneTree| {
4788            tree.attach_scope(cmd_modal, cmd_scope);
4789            tree.attach_scope(cmd_modal, modal_theme_scope);
4790        },
4791        (),
4792    );
4793    let router: EuvRouter = state.get_router().clone();
4794    let cur_route: String = active_route.get_untracked();
4795    if router.get_current_path().get_untracked() != cur_route {
4796        router.replace(&cur_route);
4797    }
4798    let breadcrumb_sig: Signal<String> = Signal::new(state.breadcrumb_for_route(&cur_route));
4799    let page_pad_sig: Signal<Edges> = Signal::new(Edges::all(SPACE_LG));
4800    let swipe_routes: Vec<String> = state.ordered_routes();
4801    let state_sync: DocsViewerState = state.clone();
4802    let router_sync_in: EuvRouter = router.clone();
4803    let router_path_sig: Signal<String> = router.get_current_path();
4804    let (sync_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4805        let _: Effect = Effect::new(move || {
4806            let target: String = active_route.get();
4807            let _: bool = breadcrumb_sig.set_if_changed(state_sync.breadcrumb_for_route(&target));
4808            if router_sync_in.get_current_path().get_untracked() != target {
4809                router_sync_in.push(&target);
4810            }
4811        });
4812        Effect::new(move || {
4813            let rp: String = router_path_sig.get();
4814            if active_route.get_untracked() != rp {
4815                let _: bool = active_route.set_if_changed(rp);
4816            }
4817        })
4818    });
4819    let state_fallback: DocsViewerState = state.clone();
4820    let outlet_node: NodeId = router
4821        .outlet(move |matched: &EuvRouteMatch| {
4822            let tok: ThemeTokens = untracked(|| state_fallback.get_theme().get_tokens().get());
4823            match state_fallback
4824                .get_site()
4825                .find_by_route(matched.get_path())
4826                .or_else(|| state_fallback.get_site().get_pages().first())
4827            {
4828                Some(point_val) => mount_doc_page_with_context(point_val, &state_fallback, tok),
4829                None => view! {
4830                    EuvEmpty {
4831                        title: EMPTY_PAGE_TITLE.to_string()
4832                        description: EMPTY_PAGE_MSG.to_string()
4833                        tokens: tok
4834                    }
4835                },
4836            }
4837        })
4838        .with_theme(state.get_theme().clone())
4839        .with_page_padding(page_pad_sig)
4840        .with_route_order(swipe_routes.clone())
4841        .mount();
4842    rctx.get_scene().with_write(
4843        |tree: &mut SceneTree| {
4844            tree.attach_scope(outlet_node, sync_scope);
4845        },
4846        (),
4847    );
4848    let sidebar_node: NodeId = mount_docs_catalog_tree(state, tokens);
4849    let theme_mode_sig: Signal<ThemeMode> = state.get_theme().get_mode();
4850    let has_multi_locales: bool = state.get_site().get_locales().len() > 1;
4851    let search_pill_lbl: &'static str = state.search_button_label();
4852    let icon_btn_style_desk = move || -> Style {
4853        let live_tok: ThemeTokens = use_live_tokens(tokens);
4854        let live_p: ThemePalette = live_tok.get_palette();
4855        let live_g: ThemeGeometry = live_tok.get_geometry();
4856        style! {
4857            FlexDirection::Row
4858            Width(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4859            Height(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4860            FlexShrink(0.0)
4861            JustifyContent::Center
4862            AlignItems::Center
4863            Background(live_p.get_background())
4864            Border::new(live_g.get_border_width(), live_p.get_border())
4865            Radius(live_g.get_radius_md())
4866            CursorIcon::Pointer
4867        }
4868    };
4869    let icon_btn_style_mob = move || -> Style {
4870        let live_tok: ThemeTokens = use_live_tokens(tokens);
4871        let live_p: ThemePalette = live_tok.get_palette();
4872        let live_g: ThemeGeometry = live_tok.get_geometry();
4873        style! {
4874            FlexDirection::Row
4875            Width(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4876            Height(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4877            FlexShrink(0.0)
4878            JustifyContent::Center
4879            AlignItems::Center
4880            Background(live_p.get_background())
4881            Border::new(live_g.get_border_width(), live_p.get_border())
4882            Radius(live_g.get_radius_md())
4883            CursorIcon::Pointer
4884        }
4885    };
4886    let search_pill_style = move || -> Style {
4887        let live_tok: ThemeTokens = use_live_tokens(tokens);
4888        let live_p: ThemePalette = live_tok.get_palette();
4889        let live_g: ThemeGeometry = live_tok.get_geometry();
4890        style! {
4891            FlexDirection::Row
4892            MinWidth(Length::Px(136.0))
4893            Height(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4894            FlexShrink(0.0)
4895            Padding(Edges::symmetric(0.0, 10.0))
4896            JustifyContent::SpaceBetween
4897            AlignItems::Center
4898            Gap(SPACE_SM)
4899            Background(live_p.get_background())
4900            Border::new(live_g.get_border_width(), live_p.get_border())
4901            Radius(live_g.get_radius_md())
4902            CursorIcon::Pointer
4903        }
4904    };
4905    let search_lbl_style = move || -> Style {
4906        let live_p: ThemePalette = use_live_tokens(tokens).get_palette();
4907        style! {
4908            FontSize(12.5)
4909            TextColor(live_p.get_muted_foreground())
4910        }
4911    };
4912    let kbd_badge_style = move || -> Style {
4913        let live_tok: ThemeTokens = use_live_tokens(tokens);
4914        let live_p: ThemePalette = live_tok.get_palette();
4915        let live_g: ThemeGeometry = live_tok.get_geometry();
4916        style! {
4917            Padding(Edges::symmetric(1.0, 5.0))
4918            Background(live_p.get_muted())
4919            Border::new(live_g.get_border_width(), live_p.get_border())
4920            Radius(live_g.get_radius_sm())
4921            FontSize(11.0)
4922            TextColor(live_p.get_muted_foreground())
4923        }
4924    };
4925    let paint_search_desk = move |bounds: Rect, display_list: &mut DisplayList| {
4926        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4927        draw_docs_search_icon(bounds, display_list, live_p.get_muted_foreground());
4928    };
4929    let paint_search_mob = move |bounds: Rect, draw_commands: &mut DisplayList| {
4930        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4931        draw_docs_search_icon(bounds, draw_commands, live_p.get_foreground());
4932    };
4933    let paint_globe_desk = move |bounds: Rect, command_list: &mut DisplayList| {
4934        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4935        draw_docs_globe_icon(bounds, command_list, live_p.get_foreground());
4936    };
4937    let paint_globe_mob = move |bounds: Rect, display_list_primary: &mut DisplayList| {
4938        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4939        draw_docs_globe_icon(bounds, display_list_primary, live_p.get_foreground());
4940    };
4941    let paint_scheme_desk = move |bounds: Rect, display_list_secondary: &mut DisplayList| {
4942        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4943        draw_docs_palette_icon(
4944            bounds,
4945            display_list_secondary,
4946            live_p.get_foreground(),
4947            live_p.get_primary(),
4948        );
4949    };
4950    let paint_scheme_mob = move |bounds: Rect, display_list_next: &mut DisplayList| {
4951        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4952        draw_docs_palette_icon(
4953            bounds,
4954            display_list_next,
4955            live_p.get_foreground(),
4956            live_p.get_primary(),
4957        );
4958    };
4959    let paint_mode_desk = move |bounds: Rect, display_list_alt: &mut DisplayList| {
4960        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4961        match theme_mode_sig.get_untracked() {
4962            ThemeMode::Dark => {
4963                draw_docs_sun_icon(bounds, display_list_alt, live_p.get_foreground())
4964            }
4965            ThemeMode::Light => {
4966                draw_docs_moon_star_icon(bounds, display_list_alt, live_p.get_foreground())
4967            }
4968        }
4969    };
4970    let paint_mode_mob = move |bounds: Rect, display_list_inner: &mut DisplayList| {
4971        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4972        match theme_mode_sig.get_untracked() {
4973            ThemeMode::Dark => {
4974                draw_docs_sun_icon(bounds, display_list_inner, live_p.get_foreground())
4975            }
4976            ThemeMode::Light => {
4977                draw_docs_moon_star_icon(bounds, display_list_inner, live_p.get_foreground())
4978            }
4979        }
4980    };
4981    let st_mode_desk: DocsViewerState = state.clone();
4982    let st_mode_mob: DocsViewerState = state.clone();
4983    let on_open_cmd_desk = move |_: &UiEvent| {
4984        let _: bool = locale_open.set_if_changed(false);
4985        let _: bool = scheme_open.set_if_changed(false);
4986        let _: bool = cmd_open.set_if_changed(true);
4987    };
4988    let on_open_cmd_mob = move |_: &UiEvent| {
4989        let _: bool = locale_open.set_if_changed(false);
4990        let _: bool = scheme_open.set_if_changed(false);
4991        let _: bool = cmd_open.set_if_changed(true);
4992    };
4993    let on_toggle_locale_desk = move |_: &UiEvent| {
4994        let next: bool = !locale_open.get_untracked();
4995        let _: bool = scheme_open.set_if_changed(false);
4996        let _: bool = locale_open.set_if_changed(next);
4997    };
4998    let on_toggle_locale_mob = move |_: &UiEvent| {
4999        let next: bool = !locale_open.get_untracked();
5000        let _: bool = scheme_open.set_if_changed(false);
5001        let _: bool = locale_open.set_if_changed(next);
5002    };
5003    let on_toggle_scheme_desk = move |_: &UiEvent| {
5004        let next: bool = !scheme_open.get_untracked();
5005        let _: bool = locale_open.set_if_changed(false);
5006        let _: bool = scheme_open.set_if_changed(next);
5007    };
5008    let on_toggle_scheme_mob = move |_: &UiEvent| {
5009        let next: bool = !scheme_open.get_untracked();
5010        let _: bool = locale_open.set_if_changed(false);
5011        let _: bool = scheme_open.set_if_changed(next);
5012    };
5013    let on_toggle_mode_desk = move |_: &UiEvent| {
5014        st_mode_desk.toggle_theme_mode();
5015    };
5016    let on_toggle_mode_mob = move |_: &UiEvent| {
5017        st_mode_mob.toggle_theme_mode();
5018    };
5019    let mut locale_btn_desk: NodeId = NodeId::default();
5020    let mut locale_btn_mob: NodeId = NodeId::default();
5021    let mut scheme_btn_desk: NodeId = NodeId::default();
5022    let mut scheme_btn_mob: NodeId = NodeId::default();
5023    let row_tertiary_style: Style = style! {
5024        Gap(SPACE_XS)
5025        AlignItems::Center
5026    };
5027    let row_quaternary_style: Style = style! {
5028        AlignItems::Center
5029        Gap(6.0)
5030    };
5031    let canvas_secondary_style: Style = style! {
5032        Width(Length::Px(15.0))
5033        Height(Length::Px(15.0))
5034        FlexShrink(0.0)
5035    };
5036    let canvas_tertiary_style: Style = style! {
5037        Width(Length::Px(DOCS_TOPBAR_ICON_SIZE))
5038        Height(Length::Px(DOCS_TOPBAR_ICON_SIZE))
5039    };
5040    let top_actions: NodeId = view! {
5041        row {
5042            style: row_tertiary_style
5043            row {
5044                bind_style: search_pill_style
5045                role: A11yRole::Button
5046                a11y_label: BTN_SEARCH_A11Y.to_string()
5047                on_click: on_open_cmd_desk
5048                row {
5049                    style: row_quaternary_style
5050                    canvas {
5051                        style: canvas_secondary_style
5052                        caching: CanvasCaching::RetainedStatic
5053                        painter: paint_search_desk
5054                    }
5055                    text {
5056                        bind_style: search_lbl_style
5057                        { search_pill_lbl }
5058                    }
5059                }
5060                text {
5061                    bind_style: kbd_badge_style
5062                    { DOCS_SEARCH_SHORTCUT_HINT }
5063                }
5064            }
5065            if has_multi_locales {
5066                row {
5067                    node_ref: locale_btn_desk
5068                    bind_style: icon_btn_style_desk
5069                    role: A11yRole::Button
5070                    a11y_label: BTN_LOCALE_A11Y.to_string()
5071                    on_click: on_toggle_locale_desk
5072                    canvas {
5073                        style: canvas_tertiary_style
5074                        caching: CanvasCaching::RetainedStatic
5075                        painter: paint_globe_desk
5076                    }
5077                }
5078            }
5079            row {
5080                node_ref: scheme_btn_desk
5081                bind_style: icon_btn_style_desk
5082                role: A11yRole::Button
5083                a11y_label: BTN_SCHEME_A11Y.to_string()
5084                on_click: on_toggle_scheme_desk
5085                canvas {
5086                    style: canvas_tertiary_style
5087                    caching: CanvasCaching::RetainedStatic
5088                    painter: paint_scheme_desk
5089                }
5090            }
5091            row {
5092                bind_style: icon_btn_style_desk
5093                role: A11yRole::Button
5094                a11y_label: BTN_MODE_A11Y.to_string()
5095                on_click: on_toggle_mode_desk
5096                canvas {
5097                    style: canvas_tertiary_style
5098                    caching: CanvasCaching::RetainedStatic
5099                    painter: paint_mode_desk
5100                }
5101            }
5102        }
5103    };
5104    let row_secondary_style: Style = style! {
5105        Gap(SPACE_XS)
5106        AlignItems::Center
5107    };
5108    let canvas_style: Style = style! {
5109        Width(Length::Px(DOCS_TOPBAR_ICON_SIZE))
5110        Height(Length::Px(DOCS_TOPBAR_ICON_SIZE))
5111    };
5112    let mobile_actions: NodeId = view! {
5113        row {
5114            style: row_secondary_style
5115            row {
5116                bind_style: icon_btn_style_mob
5117                role: A11yRole::Button
5118                a11y_label: BTN_SEARCH_A11Y.to_string()
5119                on_click: on_open_cmd_mob
5120                canvas {
5121                    style: canvas_style
5122                    caching: CanvasCaching::RetainedStatic
5123                    painter: paint_search_mob
5124                }
5125            }
5126            if has_multi_locales {
5127                row {
5128                    node_ref: locale_btn_mob
5129                    bind_style: icon_btn_style_mob
5130                    role: A11yRole::Button
5131                    a11y_label: BTN_LOCALE_A11Y.to_string()
5132                    on_click: on_toggle_locale_mob
5133                    canvas {
5134                        style: canvas_style
5135                        caching: CanvasCaching::RetainedStatic
5136                        painter: paint_globe_mob
5137                    }
5138                }
5139            }
5140            row {
5141                node_ref: scheme_btn_mob
5142                bind_style: icon_btn_style_mob
5143                role: A11yRole::Button
5144                a11y_label: BTN_SCHEME_A11Y.to_string()
5145                on_click: on_toggle_scheme_mob
5146                canvas {
5147                    style: canvas_style
5148                    caching: CanvasCaching::RetainedStatic
5149                    painter: paint_scheme_mob
5150                }
5151            }
5152            row {
5153                bind_style: icon_btn_style_mob
5154                role: A11yRole::Button
5155                a11y_label: BTN_MODE_A11Y.to_string()
5156                on_click: on_toggle_mode_mob
5157                canvas {
5158                    style: canvas_style
5159                    caching: CanvasCaching::RetainedStatic
5160                    painter: paint_mode_mob
5161                }
5162            }
5163        }
5164    };
5165    let bottom_items: Vec<EuvNavItem> = state.bottom_nav_items();
5166    let home_route_path: String = state.home_route();
5167    let catalog_open: Signal<bool> = state.get_catalog_drawer_open();
5168    let bnav_route: Signal<String> =
5169        Signal::new(if active_route.get_untracked() == home_route_path {
5170            home_route_path.clone()
5171        } else {
5172            DOCS_BNAV_CATALOG_ROUTE.to_string()
5173        });
5174    let home_for_bnav: String = home_route_path.clone();
5175    let home_for_sync: String = home_route_path.clone();
5176    let home_for_brand: String = home_route_path;
5177    let vp_for_drawer: Signal<Size> = rctx.get_viewport_size();
5178    let (bnav_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
5179        let _: Effect = Effect::new(move || {
5180            let picked: String = bnav_route.get();
5181            if picked == DOCS_BNAV_CATALOG_ROUTE {
5182                let _: bool = catalog_open.set_if_changed(true);
5183            } else if picked == home_for_bnav {
5184                let _: bool = catalog_open.set_if_changed(false);
5185                if active_route.get_untracked() != home_for_bnav {
5186                    let _: bool = active_route.set_if_changed(home_for_bnav.clone());
5187                }
5188            }
5189        });
5190        let _: Effect = Effect::new(move || {
5191            let cur: String = active_route.get();
5192            let _: bool = catalog_open.set_if_changed(false);
5193            let next_tab: String = if cur == home_for_sync {
5194                home_for_sync.clone()
5195            } else {
5196                String::new()
5197            };
5198            if bnav_route.get_untracked() != next_tab {
5199                let _: bool = bnav_route.set_if_changed(next_tab);
5200            }
5201        });
5202        let _: Effect = Effect::new(move || {
5203            let open_now: bool = catalog_open.get();
5204            if !open_now && bnav_route.get_untracked() == DOCS_BNAV_CATALOG_ROUTE {
5205                let cur: String = active_route.get_untracked();
5206                let _: bool = bnav_route.set_if_changed(cur);
5207            }
5208        });
5209        Effect::new(move || {
5210            let box_size: Size = vp_for_drawer.get();
5211            if box_size.get_width() >= DESKTOP_LAYOUT_BREAKPOINT {
5212                let _: bool = catalog_open.set_if_changed(false);
5213            }
5214        })
5215    });
5216    let bottom_nav_opt: Option<NodeId> = if bottom_items.len() >= 2 {
5217        Some(view! {
5218            EuvBottomNav {
5219                items: bottom_items
5220                active_route: bnav_route
5221                tokens: tokens
5222            }
5223        })
5224    } else {
5225        None
5226    };
5227    let brand_scene: SceneHandle = rctx.get_scene().clone();
5228    let on_brand_home = move |_: &UiEvent| {
5229        let _: bool = catalog_open.set_if_changed(false);
5230        let _: bool = locale_open.set_if_changed(false);
5231        let _: bool = scheme_open.set_if_changed(false);
5232        let _: bool = active_route.set_if_changed(home_for_brand.clone());
5233        brand_scene.with_write(
5234            |tree: &mut SceneTree| {
5235                reset_active_scroll_in_subtree(tree, outlet_node);
5236            },
5237            (),
5238        );
5239    };
5240    let mut shell: EuvAppShell = EuvAppShell::new(
5241        state.get_site().get_title().clone(),
5242        sidebar_node,
5243        outlet_node,
5244        tokens,
5245    )
5246    .route(active_route)
5247    .drawer_open(catalog_open)
5248    .brand_logo(euv_brand_logo_image())
5249    .auto_hide_chrome_on_scroll(true)
5250    .on_brand_click(on_brand_home)
5251    .top_bar_actions(top_actions)
5252    .mobile_header_actions(mobile_actions)
5253    .breadcrumb(breadcrumb_sig)
5254    .swipe_routes(swipe_routes)
5255    .theme(state.get_theme().clone())
5256    .page_padding(page_pad_sig);
5257    if let Some(bnav) = bottom_nav_opt {
5258        shell = shell.bottom_nav(bnav);
5259    }
5260    state.get_outlet_root().set(outlet_node);
5261    let scroll_tick_sig: Signal<u64> = state.get_scroll_tick();
5262    let shell_node: NodeId = shell.mount();
5263    let hooked_page_scrolls: Rc<RefCell<Vec<NodeId>>> = Rc::new(RefCell::new(Vec::new()));
5264    let hook_scene: SceneHandle = rctx.get_scene().clone();
5265    let sync_state: DocsViewerState = state.clone();
5266    let sync_scene: SceneHandle = rctx.get_scene().clone();
5267    hook_outlet_page_scrolls(
5268        &hook_scene,
5269        outlet_node,
5270        &hooked_page_scrolls,
5271        scroll_tick_sig,
5272    );
5273    let (scroll_hook_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
5274        Effect::new(move || {
5275            let _: String = active_route.get();
5276            let _: bool = catalog_open.get();
5277            hook_outlet_page_scrolls(
5278                &hook_scene,
5279                outlet_node,
5280                &hooked_page_scrolls,
5281                scroll_tick_sig,
5282            );
5283            sync_state.get_pending_post_layout_sync().set(true);
5284            sync_docs_post_layout_positions(&sync_state, &sync_scene);
5285            notify_frame_needed();
5286        })
5287    });
5288    let locale_portal_opt: Option<NodeId> = if has_multi_locales {
5289        Some(mount_docs_locale_dropdown_portal(
5290            state,
5291            tokens,
5292            vec![locale_btn_desk, locale_btn_mob],
5293        ))
5294    } else {
5295        None
5296    };
5297    let scheme_portal: NodeId =
5298        mount_docs_scheme_dropdown_portal(state, tokens, vec![scheme_btn_desk, scheme_btn_mob]);
5299    rctx.get_scene().with_write(
5300        |tree: &mut SceneTree| {
5301            tree.attach_scope(shell_node, bnav_scope);
5302            tree.attach_scope(shell_node, scroll_hook_scope);
5303        },
5304        (),
5305    );
5306    let column_style: Style = style! {
5307        Width(Length::Percent(100.0))
5308        Height(Length::Percent(100.0))
5309    };
5310    let viewer_root: NodeId = view! {
5311        column {
5312            style: column_style
5313            { shell_node }
5314            { cmd_modal }
5315            if let Some(lp) = locale_portal_opt {
5316                { lp }
5317            }
5318            { scheme_portal }
5319        }
5320    };
5321    rctx.on_key(viewer_root, move |ui_event: &UiEvent| {
5322        if let UiEventKind::KeyDown(KeyCode::Character(ch), mods) = ui_event.get_kind()
5323            && (mods.get_meta() || mods.get_ctrl())
5324            && (*ch == 'k' || *ch == 'K')
5325        {
5326            let _: bool = locale_open.set_if_changed(false);
5327            let _: bool = scheme_open.set_if_changed(false);
5328            let _: bool = cmd_open.set_if_changed(true);
5329        }
5330    });
5331    viewer_root
5332}
5333
5334/// Mounts the cross-platform reactive showcase-parity documentation viewer for `site` using `euv-ui`.
5335///
5336/// # Arguments
5337///
5338/// - `&DocSite` - Parsed documentation site.
5339/// - `Signal<String>` - Active route path signal.
5340/// - `Signal<String>` - Search query input signal.
5341/// - `ThemeTokens` - Active design tokens.
5342///
5343/// # Returns
5344///
5345/// - `NodeId` - Mounted reactive documentation shell node.
5346pub fn mount_docs_viewer(
5347    site: &DocSite,
5348    active_route: Signal<String>,
5349    search_query: Signal<String>,
5350    tokens: ThemeTokens,
5351) -> NodeId {
5352    let state: DocsViewerState =
5353        DocsViewerState::new(site.clone(), active_route, search_query, tokens);
5354    mount_docs_viewer_with_state(&state)
5355}
5356
5357/// Launches the documentation viewer app and steps one headless or native frame.
5358///
5359/// # Arguments
5360///
5361/// - `&DocSite` - Loaded documentation site.
5362/// - `bool` - When `true`, renders headlessly via `HeadlessPlatform`.
5363///
5364/// # Returns
5365///
5366/// - `Result<FrameStats, PlatformError>` - Frame render telemetry.
5367pub fn render_docs_smoke(site: &DocSite, headless: bool) -> Result<FrameStats, PlatformError> {
5368    render_docs_app(site, headless, false)
5369}
5370
5371/// Launches the documentation viewer app in either single-frame or interactive event-loop mode.
5372///
5373/// # Arguments
5374///
5375/// - `&DocSite` - Loaded documentation site.
5376/// - `bool` - When `true`, renders headlessly via `HeadlessPlatform`.
5377/// - `bool` - When `true` and not headless, runs the interactive frame loop until window close.
5378///
5379/// # Returns
5380///
5381/// - `Result<FrameStats, PlatformError>` - Final rendered frame telemetry.
5382pub fn render_docs_app(
5383    site: &DocSite,
5384    headless: bool,
5385    interactive: bool,
5386) -> Result<FrameStats, PlatformError> {
5387    EuvOverlayStack::clear();
5388    reset_fullscreen_state();
5389    clear_provided_theme();
5390    let mut window_cfg: WindowConfig = WindowConfig::default();
5391    window_cfg
5392        .set_title(DOCS_WINDOW_TITLE.to_string())
5393        .set_size(DOCS_WINDOW_WIDTH, DOCS_WINDOW_HEIGHT)
5394        .set_render(RenderConfig::software())
5395        .set_icon(Some(euv_brand_logo_image()));
5396    let mut app_cfg: AppConfig = AppConfig::default();
5397    app_cfg.set_window(window_cfg);
5398    let mut app: App = if headless {
5399        App::headless(app_cfg)?
5400    } else {
5401        App::new(app_cfg)?
5402    };
5403    let initial_route: String = site
5404        .get_pages()
5405        .first()
5406        .map(|point_val: &DocPage| point_val.get_route().clone())
5407        .unwrap_or_else(|| "/".to_string());
5408    let active_route: Signal<String> = Signal::new(initial_route);
5409    let search_query: Signal<String> = Signal::new(String::new());
5410    let tokens: ThemeTokens = ThemeTokens::resolve(active_feature_scheme(), ThemeMode::Light);
5411    let state: DocsViewerState =
5412        DocsViewerState::new(site.clone(), active_route, search_query, tokens);
5413    let mount_state: DocsViewerState = state.clone();
5414    let _: NodeId = app.mount(move || mount_docs_viewer_with_state(&mount_state));
5415    let limit: Option<u64> = if interactive && !headless {
5416        None
5417    } else {
5418        Some(1)
5419    };
5420    app.run_frames(limit)
5421}
5422
5423/// Resolves a candidate path or locale-prefixed path against `site` pages, normalizing duplicate slashes and `.html` suffixes.
5424///
5425/// # Arguments
5426///
5427/// - `&DocSite` - Loaded documentation site.
5428/// - `&str` - Raw path fragment or URL pathname candidate.
5429///
5430/// # Returns
5431///
5432/// - `Option<String>` - Matching canonical page route when found.
5433fn resolve_docs_candidate_path(site: &DocSite, raw_path: &str) -> Option<String> {
5434    let without_query: &str = raw_path.split(['?', '#']).next().unwrap_or("").trim();
5435    let mut segments: Vec<&str> = without_query
5436        .split('/')
5437        .filter(|seg: &&str| !seg.is_empty())
5438        .collect();
5439    if segments
5440        .last()
5441        .is_some_and(|last: &&str| last.eq_ignore_ascii_case(DOCS_SUFFIX_INDEX_HTML))
5442    {
5443        let _: Option<&str> = segments.pop();
5444    }
5445    let normalized_segments: Vec<String> = segments
5446        .into_iter()
5447        .map(|seg: &str| {
5448            seg.strip_suffix(DOCS_SUFFIX_HTML)
5449                .unwrap_or(seg)
5450                .to_string()
5451        })
5452        .filter(|seg: &String| !seg.is_empty())
5453        .collect();
5454    let candidate: String = if normalized_segments.is_empty() {
5455        "/".to_string()
5456    } else {
5457        format!("/{}", normalized_segments.join("/"))
5458    };
5459    if let Some(found) = site.resolve_readable_route(&candidate) {
5460        return Some(found);
5461    }
5462    if let Some(first_seg) = normalized_segments.first() {
5463        let active_locale: &str = site.get_locale_prefix().trim_matches('/');
5464        let matches_builtin: bool = DOCS_KNOWN_LOCALE_SEGMENTS
5465            .iter()
5466            .any(|loc: &&str| loc.eq_ignore_ascii_case(first_seg));
5467        let matches_active: bool =
5468            !active_locale.is_empty() && active_locale.eq_ignore_ascii_case(first_seg);
5469        let matches_configured: bool = site.get_locales().iter().any(|loc: &DocLocaleConfig| {
5470            let dir_match: bool = loc.get_dir().eq_ignore_ascii_case(first_seg);
5471            let pref_match: bool = loc
5472                .get_prefix()
5473                .trim_matches('/')
5474                .eq_ignore_ascii_case(first_seg);
5475            dir_match || pref_match
5476        });
5477        let is_known_locale: bool = [matches_builtin, matches_active, matches_configured]
5478            .into_iter()
5479            .any(|matched: bool| matched);
5480        if is_known_locale {
5481            let rest: &[String] = &normalized_segments[1..];
5482            let stripped: String = if rest.is_empty() {
5483                "/".to_string()
5484            } else {
5485                format!("/{}", rest.join("/"))
5486            };
5487            if let Some(found) = site.resolve_readable_route(&stripped) {
5488                return Some(found);
5489            }
5490        }
5491    }
5492    None
5493}
5494
5495/// Normalizes browser `location.hash` and `location.pathname` into a valid `DocSite` route and optional heading anchor slug.
5496///
5497/// # Arguments
5498///
5499/// - `&DocSite` - Loaded documentation site.
5500/// - `&str` - Raw `window.location.hash` value.
5501/// - `&str` - Raw `window.location.pathname` value.
5502///
5503/// # Returns
5504///
5505/// - `(String, Option<String>)` - Resolved canonical route path and optional heading anchor slug.
5506#[must_use]
5507pub fn normalize_docs_history_target(
5508    site: &DocSite,
5509    raw_hash: &str,
5510    raw_pathname: &str,
5511) -> (String, Option<String>) {
5512    let default_route: String = site
5513        .find_by_route("/")
5514        .or_else(|| site.get_pages().first())
5515        .map(|point_val: &DocPage| point_val.get_route().clone())
5516        .unwrap_or_else(|| "/".to_string());
5517    let path_fallback: String =
5518        resolve_docs_candidate_path(site, raw_pathname).unwrap_or_else(|| default_route.clone());
5519    let trimmed_hash: &str = raw_hash.trim().trim_start_matches('#').trim();
5520    if trimmed_hash.is_empty() {
5521        return (path_fallback, None);
5522    }
5523    if trimmed_hash.starts_with('/') {
5524        let (route_part, anchor_raw): (&str, Option<&str>) = match trimmed_hash.split_once('#') {
5525            Some((red_val, alpha_val)) => (red_val, Some(alpha_val)),
5526            None => (trimmed_hash, None),
5527        };
5528        let anchor: Option<String> = anchor_raw
5529            .map(str::trim)
5530            .filter(|first_val: &&str| !first_val.is_empty())
5531            .map(str::to_string);
5532        if route_part.trim_matches('/').is_empty() {
5533            return (path_fallback, anchor);
5534        }
5535        if let Some(found) = resolve_docs_candidate_path(site, route_part) {
5536            return (found, anchor);
5537        }
5538        return (default_route, None);
5539    }
5540    let (head_part, anchor_raw): (&str, Option<&str>) = match trimmed_hash.split_once('#') {
5541        Some((height_val, area_val)) => (height_val, Some(area_val)),
5542        None => (trimmed_hash, None),
5543    };
5544    let tail_anchor: Option<String> = anchor_raw
5545        .map(str::trim)
5546        .filter(|alpha_val_primary: &&str| !alpha_val_primary.is_empty())
5547        .map(str::to_string);
5548    if head_part.contains('/') {
5549        if let Some(found) = resolve_docs_candidate_path(site, head_part) {
5550            return (found, tail_anchor);
5551        }
5552        return (default_route, None);
5553    }
5554    (path_fallback, Some(head_part.to_string()))
5555}
5556
5557/// Applies an incoming browser history location (`popstate` / `hashchange`) to `app` and `state`, dismissing overlays and exiting fullscreen first.
5558///
5559/// # Arguments
5560///
5561/// - `&mut App` - Running documentation viewer application instance.
5562/// - `&DocsViewerState` - Shared reactive documentation viewer state.
5563/// - `&str` - Raw `window.location.hash` value.
5564/// - `&str` - Raw `window.location.pathname` value.
5565///
5566/// # Returns
5567///
5568/// - `String` - Normalized canonical documentation route applied to `state`.
5569pub fn apply_docs_history_navigation(
5570    app: &mut App,
5571    state: &DocsViewerState,
5572    raw_hash: &str,
5573    raw_pathname: &str,
5574) -> String {
5575    let (target_route, anchor): (String, Option<String>) =
5576        normalize_docs_history_target(state.get_site(), raw_hash, raw_pathname);
5577    let _: usize = EuvOverlayStack::dismiss_all();
5578    let _: bool = state.get_cmd_open().set_if_changed(false);
5579    if app.is_immersive_fullscreen() || is_fullscreen_active() || EuvOverlayStack::has_fullscreen()
5580    {
5581        let _: usize = sync_external_fullscreen_exit();
5582        app.set_immersive_fullscreen(false);
5583    }
5584    let _: bool = state
5585        .get_active_route()
5586        .set_if_changed(target_route.clone());
5587    let resolved_slug: String = anchor.clone().unwrap_or_else(|| {
5588        state
5589            .get_site()
5590            .find_by_route(&target_route)
5591            .and_then(|point_val: &DocPage| point_val.get_toc().first())
5592            .map(|it: &DocTocItem| it.get_slug().clone())
5593            .unwrap_or_default()
5594    });
5595    if let Ok(mut guard) = state.get_toc_click_lock().try_borrow_mut() {
5596        *guard = None;
5597    }
5598    let _: bool = state.get_active_toc_slug().set_if_changed(resolved_slug);
5599    let _: bool = state.get_pending_anchor_scroll().set_if_changed(anchor);
5600    let _: bool = state.get_pending_scroll_restore().set_if_changed(None);
5601    state.get_pending_post_layout_sync().set(true);
5602    target_route
5603}
5604
5605/// Synchronizes browser URL hash (`#<route>` or `#<route>#<anchor>`) without pushing redundant history entries or triggering reload loops.
5606///
5607/// # Arguments
5608///
5609/// - `&str` - Active canonical documentation route path.
5610/// - `Option<&str>` - Optional active TOC heading anchor slug.
5611pub(crate) fn sync_docs_browser_hash(route: &str, anchor: Option<&str>) {
5612    #[cfg(target_arch = "wasm32")]
5613    {
5614        if WEB_DOCS_SYNCING_FROM_HISTORY.with(Cell::get) {
5615            return;
5616        }
5617        let Some(win) = window() else {
5618            return;
5619        };
5620        let norm_route: String = if route.is_empty() || route == "/" {
5621            "/".to_string()
5622        } else if route.starts_with('/') {
5623            route.to_string()
5624        } else {
5625            format!("/{route}")
5626        };
5627        let clean_anchor: Option<&str> = anchor
5628            .map(|text_value: &str| text_value.trim().trim_start_matches('#').trim())
5629            .filter(|alpha_val: &&str| !alpha_val.is_empty());
5630        let target_hash: String = match clean_anchor {
5631            Some(slug) => format!("#{norm_route}#{slug}"),
5632            None => format!("#{norm_route}"),
5633        };
5634        if win.location().hash().ok().as_deref() == Some(target_hash.as_str()) {
5635            return;
5636        }
5637        let replaced: bool = win
5638            .history()
5639            .ok()
5640            .and_then(|hist: History| {
5641                hist.replace_state_with_url(&JsValue::NULL, "", Some(&target_hash))
5642                    .ok()
5643            })
5644            .is_some();
5645        if !replaced {
5646            let prev: bool =
5647                WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
5648            let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
5649            WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev));
5650        }
5651    }
5652    #[cfg(not(target_arch = "wasm32"))]
5653    let _: (&str, Option<&str>) = (route, anchor);
5654}
5655
5656/// Persists `(route, scroll_y, active_slug)` into browser `sessionStorage` (`DOCS_SCROLL_STORAGE_KEY`) so refreshing preserves reading position.
5657///
5658/// # Arguments
5659///
5660/// - `&str` - Active canonical route path.
5661/// - `f32` - Current vertical scroll offset in logical pixels.
5662/// - `&str` - Active TOC heading anchor slug.
5663pub(crate) fn persist_docs_scroll_state(route: &str, scroll_y: f32, active_slug: &str) {
5664    #[cfg(target_arch = "wasm32")]
5665    {
5666        if let Some(win) = window()
5667            && let Ok(Some(storage)) = win.session_storage()
5668        {
5669            let payload: String = format_docs_scroll_snapshot(route, scroll_y, active_slug);
5670            let _: Result<(), JsValue> = storage.set_item(DOCS_SCROLL_STORAGE_KEY, &payload);
5671        }
5672    }
5673    #[cfg(not(target_arch = "wasm32"))]
5674    let _: (&str, f32, &str) = (route, scroll_y, active_slug);
5675}
5676
5677/// Loads a previously persisted `(scroll_y, slug)` snapshot for `expected_route` from browser `sessionStorage`.
5678///
5679/// # Arguments
5680///
5681/// - `&str` - Canonical documentation route being restored.
5682///
5683/// # Returns
5684///
5685/// - `Option<(f32, Option<String>)>` - Saved scroll position and optional TOC slug when available.
5686#[cfg(target_arch = "wasm32")]
5687pub(crate) fn load_persisted_docs_scroll_state(
5688    expected_route: &str,
5689) -> Option<(f32, Option<String>)> {
5690    let win: Window = window()?;
5691    let storage: Storage = win.session_storage().ok()??;
5692    let raw: String = storage.get_item(DOCS_SCROLL_STORAGE_KEY).ok()??;
5693    parse_docs_scroll_snapshot(&raw, expected_route)
5694}
5695
5696/// Loads persisted unlocked documentation password secrets from browser `localStorage` (`"euv_docs_unlocked_v1"`).
5697///
5698/// # Returns
5699///
5700/// - `Vec<String>` - Previously unlocked password secrets, or an empty vector when unavailable.
5701pub(crate) fn load_persisted_unlocked_passwords() -> Vec<String> {
5702    #[cfg(target_arch = "wasm32")]
5703    {
5704        if let Some(win) = window()
5705            && let Ok(Some(storage)) = win.local_storage()
5706            && let Ok(Some(raw)) = storage.get_item(DOCS_UNLOCKED_STORAGE_KEY)
5707            && let Ok(parsed) = serde_json::from_str::<Vec<String>>(&raw)
5708        {
5709            return parsed;
5710        }
5711    }
5712    Vec::new()
5713}
5714
5715/// Persists unlocked documentation password secrets into browser `localStorage` (`"euv_docs_unlocked_v1"`).
5716///
5717/// # Arguments
5718///
5719/// - `&[String]` - Active list of unlocked password secrets.
5720pub(crate) fn persist_unlocked_passwords(list: &[String]) {
5721    #[cfg(target_arch = "wasm32")]
5722    {
5723        if let Some(win) = window()
5724            && let Ok(Some(storage)) = win.local_storage()
5725            && let Ok(encoded) = serde_json::to_string(list)
5726        {
5727            let _: Result<(), JsValue> = storage.set_item(DOCS_UNLOCKED_STORAGE_KEY, &encoded);
5728        }
5729    }
5730    #[cfg(not(target_arch = "wasm32"))]
5731    let _: usize = list.len();
5732}
5733
5734/// Synchronizes the running WebAssembly documentation viewer from browser `popstate` or `hashchange` and immediately repaints.
5735///
5736/// # Arguments
5737///
5738/// - `&Window` - Active browser `Window`.
5739#[cfg(target_arch = "wasm32")]
5740fn web_docs_sync_from_browser_history(win: &Window) {
5741    let raw_hash: String = win.location().hash().unwrap_or_default();
5742    let raw_pathname: String = win.location().pathname().unwrap_or_default();
5743    let prev_guard: bool =
5744        WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
5745    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5746        if let Ok(mut borrow) = slot.try_borrow_mut()
5747            && let Some((app, state)) = borrow.as_mut()
5748        {
5749            let _: String = apply_docs_history_navigation(app, state, &raw_hash, &raw_pathname);
5750            let _: Result<FrameStats, PlatformError> = app.step_frame();
5751            state.get_pending_post_layout_sync().set(false);
5752            state.sync_post_layout_positions(app.get_scene());
5753            let _: Result<FrameStats, PlatformError> = app.step_frame();
5754        }
5755    });
5756    WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
5757}
5758
5759/// Extracts plain UTF-8 clipboard text from a browser `paste` DOM event.
5760///
5761/// # Arguments
5762///
5763/// - `&web_sys::Event` - Browser DOM `paste` event.
5764///
5765/// # Returns
5766///
5767/// - `Option<String>` - Non-empty pasted text when available.
5768#[cfg(target_arch = "wasm32")]
5769fn web_docs_extract_paste_text(ui_event: &web_sys::Event) -> Option<String> {
5770    let data: JsValue = Reflect::get(
5771        ui_event.as_ref(),
5772        &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA),
5773    )
5774    .ok()?;
5775    if data.is_null() || data.is_undefined() {
5776        return None;
5777    }
5778    let get_fn_val: JsValue = Reflect::get(&data, &JsValue::from_str(WEB_PROP_GET_DATA)).ok()?;
5779    let get_fn: Function = get_fn_val.dyn_into::<Function>().ok()?;
5780    let result: JsValue = get_fn
5781        .call1(&data, &JsValue::from_str(WEB_MIME_TEXT_PLAIN))
5782        .ok()?;
5783    result
5784        .as_string()
5785        .filter(|text_value: &String| !text_value.is_empty())
5786}
5787
5788/// Returns `true` when the browser document currently has a standard or WebKit fullscreen element active.
5789///
5790/// # Arguments
5791///
5792/// - `&Document` - Active browser `Document`.
5793///
5794/// # Returns
5795///
5796/// - `bool` - `true` while browser fullscreen mode is active.
5797#[cfg(target_arch = "wasm32")]
5798fn web_docs_doc_is_fullscreen(doc: &Document) -> bool {
5799    if doc.fullscreen_element().is_some() {
5800        return true;
5801    }
5802    Reflect::get(
5803        doc.as_ref(),
5804        &JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
5805    )
5806    .ok()
5807    .map(|item_val: JsValue| !item_val.is_null() && !item_val.is_undefined())
5808    .unwrap_or(false)
5809}
5810
5811/// Attaches browser `popstate`, `hashchange`, `pageshow`, `blur`, `touchcancel`, `paste`, `fullscreenchange`, and color-scheme listeners once for the docs viewer.
5812///
5813/// # Arguments
5814///
5815/// - `&Window` - Active browser `Window`.
5816#[cfg(target_arch = "wasm32")]
5817fn web_docs_attach_browser_listeners(win: &Window) {
5818    let already_attached: bool =
5819        WEB_DOCS_LISTENERS_ATTACHED.with(|flag: &Cell<bool>| flag.replace(true));
5820    if already_attached {
5821        return;
5822    }
5823    let win_hist: Window = win.clone();
5824    let on_history: Closure<dyn FnMut(web_sys::Event)> =
5825        Closure::wrap(Box::new(move |_: web_sys::Event| {
5826            web_docs_sync_from_browser_history(&win_hist);
5827        }) as Box<dyn FnMut(web_sys::Event)>);
5828    drop(win.add_event_listener_with_callback(
5829        WEB_EVENT_POP_STATE,
5830        on_history.as_ref().unchecked_ref(),
5831    ));
5832    drop(win.add_event_listener_with_callback(
5833        WEB_EVENT_HASH_CHANGE,
5834        on_history.as_ref().unchecked_ref(),
5835    ));
5836    drop(win.add_event_listener_with_callback(
5837        WEB_EVENT_PAGE_SHOW,
5838        on_history.as_ref().unchecked_ref(),
5839    ));
5840    on_history.forget();
5841    let on_cancel: Closure<dyn FnMut(web_sys::Event)> =
5842        Closure::wrap(Box::new(move |_: web_sys::Event| {
5843            WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5844                if let Ok(mut borrow) = slot.try_borrow_mut()
5845                    && let Some((app, _)) = borrow.as_mut()
5846                {
5847                    let wid: WindowId = app.get_window_state().get_id();
5848                    app.dispatch_window_event(WindowEvent::PointerCancel(wid, 0));
5849                    let _: Result<FrameStats, PlatformError> = app.step_frame();
5850                }
5851            });
5852        }) as Box<dyn FnMut(web_sys::Event)>);
5853    drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_cancel.as_ref().unchecked_ref()));
5854    drop(win.add_event_listener_with_callback(
5855        WEB_EVENT_TOUCH_CANCEL,
5856        on_cancel.as_ref().unchecked_ref(),
5857    ));
5858    on_cancel.forget();
5859    let on_paste: Closure<dyn FnMut(web_sys::Event)> =
5860        Closure::wrap(Box::new(move |ui_event: web_sys::Event| {
5861            if let Some(pasted) = web_docs_extract_paste_text(&ui_event) {
5862                ui_event.prevent_default();
5863                WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5864                    if let Ok(mut borrow) = slot.try_borrow_mut()
5865                        && let Some((app, _)) = borrow.as_mut()
5866                    {
5867                        let wid: WindowId = app.get_window_state().get_id();
5868                        app.dispatch_window_event(WindowEvent::TextInput(wid, pasted));
5869                        let _: Result<FrameStats, PlatformError> = app.step_frame();
5870                    }
5871                });
5872            }
5873        }) as Box<dyn FnMut(web_sys::Event)>);
5874    drop(win.add_event_listener_with_callback(WEB_EVENT_PASTE, on_paste.as_ref().unchecked_ref()));
5875    on_paste.forget();
5876    if let Some(doc) = win.document() {
5877        let doc_fs: Document = doc.clone();
5878        let on_fs: Closure<dyn FnMut(web_sys::Event)> =
5879            Closure::wrap(Box::new(move |_: web_sys::Event| {
5880                if !web_docs_doc_is_fullscreen(&doc_fs) {
5881                    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5882                        if let Ok(mut borrow) = slot.try_borrow_mut()
5883                            && let Some((app, _)) = borrow.as_mut()
5884                            && (app.is_immersive_fullscreen()
5885                                || is_fullscreen_active()
5886                                || EuvOverlayStack::has_fullscreen())
5887                        {
5888                            let _: usize = sync_external_fullscreen_exit();
5889                            app.set_immersive_fullscreen(false);
5890                            let wid: WindowId = app.get_window_state().get_id();
5891                            let measured: SafeAreaInsets = web_query_safe_area_insets();
5892                            app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, measured));
5893                            let _: Result<FrameStats, PlatformError> = app.step_frame();
5894                        }
5895                    });
5896                }
5897            }) as Box<dyn FnMut(web_sys::Event)>);
5898        drop(doc.add_event_listener_with_callback(
5899            WEB_EVENT_FULLSCREEN_CHANGE,
5900            on_fs.as_ref().unchecked_ref(),
5901        ));
5902        drop(doc.add_event_listener_with_callback(
5903            WEB_EVENT_WEBKIT_FULLSCREEN_CHANGE,
5904            on_fs.as_ref().unchecked_ref(),
5905        ));
5906        on_fs.forget();
5907    }
5908    if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
5909        let mql_cb: MediaQueryList = mql.clone();
5910        let on_theme: Closure<dyn FnMut(web_sys::Event)> =
5911            Closure::wrap(Box::new(move |_: web_sys::Event| {
5912                let next_theme: ThemeMode = if mql_cb.matches() {
5913                    ThemeMode::Dark
5914                } else {
5915                    ThemeMode::Light
5916                };
5917                WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5918                    if let Ok(mut borrow) = slot.try_borrow_mut()
5919                        && let Some((app, _)) = borrow.as_mut()
5920                    {
5921                        let wid: WindowId = app.get_window_state().get_id();
5922                        app.dispatch_window_event(WindowEvent::ThemeChanged(wid, next_theme));
5923                        let _: Result<FrameStats, PlatformError> = app.step_frame();
5924                    }
5925                });
5926            }) as Box<dyn FnMut(web_sys::Event)>);
5927        drop(
5928            mql.add_event_listener_with_callback(
5929                WEB_EVENT_CHANGE,
5930                on_theme.as_ref().unchecked_ref(),
5931            ),
5932        );
5933        on_theme.forget();
5934    }
5935}
5936
5937/// Boots the persistent WebAssembly showcase-parity documentation viewer from a serialized `DocSite` JSON bundle.
5938///
5939/// # Arguments
5940///
5941/// - `&str` - Compact UTF-8 JSON payload produced for the active locale bundle.
5942///
5943/// # Returns
5944///
5945/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
5946#[cfg(target_arch = "wasm32")]
5947pub fn boot_wasm_docs_bundle(bundle_json: &str) -> u64 {
5948    let site: DocSite = serde_json::from_str::<DocSite>(bundle_json).unwrap_or_else(|_| {
5949        DocSite::new(
5950            DOCS_SITE_TITLE.to_string(),
5951            DOCS_SITE_TAGLINE.to_string(),
5952            Vec::new(),
5953        )
5954    });
5955    boot_wasm_docs_site(site)
5956}
5957
5958/// Boots the persistent WebAssembly showcase-parity documentation viewer from a split plaintext shell and `EUVZ`-compressed bodies.
5959///
5960/// # Arguments
5961///
5962/// - `&str` - Compact plaintext `DocSite` shell JSON carrying metadata and TOC headings.
5963/// - `&[u8]` - `EUVZ`-compressed page body payload bytes.
5964///
5965/// # Returns
5966///
5967/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
5968#[cfg(target_arch = "wasm32")]
5969pub fn boot_wasm_docs_compressed_bundle(shell_json: &str, compressed_bodies: &[u8]) -> u64 {
5970    let site: DocSite = unpack_site_bundle(shell_json, compressed_bodies).unwrap_or_else(|_| {
5971        DocSite::new(
5972            DOCS_SITE_TITLE.to_string(),
5973            DOCS_SITE_TAGLINE.to_string(),
5974            Vec::new(),
5975        )
5976    });
5977    boot_wasm_docs_site(site)
5978}
5979
5980/// Mounts the hydrated `DocSite` into the persistent WebAssembly viewer runtime and renders the initial frame.
5981///
5982/// # Arguments
5983///
5984/// - `DocSite` - Hydrated documentation site for the active locale.
5985///
5986/// # Returns
5987///
5988/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
5989#[cfg(target_arch = "wasm32")]
5990fn boot_wasm_docs_site(site: DocSite) -> u64 {
5991    console_error_panic_hook::set_once();
5992    reset_reactive_runtime();
5993    EuvOverlayStack::clear();
5994    reset_fullscreen_state();
5995    clear_provided_theme();
5996    let mut window_cfg: WindowConfig = WindowConfig::default();
5997    window_cfg
5998        .set_title(format!("{} · {EUV_DOCS_RELEASE_MARKER}", site.get_title()))
5999        .set_size(DOCS_WINDOW_WIDTH, DOCS_WINDOW_HEIGHT)
6000        .set_render(RenderConfig::software());
6001    let mut app_cfg: AppConfig = AppConfig::default();
6002    app_cfg.set_window(window_cfg);
6003    let mut app: App = match App::new(app_cfg) {
6004        Ok(alpha_val) => alpha_val,
6005        Err(_) => return 0,
6006    };
6007    let (initial_route, initial_anchor): (String, Option<String>) = if let Some(win) = window() {
6008        let raw_hash: String = win.location().hash().unwrap_or_default();
6009        let raw_pathname: String = win.location().pathname().unwrap_or_default();
6010        normalize_docs_history_target(&site, &raw_hash, &raw_pathname)
6011    } else {
6012        let fallback: String = site
6013            .get_pages()
6014            .first()
6015            .map(|point_val: &DocPage| point_val.get_route().clone())
6016            .unwrap_or_else(|| "/".to_string());
6017        (fallback, None)
6018    };
6019    let active_route: Signal<String> = Signal::new(initial_route.clone());
6020    let search_query: Signal<String> = Signal::new(String::new());
6021    let tokens: ThemeTokens = ThemeTokens::resolve(active_feature_scheme(), ThemeMode::Light);
6022    let state: DocsViewerState = DocsViewerState::new(site, active_route, search_query, tokens);
6023    if let Some(anchor) = initial_anchor {
6024        let _: bool = state.get_active_toc_slug().set_if_changed(anchor.clone());
6025        let _: bool = state
6026            .get_pending_anchor_scroll()
6027            .set_if_changed(Some(anchor));
6028    } else if let Some((saved_y, saved_slug)) =
6029        load_persisted_docs_scroll_state(initial_route.as_str())
6030    {
6031        if let Some(ref slug) = saved_slug {
6032            let _: bool = state.get_active_toc_slug().set_if_changed(slug.clone());
6033        }
6034        let _: bool = state
6035            .get_pending_scroll_restore()
6036            .set_if_changed(Some((saved_y, saved_slug)));
6037    }
6038    let has_home: bool = state
6039        .get_site()
6040        .get_pages()
6041        .iter()
6042        .any(|palette_val: &DocPage| palette_val.get_is_home());
6043    let mount_state: DocsViewerState = state.clone();
6044    let _: NodeId = app.mount(move || mount_docs_viewer_with_state(&mount_state));
6045    let route_watch: Signal<String> = state.get_active_route();
6046    let site_watch: Rc<DocSite> = state.get_site().clone();
6047    let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
6048        Effect::new(move || {
6049            let text_value: String = route_watch.get();
6050            if WEB_DOCS_SYNCING_FROM_HISTORY.with(Cell::get) {
6051                return;
6052            }
6053            if let Some(win) = window() {
6054                let raw_hash: String = win.location().hash().unwrap_or_default();
6055                let raw_pathname: String = win.location().pathname().unwrap_or_default();
6056                let (cur_route, _): (String, Option<String>) =
6057                    normalize_docs_history_target(&site_watch, &raw_hash, &raw_pathname);
6058                if cur_route != text_value {
6059                    let target_hash: String = format!("#{text_value}");
6060                    let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
6061                }
6062            }
6063        })
6064    });
6065    let root_id: NodeId = app
6066        .get_scene()
6067        .with_read(SceneTree::get_root, NodeId::default());
6068    app.get_scene().with_write(
6069        |tree: &mut SceneTree| {
6070            tree.attach_scope(root_id, hash_scope);
6071        },
6072        (),
6073    );
6074    let first_hash: u64 = app
6075        .step_frame()
6076        .map(|stats: FrameStats| stats.get_frame_hash())
6077        .unwrap_or(0);
6078    state.get_pending_post_layout_sync().set(false);
6079    state.sync_post_layout_positions(app.get_scene());
6080    let hash: u64 = app
6081        .step_frame()
6082        .map(|stats: FrameStats| stats.get_frame_hash())
6083        .unwrap_or(first_hash);
6084    let fetch_state: DocsViewerState = state.clone();
6085    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6086        if let Ok(mut borrow) = slot.try_borrow_mut() {
6087            *borrow = Some((app, state));
6088        }
6089    });
6090    if let Some(win) = window() {
6091        web_docs_attach_browser_listeners(&win);
6092    }
6093    if has_home {
6094        trigger_wasm_catalog_fetch(&fetch_state);
6095    }
6096    hash
6097}
6098
6099/// Switches the active route in the running WebAssembly documentation viewer and renders immediately.
6100///
6101/// # Arguments
6102///
6103/// - `&str` - Canonical route path.
6104///
6105/// # Returns
6106///
6107/// - `u64` - Rendered frame hash.
6108#[cfg(target_arch = "wasm32")]
6109pub fn wasm_docs_render_route(route: &str) -> u64 {
6110    let prev_guard: bool =
6111        WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
6112    let raw_pathname: String = window()
6113        .and_then(|win: Window| win.location().pathname().ok())
6114        .unwrap_or_default();
6115    let frame_hash: u64 =
6116        WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6117            let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut()
6118            {
6119                Ok(guard) => guard,
6120                Err(_) => return 0,
6121            };
6122            let Some((app, state)) = borrow.as_mut() else {
6123                return 0;
6124            };
6125            let _: String = apply_docs_history_navigation(app, state, route, &raw_pathname);
6126            let _: Result<FrameStats, PlatformError> = app.step_frame();
6127            state.get_pending_post_layout_sync().set(false);
6128            state.sync_post_layout_positions(app.get_scene());
6129            app.step_frame()
6130                .map(|stats: FrameStats| stats.get_frame_hash())
6131                .unwrap_or(0)
6132        });
6133    WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
6134    frame_hash
6135}
6136
6137/// Dispatches a browser pointer move event into the running WebAssembly documentation viewer.
6138///
6139/// # Arguments
6140///
6141/// - `f32` - Logical X coordinate inside the canvas.
6142/// - `f32` - Logical Y coordinate inside the canvas.
6143///
6144/// # Returns
6145///
6146/// - `u64` - Rendered frame hash.
6147#[cfg(target_arch = "wasm32")]
6148pub fn wasm_docs_pointer_move(pos_x: f32, pos_y: f32) -> u64 {
6149    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6150        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6151            Ok(guard) => guard,
6152            Err(_) => return 0,
6153        };
6154        let Some((app, _)) = borrow.as_mut() else {
6155            return 0;
6156        };
6157        let wid: WindowId = app.get_window_state().get_id();
6158        app.dispatch_window_event(WindowEvent::PointerMove(
6159            wid,
6160            PointerEvent::mouse(pos_x, pos_y),
6161        ));
6162        app.step_frame()
6163            .map(|stats: FrameStats| stats.get_frame_hash())
6164            .unwrap_or(0)
6165    })
6166}
6167
6168/// Dispatches a browser pointer press event into the running WebAssembly documentation viewer.
6169///
6170/// # Arguments
6171///
6172/// - `f32` - Logical X coordinate inside the canvas.
6173/// - `f32` - Logical Y coordinate inside the canvas.
6174///
6175/// # Returns
6176///
6177/// - `u64` - Rendered frame hash.
6178#[cfg(target_arch = "wasm32")]
6179pub fn wasm_docs_pointer_down(pos_x: f32, pos_y: f32) -> u64 {
6180    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6181        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6182            Ok(guard) => guard,
6183            Err(_) => return 0,
6184        };
6185        let Some((app, _)) = borrow.as_mut() else {
6186            return 0;
6187        };
6188        let wid: WindowId = app.get_window_state().get_id();
6189        app.dispatch_window_event(WindowEvent::PointerDown(
6190            wid,
6191            PointerEvent::mouse(pos_x, pos_y),
6192        ));
6193        app.step_frame()
6194            .map(|stats: FrameStats| stats.get_frame_hash())
6195            .unwrap_or(0)
6196    })
6197}
6198
6199/// Dispatches a browser pointer release event into the running WebAssembly documentation viewer.
6200///
6201/// # Arguments
6202///
6203/// - `f32` - Logical X coordinate inside the canvas.
6204/// - `f32` - Logical Y coordinate inside the canvas.
6205///
6206/// # Returns
6207///
6208/// - `u64` - Rendered frame hash.
6209#[cfg(target_arch = "wasm32")]
6210pub fn wasm_docs_pointer_up(pos_x: f32, pos_y: f32) -> u64 {
6211    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6212        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6213            Ok(guard) => guard,
6214            Err(_) => return 0,
6215        };
6216        let Some((app, _)) = borrow.as_mut() else {
6217            return 0;
6218        };
6219        let wid: WindowId = app.get_window_state().get_id();
6220        app.dispatch_window_event(WindowEvent::PointerUp(
6221            wid,
6222            PointerEvent::mouse(pos_x, pos_y),
6223        ));
6224        app.step_frame()
6225            .map(|stats: FrameStats| stats.get_frame_hash())
6226            .unwrap_or(0)
6227    })
6228}
6229
6230/// 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.
6231///
6232/// # Arguments
6233///
6234/// - `u8` - Event kind (`0` move, `1` down, `2` up, `3` cancel).
6235/// - `u32` - Browser DOM `PointerEvent.pointerId`.
6236/// - `bool` - Whether the source pointer is a touch contact (`PointerDevice::Touch`).
6237/// - `f32` - Logical X coordinate inside the canvas.
6238/// - `f32` - Logical Y coordinate inside the canvas.
6239/// - `f32` - Normalized contact pressure (`0.0..=1.0`).
6240///
6241/// # Returns
6242///
6243/// - `u64` - Rendered frame hash.
6244#[cfg(target_arch = "wasm32")]
6245pub fn wasm_docs_pointer_event(
6246    kind: u8,
6247    pointer_id: u32,
6248    is_touch: bool,
6249    pos_x: f32,
6250    pos_y: f32,
6251    pressure: f32,
6252) -> u64 {
6253    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6254        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6255            Ok(guard) => guard,
6256            Err(_) => return 0,
6257        };
6258        let Some((app, _)) = borrow.as_mut() else {
6259            return 0;
6260        };
6261        let wid: WindowId = app.get_window_state().get_id();
6262        let pid: u64 = u64::from(pointer_id);
6263        let device: PointerDevice = if is_touch {
6264            PointerDevice::Touch
6265        } else {
6266            PointerDevice::Mouse
6267        };
6268        let ptr: PointerEvent = PointerEvent::new(
6269            pid,
6270            device,
6271            Point::new(pos_x, pos_y),
6272            PointerButton::Primary,
6273            pressure.clamp(0.0, 1.0),
6274            Modifiers::default(),
6275        );
6276        match kind {
6277            1 => app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr)),
6278            2 => app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr)),
6279            3 => app.dispatch_window_event(WindowEvent::PointerCancel(wid, pid)),
6280            _ => app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr)),
6281        }
6282        app.step_frame()
6283            .map(|stats: FrameStats| stats.get_frame_hash())
6284            .unwrap_or(0)
6285    })
6286}
6287
6288/// Dispatches a browser wheel scroll delta into the running WebAssembly documentation viewer.
6289///
6290/// # Arguments
6291///
6292/// - `f32` - Horizontal scroll delta.
6293/// - `f32` - Vertical scroll delta.
6294///
6295/// # Returns
6296///
6297/// - `u64` - Rendered frame hash.
6298#[cfg(target_arch = "wasm32")]
6299pub fn wasm_docs_scroll(dx: f32, dy: f32) -> u64 {
6300    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6301        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6302            Ok(guard) => guard,
6303            Err(_) => return 0,
6304        };
6305        let Some((app, _)) = borrow.as_mut() else {
6306            return 0;
6307        };
6308        let wid: WindowId = app.get_window_state().get_id();
6309        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
6310        app.step_frame()
6311            .map(|stats: FrameStats| stats.get_frame_hash())
6312            .unwrap_or(0)
6313    })
6314}
6315
6316/// Dispatches a browser wheel scroll delta anchored at logical pointer `(x, y)` so scrolling over any container works immediately.
6317///
6318/// # Arguments
6319///
6320/// - `f32` - Logical pointer X coordinate inside the canvas.
6321/// - `f32` - Logical pointer Y coordinate inside the canvas.
6322/// - `f32` - Horizontal scroll delta in CSS pixels.
6323/// - `f32` - Vertical scroll delta in CSS pixels.
6324///
6325/// # Returns
6326///
6327/// - `u64` - Rendered frame hash.
6328#[cfg(target_arch = "wasm32")]
6329pub fn wasm_docs_scroll_at(pos_x: f32, pos_y: f32, dx: f32, dy: f32) -> u64 {
6330    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6331        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6332            Ok(guard) => guard,
6333            Err(_) => return 0,
6334        };
6335        let Some((app, _)) = borrow.as_mut() else {
6336            return 0;
6337        };
6338        let wid: WindowId = app.get_window_state().get_id();
6339        app.dispatch_window_event(WindowEvent::PointerMove(
6340            wid,
6341            PointerEvent::mouse(pos_x, pos_y),
6342        ));
6343        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
6344        app.step_frame()
6345            .map(|stats: FrameStats| stats.get_frame_hash())
6346            .unwrap_or(0)
6347    })
6348}
6349
6350/// Re-queries real browser CSS `env(safe-area-inset-*)` values and dispatches `WindowEvent::SafeAreaChanged` only when insets actually change.
6351///
6352/// # Returns
6353///
6354/// - `u64` - Rendered frame hash.
6355#[cfg(target_arch = "wasm32")]
6356pub fn wasm_docs_sync_safe_area() -> u64 {
6357    let measured: SafeAreaInsets = web_query_safe_area_insets();
6358    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6359        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6360            Ok(guard) => guard,
6361            Err(_) => return 0,
6362        };
6363        let Some((app, _)) = borrow.as_mut() else {
6364            return 0;
6365        };
6366        let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
6367            SafeAreaInsets::default()
6368        } else {
6369            measured
6370        };
6371        let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
6372        if current == effective {
6373            return app.get_renderer().get_last_stats().get_frame_hash();
6374        }
6375        let wid: WindowId = app.get_window_state().get_id();
6376        app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
6377        app.step_frame()
6378            .map(|stats: FrameStats| stats.get_frame_hash())
6379            .unwrap_or(0)
6380    })
6381}
6382
6383/// Dispatches a browser keyboard event with full modifier flags into the running WebAssembly documentation viewer.
6384///
6385/// # Arguments
6386///
6387/// - `&str` - DOM `KeyboardEvent.key` string.
6388/// - `bool` - Whether Control is pressed.
6389/// - `bool` - Whether Shift is pressed.
6390/// - `bool` - Whether Alt / Option is pressed.
6391/// - `bool` - Whether Meta / Command is pressed.
6392///
6393/// # Returns
6394///
6395/// - `u64` - Rendered frame hash.
6396#[cfg(target_arch = "wasm32")]
6397pub fn wasm_docs_key_down_mods(key: &str, ctrl: bool, shift: bool, alt: bool, meta: bool) -> u64 {
6398    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6399        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6400            Ok(guard) => guard,
6401            Err(_) => return 0,
6402        };
6403        let Some((app, _)) = borrow.as_mut() else {
6404            return 0;
6405        };
6406        let wid: WindowId = app.get_window_state().get_id();
6407        let code: KeyCode = match key {
6408            WEB_KEY_ENTER => KeyCode::Enter,
6409            WEB_KEY_BACKSPACE => KeyCode::Backspace,
6410            WEB_KEY_DELETE => KeyCode::Delete,
6411            WEB_KEY_ESCAPE => KeyCode::Escape,
6412            WEB_KEY_TAB => KeyCode::Tab,
6413            WEB_KEY_SPACE => KeyCode::Space,
6414            WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
6415            WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
6416            WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
6417            WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
6418            WEB_KEY_PAGE_UP => KeyCode::PageUp,
6419            WEB_KEY_PAGE_DOWN => KeyCode::PageDown,
6420            WEB_KEY_HOME => KeyCode::Home,
6421            WEB_KEY_END => KeyCode::End,
6422            other => other
6423                .chars()
6424                .next()
6425                .map(KeyCode::Character)
6426                .unwrap_or(KeyCode::Unknown),
6427        };
6428        let mods: Modifiers = Modifiers::new(shift, ctrl, alt, meta);
6429        app.dispatch_window_event(WindowEvent::KeyDown(wid, KeyEvent::new(code, mods, false)));
6430        if !ctrl && !alt && !meta && key.chars().count() == 1 {
6431            app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
6432        }
6433        app.step_frame()
6434            .map(|stats: FrameStats| stats.get_frame_hash())
6435            .unwrap_or(0)
6436    })
6437}
6438
6439/// Copies and returns the currently selected text from the running WebAssembly documentation viewer (`""` when nothing is selected).
6440///
6441/// # Returns
6442///
6443/// - `String` - Selected UTF-8 text copied to the clipboard, or empty string.
6444#[cfg(target_arch = "wasm32")]
6445pub fn wasm_docs_copy_selected() -> String {
6446    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6447        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6448            Ok(guard) => guard,
6449            Err(_) => return String::new(),
6450        };
6451        let Some((app, _)) = borrow.as_mut() else {
6452            return String::new();
6453        };
6454        app.copy_selection()
6455            .or_else(|| app.get_scene().get_selected_text())
6456            .unwrap_or_default()
6457    })
6458}
6459
6460/// Dispatches UTF-8 text input (including composed IME/CJK text) into the running WebAssembly documentation viewer and renders immediately.
6461///
6462/// # Arguments
6463///
6464/// - `&str` - Composed or typed UTF-8 text string.
6465///
6466/// # Returns
6467///
6468/// - `u64` - Rendered frame hash.
6469#[cfg(target_arch = "wasm32")]
6470pub fn wasm_docs_text_input(text: &str) -> u64 {
6471    if text.is_empty() {
6472        return 0;
6473    }
6474    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6475        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6476            Ok(guard) => guard,
6477            Err(_) => return 0,
6478        };
6479        let Some((app, _)) = borrow.as_mut() else {
6480            return 0;
6481        };
6482        let wid: WindowId = app.get_window_state().get_id();
6483        app.dispatch_window_event(WindowEvent::TextInput(wid, text.to_string()));
6484        app.step_frame()
6485            .map(|stats: FrameStats| stats.get_frame_hash())
6486            .unwrap_or(0)
6487    })
6488}
6489
6490/// Returns `true` when the running WebAssembly documentation viewer currently has a focused `NodeKind::Input` text field.
6491///
6492/// # Returns
6493///
6494/// - `bool` - Whether an interactive text input (for example Search modal or Password gate) currently holds focus.
6495#[cfg(target_arch = "wasm32")]
6496#[must_use]
6497pub fn wasm_docs_has_focused_input() -> bool {
6498    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6499        let borrow: Ref<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow() {
6500            Ok(guard) => guard,
6501            Err(_) => return false,
6502        };
6503        let Some((app, _)) = borrow.as_ref() else {
6504            return false;
6505        };
6506        app.get_scene().with_read(
6507            |tree: &SceneTree| {
6508                tree.get_focus()
6509                    .focused_node()
6510                    .and_then(|id: NodeId| tree.get_node(id))
6511                    .is_some_and(|scene_node: &SceneNode| {
6512                        matches!(scene_node.get_kind(), NodeKind::Input(_))
6513                    })
6514            },
6515            false,
6516        )
6517    })
6518}
6519
6520/// Dispatches a browser keyboard event into the running WebAssembly documentation viewer.
6521///
6522/// # Arguments
6523///
6524/// - `&str` - DOM `KeyboardEvent.key` string.
6525///
6526/// # Returns
6527///
6528/// - `u64` - Rendered frame hash.
6529#[cfg(target_arch = "wasm32")]
6530pub fn wasm_docs_key_down(key: &str) -> u64 {
6531    wasm_docs_key_down_mods(key, false, false, false, false)
6532}
6533
6534/// Advances animations or repaints the running WebAssembly documentation viewer whenever animations or async image/data loads dirty the scene.
6535///
6536/// # Arguments
6537///
6538/// - `f32` - Elapsed seconds since the previous animation frame.
6539///
6540/// # Returns
6541///
6542/// - `u64` - Rendered frame hash.
6543#[cfg(target_arch = "wasm32")]
6544pub fn wasm_docs_tick(dt_secs: f32) -> u64 {
6545    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6546        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6547            Ok(guard) => guard,
6548            Err(_) => return 0,
6549        };
6550        let Some((app, state)) = borrow.as_mut() else {
6551            return 0;
6552        };
6553        let needs_post_sync: bool = state.get_pending_post_layout_sync().replace(false);
6554        if needs_post_sync {
6555            let _: Result<FrameStats, PlatformError> = app.step_game_frame(dt_secs.max(0.0));
6556            state.sync_post_layout_positions(app.get_scene());
6557            return app
6558                .step_game_frame(0.0)
6559                .map(|stats: FrameStats| stats.get_frame_hash())
6560                .unwrap_or(0);
6561        }
6562        if dt_secs <= 0.0 || app.has_active_animations() || take_frame_needed() {
6563            return app
6564                .step_game_frame(dt_secs.max(0.0))
6565                .map(|stats: FrameStats| stats.get_frame_hash())
6566                .unwrap_or(0);
6567        }
6568        app.get_renderer().get_last_stats().get_frame_hash()
6569    })
6570}
6571
6572/// Resizes the WebAssembly documentation viewer canvas and logical viewport immediately from CSS pixels and `dpr`, delegating to exact physical pixel synchronization.
6573///
6574/// # Arguments
6575///
6576/// - `u32` - Logical viewport width in CSS pixels.
6577/// - `u32` - Logical viewport height in CSS pixels.
6578/// - `f32` - Active browser `window.devicePixelRatio`.
6579///
6580/// # Returns
6581///
6582/// - `u64` - Rendered frame hash.
6583#[cfg(target_arch = "wasm32")]
6584pub fn wasm_docs_resize(width: u32, height: u32, dpr: f32) -> u64 {
6585    let width_val: u32 = width.max(64);
6586    let height_val: u32 = height.max(64);
6587    let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
6588        dpr.clamp(0.5, 6.0)
6589    } else {
6590        1.0
6591    };
6592    let phys_w: u32 = ((width_val as f64) * (scale as f64))
6593        .round()
6594        .clamp(64.0, 8192.0) as u32;
6595    let phys_h: u32 = ((height_val as f64) * (scale as f64))
6596        .round()
6597        .clamp(64.0, 8192.0) as u32;
6598    wasm_docs_resize_physical(phys_w, phys_h, scale)
6599}
6600
6601/// Resizes the active WebAssembly documentation canvas and `App` to exact compositor physical pixels `(phys_w, phys_h)` at `dpr` and re-renders.
6602///
6603/// # Arguments
6604///
6605/// - `u32` - Exact physical surface width in device pixels.
6606/// - `u32` - Exact physical surface height in device pixels.
6607/// - `f32` - Active browser `window.devicePixelRatio`.
6608///
6609/// # Returns
6610///
6611/// - `u64` - Rendered frame hash.
6612#[cfg(target_arch = "wasm32")]
6613pub fn wasm_docs_resize_physical(phys_w: u32, phys_h: u32, dpr: f32) -> u64 {
6614    let measured_safe: SafeAreaInsets = web_query_safe_area_insets();
6615    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6616        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6617            Ok(guard) => guard,
6618            Err(_) => return 0,
6619        };
6620        let Some((app, state)) = borrow.as_mut() else {
6621            return 0;
6622        };
6623        let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
6624            dpr.clamp(0.5, 6.0)
6625        } else {
6626            1.0
6627        };
6628        let pw: u32 = phys_w.clamp(64, 8192);
6629        let ph: u32 = phys_h.clamp(64, 8192);
6630        if let Some(win) = window()
6631            && let Some(doc) = win.document()
6632            && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
6633            && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
6634        {
6635            if canvas.width() != pw {
6636                canvas.set_width(pw);
6637            }
6638            if canvas.height() != ph {
6639                canvas.set_height(ph);
6640            }
6641        }
6642        app.set_exact_physical_viewport(pw, ph, scale);
6643        app.get_scene().with_write(
6644            |tree: &mut SceneTree| {
6645                let root: NodeId = tree.get_root();
6646                let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
6647                tree.mark_dirty(root, dirty_l | DIRTY_PAINT);
6648            },
6649            (),
6650        );
6651        let effective_safe: SafeAreaInsets = if app.is_immersive_fullscreen() {
6652            SafeAreaInsets::default()
6653        } else {
6654            measured_safe
6655        };
6656        let current_safe: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
6657        if current_safe != effective_safe {
6658            let wid: WindowId = app.get_window_state().get_id();
6659            app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective_safe));
6660        }
6661        let first_hash: u64 = app
6662            .step_frame()
6663            .map(|stats: FrameStats| stats.get_frame_hash())
6664            .unwrap_or(0);
6665        state.get_pending_post_layout_sync().set(false);
6666        state.sync_post_layout_positions(app.get_scene());
6667        let final_hash: u64 = app
6668            .step_frame()
6669            .map(|stats: FrameStats| stats.get_frame_hash())
6670            .unwrap_or(first_hash);
6671        notify_frame_needed();
6672        final_hash
6673    })
6674}