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        web_docs_wake_raf();
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 has_link: bool = !click_url.is_empty();
1373        let seg_hov: Signal<bool> = Signal::new(false);
1374        let on_seg_enter = move |_: &UiEvent| {
1375            if has_link {
1376                let _: bool = seg_hov.set_if_changed(true);
1377            }
1378        };
1379        let on_seg_leave = move |_: &UiEvent| {
1380            let _: bool = seg_hov.set_if_changed(false);
1381        };
1382        let on_click_seg = move |_: &UiEvent| {
1383            if !click_url.is_empty() {
1384                if let Some(sig) = opened_url_sig {
1385                    let _: bool = sig.set_if_changed(click_url.clone());
1386                }
1387                #[cfg(target_arch = "wasm32")]
1388                open_browser_url(&click_url, true);
1389            }
1390        };
1391        let seg_row_style = move || -> Style {
1392            let tok: ThemeTokens = use_live_tokens(tokens);
1393            let lp: ThemePalette = tok.get_palette();
1394            let lg: ThemeGeometry = tok.get_geometry();
1395            let hovered: bool = has_link && seg_hov.get();
1396            let bg: Color = if hovered {
1397                lp.interaction_colors(InteractionRole::GhostSurface, false, true, false)
1398                    .get_bg()
1399            } else {
1400                COLOR_TRANSPARENT
1401            };
1402            style! {
1403                FlexDirection::Row
1404                AlignItems::Center
1405                JustifyContent::Center
1406                Padding(Edges::symmetric(SPACE_XS, SPACE_SM))
1407                Radius(lg.get_radius_sm())
1408                Background(bg)
1409                Gap(SPACE_XS)
1410                if has_link {
1411                    CursorIcon::Pointer
1412                } else {
1413                    CursorIcon::Default
1414                }
1415            }
1416        };
1417        let text_color: Color = palette.get_muted_foreground();
1418        row_children.push({
1419            let text_sixth_style: Style = style! {
1420                FontSize(12.0)
1421                FontWeight::Normal
1422                TextColor(text_color)
1423                TextAlign::Center
1424                Selectable(true)
1425            };
1426            view! {
1427                row {
1428                    bind_style: seg_row_style
1429                    role: if has_link { A11yRole::Link } else { A11yRole::Group }
1430                    a11y_label: a11y_txt
1431                    on_click: on_click_seg
1432                    on_pointer_enter: on_seg_enter
1433                    on_pointer_leave: on_seg_leave
1434                    if let Some(ic) = icon_node_opt {
1435                        { ic }
1436                    }
1437                    text {
1438                        style: text_sixth_style
1439                        { label }
1440                    }
1441                }
1442            }
1443        });
1444    }
1445    let column_group_beta_style: Style = style! {
1446        Width(Length::Percent(100.0))
1447        AlignItems::Center
1448        Gap(SPACE_SM)
1449        Padding(Edges::new(SPACE_MD, SPACE_MD, SPACE_SM, SPACE_MD))
1450    };
1451    let row_thirteenth_style: Style = style! {
1452        Width(Length::Percent(100.0))
1453        FlexWrap::Wrap
1454        JustifyContent::Center
1455        AlignItems::Center
1456        Gap(DOCS_FOOTER_SEP_GAP)
1457        Padding(Edges::symmetric(0.0, SPACE_SM))
1458    };
1459    view! {
1460        column {
1461            style: column_group_beta_style
1462            EuvDivider {
1463                tokens: tokens
1464            }
1465            row {
1466                style: row_thirteenth_style
1467                ..row_children
1468            }
1469        }
1470    }
1471}
1472
1473/// Renders a `home: true` landing page with hero banner, CTA buttons, stat KPI grid, feature cards, Markdown body, and `/api/page-artifacts` catalog.
1474///
1475/// # Arguments
1476///
1477/// - `&DocPage` - Home page carrying hero, actions, stats, features, and body Markdown.
1478/// - `&DocsViewerState` - Shared reactive viewer state.
1479/// - `ThemeTokens` - Active design tokens.
1480///
1481/// # Returns
1482///
1483/// - `NodeId` - Mounted landing page container node.
1484fn mount_doc_home_page(page: &DocPage, state: &DocsViewerState, tokens: ThemeTokens) -> NodeId {
1485    let palette: ThemePalette = tokens.get_palette();
1486    let hero_title: String = page
1487        .try_get_hero_text()
1488        .clone()
1489        .filter(|text_value: &String| !text_value.trim().is_empty())
1490        .unwrap_or_else(|| page.get_title().clone());
1491    let hero_sub: String = if !page.get_summary().trim().is_empty() {
1492        page.get_summary().clone()
1493    } else {
1494        state.get_site().get_tagline().clone()
1495    };
1496    let action_buttons: Vec<NodeId> = page
1497        .get_actions()
1498        .iter()
1499        .map(|act: &DocHomeAction| {
1500            let link_url: String = act.get_link().clone();
1501            let site_c: Rc<DocSite> = Rc::clone(state.get_site());
1502            let route_sig: Signal<String> = state.get_active_route();
1503            let toc_sig: Signal<String> = state.get_active_toc_slug();
1504            let on_act = move |_: &UiEvent| {
1505                navigate_doc_href(&link_url, &site_c, route_sig, toc_sig);
1506            };
1507            let variant: EuvButtonVariant = if act
1508                .get_kind()
1509                .eq_ignore_ascii_case(DOCS_HOME_ACTION_PRIMARY)
1510            {
1511                EuvButtonVariant::Primary
1512            } else {
1513                EuvButtonVariant::Outline
1514            };
1515            view! {
1516                EuvButton {
1517                    label: act.get_text().clone()
1518                    variant: variant
1519                    tokens: tokens
1520                    on_click: on_act
1521                }
1522            }
1523        })
1524        .collect();
1525    let stat_cards: Vec<NodeId> = page
1526        .get_stats()
1527        .iter()
1528        .map(|stat_item: &DocHomeStat| {
1529            let label_str: String = if stat_item.get_icon().is_empty() {
1530                stat_item.get_label().clone()
1531            } else {
1532                format!("{} {}", stat_item.get_icon(), stat_item.get_label())
1533            };
1534            view! {
1535                EuvStatCard {
1536                    label: label_str
1537                    value: stat_item.get_value().clone()
1538                    caption: String::new()
1539                    tokens: tokens
1540                }
1541            }
1542        })
1543        .collect();
1544    let feature_cards: Vec<NodeId> = page
1545        .get_features()
1546        .iter()
1547        .map(|feat: &DocHomeFeature| {
1548            let link_url: String = feat.get_link().trim().to_string();
1549            let has_link: bool = !link_url.is_empty();
1550            let opened_sig: Signal<String> = state.get_last_opened_url();
1551            let feat_title: String = feat.get_title().clone();
1552            let card_hov: Signal<bool> = Signal::new(false);
1553            let on_feat_enter = move |_: &UiEvent| {
1554                if has_link {
1555                    let _: bool = card_hov.set_if_changed(true);
1556                }
1557            };
1558            let on_feat_leave = move |_: &UiEvent| {
1559                let _: bool = card_hov.set_if_changed(false);
1560            };
1561            let on_open_feat = move |_: &UiEvent| {
1562                if !has_link {
1563                    return;
1564                }
1565                let _: bool = opened_sig.set_if_changed(link_url.clone());
1566                #[cfg(target_arch = "wasm32")]
1567                open_browser_url(&link_url, true);
1568            };
1569            let feat_wrap_style = move || -> Style {
1570                let tok: ThemeTokens = use_live_tokens(tokens);
1571                let lp: ThemePalette = tok.get_palette();
1572                let lg: ThemeGeometry = tok.get_geometry();
1573                let hovered: bool = has_link && card_hov.get();
1574                let wrap_bg: Color = if hovered {
1575                    lp.get_accent().with_alpha(96)
1576                } else {
1577                    COLOR_TRANSPARENT
1578                };
1579                style! {
1580                    FlexDirection::Column
1581                    Width(Length::Percent(100.0))
1582                    if has_link {
1583                        Padding(Edges::all(SPACE_XS))
1584                    } else {
1585                        Padding(Edges::all(0.0))
1586                    }
1587                    Radius(lg.get_radius_lg() + if has_link { SPACE_XS } else { 0.0 })
1588                    Background(wrap_bg)
1589                    Overflow::Hidden
1590                    if has_link {
1591                        CursorIcon::Pointer
1592                    } else {
1593                        CursorIcon::Default
1594                    }
1595                }
1596            };
1597            let text_fifth_style: Style = style! {
1598                Width(Length::Percent(100.0))
1599                FontSize(13.0)
1600                TextColor(palette.get_muted_foreground())
1601                Selectable(true)
1602            };
1603            view! {
1604                column {
1605                    bind_style: feat_wrap_style
1606                    role: if has_link { A11yRole::Link } else { A11yRole::Group }
1607                    a11y_label: feat_title.clone()
1608                    on_click: on_open_feat
1609                    on_pointer_enter: on_feat_enter
1610                    on_pointer_leave: on_feat_leave
1611                    EuvCard {
1612                        title: feat_title
1613                        tokens: tokens
1614                        text {
1615                            style: text_fifth_style
1616                            { feat.get_details().clone() }
1617                        }
1618                    }
1619                }
1620            }
1621        })
1622        .collect();
1623    let site_for_link: Rc<DocSite> = Rc::clone(state.get_site());
1624    let route_for_link: Signal<String> = state.get_active_route();
1625    let toc_for_link: Signal<String> = state.get_active_toc_slug();
1626    let asset_base: String = state.asset_base();
1627    let md_body: NodeId = if !page.get_markdown_body().trim().is_empty() {
1628        EuvMarkdown::new(page.get_markdown_body().clone(), tokens)
1629            .style(style! {
1630                TextSelectMode::SelectAndCopy
1631            })
1632            .asset_base(asset_base)
1633            .on_link(move |url: &str| {
1634                navigate_doc_href(url, &site_for_link, route_for_link, toc_for_link);
1635            })
1636            .mount()
1637    } else {
1638        let column_group_alpha_style: Style = style! {
1639            Width(Length::Percent(100.0))
1640        };
1641        view! {
1642            column {
1643                style: column_group_alpha_style
1644            }
1645        }
1646    };
1647    let catalog_node: NodeId = mount_docs_catalog(state, tokens);
1648    let (prev_opt, next_opt): (Option<EuvDocPagerLink>, Option<EuvDocPagerLink>) =
1649        state.pager_links_for_route(page.get_route());
1650    let pager_route: Signal<String> = state.get_active_route();
1651    let pager_node: NodeId = EuvDocPager::new(prev_opt, next_opt, pager_route, tokens)
1652        .prev_label(state.get_site().resolved_prev_label())
1653        .next_label(state.get_site().resolved_next_label())
1654        .mount();
1655    let footer_node: NodeId = mount_docs_footer(state.get_site(), tokens);
1656    let mut action_row: EuvActionRow = EuvActionRow::new();
1657    for button_node in action_buttons.into_iter() {
1658        action_row = action_row.child(button_node);
1659    }
1660    let action_bar: NodeId = action_row.mount();
1661    let mut stat_grid_builder: EuvStatGrid = EuvStatGrid::new();
1662    for card in stat_cards.into_iter() {
1663        stat_grid_builder = stat_grid_builder.card(card);
1664    }
1665    let stat_grid: NodeId = stat_grid_builder.mount();
1666    let hero_brand_logo: ImageBuffer = euv_brand_logo_image();
1667    let geometry: ThemeGeometry = tokens.get_geometry();
1668    let home_outer_style: Style = style! {
1669        Width(Length::Percent(100.0))
1670        AlignItems::Center
1671    };
1672    let column_eighteenth_style: Style = style! {
1673        Width(Length::Percent(100.0))
1674        MaxWidth(Length::Px(DOCS_HOME_MAX_WIDTH))
1675        Gap(SPACE_LG)
1676    };
1677    let row_eleventh_style: Style = style! {
1678        Width(Length::Percent(100.0))
1679        AlignItems::Center
1680        Gap(SPACE_MD)
1681    };
1682    let row_twelfth_style: Style = style! {
1683        Width(Length::Px(44.0))
1684        Height(Length::Px(44.0))
1685        FlexShrink(0.0)
1686        Radius(geometry.get_radius_md())
1687        Background(palette.get_background())
1688        Border::new(geometry.get_border_width(), palette.get_border())
1689        JustifyContent::Center
1690        AlignItems::Center
1691        Overflow::Hidden
1692    };
1693    let image_style: Style = style! {
1694        Width(Length::Px(40.0))
1695        Height(Length::Px(40.0))
1696    };
1697    let column_nineteenth_style: Style = style! {
1698        FlexGrow(1.0)
1699        FlexShrink(1.0)
1700        MinWidth(Length::Px(0.0))
1701        Gap(SPACE_XS)
1702    };
1703    let text_tertiary_style: Style = style! {
1704        Width(Length::Percent(100.0))
1705        FontSize(20.0)
1706        FontWeight::SemiBold
1707        TextColor(palette.get_foreground())
1708    };
1709    let text_quaternary_style: Style = style! {
1710        Width(Length::Percent(100.0))
1711        FontSize(13.5)
1712        FontWeight::Normal
1713        TextColor(palette.get_muted_foreground())
1714    };
1715    let column_twentieth_style: Style = style! {
1716        Width(Length::Percent(100.0))
1717        Gap(SPACE_SM)
1718    };
1719    let grid_style: Style = style! {
1720        GridColumns(2)
1721        Width(Length::Percent(100.0))
1722        Gap(SPACE_SM)
1723    };
1724    view! {
1725        column {
1726            style: home_outer_style
1727            column {
1728                style: column_eighteenth_style
1729                EuvCard {
1730                    title: String::new()
1731                    tokens: tokens
1732                    row {
1733                        style: row_eleventh_style
1734                        row {
1735                            style: row_twelfth_style
1736                            image {
1737                                source: hero_brand_logo
1738                                style: image_style
1739                            }
1740                        }
1741                        column {
1742                            style: column_nineteenth_style
1743                            text {
1744                                style: text_tertiary_style
1745                                { hero_title }
1746                            }
1747                            if !hero_sub.trim().is_empty() {
1748                                text {
1749                                    style: text_quaternary_style
1750                                    { hero_sub }
1751                                }
1752                            }
1753                        }
1754                    }
1755                    if !page.get_actions().is_empty() {
1756                        { action_bar }
1757                    }
1758                }
1759                if !page.get_stats().is_empty() {
1760                    { stat_grid }
1761                }
1762                if !feature_cards.is_empty() {
1763                    column {
1764                        style: column_twentieth_style
1765                        EuvHeader {
1766                            title: DOCS_HOME_FEATURES_TITLE.to_string()
1767                            subtitle: String::new()
1768                            tokens: tokens
1769                        }
1770                        grid {
1771                            style: grid_style
1772                            ..feature_cards
1773                        }
1774                    }
1775                }
1776                { md_body }
1777                { catalog_node }
1778                { pager_node }
1779                { footer_node }
1780            }
1781        }
1782    }
1783}
1784
1785/// Finds the nearest enclosing `ScrollView` ancestor of `node_id` in `tree`.
1786///
1787/// # Arguments
1788///
1789/// - `&SceneTree` - Active scene graph.
1790/// - `NodeId` - Starting descendant node.
1791///
1792/// # Returns
1793///
1794/// - `Option<NodeId>` - Enclosing scroll container handle when present.
1795fn find_enclosing_scroll_view(tree: &SceneTree, node_id: NodeId) -> Option<NodeId> {
1796    let mut cur: Option<NodeId> = tree.get_node(node_id).and_then(SceneNode::parent_id);
1797    while let Some(pid) = cur {
1798        if let Some(item_count) = tree.get_node(pid) {
1799            if matches!(item_count.get_kind(), NodeKind::ScrollView) {
1800                return Some(pid);
1801            }
1802            cur = item_count.parent_id();
1803        } else {
1804            break;
1805        }
1806    }
1807    None
1808}
1809
1810/// Resets vertical scroll offset to `0.0` on the active visible scroll view inside `root`.
1811///
1812/// # Arguments
1813///
1814/// - `&mut SceneTree` - Mutable scene graph.
1815/// - `NodeId` - Subtree root to search.
1816fn reset_active_scroll_in_subtree(tree: &mut SceneTree, root: NodeId) {
1817    let mut stack: Vec<NodeId> = vec![root];
1818    while let Some(nid) = stack.pop() {
1819        let Some(node) = tree.get_node(nid) else {
1820            continue;
1821        };
1822        if node.style_ref().get_layout().get_display() == Display::None {
1823            continue;
1824        }
1825        if matches!(node.get_kind(), NodeKind::ScrollView) {
1826            let cur: Point = node.get_layout_box().get_scroll_offset();
1827            if cur.get_y().abs() > 0.5 || cur.get_x().abs() > 0.5 {
1828                tree.set_scroll_offset(nid, Point::new(0.0, 0.0));
1829                tree.mark_dirty(nid, DIRTY_PAINT);
1830            }
1831        }
1832        for child in tree.children_vec(nid).into_iter() {
1833            stack.push(child);
1834        }
1835    }
1836}
1837
1838/// Normalizes a heading title for resilient TOC-to-scene matching (case-insensitive, stripped of inline code ticks and collapsed whitespace).
1839///
1840/// # Arguments
1841///
1842/// - `&str` - Raw heading title string.
1843///
1844/// # Returns
1845///
1846/// - `String` - Normalized lowercase heading comparison key.
1847#[must_use]
1848fn normalize_heading_match_key(raw: &str) -> String {
1849    let mut out: String = String::with_capacity(raw.len());
1850    let mut prev_space: bool = true;
1851    for ch in raw.chars() {
1852        if ch == '`' {
1853            continue;
1854        }
1855        if ch.is_whitespace() {
1856            if !prev_space {
1857                out.push(' ');
1858                prev_space = true;
1859            }
1860        } else {
1861            for low in ch.to_lowercase() {
1862                out.push(low);
1863            }
1864            prev_space = false;
1865        }
1866    }
1867    if out.ends_with(' ') {
1868        let _: Option<char> = out.pop();
1869    }
1870    out
1871}
1872
1873/// Resolves every TOC heading's exact content-space vertical coordinate `content_y = heading_rect.y - scroll_rect.y + cur_scroll_y` in document order.
1874///
1875/// # Arguments
1876///
1877/// - `&SceneTree` - Laid-out scene graph.
1878/// - `NodeId` - Mounted document Markdown body root handle.
1879/// - `NodeId` - Enclosing page `NodeKind::ScrollView` handle.
1880/// - `&[DocTocItem]` - Ordered page table-of-contents heading descriptors.
1881///
1882/// # Returns
1883///
1884/// - `Vec<(String, f32)>` - Matched `(slug, content_y)` pairs in canonical document order.
1885fn resolve_toc_heading_positions(
1886    tree: &SceneTree,
1887    body_root: NodeId,
1888    scroll_id: NodeId,
1889    toc_items: &[DocTocItem],
1890) -> Vec<(String, f32)> {
1891    if toc_items.is_empty() {
1892        return Vec::new();
1893    }
1894    let Some(scroll_rect) = tree.node_screen_bounds(scroll_id) else {
1895        return Vec::new();
1896    };
1897    if scroll_rect.get_height() < 2.0 {
1898        return Vec::new();
1899    }
1900    let cur_scroll_y: f32 = tree
1901        .get_node(scroll_id)
1902        .map(|scene_node: &SceneNode| {
1903            scene_node
1904                .get_layout_box()
1905                .get_scroll_offset()
1906                .get_y()
1907                .max(0.0)
1908        })
1909        .unwrap_or(0.0);
1910    let mut rendered_headings: Vec<(String, f32)> = Vec::new();
1911    let mut stack: Vec<NodeId> = vec![body_root];
1912    while let Some(nid) = stack.pop() {
1913        let Some(node) = tree.get_node(nid) else {
1914            continue;
1915        };
1916        if node.style_ref().get_layout().get_display() == Display::None {
1917            continue;
1918        }
1919        if let Some(a11y) = node.a11y_props_ref()
1920            && a11y.get_role() == A11yRole::Heading
1921            && let Some(bounds) = tree.node_screen_bounds(nid)
1922            && bounds.get_height() > 1.0
1923        {
1924            let content_y: f32 = (bounds.get_y() - scroll_rect.get_y() + cur_scroll_y).max(0.0);
1925            rendered_headings.push((
1926                normalize_heading_match_key(a11y.get_label().as_str()),
1927                content_y,
1928            ));
1929            continue;
1930        }
1931        if let NodeKind::Text(txt) = node.get_kind()
1932            && node.style_ref().get_text().get_font_size() >= 15.0
1933            && let Some(bounds) = tree.node_screen_bounds(nid)
1934            && bounds.get_height() > 1.0
1935        {
1936            let content_y: f32 = (bounds.get_y() - scroll_rect.get_y() + cur_scroll_y).max(0.0);
1937            rendered_headings.push((normalize_heading_match_key(txt.as_str()), content_y));
1938        }
1939        let children: Vec<NodeId> = tree.children_vec(nid);
1940        for child in children.into_iter().rev() {
1941            stack.push(child);
1942        }
1943    }
1944    let mut matched: Vec<(String, f32)> = Vec::with_capacity(toc_items.len());
1945    let mut search_from: usize = 0;
1946    for item in toc_items.iter() {
1947        let needle: String = normalize_heading_match_key(item.get_title().as_str());
1948        if needle.is_empty() {
1949            continue;
1950        }
1951        let mut found_pos: Option<(usize, f32)> = None;
1952        for (idx, (txt, cy)) in rendered_headings.iter().enumerate().skip(search_from) {
1953            if txt == &needle {
1954                found_pos = Some((idx, *cy));
1955                break;
1956            }
1957        }
1958        if found_pos.is_none() {
1959            for (idx, (txt, cy)) in rendered_headings.iter().enumerate().skip(search_from) {
1960                if txt.contains(&needle) || needle.contains(txt.as_str()) {
1961                    found_pos = Some((idx, *cy));
1962                    break;
1963                }
1964            }
1965        }
1966        if let Some((idx, cy)) = found_pos {
1967            search_from = idx + 1;
1968            matched.push((item.get_slug().clone(), cy));
1969        }
1970    }
1971    matched
1972}
1973
1974/// Scrolls the enclosing `ScrollView` to the exact `content_y` resolved for `target_slug`, returning the clamped scroll Y actually applied.
1975///
1976/// # Arguments
1977///
1978/// - `&mut SceneTree` - Mutable scene graph.
1979/// - `NodeId` - Mounted document body root.
1980/// - `NodeId` - Enclosing page `NodeKind::ScrollView` handle.
1981/// - `&[DocTocItem]` - Ordered page table-of-contents descriptors.
1982/// - `&str` - Target TOC heading anchor slug.
1983///
1984/// # Returns
1985///
1986/// - `Option<f32>` - Applied clamped `scroll_y` offset when the heading resolved in layout.
1987fn scroll_doc_to_toc_slug(
1988    tree: &mut SceneTree,
1989    body_root: NodeId,
1990    scroll_id: NodeId,
1991    toc_items: &[DocTocItem],
1992    target_slug: &str,
1993) -> Option<f32> {
1994    let scroll_bounds: Rect = tree.node_screen_bounds(scroll_id)?;
1995    if scroll_bounds.get_height() < 2.0 {
1996        return None;
1997    }
1998    let positions: Vec<(String, f32)> =
1999        resolve_toc_heading_positions(tree, body_root, scroll_id, toc_items);
2000    let content_y: f32 = positions
2001        .iter()
2002        .find(|(slug, _): &&(String, f32)| slug == target_slug)
2003        .map(|(_, cy): &(String, f32)| *cy)?;
2004    let (cur_scroll, content_h, scroll_view_h): (Point, f32, f32) = tree
2005        .get_node(scroll_id)
2006        .map(|scene_node: &SceneNode| {
2007            let layout_box: LayoutBox = scene_node.get_layout_box();
2008            let inner_h: f32 = layout_box.get_content_bounds().get_height();
2009            let resolved_h: f32 = if inner_h > 1.0 {
2010                inner_h
2011            } else {
2012                scroll_bounds.get_height()
2013            };
2014            (
2015                layout_box.get_scroll_offset(),
2016                layout_box.get_content_size().get_height(),
2017                resolved_h,
2018            )
2019        })
2020        .unwrap_or((Point::default(), 0.0, scroll_bounds.get_height()));
2021    let max_scroll: f32 = (content_h - scroll_view_h).max(0.0);
2022    let target_y: f32 = (content_y - 16.0).clamp(0.0, max_scroll);
2023    tree.set_scroll_offset(scroll_id, Point::new(cur_scroll.get_x(), target_y));
2024    tree.mark_dirty(scroll_id, DIRTY_PAINT);
2025    Some(target_y)
2026}
2027
2028/// Ensures `target_id` sits comfortably inside the visible viewport of `scroll_id`, scrolling only when outside the inset band.
2029///
2030/// # Arguments
2031///
2032/// - `&mut SceneTree` - Mutable scene graph with computed layout bounds.
2033/// - `NodeId` - Enclosing `NodeKind::ScrollView` handle.
2034/// - `NodeId` - Descendant item handle to bring into view.
2035/// - `f32` - Minimum vertical breathing margin in logical pixels.
2036///
2037/// # Returns
2038///
2039/// - `bool` - `true` when layout bounds were valid and visibility was verified or adjusted.
2040fn scroll_node_into_scroll_view(
2041    tree: &mut SceneTree,
2042    scroll_id: NodeId,
2043    target_id: NodeId,
2044    margin: f32,
2045) -> bool {
2046    if !tree.is_node_visible(scroll_id) || !tree.is_node_visible(target_id) {
2047        return false;
2048    }
2049    let Some(scroll_rect) = tree.node_screen_bounds(scroll_id) else {
2050        return false;
2051    };
2052    let Some(target_rect) = tree.node_screen_bounds(target_id) else {
2053        return false;
2054    };
2055    let item_h: f32 = target_rect.get_height();
2056    let (cur_off, content_h, inner_top_pad, view_h): (Point, f32, f32, f32) =
2057        match tree.get_node(scroll_id) {
2058            Some(scroll_node) => {
2059                let layout_box: LayoutBox = scroll_node.get_layout_box();
2060                let outer_bounds: Rect = layout_box.get_bounds();
2061                let inner_bounds: Rect = layout_box.get_content_bounds();
2062                let top_pad: f32 = (inner_bounds.get_y() - outer_bounds.get_y()).max(0.0);
2063                let resolved_h: f32 = if inner_bounds.get_height() > 1.0 {
2064                    inner_bounds.get_height()
2065                } else {
2066                    scroll_rect.get_height()
2067                };
2068                (
2069                    layout_box.get_scroll_offset(),
2070                    layout_box.get_content_size().get_height(),
2071                    top_pad,
2072                    resolved_h,
2073                )
2074            }
2075            None => return false,
2076        };
2077    if view_h < 2.0 || item_h < 1.0 {
2078        return false;
2079    }
2080    let max_scroll: f32 = (content_h - view_h).max(0.0);
2081    if max_scroll <= 0.5 {
2082        return true;
2083    }
2084    let view_top: f32 = scroll_rect.get_y() + inner_top_pad;
2085    let eff_margin: f32 = margin.min((view_h - item_h).max(0.0) * 0.4);
2086    let safe_top: f32 = view_top + eff_margin;
2087    let safe_bottom: f32 = view_top + view_h - eff_margin;
2088    let item_top: f32 = target_rect.get_y();
2089    let item_bottom: f32 = item_top + item_h;
2090    if item_top >= safe_top && item_bottom <= safe_bottom {
2091        return true;
2092    }
2093    let rel_top: f32 = cur_off.get_y() + (item_top - view_top);
2094    let centered: f32 = (rel_top - (view_h - item_h) * 0.5).clamp(0.0, max_scroll);
2095    if (centered - cur_off.get_y()).abs() > 0.5 {
2096        tree.set_scroll_offset(scroll_id, Point::new(cur_off.get_x(), centered));
2097        tree.mark_dirty(scroll_id, DIRTY_PAINT);
2098    }
2099    true
2100}
2101
2102/// Computes the currently active TOC heading slug matching the live scroll position of `body_root` inside `scroll_id`.
2103///
2104/// # Arguments
2105///
2106/// - `&SceneTree` - Laid-out scene graph.
2107/// - `NodeId` - Mounted document Markdown body root handle.
2108/// - `NodeId` - Enclosing page `NodeKind::ScrollView` handle.
2109/// - `&[DocTocItem]` - Ordered page table-of-contents heading descriptors.
2110///
2111/// # Returns
2112///
2113/// - `Option<String>` - Active heading slug closest to the reading viewport top.
2114fn compute_active_toc_slug_for_scroll(
2115    tree: &SceneTree,
2116    body_root: NodeId,
2117    scroll_id: NodeId,
2118    toc_items: &[DocTocItem],
2119) -> Option<String> {
2120    if toc_items.is_empty() {
2121        return None;
2122    }
2123    let scroll_rect: Rect = tree.node_screen_bounds(scroll_id)?;
2124    if scroll_rect.get_height() < 2.0 {
2125        return toc_items
2126            .first()
2127            .map(|it: &DocTocItem| it.get_slug().clone());
2128    }
2129    let (cur_y, content_h, scroll_view_h): (f32, f32, f32) = tree
2130        .get_node(scroll_id)
2131        .map(|scene_node: &SceneNode| {
2132            let layout_box: LayoutBox = scene_node.get_layout_box();
2133            let inner_h: f32 = layout_box.get_content_bounds().get_height();
2134            let resolved_h: f32 = if inner_h > 1.0 {
2135                inner_h
2136            } else {
2137                scroll_rect.get_height()
2138            };
2139            (
2140                layout_box.get_scroll_offset().get_y().max(0.0),
2141                layout_box.get_content_size().get_height(),
2142                resolved_h,
2143            )
2144        })
2145        .unwrap_or((0.0, 0.0, scroll_rect.get_height()));
2146    let max_scroll: f32 = (content_h - scroll_view_h).max(0.0);
2147    if max_scroll > 8.0 && cur_y >= max_scroll - 4.0 {
2148        return toc_items
2149            .last()
2150            .map(|it: &DocTocItem| it.get_slug().clone());
2151    }
2152    let positions: Vec<(String, f32)> =
2153        resolve_toc_heading_positions(tree, body_root, scroll_id, toc_items);
2154    let threshold_content_y: f32 = cur_y + 24.0;
2155    let mut active: Option<String> = None;
2156    for (slug, content_y) in positions.into_iter() {
2157        if content_y <= threshold_content_y {
2158            active = Some(slug);
2159        }
2160    }
2161    active.or_else(|| {
2162        toc_items
2163            .first()
2164            .map(|it: &DocTocItem| it.get_slug().clone())
2165    })
2166}
2167
2168/// Attaches a non-destructive scroll observer to every child `NodeKind::ScrollView` inside `outlet_host` so page scrolling pulses `scroll_tick`.
2169///
2170/// # Arguments
2171///
2172/// - `&SceneHandle` - Shared scene handle.
2173/// - `NodeId` - Mounted `EuvRouterOutlet` root container handle.
2174/// - `&Rc<RefCell<Vec<NodeId>>>` - Registry of already-hooked page scroll view handles.
2175/// - `Signal<u64>` - Monotonic scroll tick signal pulsed on every page scroll event.
2176fn hook_outlet_page_scrolls(
2177    scene: &SceneHandle,
2178    outlet_host: NodeId,
2179    hooked: &Rc<RefCell<Vec<NodeId>>>,
2180    scroll_tick: Signal<u64>,
2181) {
2182    if outlet_host == NodeId::default() {
2183        return;
2184    }
2185    scene.with_write(
2186        |tree: &mut SceneTree| {
2187            let kids: Vec<NodeId> = tree.children_vec(outlet_host);
2188            for kid in kids.into_iter() {
2189                let already: bool = hooked
2190                    .try_borrow()
2191                    .ok()
2192                    .map(|list: Ref<'_, Vec<NodeId>>| list.contains(&kid))
2193                    .unwrap_or(false);
2194                if already {
2195                    continue;
2196                }
2197                let is_scroll: bool = tree
2198                    .get_node(kid)
2199                    .map(|scene_node: &SceneNode| {
2200                        matches!(scene_node.get_kind(), NodeKind::ScrollView)
2201                    })
2202                    .unwrap_or(false);
2203                if !is_scroll {
2204                    continue;
2205                }
2206                if let Some(wn) = tree.get_node_mut(kid) {
2207                    let prev_handler: Option<UiEventHandler> = wn
2208                        .get_handlers()
2209                        .handler_for(&UiEventKind::Scroll(Point::default()));
2210                    let wrapped: UiEventHandler =
2211                        Rc::new(RefCell::new(move |ui_event: &UiEvent| {
2212                            if let Some(prev) = prev_handler.as_ref()
2213                                && let Ok(mut factor_val) = prev.try_borrow_mut()
2214                            {
2215                                factor_val(ui_event);
2216                            }
2217                            let _: bool = {
2218                                if let Some(mut updated_value) = scroll_tick.try_get_untracked() {
2219                                    {
2220                                        let item_val: &mut u64 = &mut updated_value;
2221                                        *item_val = item_val.wrapping_add(1);
2222                                    }
2223                                    scroll_tick.set(updated_value)
2224                                } else {
2225                                    false
2226                                }
2227                            };
2228                        }));
2229                    wn.get_mut_handlers().set_on_scroll(Some(wrapped));
2230                    if let Ok(mut list) = hooked.try_borrow_mut() {
2231                        list.push(kid);
2232                    }
2233                }
2234            }
2235        },
2236        (),
2237    );
2238}
2239
2240/// Aligns the left-sidebar active catalog row into viewport bounds and refreshes sticky TOC / ScrollSpy after layout completes.
2241///
2242/// # Arguments
2243///
2244/// - `&DocsViewerState` - Shared documentation viewer state.
2245/// - `&SceneHandle` - Laid-out scene graph handle.
2246pub(crate) fn sync_docs_post_layout_positions(state: &DocsViewerState, scene: &SceneHandle) {
2247    let cur_route: String = state.get_active_route().get_untracked();
2248    let target_row_opt: Option<NodeId> = state.get_catalog_row_nodes().try_borrow().ok().and_then(
2249        |map: Ref<'_, HashMap<String, NodeId>>| {
2250            if let Some(&nid) = map.get(&cur_route) {
2251                return Some(nid);
2252            }
2253            let mut prefix: &str = cur_route.as_str();
2254            while let Some((head, _)) = prefix.rsplit_once('/') {
2255                if head.is_empty() {
2256                    break;
2257                }
2258                if let Some(&nid) = map.get(head) {
2259                    return Some(nid);
2260                }
2261                prefix = head;
2262            }
2263            None
2264        },
2265    );
2266    if let Some(row_id) = target_row_opt {
2267        scene.with_write(
2268            |tree: &mut SceneTree| {
2269                if let Some(scroll_id) = find_enclosing_scroll_view(tree, row_id) {
2270                    let _: bool = scroll_node_into_scroll_view(tree, scroll_id, row_id, 24.0);
2271                }
2272            },
2273            (),
2274        );
2275    }
2276    let _: bool = {
2277        if let Some(mut updated_value) = (state.get_scroll_tick()).try_get_untracked() {
2278            {
2279                let item_val: &mut u64 = &mut updated_value;
2280                *item_val = item_val.wrapping_add(1);
2281            }
2282            (state.get_scroll_tick()).set(updated_value)
2283        } else {
2284            false
2285        }
2286    };
2287}
2288
2289/// Recursively mounts one nested tree-structured TOC branch with vertical guide hairlines, collapsible sub-branches, and active heading accent.
2290///
2291/// # Arguments
2292///
2293/// - `&DocTocTreeNode` - Tree heading node.
2294/// - `usize` - Zero-based nesting depth inside the TOC tree.
2295/// - `Signal<String>` - Active heading anchor slug signal.
2296/// - `DocTocPickCallback` - Callback invoked with `(slug, title)` when a heading entry is clicked.
2297/// - `Option<&Rc<RefCell<HashMap<String, NodeId>>>>` - Optional registry recording `(slug -> row_id)` for auto-scrolling the active TOC entry into view.
2298/// - `ThemeTokens` - Base design tokens.
2299///
2300/// # Returns
2301///
2302/// - `NodeId` - Mounted TOC tree branch node.
2303fn mount_docs_toc_tree_branch(
2304    node: &DocTocTreeNode,
2305    depth: usize,
2306    active_slug: Signal<String>,
2307    on_pick: DocTocPickCallback,
2308    row_registry: Option<&Rc<RefCell<HashMap<String, NodeId>>>>,
2309    tokens: ThemeTokens,
2310) -> NodeId {
2311    let has_children: bool = !node.get_children().is_empty();
2312    let slug_owned: String = node.get_item().get_slug().clone();
2313    let title_owned: String = node.get_item().get_title().clone();
2314    let expanded_sig: Signal<bool> = Signal::new(true);
2315    let hovered_sig: Signal<bool> = Signal::new(false);
2316    let slug_for_style: String = slug_owned.clone();
2317    let row_style = move || -> Style {
2318        let tok: ThemeTokens = use_live_tokens(tokens);
2319        let lp: ThemePalette = tok.get_palette();
2320        let lg: ThemeGeometry = tok.get_geometry();
2321        let is_active: bool = active_slug.get() == slug_for_style;
2322        let is_hov: bool = hovered_sig.get();
2323        let bg: Color = if is_active {
2324            lp.surface(SurfaceRole::Accent).get_bg()
2325        } else if is_hov {
2326            lp.get_muted()
2327        } else {
2328            COLOR_TRANSPARENT
2329        };
2330        style! {
2331            FlexDirection::Row
2332            Width(Length::Percent(100.0))
2333            MinHeight(Length::Px(28.0))
2334            AlignItems::Center
2335            Gap(SPACE_XS)
2336            Padding(Edges::symmetric(4.0, SPACE_SM))
2337            Background(bg)
2338            Radius(lg.get_radius_sm())
2339            Overflow::Hidden
2340            CursorIcon::Pointer
2341        }
2342    };
2343    let slug_for_bar: String = slug_owned.clone();
2344    let bar_style = move || -> Style {
2345        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
2346        let is_active: bool = active_slug.get() == slug_for_bar;
2347        style! {
2348            Width(Length::Px(2.0))
2349            Height(Length::Px(14.0))
2350            FlexShrink(0.0)
2351            Radius(RADIUS_PILL)
2352            Background(if is_active {
2353                lp.get_primary()
2354                } else {
2355                    COLOR_TRANSPARENT
2356            })
2357        }
2358    };
2359    let slug_for_txt: String = slug_owned.clone();
2360    let txt_style = move || -> Style {
2361        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
2362        let is_active: bool = active_slug.get() == slug_for_txt;
2363        let fg: Color = if is_active {
2364            lp.get_primary()
2365        } else if depth == 0 {
2366            lp.get_foreground()
2367        } else {
2368            lp.get_muted_foreground()
2369        };
2370        let mut computed_style: Style = style! {
2371            FlexGrow(1.0)
2372            FlexShrink(1.0)
2373            MinWidth(Length::Px(0.0))
2374            FontSize(if depth == 0 { 12.5 } else { 12.0 })
2375            if is_active {
2376                FontWeight::Medium
2377            } else {
2378                FontWeight::Normal
2379            }
2380            TextColor(fg)
2381            Overflow::Hidden
2382            TextOverflow::Ellipsis
2383        };
2384        computed_style.get_mut_text().set_line_height(1.25);
2385        computed_style
2386    };
2387    let slug_for_click: String = slug_owned.clone();
2388    let title_for_click: String = title_owned.clone();
2389    let pick_cb: DocTocPickCallback = Rc::clone(&on_pick);
2390    let on_row_click = move |_: &UiEvent| {
2391        let _: bool = active_slug.set_if_changed(slug_for_click.clone());
2392        pick_cb(&slug_for_click, &title_for_click);
2393    };
2394    let on_row_enter = move |_: &UiEvent| {
2395        let _: bool = hovered_sig.set_if_changed(true);
2396    };
2397    let on_row_leave = move |_: &UiEvent| {
2398        let _: bool = hovered_sig.set_if_changed(false);
2399    };
2400    let on_toggle_branch = move |_: &UiEvent| {
2401        let _: bool = expanded_sig.set(!expanded_sig.get_untracked());
2402    };
2403    let paint_chev = move |bounds: Rect, display_list: &mut DisplayList| {
2404        let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
2405        draw_docs_tree_chevron(
2406            bounds,
2407            display_list,
2408            lp.get_muted_foreground(),
2409            expanded_sig.get_untracked(),
2410        );
2411    };
2412    let mut row_node: NodeId = NodeId::default();
2413    let mut chev_canvas: NodeId = NodeId::default();
2414    let child_nodes: Vec<NodeId> = node
2415        .get_children()
2416        .iter()
2417        .map(|child: &DocTocTreeNode| {
2418            mount_docs_toc_tree_branch(
2419                child,
2420                depth + 1,
2421                active_slug,
2422                Rc::clone(&on_pick),
2423                row_registry,
2424                tokens,
2425            )
2426        })
2427        .collect();
2428    let child_wrap_style = move || -> Style {
2429        let is_open: bool = expanded_sig.get();
2430        style! {
2431            FlexDirection::Row
2432            if is_open {
2433                Display::Flex
2434            } else {
2435                Display::None
2436            }
2437            Width(Length::Percent(100.0))
2438            Padding(Edges::new(2.0, 0.0, 2.0, 8.0))
2439            Gap(SPACE_SM)
2440            AlignItems::Stretch
2441        }
2442    };
2443    let guide_line_style = move || -> Style {
2444        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
2445        style! {
2446            Width(Length::Px(1.0))
2447            FlexShrink(0.0)
2448            Background(lp.get_border())
2449        }
2450    };
2451    let column_sixteenth_style: Style = style! {
2452        Width(Length::Percent(100.0))
2453        Gap(1.0)
2454    };
2455    let row_tenth_style: Style = style! {
2456        Width(Length::Px(20.0))
2457        Height(Length::Px(20.0))
2458        Padding(Edges::all(SPACE_XS))
2459        Radius(tokens.get_geometry().get_radius_sm())
2460        FlexShrink(0.0)
2461        JustifyContent::Center
2462        AlignItems::Center
2463        CursorIcon::Pointer
2464        StopEventPropagation(true)
2465    };
2466    let canvas_eighth_style: Style = style! {
2467        Width(Length::Px(10.0))
2468        Height(Length::Px(10.0))
2469    };
2470    let column_seventeenth_style: Style = style! {
2471        FlexGrow(1.0)
2472        FlexShrink(1.0)
2473        MinWidth(Length::Px(0.0))
2474        Gap(1.0)
2475    };
2476    let branch: NodeId = view! {
2477        column {
2478            style: column_sixteenth_style
2479            row {
2480                node_ref: row_node
2481                bind_style: row_style
2482                role: A11yRole::Link
2483                a11y_label: title_owned.clone()
2484                on_click: on_row_click
2485                on_pointer_enter: on_row_enter
2486                on_pointer_leave: on_row_leave
2487                view {
2488                    bind_style: bar_style
2489                }
2490                text {
2491                    bind_style: txt_style
2492                    { title_owned }
2493                }
2494                if has_children {
2495                    row {
2496                        style: row_tenth_style
2497                        on_click: on_toggle_branch
2498                        canvas {
2499                            node_ref: chev_canvas
2500                            style: canvas_eighth_style
2501                            painter: paint_chev
2502                        }
2503                    }
2504                }
2505            }
2506            if has_children {
2507                row {
2508                    bind_style: child_wrap_style
2509                    view {
2510                        bind_style: guide_line_style
2511                    }
2512                    column {
2513                        style: column_seventeenth_style
2514                        ..child_nodes
2515                    }
2516                }
2517            }
2518        }
2519    };
2520    if let Some(reg) = row_registry
2521        && let Ok(mut map) = reg.try_borrow_mut()
2522    {
2523        let _: Option<NodeId> = map.insert(slug_owned, row_node);
2524    }
2525    if has_children {
2526        let ctx: Context = current_context();
2527        let scale_factor: SceneHandle = ctx.get_scene().clone();
2528        let (chev_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2529            Effect::new(move || {
2530                let _: bool = expanded_sig.get();
2531                let _: ThemeTokens = use_live_tokens(tokens);
2532                scale_factor.with_write(
2533                    |tree: &mut SceneTree| {
2534                        tree.mark_dirty(chev_canvas, DIRTY_PAINT);
2535                    },
2536                    (),
2537                );
2538            })
2539        });
2540        ctx.get_scene().with_write(
2541            |tree: &mut SceneTree| {
2542                tree.attach_scope(branch, chev_scope);
2543            },
2544            (),
2545        );
2546    }
2547    branch
2548}
2549
2550/// Mounts the tree-structured document TOC widget (`On This Page` / `本页目录`) with nested heading branches and optional collapsible header for compact viewports.
2551///
2552/// # Arguments
2553///
2554/// - `&[DocTocItem]` - Flat page heading items.
2555/// - `&str` - Localized TOC heading title.
2556/// - `Signal<String>` - Reactive active heading slug signal.
2557/// - `DocTocPickCallback` - Callback invoked with `(slug, title)` when a heading is clicked.
2558/// - `Option<&Rc<RefCell<HashMap<String, NodeId>>>>` - Optional registry recording `(slug -> row_id)` for auto-scrolling the active TOC entry into view.
2559/// - `ThemeTokens` - Base design tokens.
2560/// - `bool` - When `true`, renders with an interactive collapsed-by-default disclosure toggle for narrow screens.
2561///
2562/// # Returns
2563///
2564/// - `NodeId` - Mounted tree-structured TOC container.
2565fn mount_docs_tree_toc(
2566    items: &[DocTocItem],
2567    title: &str,
2568    active_slug: Signal<String>,
2569    on_pick: DocTocPickCallback,
2570    row_registry: Option<&Rc<RefCell<HashMap<String, NodeId>>>>,
2571    tokens: ThemeTokens,
2572    collapsible_card: bool,
2573) -> NodeId {
2574    let roots: Vec<DocTocTreeNode> = DocTocTreeNode::from_flat(items);
2575    let branches: Vec<NodeId> = roots
2576        .iter()
2577        .map(|node: &DocTocTreeNode| {
2578            mount_docs_toc_tree_branch(
2579                node,
2580                0,
2581                active_slug,
2582                Rc::clone(&on_pick),
2583                row_registry,
2584                tokens,
2585            )
2586        })
2587        .collect();
2588    let title_owned: String = title.to_string();
2589    let open_sig: Signal<bool> = Signal::new(!collapsible_card);
2590    let container_style = move || -> Style {
2591        let tok: ThemeTokens = use_live_tokens(tokens);
2592        let lp: ThemePalette = tok.get_palette();
2593        let lg: ThemeGeometry = tok.get_geometry();
2594        let card_s: SurfaceColors = lp.surface(SurfaceRole::Card);
2595        style! {
2596            FlexDirection::Column
2597            Width(Length::Percent(100.0))
2598            Padding(Edges::all(SPACE_MD))
2599            Gap(SPACE_XS)
2600            Background(card_s.get_bg())
2601            Border::new(lg.get_border_width(), card_s.get_border())
2602            Radius(lg.get_radius_md())
2603            Overflow::Hidden
2604        }
2605    };
2606    let header_txt_style = move || -> Style {
2607        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
2608        style! {
2609            FlexGrow(1.0)
2610            FlexShrink(1.0)
2611            MinWidth(Length::Px(0.0))
2612            FontSize(12.0)
2613            FontWeight::Medium
2614            TextColor(lp.get_foreground())
2615            Overflow::Hidden
2616            TextOverflow::Ellipsis
2617        }
2618    };
2619    let body_style = move || -> Style {
2620        let is_open: bool = open_sig.get();
2621        style! {
2622            FlexDirection::Column
2623            if is_open {
2624                Display::Flex
2625            } else {
2626                Display::None
2627            }
2628            Width(Length::Percent(100.0))
2629            Gap(2.0)
2630        }
2631    };
2632    let on_toggle_card = move |_: &UiEvent| {
2633        if collapsible_card {
2634            let _: bool = open_sig.set(!open_sig.get_untracked());
2635        }
2636    };
2637    let paint_hdr_chev = move |bounds: Rect, display_list: &mut DisplayList| {
2638        let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
2639        draw_docs_tree_chevron(
2640            bounds,
2641            display_list,
2642            lp.get_muted_foreground(),
2643            open_sig.get_untracked(),
2644        );
2645    };
2646    let mut hdr_chev: NodeId = NodeId::default();
2647    let row_ninth_style: Style = style! {
2648        Width(Length::Percent(100.0))
2649        if collapsible_card {
2650            Padding(Edges::symmetric(SPACE_XS, SPACE_SM))
2651        } else {
2652            Padding(Edges::all(0.0))
2653        }
2654        Radius(tokens.get_geometry().get_radius_sm())
2655        AlignItems::Center
2656        JustifyContent::SpaceBetween
2657        Gap(SPACE_XS)
2658        if collapsible_card { CursorIcon::Pointer } else { CursorIcon::Default }
2659    };
2660    let canvas_seventh_style: Style = style! {
2661        Width(Length::Px(12.0))
2662        Height(Length::Px(12.0))
2663        FlexShrink(0.0)
2664    };
2665    let toc_node: NodeId = view! {
2666        column {
2667            bind_style: container_style
2668            role: A11yRole::Navigation
2669            a11y_label: title_owned.clone()
2670            row {
2671                style: row_ninth_style
2672                on_click: on_toggle_card
2673                text {
2674                    bind_style: header_txt_style
2675                    { title_owned }
2676                }
2677                if collapsible_card {
2678                    canvas {
2679                        node_ref: hdr_chev
2680                        style: canvas_seventh_style
2681                        painter: paint_hdr_chev
2682                    }
2683                }
2684            }
2685            column {
2686                bind_style: body_style
2687                ..branches
2688            }
2689        }
2690    };
2691    if collapsible_card {
2692        let ctx: Context = current_context();
2693        let scale_factor: SceneHandle = ctx.get_scene().clone();
2694        let (hdr_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2695            Effect::new(move || {
2696                let _: bool = open_sig.get();
2697                let _: ThemeTokens = use_live_tokens(tokens);
2698                scale_factor.with_write(
2699                    |tree: &mut SceneTree| {
2700                        tree.mark_dirty(hdr_chev, DIRTY_PAINT);
2701                    },
2702                    (),
2703                );
2704            })
2705        });
2706        ctx.get_scene().with_write(
2707            |tree: &mut SceneTree| {
2708                tree.attach_scope(toc_node, hdr_scope);
2709            },
2710            (),
2711        );
2712    }
2713    toc_node
2714}
2715
2716/// Mounts a centered password unlock gate card for a password-protected documentation page or section.
2717///
2718/// # Arguments
2719///
2720/// - `&DocPage` - Protected documentation page.
2721/// - `&DocsViewerState` - Shared viewer state managing unlocked password secrets.
2722/// - `&str` - Required password string.
2723/// - `ThemeTokens` - Active design tokens.
2724///
2725/// # Returns
2726///
2727/// - `NodeId` - Mounted centered password unlock card.
2728fn mount_docs_password_gate(
2729    page: &DocPage,
2730    state: &DocsViewerState,
2731    secret: &str,
2732    tokens: ThemeTokens,
2733) -> NodeId {
2734    let is_zh: bool = state
2735        .get_site()
2736        .resolved_lang()
2737        .to_ascii_lowercase()
2738        .starts_with(DOCS_LANG_PREFIX_ZH);
2739    let title_str: String = format!(
2740        "{} · {}",
2741        if is_zh {
2742            DOCS_LOCK_TITLE_ZH
2743        } else {
2744            DOCS_LOCK_TITLE_EN
2745        },
2746        page.get_title()
2747    );
2748    let desc_str: &str = if is_zh {
2749        DOCS_LOCK_DESC_ZH
2750    } else {
2751        DOCS_LOCK_DESC_EN
2752    };
2753    let placeholder_str: &str = if is_zh {
2754        DOCS_LOCK_PLACEHOLDER_ZH
2755    } else {
2756        DOCS_LOCK_PLACEHOLDER_EN
2757    };
2758    let btn_str: &str = if is_zh {
2759        DOCS_LOCK_BTN_ZH
2760    } else {
2761        DOCS_LOCK_BTN_EN
2762    };
2763    let err_str: &str = if is_zh {
2764        DOCS_LOCK_ERR_ZH
2765    } else {
2766        DOCS_LOCK_ERR_EN
2767    };
2768    let input_sig: Signal<String> = Signal::new(String::new());
2769    let wrong_sig: Signal<bool> = Signal::new(false);
2770    let secret_owned: String = secret.to_string();
2771    let st_unlock: DocsViewerState = state.clone();
2772    let on_unlock = move |_: &UiEvent| {
2773        let attempt: String = input_sig.get_untracked();
2774        if st_unlock.try_unlock_password(&secret_owned, &attempt) {
2775            let _: bool = wrong_sig.set_if_changed(false);
2776        } else {
2777            let _: bool = wrong_sig.set_if_changed(true);
2778        }
2779    };
2780    let err_style = move || -> Style {
2781        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
2782        style! {
2783            if wrong_sig.get() {
2784                Display::Flex
2785            } else {
2786                Display::None
2787            }
2788            Width(Length::Percent(100.0))
2789            FontSize(12.0)
2790            TextColor(lp.get_destructive())
2791        }
2792    };
2793    let column_fourteenth_style: Style = style! {
2794        Width(Length::Percent(100.0))
2795        AlignItems::Center
2796        Padding(Edges::symmetric(SPACE_2XL, SPACE_MD))
2797    };
2798    let column_fifteenth_style: Style = style! {
2799        Width(Length::Percent(100.0))
2800        MaxWidth(Length::Px(420.0))
2801    };
2802    view! {
2803        column {
2804            style: column_fourteenth_style
2805            column {
2806                style: column_fifteenth_style
2807                EuvCard {
2808                    title: title_str
2809                    subtitle: desc_str
2810                    tokens: tokens
2811                    EuvInput {
2812                        value: input_sig
2813                        placeholder: placeholder_str.to_string()
2814                        tokens: tokens
2815                    }
2816                    text {
2817                        bind_style: err_style
2818                        { err_str }
2819                    }
2820                    EuvButton {
2821                        label: btn_str.to_string()
2822                        variant: EuvButtonVariant::Primary
2823                        tokens: tokens
2824                        on_click: on_unlock
2825                    }
2826                }
2827            }
2828        }
2829    }
2830}
2831
2832/// 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.
2833///
2834/// # Arguments
2835///
2836/// - `&DocPage` - Documentation page to render.
2837/// - `&DocsViewerState` - Shared reactive viewer state for route, TOC, password unlock, and pager interactivity.
2838/// - `ThemeTokens` - Active design tokens.
2839///
2840/// # Returns
2841///
2842/// - `NodeId` - Mounted article page container node.
2843pub fn mount_doc_page_with_context(
2844    page: &DocPage,
2845    state: &DocsViewerState,
2846    tokens: ThemeTokens,
2847) -> NodeId {
2848    if page.get_is_home() {
2849        return mount_doc_home_page(page, state, tokens);
2850    }
2851    if let Some(secret) = page.try_get_password().as_deref()
2852        && !secret.trim().is_empty()
2853    {
2854        let page_owned: DocPage = page.clone();
2855        let state_owned: DocsViewerState = state.clone();
2856        let secret_owned: String = secret.trim().to_string();
2857        let unlocked_sig: Signal<Vec<String>> = state.get_unlocked_passwords();
2858        let build_gated = move || -> Vec<NodeId> {
2859            let live_tok: ThemeTokens = live_tokens_untracked(tokens);
2860            let unlocked: bool = unlocked_sig
2861                .get()
2862                .iter()
2863                .any(|text_value: &String| text_value.as_str() == secret_owned.as_str());
2864            if unlocked {
2865                vec![mount_unlocked_doc_article(
2866                    &page_owned,
2867                    &state_owned,
2868                    live_tok,
2869                )]
2870            } else {
2871                vec![mount_docs_password_gate(
2872                    &page_owned,
2873                    &state_owned,
2874                    &secret_owned,
2875                    live_tok,
2876                )]
2877            }
2878        };
2879        let column_thirteenth_style: Style = style! {
2880            Width(Length::Percent(100.0))
2881        };
2882        return view! {
2883            column {
2884                style: column_thirteenth_style
2885                bind_children: build_gated
2886            }
2887        };
2888    }
2889    mount_unlocked_doc_article(page, state, tokens)
2890}
2891
2892/// Renders the unlocked documentation article layout with sticky right-hand tree TOC (`>= 1024px`) and collapsible inline tree TOC (`< 1024px`).
2893///
2894/// # Arguments
2895///
2896/// - `&DocPage` - Unlocked documentation page to render.
2897/// - `&DocsViewerState` - Shared reactive viewer state.
2898/// - `ThemeTokens` - Active design tokens.
2899///
2900/// # Returns
2901///
2902/// - `NodeId` - Mounted article layout node.
2903fn mount_unlocked_doc_article(
2904    page: &DocPage,
2905    state: &DocsViewerState,
2906    tokens: ThemeTokens,
2907) -> NodeId {
2908    let breadcrumb_segments: Vec<String> = vec![
2909        state.get_site().get_title().clone(),
2910        page.get_section().clone(),
2911        page.get_title().clone(),
2912    ];
2913    let mut meta_bar: EuvDocMetaBar = EuvDocMetaBar::new(
2914        page.get_section().clone(),
2915        page.reading_minutes(),
2916        page.word_count(),
2917        tokens,
2918    )
2919    .source_path(page.get_route().clone());
2920    if let Some(updated) = page.try_get_updated().as_deref() {
2921        meta_bar = meta_bar.updated(updated);
2922    }
2923    let meta_node: NodeId = meta_bar.mount();
2924    let show_subtitle: bool = {
2925        let sum: &str = page.get_summary().trim();
2926        !sum.is_empty() && !sum.eq_ignore_ascii_case(page.get_title().trim())
2927    };
2928    let subtitle_str: String = if show_subtitle {
2929        page.get_summary().clone()
2930    } else {
2931        String::new()
2932    };
2933    let site_for_link: Rc<DocSite> = Rc::clone(state.get_site());
2934    let route_for_link: Signal<String> = state.get_active_route();
2935    let toc_for_link: Signal<String> = state.get_active_toc_slug();
2936    let asset_base: String = state.asset_base();
2937    let body_node: NodeId = if !page.get_markdown_body().trim().is_empty() {
2938        EuvMarkdown::new(page.get_markdown_body().clone(), tokens)
2939            .style(style! {
2940                TextSelectMode::SelectAndCopy
2941            })
2942            .asset_base(asset_base.clone())
2943            .on_link(move |url: &str| {
2944                navigate_doc_href(url, &site_for_link, route_for_link, toc_for_link);
2945            })
2946            .mount()
2947    } else {
2948        mount_fallback_doc_blocks(page, &asset_base, tokens)
2949    };
2950    let (prev_opt, next_opt): (Option<EuvDocPagerLink>, Option<EuvDocPagerLink>) =
2951        state.pager_links_for_route(page.get_route());
2952    let pager_route: Signal<String> = state.get_active_route();
2953    let pager_node: NodeId = EuvDocPager::new(prev_opt, next_opt, pager_route, tokens)
2954        .prev_label(state.get_site().resolved_prev_label())
2955        .next_label(state.get_site().resolved_next_label())
2956        .mount();
2957    let footer_node: NodeId = mount_docs_footer_with_recorder(
2958        state.get_site(),
2959        tokens,
2960        Some(state.get_last_opened_url()),
2961    );
2962    let has_toc: bool = !page.get_toc().is_empty();
2963    let column_twelfth_style: Style = style! {
2964        FlexGrow(1.0)
2965        FlexShrink(1.0)
2966        MinWidth(Length::Px(0.0))
2967        Width(if has_toc { Length::Auto } else { Length::Percent(100.0) })
2968        MaxWidth(Length::Px(DOCS_ARTICLE_PROSE_MAX_WIDTH))
2969        Gap(SPACE_MD)
2970    };
2971    let doc_main_col: NodeId = view! {
2972        column {
2973            style: column_twelfth_style
2974            EuvBreadcrumb {
2975                segments: breadcrumb_segments
2976                tokens: tokens
2977            }
2978            { meta_node }
2979            EuvHeader {
2980                title: page.get_title().clone()
2981                subtitle: subtitle_str
2982                tokens: tokens
2983            }
2984            { body_node }
2985            EuvDivider {
2986                tokens: tokens
2987            }
2988            { pager_node }
2989            { footer_node }
2990        }
2991    };
2992    if !has_toc {
2993        let centered_no_toc_style: Style = style! {
2994            Width(Length::Percent(100.0))
2995            AlignItems::Center
2996        };
2997        return view! {
2998            column {
2999                style: centered_no_toc_style
3000                { doc_main_col }
3001            }
3002        };
3003    }
3004    let ctx: Context = current_context();
3005    let toc_slug_sig: Signal<String> = state.get_active_toc_slug();
3006    let scroll_tick_sig: Signal<u64> = state.get_scroll_tick();
3007    let active_route_sig: Signal<String> = state.get_active_route();
3008    let pending_anchor_sig: Signal<Option<String>> = state.get_pending_anchor_scroll();
3009    let pending_restore_sig: Signal<Option<(f32, Option<String>)>> =
3010        state.get_pending_scroll_restore();
3011    let toc_click_lock: Rc<RefCell<Option<(String, String, f32)>>> =
3012        Rc::clone(state.get_toc_click_lock());
3013    let toc_title: &str = state.get_site().resolved_toc_label();
3014    let toc_items_owned: Vec<DocTocItem> = page.get_toc().to_vec();
3015    let page_route_owned: String = page.get_route().clone();
3016    let cur_slug: String = toc_slug_sig.get_untracked();
3017    let cur_matches_page: bool = !cur_slug.is_empty()
3018        && toc_items_owned
3019            .iter()
3020            .any(|it: &DocTocItem| it.get_slug() == &cur_slug);
3021    if !cur_matches_page && let Some(first_it) = toc_items_owned.first() {
3022        let _: bool = toc_slug_sig.set_if_changed(first_it.get_slug().clone());
3023    }
3024    let toc_row_nodes: Rc<RefCell<HashMap<String, NodeId>>> = Rc::new(RefCell::new(HashMap::new()));
3025    let scene_jump: SceneHandle = ctx.get_scene().clone();
3026    let toc_items_click: Vec<DocTocItem> = toc_items_owned.clone();
3027    let route_for_click: String = page_route_owned.clone();
3028    let click_lock_pick: Rc<RefCell<Option<(String, String, f32)>>> = Rc::clone(&toc_click_lock);
3029    let on_toc_pick: DocTocPickCallback = Rc::new(move |slug: &str, _title_txt: &str| {
3030        let mut applied_y_opt: Option<f32> = None;
3031        scene_jump.with_write(
3032            |tree: &mut SceneTree| {
3033                if let Some(scroll_id) = find_enclosing_scroll_view(tree, body_node) {
3034                    applied_y_opt =
3035                        scroll_doc_to_toc_slug(tree, body_node, scroll_id, &toc_items_click, slug);
3036                }
3037            },
3038            (),
3039        );
3040        let applied_y: f32 = applied_y_opt.unwrap_or(0.0);
3041        if let Ok(mut lock_guard) = click_lock_pick.try_borrow_mut() {
3042            *lock_guard = Some((route_for_click.clone(), slug.to_string(), applied_y));
3043        }
3044        let _: bool = toc_slug_sig.set_if_changed(slug.to_string());
3045        sync_docs_browser_hash(&route_for_click, Some(slug));
3046        persist_docs_scroll_state(&route_for_click, applied_y, slug);
3047        let _: bool = {
3048            if let Some(mut updated_value) = scroll_tick_sig.try_get_untracked() {
3049                {
3050                    let item_val: &mut u64 = &mut updated_value;
3051                    *item_val = item_val.wrapping_add(1);
3052                }
3053                scroll_tick_sig.set(updated_value)
3054            } else {
3055                false
3056            }
3057        };
3058        notify_frame_needed();
3059    });
3060    let right_toc_widget: NodeId = mount_docs_tree_toc(
3061        page.get_toc(),
3062        toc_title,
3063        toc_slug_sig,
3064        Rc::clone(&on_toc_pick),
3065        Some(&toc_row_nodes),
3066        tokens,
3067        false,
3068    );
3069    let inline_toc_widget: NodeId = mount_docs_tree_toc(
3070        page.get_toc(),
3071        toc_title,
3072        toc_slug_sig,
3073        on_toc_pick,
3074        None,
3075        tokens,
3076        true,
3077    );
3078    let vp_sig: Signal<Size> = ctx.get_viewport_size();
3079    let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
3080    let init_vp: Size = vp_sig.get_untracked();
3081    let init_safe: SafeAreaInsets = safe_sig.get_untracked();
3082    let init_wide: bool = init_vp.get_width() >= DOCS_WIDE_TOC_BREAKPOINT;
3083    let init_toc_max_h: f32 = (init_vp.get_height()
3084        - SHELL_DESKTOP_HEADER_HEIGHT
3085        - init_safe.get_top().max(0.0)
3086        - init_safe.get_bottom().max(0.0)
3087        - DOCS_STICKY_TOC_TOP_GAP
3088        - SPACE_LG)
3089        .max(200.0);
3090    let mut wide_row_node: NodeId = NodeId::default();
3091    let mut inline_toc_host: NodeId = NodeId::default();
3092    let mut right_toc_host: NodeId = NodeId::default();
3093    let mut right_toc_scroll: NodeId = NodeId::default();
3094    let column_ninth_style: Style = style! {
3095        Width(Length::Percent(100.0))
3096        AlignItems::Center
3097        Gap(SPACE_MD)
3098    };
3099    let column_tenth_style: Style = style! {
3100        Width(Length::Percent(100.0))
3101        MaxWidth(Length::Px(DOCS_ARTICLE_PROSE_MAX_WIDTH))
3102        if init_wide { Display::None } else { Display::Flex }
3103    };
3104    let row_eighth_style: Style = style! {
3105        Width(Length::Percent(100.0))
3106        MaxWidth(Length::Px(DOCS_WIDE_CONTENT_MAX_WIDTH))
3107        JustifyContent::Center
3108        AlignItems::Start
3109        Gap(SPACE_2XL)
3110    };
3111    let column_eleventh_style: Style = style! {
3112        Width(Length::Px(DOCS_RIGHT_TOC_WIDTH))
3113        FlexShrink(0.0)
3114        if init_wide { Display::Flex } else { Display::None }
3115    };
3116    let scroll_secondary_style: Style = style! {
3117        FlexDirection::Column
3118        Width(Length::Percent(100.0))
3119        MaxHeight(Length::Px(init_toc_max_h))
3120        Overflow::Scroll
3121        StopScrollPropagation(true)
3122    };
3123    let layout_root: NodeId = view! {
3124        column {
3125            style: column_ninth_style
3126            column {
3127                node_ref: inline_toc_host
3128                style: column_tenth_style
3129                { inline_toc_widget }
3130            }
3131            row {
3132                node_ref: wide_row_node
3133                style: row_eighth_style
3134                { doc_main_col }
3135                column {
3136                    node_ref: right_toc_host
3137                    style: column_eleventh_style
3138                    scroll {
3139                        node_ref: right_toc_scroll
3140                        style: scroll_secondary_style
3141                        { right_toc_widget }
3142                    }
3143                }
3144            }
3145        }
3146    };
3147    let scene_toc: SceneHandle = ctx.get_scene().clone();
3148    let scene_sticky: SceneHandle = ctx.get_scene().clone();
3149    let route_for_entry: String = page_route_owned.clone();
3150    let toc_items_for_entry: Vec<DocTocItem> = toc_items_owned.clone();
3151    let row_nodes_for_spy: Rc<RefCell<HashMap<String, NodeId>>> = Rc::clone(&toc_row_nodes);
3152    let (toc_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
3153        Effect::new(move || {
3154            let box_size: Size = vp_sig.get();
3155            let safe: SafeAreaInsets = safe_sig.get();
3156            let is_wide: bool = box_size.get_width() >= DOCS_WIDE_TOC_BREAKPOINT;
3157            let max_h: f32 = (box_size.get_height()
3158                - SHELL_DESKTOP_HEADER_HEIGHT
3159                - safe.get_top().max(0.0)
3160                - safe.get_bottom().max(0.0)
3161                - DOCS_STICKY_TOC_TOP_GAP
3162                - SPACE_LG)
3163                .max(200.0);
3164            scene_toc.with_write(
3165                |tree: &mut SceneTree| {
3166                    let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
3167                    let dirty_mask: u16 = dirty_l | DIRTY_PAINT;
3168                    if let Some(item_count) = tree.get_node_mut(right_toc_host) {
3169                        item_count
3170                            .get_mut_style()
3171                            .get_mut_layout()
3172                            .set_display(if is_wide {
3173                                Display::Flex
3174                            } else {
3175                                Display::None
3176                            });
3177                        if !is_wide {
3178                            item_count
3179                                .get_mut_style()
3180                                .get_mut_paint()
3181                                .set_transform(Transform2D::default());
3182                        }
3183                        tree.mark_dirty(right_toc_host, dirty_mask);
3184                    }
3185                    if let Some(node_entry) = tree.get_node_mut(right_toc_scroll) {
3186                        node_entry
3187                            .get_mut_style()
3188                            .get_mut_layout()
3189                            .set_max_height(Length::Px(max_h));
3190                        tree.mark_dirty(right_toc_scroll, dirty_mask);
3191                    }
3192                    if let Some(normal_vec) = tree.get_node_mut(inline_toc_host) {
3193                        normal_vec
3194                            .get_mut_style()
3195                            .get_mut_layout()
3196                            .set_display(if is_wide {
3197                                Display::None
3198                            } else {
3199                                Display::Flex
3200                            });
3201                        tree.mark_dirty(inline_toc_host, dirty_mask);
3202                    }
3203                    tree.mark_dirty(wide_row_node, dirty_mask);
3204                },
3205                (),
3206            );
3207        });
3208        Effect::new(move || {
3209            let cur_r: String = active_route_sig.get();
3210            if cur_r != route_for_entry {
3211                return;
3212            }
3213            let cur_s: String = toc_slug_sig.get_untracked();
3214            let valid: bool = !cur_s.is_empty()
3215                && toc_items_for_entry
3216                    .iter()
3217                    .any(|it: &DocTocItem| it.get_slug() == &cur_s);
3218            if !valid && let Some(first_it) = toc_items_for_entry.first() {
3219                let _: bool = toc_slug_sig.set_if_changed(first_it.get_slug().clone());
3220            }
3221        });
3222        let click_lock_spy: Rc<RefCell<Option<(String, String, f32)>>> = Rc::clone(&toc_click_lock);
3223        Effect::new(move || {
3224            let _: u64 = scroll_tick_sig.get();
3225            let _: Size = vp_sig.get();
3226            let safe_now: SafeAreaInsets = safe_sig.get();
3227            let cur_r: String = active_route_sig.get();
3228            let pending_anchor: Option<String> = pending_anchor_sig.get();
3229            let pending_restore: Option<(f32, Option<String>)> = pending_restore_sig.get();
3230            if cur_r != page_route_owned {
3231                return;
3232            }
3233            let mut next_slug: Option<String> = None;
3234            let mut consumed_anchor: bool = false;
3235            let mut consumed_restore: bool = false;
3236            let mut persist_snap: Option<(f32, String)> = None;
3237            scene_sticky.with_write(
3238                |tree: &mut SceneTree| {
3239                    let Some(scroll_id) = find_enclosing_scroll_view(tree, layout_root) else {
3240                        return;
3241                    };
3242                    let Some(scroll_rect) = tree.node_screen_bounds(scroll_id) else {
3243                        return;
3244                    };
3245                    if scroll_rect.get_height() < 2.0 {
3246                        return;
3247                    }
3248                    if let Some(anchor_slug) = pending_anchor.as_deref()
3249                        && let Some(matched) = toc_items_owned
3250                            .iter()
3251                            .find(|it: &&DocTocItem| it.get_slug() == anchor_slug)
3252                    {
3253                        if let Some(applied_y) = scroll_doc_to_toc_slug(
3254                            tree,
3255                            body_node,
3256                            scroll_id,
3257                            &toc_items_owned,
3258                            matched.get_slug().as_str(),
3259                        ) {
3260                            let matched_slug: String = matched.get_slug().clone();
3261                            if let Ok(mut guard) = click_lock_spy.try_borrow_mut() {
3262                                *guard = Some((
3263                                    page_route_owned.clone(),
3264                                    matched_slug.clone(),
3265                                    applied_y,
3266                                ));
3267                            }
3268                            persist_snap = Some((applied_y, matched_slug.clone()));
3269                            next_slug = Some(matched_slug);
3270                            consumed_anchor = true;
3271                        }
3272                    } else if let Some((saved_y, saved_slug_opt)) = pending_restore.as_ref() {
3273                        let (cur_x, content_h): (f32, f32) = tree
3274                            .get_node(scroll_id)
3275                            .map(|scene_node: &SceneNode| {
3276                                (
3277                                    scene_node.get_layout_box().get_scroll_offset().get_x(),
3278                                    scene_node.get_layout_box().get_content_size().get_height(),
3279                                )
3280                            })
3281                            .unwrap_or((0.0, 0.0));
3282                        let max_scroll: f32 = (content_h - scroll_rect.get_height()).max(0.0);
3283                        let clamped_y: f32 = saved_y.clamp(0.0, max_scroll);
3284                        tree.set_scroll_offset(scroll_id, Point::new(cur_x, clamped_y));
3285                        tree.mark_dirty(scroll_id, DIRTY_PAINT);
3286                        let valid_saved: Option<String> =
3287                            saved_slug_opt.clone().filter(|text_value: &String| {
3288                                toc_items_owned
3289                                    .iter()
3290                                    .any(|it: &DocTocItem| it.get_slug() == text_value)
3291                            });
3292                        let resolved: Option<String> = valid_saved.or_else(|| {
3293                            compute_active_toc_slug_for_scroll(
3294                                tree,
3295                                body_node,
3296                                scroll_id,
3297                                &toc_items_owned,
3298                            )
3299                        });
3300                        if let Some(ref slug_str) = resolved {
3301                            if let Ok(mut guard) = click_lock_spy.try_borrow_mut() {
3302                                *guard =
3303                                    Some((page_route_owned.clone(), slug_str.clone(), clamped_y));
3304                            }
3305                            persist_snap = Some((clamped_y, slug_str.clone()));
3306                        }
3307                        next_slug = resolved;
3308                        consumed_restore = true;
3309                    }
3310                    let is_wide: bool =
3311                        tree.get_node(right_toc_host)
3312                            .is_some_and(|target_node: &SceneNode| {
3313                                target_node.style_ref().get_layout().get_display() != Display::None
3314                            });
3315                    if is_wide {
3316                        let safe_top: f32 = safe_now.get_top().max(0.0);
3317                        let safe_bottom: f32 = safe_now.get_bottom().max(0.0);
3318                        let navbar_bottom: f32 = scroll_rect
3319                            .get_y()
3320                            .max(SHELL_DESKTOP_HEADER_HEIGHT + safe_top);
3321                        let pin_screen_y: f32 = navbar_bottom + DOCS_STICKY_TOC_TOP_GAP;
3322                        let avail_h: f32 = ((scroll_rect.get_y() + scroll_rect.get_height())
3323                            - pin_screen_y
3324                            - safe_bottom
3325                            - SPACE_LG)
3326                            .max(200.0);
3327                        if let Some(sn) = tree.get_node_mut(right_toc_scroll) {
3328                            let cur_max: Length = sn.style_ref().get_layout().get_max_height();
3329                            let needs_max_update: bool = match cur_max {
3330                                Length::Px(px) => (px - avail_h).abs() > 1.0,
3331                                _ => true,
3332                            };
3333                            if needs_max_update {
3334                                sn.get_mut_style()
3335                                    .get_mut_layout()
3336                                    .set_max_height(Length::Px(avail_h));
3337                                let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
3338                                tree.mark_dirty(right_toc_scroll, dirty_l | DIRTY_PAINT);
3339                            }
3340                        }
3341                        if let Some(wide_rect) = tree.node_screen_bounds(wide_row_node) {
3342                            let toc_h: f32 = tree
3343                                .get_node(right_toc_host)
3344                                .map(|total_len: &SceneNode| {
3345                                    total_len.get_layout_box().get_bounds().get_height()
3346                                })
3347                                .unwrap_or(0.0)
3348                                .min(avail_h);
3349                            let max_sticky: f32 = (wide_rect.get_height() - toc_h).max(0.0);
3350                            let sticky_y: f32 =
3351                                (pin_screen_y - wide_rect.get_y()).clamp(0.0, max_sticky);
3352                            if let Some(item_count_primary) = tree.get_node_mut(right_toc_host) {
3353                                let cur_ty: f32 = item_count_primary
3354                                    .style_ref()
3355                                    .get_paint()
3356                                    .get_transform()
3357                                    .get_translate_y();
3358                                if (cur_ty - sticky_y).abs() > 0.25 {
3359                                    item_count_primary
3360                                        .get_mut_style()
3361                                        .get_mut_paint()
3362                                        .set_transform(Transform2D::new(
3363                                            0.0, sticky_y, 1.0, 1.0, 0.0,
3364                                        ));
3365                                    tree.mark_dirty(right_toc_host, DIRTY_PAINT);
3366                                }
3367                            }
3368                        }
3369                    }
3370                    if next_slug.is_none() {
3371                        let cur_scroll_y: f32 = tree
3372                            .get_node(scroll_id)
3373                            .map(|scene_node_primary: &SceneNode| {
3374                                scene_node_primary
3375                                    .get_layout_box()
3376                                    .get_scroll_offset()
3377                                    .get_y()
3378                                    .max(0.0)
3379                            })
3380                            .unwrap_or(0.0);
3381                        let locked_match: Option<String> = click_lock_spy
3382                            .try_borrow_mut()
3383                            .ok()
3384                            .and_then(|mut guard: RefMut<'_, Option<(String, String, f32)>>| {
3385                                let keep: Option<String> = guard.as_ref().and_then(
3386                                    |(lr, lslug, ly): &(String, String, f32)| {
3387                                        if lr == &page_route_owned
3388                                            && (cur_scroll_y - *ly).abs() <= 2.5
3389                                        {
3390                                            Some(lslug.clone())
3391                                        } else {
3392                                            None
3393                                        }
3394                                    },
3395                                );
3396                                if keep.is_none() {
3397                                    *guard = None;
3398                                }
3399                                keep
3400                            });
3401                        if let Some(locked_slug) = locked_match {
3402                            next_slug = Some(locked_slug);
3403                        } else {
3404                            let computed: Option<String> = compute_active_toc_slug_for_scroll(
3405                                tree,
3406                                body_node,
3407                                scroll_id,
3408                                &toc_items_owned,
3409                            );
3410                            if let Some(ref slug_str) = computed {
3411                                persist_snap = Some((cur_scroll_y, slug_str.clone()));
3412                            }
3413                            next_slug = computed;
3414                        }
3415                    }
3416                    let target_slug: String = next_slug
3417                        .clone()
3418                        .unwrap_or_else(|| toc_slug_sig.get_untracked());
3419                    if is_wide
3420                        && !target_slug.is_empty()
3421                        && let Ok(map) = row_nodes_for_spy.try_borrow()
3422                        && let Some(&toc_row_id) = map.get(&target_slug)
3423                    {
3424                        let _: bool =
3425                            scroll_node_into_scroll_view(tree, right_toc_scroll, toc_row_id, 20.0);
3426                    }
3427                },
3428                (),
3429            );
3430            if consumed_anchor {
3431                let _: bool = pending_anchor_sig.set_if_changed(None);
3432            }
3433            if consumed_restore {
3434                let _: bool = pending_restore_sig.set_if_changed(None);
3435            }
3436            if let Some(slug) = next_slug {
3437                let _: bool = toc_slug_sig.set_if_changed(slug);
3438            }
3439            if let Some((sy, sslug)) = persist_snap {
3440                persist_docs_scroll_state(&page_route_owned, sy, &sslug);
3441            }
3442        })
3443    });
3444    ctx.get_scene().with_write(
3445        |tree: &mut SceneTree| {
3446            tree.attach_scope(layout_root, toc_scope);
3447        },
3448        (),
3449    );
3450    layout_root
3451}
3452
3453/// Renders structured `DocBlock` nodes when a `DocPage` has no raw Markdown body text.
3454///
3455/// # Arguments
3456///
3457/// - `&DocPage` - Documentation page holding pre-parsed blocks.
3458/// - `&str` - Relative site-root asset base prefix (`"./"` or `"../"`).
3459/// - `ThemeTokens` - Active design tokens.
3460///
3461/// # Returns
3462///
3463/// - `NodeId` - Mounted fallback block column handle.
3464fn mount_fallback_doc_blocks(page: &DocPage, asset_base: &str, tokens: ThemeTokens) -> NodeId {
3465    let column_eighth_style: Style = style! {
3466        Width(Length::Percent(100.0))
3467        Gap(SPACE_MD)
3468    };
3469    view! {
3470        column {
3471            style: column_eighth_style
3472            for block in page.get_blocks().iter() {
3473                match block {
3474                    DocBlock::Heading { level, text, .. } => {
3475                        EuvMarkdownHeading {
3476                            level: *level
3477                            text: text.clone()
3478                            tokens: tokens
3479                        }
3480                    }
3481                    DocBlock::Paragraph(text) => {
3482                        EuvMarkdownParagraph {
3483                            inlines: parse_markdown_inlines(text)
3484                            tokens: tokens
3485                            asset_base: asset_base
3486                        }
3487                    }
3488                    DocBlock::ListItem(text) => EuvMarkdownList {
3489                        ordered: false
3490                        items: vec![EuvMarkdownListItem::new(text.clone(), 0, None)]
3491                        tokens: tokens
3492                    },
3493                    DocBlock::BlockQuote(text) => EuvMarkdownQuote {
3494                        kind: EuvMarkdownAlertKind::Quote
3495                        lines: vec![text.clone()]
3496                        tokens: tokens
3497                    },
3498                    DocBlock::Table { headers, rows } => EuvMarkdownTable {
3499                        headers: headers.clone()
3500                        alignments: vec![EuvMarkdownAlign::Left; headers.len()]
3501                        rows: rows.clone()
3502                        tokens: tokens
3503                    },
3504                    DocBlock::Image { alt, src } => {
3505                        EuvMarkdownImage {
3506                            alt: alt.clone()
3507                            url: src.clone()
3508                            tokens: tokens
3509                            asset_base: asset_base
3510                        }
3511                    }
3512                    DocBlock::HorizontalRule => EuvMarkdownDivider {
3513                        tokens: tokens
3514                    },
3515                    DocBlock::Code { language, code } => {
3516                        EuvCodeBlock {
3517                            code: code.clone()
3518                            tokens: tokens
3519                            language: language.clone()
3520                            line_numbers: true
3521                            selectable: true
3522                        }
3523                    }
3524                }
3525            }
3526        }
3527    }
3528}
3529
3530/// Renders a single standalone `DocPage` (meta bar, header, interactive TOC, and full `EuvMarkdown`) as native `euv-ui` nodes.
3531///
3532/// # Arguments
3533///
3534/// - `&DocPage` - Documentation page to mount.
3535/// - `ThemeTokens` - Active design tokens.
3536///
3537/// # Returns
3538///
3539/// - `NodeId` - Mounted page container node.
3540pub fn mount_doc_page(page: &DocPage, tokens: ThemeTokens) -> NodeId {
3541    let mut meta_bar: EuvDocMetaBar = EuvDocMetaBar::new(
3542        page.get_section().clone(),
3543        page.reading_minutes(),
3544        page.word_count(),
3545        tokens,
3546    )
3547    .source_path(page.get_route().clone());
3548    if let Some(updated) = page.try_get_updated().as_deref() {
3549        meta_bar = meta_bar.updated(updated);
3550    }
3551    let meta_node: NodeId = meta_bar.mount();
3552    let toc_items: Vec<EuvDocTocItem> = page
3553        .get_toc()
3554        .iter()
3555        .map(|it: &DocTocItem| {
3556            EuvDocTocItem::new(
3557                it.get_level(),
3558                it.get_slug().clone(),
3559                it.get_title().clone(),
3560            )
3561        })
3562        .collect();
3563    let toc_sig: Signal<String> = Signal::new(
3564        toc_items
3565            .first()
3566            .map(|it: &EuvDocTocItem| it.get_slug().clone())
3567            .unwrap_or_default(),
3568    );
3569    let toc_node_opt: Option<NodeId> = if toc_items.is_empty() {
3570        None
3571    } else {
3572        Some(EuvDocToc::new(toc_items, toc_sig, tokens).mount())
3573    };
3574    let body_node: NodeId = if !page.get_markdown_body().trim().is_empty() {
3575        EuvMarkdown::new(page.get_markdown_body().clone(), tokens)
3576            .style(style! {
3577                TextSelectMode::SelectAndCopy
3578            })
3579            .asset_base("./")
3580            .mount()
3581    } else {
3582        mount_fallback_doc_blocks(page, "./", tokens)
3583    };
3584    let column_seventh_style: Style = style! {
3585        Width(Length::Percent(100.0))
3586        Gap(SPACE_MD)
3587    };
3588    view! {
3589        column {
3590            style: column_seventh_style
3591            { meta_node }
3592            EuvHeader {
3593                title: page.get_title().clone()
3594                subtitle: page.get_summary().clone()
3595                tokens: tokens
3596            }
3597            if let Some(toc_node) = toc_node_opt {
3598                { toc_node }
3599            }
3600            { body_node }
3601        }
3602    }
3603}
3604
3605/// Registers every page in `state.site` lazily onto `state.router` with `PageRetention::Freeze`.
3606///
3607/// # Arguments
3608///
3609/// - `&DocsViewerState` - Shared reactive viewer state.
3610fn ensure_docs_routes_registered(state: &DocsViewerState) {
3611    if state.get_router_ready().replace(true) {
3612        return;
3613    }
3614    let mut router: EuvRouter = state.get_router().clone();
3615    for page in state.get_site().get_pages().iter() {
3616        let route_pattern: String = page.get_route().clone();
3617        let route_path: String = route_pattern.clone();
3618        let route_title: String = page.get_title().clone();
3619        let node_style: DocsViewerState = state.clone();
3620        router = router.route_with_retention(
3621            &route_pattern,
3622            &route_title,
3623            PageRetention::Freeze,
3624            move |_: &EuvRouteMatch| {
3625                let tok: ThemeTokens = untracked(|| node_style.get_theme().get_tokens().get());
3626                match node_style.get_site().find_by_route(&route_path) {
3627                    Some(point_val) => mount_doc_page_with_context(point_val, &node_style, tok),
3628                    None => view! {
3629                        EuvEmpty {
3630                            title: EMPTY_PAGE_TITLE.to_string()
3631                            description: EMPTY_PAGE_MSG.to_string()
3632                            tokens: tok
3633                        }
3634                    },
3635                }
3636            },
3637        );
3638    }
3639    let _: EuvRouter = router;
3640}
3641
3642/// Computes the viewport-clamped `(left, top, width, max_height)` anchor frame for a topbar dropdown portal.
3643///
3644/// # Arguments
3645///
3646/// - `&SceneHandle` - Active scene graph handle.
3647/// - `&[NodeId]` - Candidate desktop and mobile trigger node handles.
3648/// - `Size` - Active logical viewport size.
3649/// - `SafeAreaInsets` - Active OS safe-area insets.
3650/// - `f32` - Preferred menu width in logical pixels.
3651/// - `f32` - Preferred menu max height in logical pixels.
3652///
3653/// # Returns
3654///
3655/// - `(f32, f32, f32, f32)` - Clamped `(left, top, width, max_height)` rectangle strictly inside viewport safe bounds.
3656fn docs_dropdown_anchor_rect(
3657    scene: &SceneHandle,
3658    triggers: &[NodeId],
3659    box_size: Size,
3660    safe: SafeAreaInsets,
3661    desired_w: f32,
3662    desired_h: f32,
3663) -> (f32, f32, f32, f32) {
3664    let vp_w: f32 = box_size.get_width().max(320.0);
3665    let vp_h: f32 = box_size.get_height().max(320.0);
3666    let margin: f32 = DOCS_DROPDOWN_EDGE_MARGIN;
3667    let safe_l: f32 = safe.get_left().max(0.0);
3668    let safe_r: f32 = safe.get_right().max(0.0);
3669    let safe_t: f32 = safe.get_top().max(0.0);
3670    let safe_b: f32 = safe.get_bottom().max(0.0);
3671    let max_avail_w: f32 = (vp_w - safe_l - safe_r - margin * 2.0).max(152.0);
3672    let menu_w: f32 = desired_w.min(max_avail_w);
3673    let anchor_opt: Option<Rect> = scene.with_read(
3674        |tree: &SceneTree| {
3675            for &tid in triggers.iter() {
3676                if tree.is_node_visible(tid)
3677                    && let Some(red_val) = tree.node_screen_bounds(tid)
3678                    && red_val.get_width() > 4.0
3679                    && red_val.get_height() > 4.0
3680                {
3681                    return Some(red_val);
3682                }
3683            }
3684            None
3685        },
3686        None,
3687    );
3688    let (raw_left, raw_top): (f32, f32) = match anchor_opt {
3689        Some(radius_val) => (
3690            radius_val.get_x() + radius_val.get_width() - menu_w,
3691            radius_val.get_y() + radius_val.get_height() + 6.0,
3692        ),
3693        None => (
3694            vp_w - safe_r - menu_w - margin,
3695            SHELL_DESKTOP_HEADER_HEIGHT + safe_t + 6.0,
3696        ),
3697    };
3698    let min_left: f32 = safe_l + margin;
3699    let max_left: f32 = (vp_w - safe_r - menu_w - margin).max(min_left);
3700    let left: f32 = raw_left.clamp(min_left, max_left);
3701    let min_top: f32 = safe_t + margin;
3702    let top_clamped: f32 = raw_top.max(min_top);
3703    let avail_below: f32 = (vp_h - safe_b - top_clamped - margin).max(120.0);
3704    let max_h: f32 = desired_h.min(avail_below).max(120.0);
3705    let max_top: f32 = (vp_h - safe_b - max_h - margin).max(min_top);
3706    let top: f32 = top_clamped.min(max_top);
3707    (left, top, menu_w, max_h)
3708}
3709
3710/// Recursively mounts one node in the pure filesystem-mirrored documentation catalog tree with lazy child mounting and exact directory click semantics.
3711///
3712/// # Arguments
3713///
3714/// - `&DocCatalogNode` - Catalog directory or document node.
3715/// - `usize` - Zero-based directory nesting depth.
3716/// - `bool` - Whether small-site default top-level expansion is enabled.
3717/// - `Signal<String>` - Active canonical route signal.
3718/// - `&Rc<RefCell<HashMap<String, NodeId>>>` - Registry recording `(route -> row_node_id)` for scrolling the active item into view.
3719/// - `ThemeTokens` - Base design tokens.
3720///
3721/// # Returns
3722///
3723/// - `NodeId` - Mounted catalog tree branch handle.
3724fn mount_docs_catalog_branch(
3725    node: &DocCatalogNode,
3726    depth: usize,
3727    expand_top_default: bool,
3728    active_route: Signal<String>,
3729    row_registry: &Rc<RefCell<HashMap<String, NodeId>>>,
3730    tokens: ThemeTokens,
3731) -> NodeId {
3732    let is_dir: bool = node.get_is_dir();
3733    let has_children: bool = !node.get_children().is_empty();
3734    let init_route: String = active_route.get_untracked();
3735    let contains_init: bool = node.contains_route(&init_route);
3736    let init_expanded: bool = if !is_dir || !has_children {
3737        false
3738    } else if contains_init {
3739        true
3740    } else if let Some(pref) = node.get_expanded_pref() {
3741        pref
3742    } else if !node.get_collapsible() {
3743        true
3744    } else {
3745        expand_top_default && depth == 0
3746    };
3747    let expanded_sig: Signal<bool> = Signal::new(init_expanded);
3748    let hovered_sig: Signal<bool> = Signal::new(false);
3749    let direct_route: Option<String> = node.try_get_route().clone();
3750    let first_child: Option<String> = node.try_get_first_child_route().clone();
3751    let has_own_content: bool = node.get_has_own_content();
3752    let index_disabled: bool = node.get_index_disabled();
3753    let collapsible: bool = node.get_collapsible();
3754    let locked: bool = node.get_locked();
3755    let title_owned: String = node.get_title().clone();
3756    let node_for_ancestor: DocCatalogNode = node.clone();
3757    let route_for_style: Option<String> = direct_route.clone();
3758    let row_style = move || -> Style {
3759        let tok: ThemeTokens = use_live_tokens(tokens);
3760        let lp: ThemePalette = tok.get_palette();
3761        let lg: ThemeGeometry = tok.get_geometry();
3762        let cur: String = active_route.get();
3763        let is_active: bool = route_for_style.as_deref() == Some(cur.as_str());
3764        let is_hov: bool = hovered_sig.get();
3765        let bg: Color = if is_active {
3766            lp.surface(SurfaceRole::Primary).get_bg()
3767        } else if is_hov {
3768            lp.surface(SurfaceRole::Accent).get_bg()
3769        } else {
3770            COLOR_TRANSPARENT
3771        };
3772        style! {
3773            FlexDirection::Row
3774            Width(Length::Percent(100.0))
3775            MinHeight(Length::Px(32.0))
3776            AlignItems::Center
3777            Gap(SPACE_XS)
3778            Padding(Edges::symmetric(4.0, SPACE_SM))
3779            Background(bg)
3780            Radius(lg.get_radius_sm())
3781            Overflow::Hidden
3782            CursorIcon::Pointer
3783        }
3784    };
3785    let route_for_txt: Option<String> = direct_route.clone();
3786    let txt_style = move || -> Style {
3787        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
3788        let cur: String = active_route.get();
3789        let is_active: bool = route_for_txt.as_deref() == Some(cur.as_str());
3790        let is_hov: bool = hovered_sig.get();
3791        let fg: Color = if is_active {
3792            lp.surface(SurfaceRole::Primary).get_fg()
3793        } else if is_hov {
3794            lp.surface(SurfaceRole::Accent).get_fg()
3795        } else if is_dir {
3796            lp.get_foreground()
3797        } else {
3798            lp.get_muted_foreground()
3799        };
3800        let mut computed_style: Style = style! {
3801            FlexGrow(1.0)
3802            FlexShrink(1.0)
3803            MinWidth(Length::Px(0.0))
3804            FontSize(if is_dir && depth == 0 { 13.0 } else { 12.5 })
3805            if is_active {
3806                FontWeight::Medium
3807            } else {
3808                FontWeight::Normal
3809            }
3810            TextColor(fg)
3811            Overflow::Hidden
3812            TextOverflow::Ellipsis
3813        };
3814        computed_style.get_mut_text().set_line_height(1.25);
3815        computed_style
3816    };
3817    let route_for_click: Option<String> = direct_route.clone();
3818    let first_for_click: Option<String> = first_child;
3819    let on_row_click = move |_: &UiEvent| {
3820        if !is_dir {
3821            if let Some(target) = route_for_click.as_ref() {
3822                let _: bool = active_route.set_if_changed(target.clone());
3823            }
3824            return;
3825        }
3826        if index_disabled {
3827            let was_open: bool = expanded_sig.get_untracked();
3828            if collapsible {
3829                let _: bool = expanded_sig.set_if_changed(!was_open);
3830            }
3831            if !was_open
3832                && has_own_content
3833                && let Some(target) = route_for_click.as_ref()
3834            {
3835                let _: bool = active_route.set_if_changed(target.clone());
3836            }
3837            return;
3838        }
3839        if !has_own_content {
3840            if has_children {
3841                let _: bool = expanded_sig.set_if_changed(true);
3842            }
3843            if let Some(target) = first_for_click.as_ref() {
3844                let _: bool = active_route.set_if_changed(target.clone());
3845            }
3846            return;
3847        }
3848        if has_children {
3849            let cur_route: String = active_route.get_untracked();
3850            let already_active: bool = route_for_click.as_deref() == Some(cur_route.as_str());
3851            if already_active && collapsible {
3852                let _: bool = expanded_sig.set(!expanded_sig.get_untracked());
3853            } else {
3854                let _: bool = expanded_sig.set_if_changed(true);
3855            }
3856        }
3857        if let Some(target) = route_for_click.as_ref() {
3858            let _: bool = active_route.set_if_changed(target.clone());
3859        }
3860    };
3861    let on_chev_click = move |_: &UiEvent| {
3862        if collapsible {
3863            let _: bool = expanded_sig.set(!expanded_sig.get_untracked());
3864        }
3865    };
3866    let on_row_enter = move |_: &UiEvent| {
3867        let _: bool = hovered_sig.set_if_changed(true);
3868    };
3869    let on_row_leave = move |_: &UiEvent| {
3870        let _: bool = hovered_sig.set_if_changed(false);
3871    };
3872    let route_for_chev: Option<String> = direct_route;
3873    let paint_chev = move |bounds: Rect, display_list: &mut DisplayList| {
3874        let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
3875        let cur: String = active_route.get_untracked();
3876        let is_active: bool = route_for_chev.as_deref() == Some(cur.as_str());
3877        let col: Color = if is_active {
3878            lp.surface(SurfaceRole::Primary).get_fg()
3879        } else {
3880            lp.get_muted_foreground()
3881        };
3882        draw_docs_tree_chevron(bounds, display_list, col, expanded_sig.get_untracked());
3883    };
3884    let lock_dot_style = move || -> Style {
3885        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
3886        style! {
3887            Width(Length::Px(6.0))
3888            Height(Length::Px(6.0))
3889            FlexShrink(0.0)
3890            Radius(RADIUS_PILL)
3891            Background(lp.get_warning())
3892        }
3893    };
3894    let children_data: Vec<DocCatalogNode> = node.get_children().clone();
3895    let reg_for_children: Rc<RefCell<HashMap<String, NodeId>>> = Rc::clone(row_registry);
3896    let build_children_lazy = move || -> Vec<NodeId> {
3897        if !expanded_sig.get() {
3898            return Vec::new();
3899        }
3900        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
3901        children_data
3902            .iter()
3903            .map(|child: &DocCatalogNode| {
3904                mount_docs_catalog_branch(
3905                    child,
3906                    depth + 1,
3907                    expand_top_default,
3908                    active_route,
3909                    &reg_for_children,
3910                    live_tok,
3911                )
3912            })
3913            .collect()
3914    };
3915    let child_row_style = move || -> Style {
3916        let is_open: bool = expanded_sig.get();
3917        style! {
3918            FlexDirection::Row
3919            if is_open {
3920                Display::Flex
3921            } else {
3922                Display::None
3923            }
3924            Width(Length::Percent(100.0))
3925            Padding(Edges::new(2.0, 0.0, 2.0, 10.0))
3926            Gap(SPACE_SM)
3927            AlignItems::Stretch
3928        }
3929    };
3930    let tree_guide_style = move || -> Style {
3931        let lp: ThemePalette = use_live_tokens(tokens).get_palette();
3932        style! {
3933            Width(Length::Px(1.0))
3934            FlexShrink(0.0)
3935            Background(lp.get_border())
3936        }
3937    };
3938    let mut row_node: NodeId = NodeId::default();
3939    let mut chev_canvas: NodeId = NodeId::default();
3940    let column_fifth_style: Style = style! {
3941        Width(Length::Percent(100.0))
3942        Gap(2.0)
3943    };
3944    let row_seventh_style: Style = style! {
3945        Width(Length::Px(20.0))
3946        Height(Length::Px(20.0))
3947        Padding(Edges::all(SPACE_XS))
3948        Radius(tokens.get_geometry().get_radius_sm())
3949        FlexShrink(0.0)
3950        JustifyContent::Center
3951        AlignItems::Center
3952        CursorIcon::Pointer
3953        StopEventPropagation(true)
3954    };
3955    let canvas_sixth_style: Style = style! {
3956        Width(Length::Px(10.0))
3957        Height(Length::Px(10.0))
3958    };
3959    let column_sixth_style: Style = style! {
3960        FlexGrow(1.0)
3961        FlexShrink(1.0)
3962        MinWidth(Length::Px(0.0))
3963        Gap(2.0)
3964    };
3965    let branch_node: NodeId = view! {
3966        column {
3967            style: column_fifth_style
3968            row {
3969                node_ref: row_node
3970                bind_style: row_style
3971                role: if is_dir { A11yRole::Button } else { A11yRole::Link }
3972                a11y_label: title_owned.clone()
3973                on_click: on_row_click
3974                on_pointer_enter: on_row_enter
3975                on_pointer_leave: on_row_leave
3976                if is_dir && has_children {
3977                    row {
3978                        style: row_seventh_style
3979                        on_click: on_chev_click
3980                        canvas {
3981                            node_ref: chev_canvas
3982                            style: canvas_sixth_style
3983                            painter: paint_chev
3984                        }
3985                    }
3986                }
3987                text {
3988                    bind_style: txt_style
3989                    { title_owned }
3990                }
3991                if locked {
3992                    view {
3993                        bind_style: lock_dot_style
3994                    }
3995                }
3996            }
3997            if is_dir && has_children {
3998                row {
3999                    bind_style: child_row_style
4000                    view {
4001                        bind_style: tree_guide_style
4002                    }
4003                    column {
4004                        style: column_sixth_style
4005                        bind_children: build_children_lazy
4006                    }
4007                }
4008            }
4009        }
4010    };
4011    if let Some(route_key) = node.try_get_route().as_deref()
4012        && let Ok(mut map) = row_registry.try_borrow_mut()
4013    {
4014        let _: Option<NodeId> = map.insert(route_key.to_string(), row_node);
4015    }
4016    if is_dir && has_children {
4017        let ctx: Context = current_context();
4018        let scale_factor: SceneHandle = ctx.get_scene().clone();
4019        let (branch_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4020            let _: Effect = Effect::new(move || {
4021                let cur: String = active_route.get();
4022                if node_for_ancestor.contains_route(&cur) {
4023                    let _: bool = expanded_sig.set_if_changed(true);
4024                }
4025            });
4026            Effect::new(move || {
4027                let _: bool = expanded_sig.get();
4028                let _: String = active_route.get();
4029                let _: ThemeTokens = use_live_tokens(tokens);
4030                scale_factor.with_write(
4031                    |tree: &mut SceneTree| {
4032                        tree.mark_dirty(chev_canvas, DIRTY_PAINT);
4033                    },
4034                    (),
4035                );
4036            })
4037        });
4038        ctx.get_scene().with_write(
4039            |tree: &mut SceneTree| {
4040                tree.attach_scope(branch_node, branch_scope);
4041            },
4042            (),
4043        );
4044    }
4045    branch_node
4046}
4047
4048/// Mounts the pure filesystem-mirrored documentation left sidebar tree (without any sidebar search input).
4049///
4050/// # Arguments
4051///
4052/// - `&DocsViewerState` - Shared documentation viewer state.
4053/// - `ThemeTokens` - Base design tokens.
4054///
4055/// # Returns
4056///
4057/// - `NodeId` - Mounted recursive directory catalog tree container.
4058fn mount_docs_catalog_tree(state: &DocsViewerState, tokens: ThemeTokens) -> NodeId {
4059    let active_route: Signal<String> = state.get_active_route();
4060    let row_registry: &Rc<RefCell<HashMap<String, NodeId>>> = state.get_catalog_row_nodes();
4061    if let Ok(mut map) = row_registry.try_borrow_mut() {
4062        map.clear();
4063    }
4064    let total_pages: usize = state.get_site().get_pages().len();
4065    let expand_top_default: bool = total_pages <= 24;
4066    let nodes: Vec<NodeId> = state
4067        .get_catalog_tree()
4068        .iter()
4069        .map(|entry: &DocCatalogNode| {
4070            mount_docs_catalog_branch(
4071                entry,
4072                0,
4073                expand_top_default,
4074                active_route,
4075                row_registry,
4076                tokens,
4077            )
4078        })
4079        .collect();
4080    let column_quaternary_style: Style = style! {
4081        Width(Length::Percent(100.0))
4082        Gap(2.0)
4083    };
4084    let root: NodeId = view! {
4085        column {
4086            style: column_quaternary_style
4087            role: A11yRole::Navigation
4088            ..nodes
4089        }
4090    };
4091    state.get_sidebar_root().set(root);
4092    root
4093}
4094
4095/// Mounts the viewport-clamped floating Locale Dropdown portal anchored beneath the topbar Globe icon button.
4096///
4097/// # Arguments
4098///
4099/// - `&DocsViewerState` - Shared documentation viewer state.
4100/// - `ThemeTokens` - Base design tokens.
4101/// - `Vec<NodeId>` - Desktop and Mobile Globe trigger node handles.
4102///
4103/// # Returns
4104///
4105/// - `NodeId` - Mounted floating locale dropdown portal handle.
4106fn mount_docs_locale_dropdown_portal(
4107    state: &DocsViewerState,
4108    tokens: ThemeTokens,
4109    triggers: Vec<NodeId>,
4110) -> NodeId {
4111    let mut ctx: Context = current_context();
4112    let open_sig: Signal<bool> = state.get_locale_menu_open();
4113    let last_href_sig: Signal<String> = state.get_last_locale_href();
4114    let active_route_sig: Signal<String> = state.get_active_route();
4115    let active_toc_sig: Signal<String> = state.get_active_toc_slug();
4116    let vp_sig: Signal<Size> = ctx.get_viewport_size();
4117    let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
4118    let init_tok: ThemeTokens = live_tokens_untracked(tokens);
4119    let palette: ThemePalette = init_tok.get_palette();
4120    let geometry: ThemeGeometry = init_tok.get_geometry();
4121    let card_s: SurfaceColors = palette.surface(SurfaceRole::Card);
4122    let menu_r: f32 = geometry.get_radius_lg();
4123    let item_r: f32 = concentric_radius(menu_r, CONTROL_INSET);
4124    let active_prefix: String = state.get_site().get_locale_prefix().clone();
4125    let locales: Vec<DocLocaleConfig> = state.get_site().get_locales().clone();
4126    let hovered_idx: Signal<Option<usize>> = Signal::new(None);
4127    let mut item_rows: Vec<(NodeId, NodeId, NodeId, bool)> = Vec::with_capacity(locales.len());
4128    let mut item_nodes: Vec<NodeId> = Vec::with_capacity(locales.len());
4129    for (idx, loc) in locales.iter().enumerate() {
4130        let is_cur: bool = loc.get_prefix().as_str() == active_prefix.as_str();
4131        let display_lbl: String = if !loc.get_label().trim().is_empty() {
4132            loc.get_label().trim().to_string()
4133        } else {
4134            loc.get_dir().to_ascii_uppercase()
4135        };
4136        let active_prefix_pick: String = active_prefix.clone();
4137        let target_prefix_pick: String = loc.get_prefix().clone();
4138        let (init_bg, init_fg): (Color, Color) = if is_cur {
4139            let color_value: SurfaceColors = palette.surface(SurfaceRole::Primary);
4140            (color_value.get_bg(), color_value.get_fg())
4141        } else {
4142            (COLOR_TRANSPARENT, card_s.get_fg())
4143        };
4144        let on_pick_locale = move |_: &UiEvent| {
4145            let cur_route: String = active_route_sig.get_untracked();
4146            let cur_anchor: String = active_toc_sig.get_untracked();
4147            #[cfg(target_arch = "wasm32")]
4148            let base_dir: String = window()
4149                .and_then(|win: Window| win.location().pathname().ok())
4150                .map(|pn: String| {
4151                    resolve_site_root_from_pathname(pn.as_str(), active_prefix_pick.as_str())
4152                })
4153                .unwrap_or_else(|| asset_base_for_locale_prefix(active_prefix_pick.as_str()));
4154            #[cfg(not(target_arch = "wasm32"))]
4155            let base_dir: String = asset_base_for_locale_prefix(active_prefix_pick.as_str());
4156            let target_href: String = build_locale_switch_url(
4157                base_dir.as_str(),
4158                target_prefix_pick.as_str(),
4159                cur_route.as_str(),
4160                (!cur_anchor.is_empty()).then_some(cur_anchor.as_str()),
4161            );
4162            let _: bool = last_href_sig.set_if_changed(target_href.clone());
4163            let _: bool = open_sig.set_if_changed(false);
4164            #[cfg(target_arch = "wasm32")]
4165            if !is_cur {
4166                open_browser_url(&target_href, false);
4167            }
4168        };
4169        let paint_check = move |bounds: Rect, display_list: &mut DisplayList| {
4170            if is_cur {
4171                let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
4172                let fg: Color = lp.surface(SurfaceRole::Primary).get_fg();
4173                draw_euv_icon(EuvIconName::Check, bounds, display_list, fg);
4174            }
4175        };
4176        let mut txt_id: NodeId = NodeId::default();
4177        let mut chk_id: NodeId = NodeId::default();
4178        let row_sixth_style: Style = style! {
4179            Width(Length::Percent(100.0))
4180            Height(Length::Px(DOCS_DROPDOWN_ITEM_HEIGHT))
4181            Padding(Edges::symmetric(0.0, SPACE_SM))
4182            AlignItems::Center
4183            Gap(SPACE_SM)
4184            Background(init_bg)
4185            Radius(item_r)
4186            Overflow::Hidden
4187            CursorIcon::Pointer
4188            StopEventPropagation(true)
4189        };
4190        let text_secondary_style: Style = style! {
4191            FlexGrow(1.0)
4192            FlexShrink(1.0)
4193            MinWidth(Length::Px(0.0))
4194            FontSize(13.0)
4195            if is_cur { FontWeight::SemiBold } else { FontWeight::Normal }
4196            TextColor(init_fg)
4197            Overflow::Hidden
4198            TextOverflow::Ellipsis
4199        };
4200        let canvas_fifth_style: Style = style! {
4201            Width(Length::Px(13.0))
4202            Height(Length::Px(13.0))
4203            FlexShrink(0.0)
4204        };
4205        let row_id: NodeId = view! {
4206            row {
4207                style: row_sixth_style
4208                role: A11yRole::MenuItem
4209                a11y_label: display_lbl.clone()
4210                on_click: on_pick_locale
4211                text {
4212                    node_ref: txt_id
4213                    style: text_secondary_style
4214                    { display_lbl }
4215                }
4216                canvas {
4217                    node_ref: chk_id
4218                    style: canvas_fifth_style
4219                    painter: paint_check
4220                }
4221            }
4222        };
4223        ctx.on_pointer_enter(row_id, move |_: &UiEvent| {
4224            let _: bool = hovered_idx.set_if_changed(Some(idx));
4225        });
4226        ctx.on_pointer_leave(row_id, move |_: &UiEvent| {
4227            if hovered_idx.get_untracked() == Some(idx) {
4228                let _: bool = hovered_idx.set_if_changed(None);
4229            }
4230        });
4231        item_rows.push((row_id, txt_id, chk_id, is_cur));
4232        item_nodes.push(row_id);
4233    }
4234    let est_h: f32 =
4235        (locales.len() as f32) * (DOCS_DROPDOWN_ITEM_HEIGHT + CONTROL_INSET) + CONTROL_INSET * 2.0;
4236    let mut card: NodeId = NodeId::default();
4237    let portal_secondary_style: Style = style! {
4238        Display::None
4239        Position::Fixed
4240        Inset(Some(0.0), Some(0.0), Some(0.0), Some(0.0))
4241        Width(Length::Percent(100.0))
4242        Height(Length::Percent(100.0))
4243        Background(COLOR_TRANSPARENT)
4244        PointerEvents::None
4245        StopScrollPropagation(true)
4246        ZIndex(DOCS_DROPDOWN_Z_INDEX)
4247    };
4248    let column_tertiary_style: Style = style! {
4249        Position::Absolute
4250        Inset(Some(SHELL_DESKTOP_HEADER_HEIGHT + 6.0), None, None, Some(8.0))
4251        Width(Length::Px(DOCS_LOCALE_MENU_WIDTH))
4252        Padding(Edges::all(CONTROL_INSET))
4253        Gap(CONTROL_INSET)
4254        Background(card_s.get_bg())
4255        Border::new(geometry.get_border_width(), card_s.get_border())
4256        Radius(menu_r)
4257        geometry.get_shadow_lg()
4258        Overflow::Hidden
4259        StopEventPropagation(true)
4260    };
4261    let portal: NodeId = view! {
4262        portal {
4263            style: portal_secondary_style
4264            column {
4265                node_ref: card
4266                style: column_tertiary_style
4267                role: A11yRole::Menu
4268                a11y_label: BTN_LOCALE_A11Y.to_string()
4269                ..item_nodes
4270            }
4271        }
4272    };
4273    ctx.on_click(portal, move |ui_event: &UiEvent| {
4274        if ui_event.get_target() == portal {
4275            let _: bool = open_sig.set_if_changed(false);
4276        }
4277    });
4278    for key_target in [portal, card].into_iter() {
4279        ctx.on_key(key_target, move |interaction_event: &UiEvent| {
4280            let is_esc: bool = matches!(
4281                interaction_event.get_kind(),
4282                UiEventKind::KeyDown(KeyCode::Escape, _)
4283            ) || matches!(
4284                interaction_event.get_kind(),
4285                UiEventKind::KeyDown(KeyCode::Back, _)
4286            );
4287            if is_esc && open_sig.get_untracked() {
4288                let _: bool = open_sig.set_if_changed(false);
4289            }
4290        });
4291    }
4292    let sc_pos: SceneHandle = ctx.get_scene().clone();
4293    let sc_paint: SceneHandle = sc_pos.clone();
4294    let owned_nodes: Vec<NodeId> = {
4295        let mut target_node_id: Vec<NodeId> = Vec::with_capacity(item_rows.len() * 3 + 2);
4296        target_node_id.push(portal);
4297        target_node_id.push(card);
4298        for &(rid, tid, cid, _) in item_rows.iter() {
4299            target_node_id.push(rid);
4300            target_node_id.push(tid);
4301            target_node_id.push(cid);
4302        }
4303        target_node_id
4304    };
4305    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4306        let _: Effect =
4307            EuvOverlayStack::bind_signal(open_sig, DOCS_LOCALE_OVERLAY_NAME, DOCS_DROPDOWN_Z_INDEX);
4308        let _: Effect = Effect::new(move || {
4309            let is_open: bool = open_sig.get();
4310            let box_size: Size = vp_sig.get();
4311            let safe: SafeAreaInsets = safe_sig.get();
4312            let (left, top, width, _): (f32, f32, f32, f32) = docs_dropdown_anchor_rect(
4313                &sc_pos,
4314                &triggers,
4315                box_size,
4316                safe,
4317                DOCS_LOCALE_MENU_WIDTH,
4318                est_h.min(DOCS_DROPDOWN_MAX_HEIGHT),
4319            );
4320            if !is_open {
4321                let _: bool = hovered_idx.set_if_changed(None);
4322            }
4323            sc_pos.with_write(
4324                |tree: &mut SceneTree| {
4325                    let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4326                    let dirty_all: u16 = dirty_l | DIRTY_PAINT;
4327                    if let Some(item_count) = tree.get_node_mut(card) {
4328                        let lay: &mut LayoutStyle = item_count.get_mut_style().get_mut_layout();
4329                        lay.set_left(Some(left))
4330                            .set_top(Some(top))
4331                            .set_width(Length::Px(width));
4332                        tree.mark_dirty(card, dirty_all);
4333                    }
4334                    if let Some(node_entry) = tree.get_node_mut(portal) {
4335                        let computed_style: &mut Style = node_entry.get_mut_style();
4336                        computed_style.get_mut_layout().set_display(if is_open {
4337                            Display::Flex
4338                        } else {
4339                            Display::None
4340                        });
4341                        computed_style
4342                            .get_mut_paint()
4343                            .set_pointer_events(if is_open {
4344                                PointerEvents::Auto
4345                            } else {
4346                                PointerEvents::None
4347                            });
4348                        tree.mark_dirty(portal, dirty_all);
4349                    }
4350                },
4351                (),
4352            );
4353        });
4354        Effect::new(move || {
4355            let hov: Option<usize> = hovered_idx.get();
4356            let tok: ThemeTokens = use_live_tokens(tokens);
4357            let lp: ThemePalette = tok.get_palette();
4358            let lg: ThemeGeometry = tok.get_geometry();
4359            let cs: SurfaceColors = lp.surface(SurfaceRole::Card);
4360            let ps: SurfaceColors = lp.surface(SurfaceRole::Primary);
4361            let ac: SurfaceColors = lp.surface(SurfaceRole::Accent);
4362            sc_paint.with_write(
4363                |tree: &mut SceneTree| {
4364                    if let Some(normal_vec) = tree.get_node_mut(card) {
4365                        normal_vec
4366                            .get_mut_style()
4367                            .get_mut_paint()
4368                            .set_background(Some(cs.get_bg()))
4369                            .set_border(Border::new(lg.get_border_width(), cs.get_border()))
4370                            .set_shadow(Some(lg.get_shadow_lg()));
4371                        tree.mark_dirty(card, DIRTY_PAINT);
4372                    }
4373                    for (idx, &(rid, tid, cid, is_cur)) in item_rows.iter().enumerate() {
4374                        let is_hov: bool = hov == Some(idx);
4375                        let (bg, fg): (Color, Color) = if is_cur {
4376                            (ps.get_bg(), ps.get_fg())
4377                        } else if is_hov {
4378                            (ac.get_bg(), ac.get_fg())
4379                        } else {
4380                            (COLOR_TRANSPARENT, cs.get_fg())
4381                        };
4382                        if let Some(total_len) = tree.get_node_mut(rid) {
4383                            total_len
4384                                .get_mut_style()
4385                                .get_mut_paint()
4386                                .set_background(Some(bg));
4387                            tree.mark_dirty(rid, DIRTY_PAINT);
4388                        }
4389                        if let Some(item_count_primary) = tree.get_node_mut(tid) {
4390                            item_count_primary
4391                                .get_mut_style()
4392                                .get_mut_text()
4393                                .set_color(fg);
4394                            tree.mark_dirty(tid, DIRTY_PAINT);
4395                        }
4396                        tree.mark_dirty(cid, DIRTY_PAINT);
4397                    }
4398                },
4399                (),
4400            );
4401        })
4402    });
4403    ctx.get_scene().with_write(
4404        |tree: &mut SceneTree| {
4405            mark_theme_owned(tree, owned_nodes.as_slice());
4406            tree.attach_scope(portal, scope);
4407        },
4408        (),
4409    );
4410    portal
4411}
4412
4413/// Mounts the viewport-clamped scrollable floating 17-Scheme Theme Color Dropdown portal anchored beneath the topbar Palette icon button.
4414///
4415/// # Arguments
4416///
4417/// - `&DocsViewerState` - Shared documentation viewer state.
4418/// - `ThemeTokens` - Base design tokens.
4419/// - `Vec<NodeId>` - Desktop and Mobile Palette trigger node handles.
4420///
4421/// # Returns
4422///
4423/// - `NodeId` - Mounted floating 17-scheme dropdown portal handle.
4424fn mount_docs_scheme_dropdown_portal(
4425    state: &DocsViewerState,
4426    tokens: ThemeTokens,
4427    triggers: Vec<NodeId>,
4428) -> NodeId {
4429    let mut ctx: Context = current_context();
4430    let open_sig: Signal<bool> = state.get_scheme_menu_open();
4431    let scheme_sig: Signal<DesignScheme> = state.get_theme().get_scheme();
4432    let mode_sig: Signal<ThemeMode> = state.get_theme().get_mode();
4433    let vp_sig: Signal<Size> = ctx.get_viewport_size();
4434    let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
4435    let init_tok: ThemeTokens = live_tokens_untracked(tokens);
4436    let palette: ThemePalette = init_tok.get_palette();
4437    let geometry: ThemeGeometry = init_tok.get_geometry();
4438    let card_s: SurfaceColors = palette.surface(SurfaceRole::Card);
4439    let menu_r: f32 = geometry.get_radius_lg();
4440    let item_r: f32 = concentric_radius(menu_r, CONTROL_INSET);
4441    let all_schemes: [DesignScheme; 17] = DesignScheme::all();
4442    let init_scheme: DesignScheme = scheme_sig.get_untracked();
4443    let init_mode: ThemeMode = mode_sig.get_untracked();
4444    let hovered_idx: Signal<Option<usize>> = Signal::new(None);
4445    let mut item_handles: Vec<(DesignScheme, NodeId, NodeId, NodeId, NodeId)> =
4446        Vec::with_capacity(all_schemes.len());
4447    let mut item_nodes: Vec<NodeId> = Vec::with_capacity(all_schemes.len());
4448    for (idx, scheme) in all_schemes.into_iter().enumerate() {
4449        let is_sel: bool = scheme == init_scheme;
4450        let (init_bg, init_fg): (Color, Color) = if is_sel {
4451            let ps: SurfaceColors = palette.surface(SurfaceRole::Primary);
4452            (ps.get_bg(), ps.get_fg())
4453        } else {
4454            (COLOR_TRANSPARENT, card_s.get_fg())
4455        };
4456        let init_swatch: Color = ThemeTokens::resolve(scheme, init_mode)
4457            .get_palette()
4458            .get_primary();
4459        let lbl_str: &'static str = docs_scheme_display_label(scheme);
4460        let on_pick_scheme = move |_: &UiEvent| {
4461            let _: bool = scheme_sig.set_if_changed(scheme);
4462            let _: bool = open_sig.set_if_changed(false);
4463        };
4464        let paint_check = move |bounds: Rect, display_list: &mut DisplayList| {
4465            if scheme_sig.get_untracked() == scheme {
4466                let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
4467                let fg: Color = lp.surface(SurfaceRole::Primary).get_fg();
4468                draw_euv_icon(EuvIconName::Check, bounds, display_list, fg);
4469            }
4470        };
4471        let mut dot_id: NodeId = NodeId::default();
4472        let mut txt_id: NodeId = NodeId::default();
4473        let mut chk_id: NodeId = NodeId::default();
4474        let row_fifth_style: Style = style! {
4475            Width(Length::Percent(100.0))
4476            Height(Length::Px(DOCS_DROPDOWN_ITEM_HEIGHT))
4477            Padding(Edges::symmetric(0.0, SPACE_SM))
4478            AlignItems::Center
4479            Gap(SPACE_SM)
4480            Background(init_bg)
4481            Radius(item_r)
4482            Overflow::Hidden
4483            CursorIcon::Pointer
4484            StopEventPropagation(true)
4485        };
4486        let view_style: Style = style! {
4487            Width(Length::Px(12.0))
4488            Height(Length::Px(12.0))
4489            FlexShrink(0.0)
4490            Background(init_swatch)
4491            Border::new(1.0, palette.get_border())
4492            Radius(RADIUS_PILL)
4493        };
4494        let text_style: Style = style! {
4495            FlexGrow(1.0)
4496            FlexShrink(1.0)
4497            MinWidth(Length::Px(0.0))
4498            FontSize(13.0)
4499            if is_sel { FontWeight::SemiBold } else { FontWeight::Normal }
4500            TextColor(init_fg)
4501            Overflow::Hidden
4502            TextOverflow::Ellipsis
4503        };
4504        let canvas_quaternary_style: Style = style! {
4505            Width(Length::Px(13.0))
4506            Height(Length::Px(13.0))
4507            FlexShrink(0.0)
4508        };
4509        let row_id: NodeId = view! {
4510            row {
4511                style: row_fifth_style
4512                role: A11yRole::MenuItem
4513                a11y_label: lbl_str.to_string()
4514                on_click: on_pick_scheme
4515                view {
4516                    node_ref: dot_id
4517                    style: view_style
4518                }
4519                text {
4520                    node_ref: txt_id
4521                    style: text_style
4522                    { lbl_str }
4523                }
4524                canvas {
4525                    node_ref: chk_id
4526                    style: canvas_quaternary_style
4527                    painter: paint_check
4528                }
4529            }
4530        };
4531        ctx.on_pointer_enter(row_id, move |_: &UiEvent| {
4532            let _: bool = hovered_idx.set_if_changed(Some(idx));
4533        });
4534        ctx.on_pointer_leave(row_id, move |_: &UiEvent| {
4535            if hovered_idx.get_untracked() == Some(idx) {
4536                let _: bool = hovered_idx.set_if_changed(None);
4537            }
4538        });
4539        item_handles.push((scheme, row_id, dot_id, txt_id, chk_id));
4540        item_nodes.push(row_id);
4541    }
4542    let mut card: NodeId = NodeId::default();
4543    let mut scroll_list: NodeId = NodeId::default();
4544    let portal_style: Style = style! {
4545        Display::None
4546        Position::Fixed
4547        Inset(Some(0.0), Some(0.0), Some(0.0), Some(0.0))
4548        Width(Length::Percent(100.0))
4549        Height(Length::Percent(100.0))
4550        Background(COLOR_TRANSPARENT)
4551        PointerEvents::None
4552        StopScrollPropagation(true)
4553        ZIndex(DOCS_DROPDOWN_Z_INDEX)
4554    };
4555    let column_secondary_style: Style = style! {
4556        Position::Absolute
4557        Inset(Some(SHELL_DESKTOP_HEADER_HEIGHT + 6.0), None, None, Some(8.0))
4558        Width(Length::Px(DOCS_SCHEME_MENU_WIDTH))
4559        Padding(Edges::all(CONTROL_INSET))
4560        Background(card_s.get_bg())
4561        Border::new(geometry.get_border_width(), card_s.get_border())
4562        Radius(menu_r)
4563        geometry.get_shadow_lg()
4564        Overflow::Hidden
4565        StopEventPropagation(true)
4566    };
4567    let scroll_style: Style = style! {
4568        FlexDirection::Column
4569        Width(Length::Percent(100.0))
4570        MaxHeight(Length::Px(DOCS_DROPDOWN_MAX_HEIGHT))
4571        Gap(CONTROL_INSET)
4572    };
4573    let portal: NodeId = view! {
4574        portal {
4575            style: portal_style
4576            column {
4577                node_ref: card
4578                style: column_secondary_style
4579                role: A11yRole::Menu
4580                a11y_label: BTN_SCHEME_A11Y.to_string()
4581                scroll {
4582                    node_ref: scroll_list
4583                    style: scroll_style
4584                    ..item_nodes
4585                }
4586            }
4587        }
4588    };
4589    ctx.on_click(portal, move |ui_event: &UiEvent| {
4590        if ui_event.get_target() == portal {
4591            let _: bool = open_sig.set_if_changed(false);
4592        }
4593    });
4594    for key_target in [portal, card].into_iter() {
4595        ctx.on_key(key_target, move |interaction_event: &UiEvent| {
4596            let is_esc: bool = matches!(
4597                interaction_event.get_kind(),
4598                UiEventKind::KeyDown(KeyCode::Escape, _)
4599            ) || matches!(
4600                interaction_event.get_kind(),
4601                UiEventKind::KeyDown(KeyCode::Back, _)
4602            );
4603            if is_esc && open_sig.get_untracked() {
4604                let _: bool = open_sig.set_if_changed(false);
4605            }
4606        });
4607    }
4608    let sc_pos: SceneHandle = ctx.get_scene().clone();
4609    let sc_paint: SceneHandle = sc_pos.clone();
4610    let owned_nodes: Vec<NodeId> = {
4611        let mut target_node_id: Vec<NodeId> = Vec::with_capacity(item_handles.len() * 4 + 3);
4612        target_node_id.push(portal);
4613        target_node_id.push(card);
4614        target_node_id.push(scroll_list);
4615        for &(_, rid, did, tid, cid) in item_handles.iter() {
4616            target_node_id.push(rid);
4617            target_node_id.push(did);
4618            target_node_id.push(tid);
4619            target_node_id.push(cid);
4620        }
4621        target_node_id
4622    };
4623    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4624        let _: Effect =
4625            EuvOverlayStack::bind_signal(open_sig, DOCS_SCHEME_OVERLAY_NAME, DOCS_DROPDOWN_Z_INDEX);
4626        let _: Effect = Effect::new(move || {
4627            let is_open: bool = open_sig.get();
4628            let box_size: Size = vp_sig.get();
4629            let safe: SafeAreaInsets = safe_sig.get();
4630            let (left, top, width, max_h): (f32, f32, f32, f32) = docs_dropdown_anchor_rect(
4631                &sc_pos,
4632                &triggers,
4633                box_size,
4634                safe,
4635                DOCS_SCHEME_MENU_WIDTH,
4636                DOCS_DROPDOWN_MAX_HEIGHT,
4637            );
4638            if !is_open {
4639                let _: bool = hovered_idx.set_if_changed(None);
4640            }
4641            let inner_max_h: f32 = (max_h - CONTROL_INSET * 2.0).max(96.0);
4642            sc_pos.with_write(
4643                |tree: &mut SceneTree| {
4644                    let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4645                    let dirty_all: u16 = dirty_l | DIRTY_PAINT;
4646                    if let Some(item_count) = tree.get_node_mut(scroll_list) {
4647                        item_count
4648                            .get_mut_style()
4649                            .get_mut_layout()
4650                            .set_max_height(Length::Px(inner_max_h));
4651                        tree.mark_dirty(scroll_list, dirty_all);
4652                    }
4653                    if let Some(node_entry) = tree.get_node_mut(card) {
4654                        let lay: &mut LayoutStyle = node_entry.get_mut_style().get_mut_layout();
4655                        lay.set_left(Some(left))
4656                            .set_top(Some(top))
4657                            .set_width(Length::Px(width));
4658                        tree.mark_dirty(card, dirty_all);
4659                    }
4660                    if let Some(normal_vec) = tree.get_node_mut(portal) {
4661                        let computed_style: &mut Style = normal_vec.get_mut_style();
4662                        computed_style.get_mut_layout().set_display(if is_open {
4663                            Display::Flex
4664                        } else {
4665                            Display::None
4666                        });
4667                        computed_style
4668                            .get_mut_paint()
4669                            .set_pointer_events(if is_open {
4670                                PointerEvents::Auto
4671                            } else {
4672                                PointerEvents::None
4673                            });
4674                        tree.mark_dirty(portal, dirty_all);
4675                    }
4676                },
4677                (),
4678            );
4679        });
4680        Effect::new(move || {
4681            let cur_scheme: DesignScheme = scheme_sig.get();
4682            let cur_mode: ThemeMode = mode_sig.get();
4683            let hov: Option<usize> = hovered_idx.get();
4684            let tok: ThemeTokens = use_live_tokens(tokens);
4685            let lp: ThemePalette = tok.get_palette();
4686            let lg: ThemeGeometry = tok.get_geometry();
4687            let cs: SurfaceColors = lp.surface(SurfaceRole::Card);
4688            let ps: SurfaceColors = lp.surface(SurfaceRole::Primary);
4689            let ac: SurfaceColors = lp.surface(SurfaceRole::Accent);
4690            sc_paint.with_write(
4691                |tree: &mut SceneTree| {
4692                    if let Some(total_len) = tree.get_node_mut(card) {
4693                        total_len
4694                            .get_mut_style()
4695                            .get_mut_paint()
4696                            .set_background(Some(cs.get_bg()))
4697                            .set_border(Border::new(lg.get_border_width(), cs.get_border()))
4698                            .set_shadow(Some(lg.get_shadow_lg()));
4699                        tree.mark_dirty(card, DIRTY_PAINT);
4700                    }
4701                    for (idx, &(sc_item, rid, did, tid, cid)) in item_handles.iter().enumerate() {
4702                        let is_sel: bool = sc_item == cur_scheme;
4703                        let is_hov: bool = hov == Some(idx);
4704                        let (bg, fg): (Color, Color) = if is_sel {
4705                            (ps.get_bg(), ps.get_fg())
4706                        } else if is_hov {
4707                            (ac.get_bg(), ac.get_fg())
4708                        } else {
4709                            (COLOR_TRANSPARENT, cs.get_fg())
4710                        };
4711                        let sw_col: Color = ThemeTokens::resolve(sc_item, cur_mode)
4712                            .get_palette()
4713                            .get_primary();
4714                        let sw_border: Color = if is_sel {
4715                            ps.get_fg().with_alpha(160)
4716                        } else {
4717                            lp.get_border()
4718                        };
4719                        if let Some(item_count_primary) = tree.get_node_mut(rid) {
4720                            item_count_primary
4721                                .get_mut_style()
4722                                .get_mut_paint()
4723                                .set_background(Some(bg));
4724                            tree.mark_dirty(rid, DIRTY_PAINT);
4725                        }
4726                        if let Some(item_count_secondary) = tree.get_node_mut(did) {
4727                            item_count_secondary
4728                                .get_mut_style()
4729                                .get_mut_paint()
4730                                .set_background(Some(sw_col))
4731                                .set_border(Border::new(1.0, sw_border));
4732                            tree.mark_dirty(did, DIRTY_PAINT);
4733                        }
4734                        if let Some(item_count_next) = tree.get_node_mut(tid) {
4735                            item_count_next
4736                                .get_mut_style()
4737                                .get_mut_text()
4738                                .set_color(fg)
4739                                .set_weight(if is_sel {
4740                                    FontWeight::SemiBold
4741                                } else {
4742                                    FontWeight::Normal
4743                                });
4744                            tree.mark_dirty(tid, DIRTY_PAINT);
4745                        }
4746                        tree.mark_dirty(cid, DIRTY_PAINT);
4747                    }
4748                },
4749                (),
4750            );
4751        })
4752    });
4753    ctx.get_scene().with_write(
4754        |tree: &mut SceneTree| {
4755            mark_theme_owned(tree, owned_nodes.as_slice());
4756            tree.attach_scope(portal, scope);
4757        },
4758        (),
4759    );
4760    portal
4761}
4762
4763/// 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`).
4764///
4765/// # Arguments
4766///
4767/// - `&DocsViewerState` - Shared reactive documentation viewer state.
4768///
4769/// # Returns
4770///
4771/// - `NodeId` - Mounted documentation application root handle.
4772pub fn mount_docs_viewer_with_state(state: &DocsViewerState) -> NodeId {
4773    provide_theme(state.get_theme().clone());
4774    ensure_docs_routes_registered(state);
4775    let tokens: ThemeTokens = untracked(|| state.get_theme().get_tokens().get());
4776    let active_route: Signal<String> = state.get_active_route();
4777    let cmd_open: Signal<bool> = state.get_cmd_open();
4778    let cmd_query: Signal<String> = state.get_cmd_query();
4779    let locale_open: Signal<bool> = state.get_locale_menu_open();
4780    let scheme_open: Signal<bool> = state.get_scheme_menu_open();
4781    let all_pages: &[DocPage] = state.get_site().get_pages().as_slice();
4782    let mut cmd_routes: Vec<String> = Vec::with_capacity(all_pages.len());
4783    let mut cmd_items: Vec<String> = Vec::with_capacity(all_pages.len() + 2);
4784    for page in all_pages.iter() {
4785        if !page.has_readable_content() {
4786            continue;
4787        }
4788        cmd_routes.push(page.get_route().clone());
4789        cmd_items.push(format!("{} — {}", page.get_title(), page.get_section()));
4790    }
4791    let toggle_idx: usize = cmd_items.len();
4792    cmd_items.push(CMD_ACTION_TOGGLE_MODE.to_string());
4793    let scheme_idx: usize = cmd_items.len();
4794    cmd_items.push(CMD_ACTION_NEXT_SCHEME.to_string());
4795    let cmd_sel: Signal<Option<usize>> = Signal::new(None);
4796    let cmd_list: NodeId = view! {
4797        EuvCommand {
4798            items: cmd_items
4799            selected: cmd_sel
4800            tokens: tokens
4801            query: cmd_query
4802            placeholder: CMD_PLACEHOLDER
4803            frameless: true
4804        }
4805    };
4806    let cmd_state: DocsViewerState = state.clone();
4807    let (cmd_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4808        Effect::new(move || {
4809            if let Some(idx) = cmd_sel.get() {
4810                if let Some(target) = cmd_routes.get(idx) {
4811                    let _: bool = active_route.set_if_changed(target.clone());
4812                } else if idx == toggle_idx {
4813                    cmd_state.toggle_theme_mode();
4814                } else if idx == scheme_idx {
4815                    cmd_state.next_scheme();
4816                }
4817                let _: bool = cmd_sel.set_if_changed(None);
4818                let _: bool = cmd_open.set_if_changed(false);
4819            }
4820        })
4821    });
4822    let cmd_modal: NodeId = view! {
4823        EuvModal {
4824            open: cmd_open
4825            title: CMD_MODAL_TITLE.to_string()
4826            body: cmd_list
4827            tokens: tokens
4828        }
4829    };
4830    let mut rctx: Context = current_context();
4831    let theme_memo: Memo<ThemeTokens> = state.get_theme().get_tokens();
4832    let prev_modal_tok: Rc<Cell<ThemeTokens>> = Rc::new(Cell::new(tokens));
4833    let modal_theme_ctx: Context = rctx.clone();
4834    let (modal_theme_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4835        Effect::new(move || {
4836            let next_tok: ThemeTokens = theme_memo.get();
4837            let old_tok: ThemeTokens = prev_modal_tok.replace(next_tok);
4838            if old_tok == next_tok {
4839                return;
4840            }
4841            modal_theme_ctx.get_scene().with_write(
4842                |tree: &mut SceneTree| {
4843                    remap_subtree_theme_in_place(tree, cmd_modal, old_tok, next_tok);
4844                },
4845                (),
4846            );
4847        })
4848    });
4849    rctx.get_scene().with_write(
4850        |tree: &mut SceneTree| {
4851            tree.attach_scope(cmd_modal, cmd_scope);
4852            tree.attach_scope(cmd_modal, modal_theme_scope);
4853        },
4854        (),
4855    );
4856    let router: EuvRouter = state.get_router().clone();
4857    let cur_route: String = active_route.get_untracked();
4858    if router.get_current_path().get_untracked() != cur_route {
4859        router.replace(&cur_route);
4860    }
4861    let breadcrumb_sig: Signal<String> = Signal::new(state.breadcrumb_for_route(&cur_route));
4862    let page_pad_sig: Signal<Edges> = Signal::new(Edges::all(SPACE_LG));
4863    let swipe_routes: Vec<String> = state.ordered_routes();
4864    let state_sync: DocsViewerState = state.clone();
4865    let router_sync_in: EuvRouter = router.clone();
4866    let router_path_sig: Signal<String> = router.get_current_path();
4867    let (sync_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4868        let _: Effect = Effect::new(move || {
4869            let target: String = active_route.get();
4870            let _: bool = breadcrumb_sig.set_if_changed(state_sync.breadcrumb_for_route(&target));
4871            if router_sync_in.get_current_path().get_untracked() != target {
4872                router_sync_in.push(&target);
4873            }
4874        });
4875        Effect::new(move || {
4876            let rp: String = router_path_sig.get();
4877            if active_route.get_untracked() != rp {
4878                let _: bool = active_route.set_if_changed(rp);
4879            }
4880        })
4881    });
4882    let state_fallback: DocsViewerState = state.clone();
4883    let outlet_node: NodeId = router
4884        .outlet(move |matched: &EuvRouteMatch| {
4885            let tok: ThemeTokens = untracked(|| state_fallback.get_theme().get_tokens().get());
4886            match state_fallback
4887                .get_site()
4888                .find_by_route(matched.get_path())
4889                .or_else(|| state_fallback.get_site().get_pages().first())
4890            {
4891                Some(point_val) => mount_doc_page_with_context(point_val, &state_fallback, tok),
4892                None => view! {
4893                    EuvEmpty {
4894                        title: EMPTY_PAGE_TITLE.to_string()
4895                        description: EMPTY_PAGE_MSG.to_string()
4896                        tokens: tok
4897                    }
4898                },
4899            }
4900        })
4901        .with_theme(state.get_theme().clone())
4902        .with_page_padding(page_pad_sig)
4903        .with_route_order(swipe_routes.clone())
4904        .mount();
4905    rctx.get_scene().with_write(
4906        |tree: &mut SceneTree| {
4907            tree.attach_scope(outlet_node, sync_scope);
4908        },
4909        (),
4910    );
4911    let sidebar_node: NodeId = mount_docs_catalog_tree(state, tokens);
4912    let theme_mode_sig: Signal<ThemeMode> = state.get_theme().get_mode();
4913    let has_multi_locales: bool = state.get_site().get_locales().len() > 1;
4914    let search_pill_lbl: &'static str = state.search_button_label();
4915    let icon_btn_style_desk = move || -> Style {
4916        let live_tok: ThemeTokens = use_live_tokens(tokens);
4917        let live_p: ThemePalette = live_tok.get_palette();
4918        let live_g: ThemeGeometry = live_tok.get_geometry();
4919        style! {
4920            FlexDirection::Row
4921            Width(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4922            Height(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4923            FlexShrink(0.0)
4924            JustifyContent::Center
4925            AlignItems::Center
4926            Background(live_p.get_background())
4927            Border::new(live_g.get_border_width(), live_p.get_border())
4928            Radius(live_g.get_radius_md())
4929            CursorIcon::Pointer
4930        }
4931    };
4932    let icon_btn_style_mob = move || -> Style {
4933        let live_tok: ThemeTokens = use_live_tokens(tokens);
4934        let live_p: ThemePalette = live_tok.get_palette();
4935        let live_g: ThemeGeometry = live_tok.get_geometry();
4936        style! {
4937            FlexDirection::Row
4938            Width(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4939            Height(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4940            FlexShrink(0.0)
4941            JustifyContent::Center
4942            AlignItems::Center
4943            Background(live_p.get_background())
4944            Border::new(live_g.get_border_width(), live_p.get_border())
4945            Radius(live_g.get_radius_md())
4946            CursorIcon::Pointer
4947        }
4948    };
4949    let search_pill_style = move || -> Style {
4950        let live_tok: ThemeTokens = use_live_tokens(tokens);
4951        let live_p: ThemePalette = live_tok.get_palette();
4952        let live_g: ThemeGeometry = live_tok.get_geometry();
4953        style! {
4954            FlexDirection::Row
4955            MinWidth(Length::Px(136.0))
4956            Height(Length::Px(SHELL_TOPBAR_CONTROL_HEIGHT))
4957            FlexShrink(0.0)
4958            Padding(Edges::symmetric(0.0, 10.0))
4959            JustifyContent::SpaceBetween
4960            AlignItems::Center
4961            Gap(SPACE_SM)
4962            Background(live_p.get_background())
4963            Border::new(live_g.get_border_width(), live_p.get_border())
4964            Radius(live_g.get_radius_md())
4965            CursorIcon::Pointer
4966        }
4967    };
4968    let search_lbl_style = move || -> Style {
4969        let live_p: ThemePalette = use_live_tokens(tokens).get_palette();
4970        style! {
4971            FontSize(12.5)
4972            TextColor(live_p.get_muted_foreground())
4973        }
4974    };
4975    let kbd_badge_style = move || -> Style {
4976        let live_tok: ThemeTokens = use_live_tokens(tokens);
4977        let live_p: ThemePalette = live_tok.get_palette();
4978        let live_g: ThemeGeometry = live_tok.get_geometry();
4979        style! {
4980            Padding(Edges::symmetric(1.0, 5.0))
4981            Background(live_p.get_muted())
4982            Border::new(live_g.get_border_width(), live_p.get_border())
4983            Radius(live_g.get_radius_sm())
4984            FontSize(11.0)
4985            TextColor(live_p.get_muted_foreground())
4986        }
4987    };
4988    let paint_search_desk = move |bounds: Rect, display_list: &mut DisplayList| {
4989        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4990        draw_docs_search_icon(bounds, display_list, live_p.get_muted_foreground());
4991    };
4992    let paint_search_mob = move |bounds: Rect, draw_commands: &mut DisplayList| {
4993        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4994        draw_docs_search_icon(bounds, draw_commands, live_p.get_foreground());
4995    };
4996    let paint_globe_desk = move |bounds: Rect, command_list: &mut DisplayList| {
4997        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4998        draw_docs_globe_icon(bounds, command_list, live_p.get_foreground());
4999    };
5000    let paint_globe_mob = move |bounds: Rect, display_list_primary: &mut DisplayList| {
5001        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
5002        draw_docs_globe_icon(bounds, display_list_primary, live_p.get_foreground());
5003    };
5004    let paint_scheme_desk = move |bounds: Rect, display_list_secondary: &mut DisplayList| {
5005        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
5006        draw_docs_palette_icon(
5007            bounds,
5008            display_list_secondary,
5009            live_p.get_foreground(),
5010            live_p.get_primary(),
5011        );
5012    };
5013    let paint_scheme_mob = move |bounds: Rect, display_list_next: &mut DisplayList| {
5014        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
5015        draw_docs_palette_icon(
5016            bounds,
5017            display_list_next,
5018            live_p.get_foreground(),
5019            live_p.get_primary(),
5020        );
5021    };
5022    let paint_mode_desk = move |bounds: Rect, display_list_alt: &mut DisplayList| {
5023        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
5024        match theme_mode_sig.get_untracked() {
5025            ThemeMode::Dark => {
5026                draw_docs_sun_icon(bounds, display_list_alt, live_p.get_foreground())
5027            }
5028            ThemeMode::Light => {
5029                draw_docs_moon_star_icon(bounds, display_list_alt, live_p.get_foreground())
5030            }
5031        }
5032    };
5033    let paint_mode_mob = move |bounds: Rect, display_list_inner: &mut DisplayList| {
5034        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
5035        match theme_mode_sig.get_untracked() {
5036            ThemeMode::Dark => {
5037                draw_docs_sun_icon(bounds, display_list_inner, live_p.get_foreground())
5038            }
5039            ThemeMode::Light => {
5040                draw_docs_moon_star_icon(bounds, display_list_inner, live_p.get_foreground())
5041            }
5042        }
5043    };
5044    let st_mode_desk: DocsViewerState = state.clone();
5045    let st_mode_mob: DocsViewerState = state.clone();
5046    let on_open_cmd_desk = move |_: &UiEvent| {
5047        let _: bool = locale_open.set_if_changed(false);
5048        let _: bool = scheme_open.set_if_changed(false);
5049        let _: bool = cmd_open.set_if_changed(true);
5050    };
5051    let on_open_cmd_mob = move |_: &UiEvent| {
5052        let _: bool = locale_open.set_if_changed(false);
5053        let _: bool = scheme_open.set_if_changed(false);
5054        let _: bool = cmd_open.set_if_changed(true);
5055    };
5056    let on_toggle_locale_desk = move |_: &UiEvent| {
5057        let next: bool = !locale_open.get_untracked();
5058        let _: bool = scheme_open.set_if_changed(false);
5059        let _: bool = locale_open.set_if_changed(next);
5060    };
5061    let on_toggle_locale_mob = move |_: &UiEvent| {
5062        let next: bool = !locale_open.get_untracked();
5063        let _: bool = scheme_open.set_if_changed(false);
5064        let _: bool = locale_open.set_if_changed(next);
5065    };
5066    let on_toggle_scheme_desk = move |_: &UiEvent| {
5067        let next: bool = !scheme_open.get_untracked();
5068        let _: bool = locale_open.set_if_changed(false);
5069        let _: bool = scheme_open.set_if_changed(next);
5070    };
5071    let on_toggle_scheme_mob = move |_: &UiEvent| {
5072        let next: bool = !scheme_open.get_untracked();
5073        let _: bool = locale_open.set_if_changed(false);
5074        let _: bool = scheme_open.set_if_changed(next);
5075    };
5076    let on_toggle_mode_desk = move |_: &UiEvent| {
5077        st_mode_desk.toggle_theme_mode();
5078    };
5079    let on_toggle_mode_mob = move |_: &UiEvent| {
5080        st_mode_mob.toggle_theme_mode();
5081    };
5082    let mut locale_btn_desk: NodeId = NodeId::default();
5083    let mut locale_btn_mob: NodeId = NodeId::default();
5084    let mut scheme_btn_desk: NodeId = NodeId::default();
5085    let mut scheme_btn_mob: NodeId = NodeId::default();
5086    let row_tertiary_style: Style = style! {
5087        Gap(SPACE_XS)
5088        AlignItems::Center
5089    };
5090    let row_quaternary_style: Style = style! {
5091        AlignItems::Center
5092        Gap(6.0)
5093    };
5094    let canvas_secondary_style: Style = style! {
5095        Width(Length::Px(15.0))
5096        Height(Length::Px(15.0))
5097        FlexShrink(0.0)
5098    };
5099    let canvas_tertiary_style: Style = style! {
5100        Width(Length::Px(DOCS_TOPBAR_ICON_SIZE))
5101        Height(Length::Px(DOCS_TOPBAR_ICON_SIZE))
5102    };
5103    let top_actions: NodeId = view! {
5104        row {
5105            style: row_tertiary_style
5106            row {
5107                bind_style: search_pill_style
5108                role: A11yRole::Button
5109                a11y_label: BTN_SEARCH_A11Y.to_string()
5110                on_click: on_open_cmd_desk
5111                row {
5112                    style: row_quaternary_style
5113                    canvas {
5114                        style: canvas_secondary_style
5115                        caching: CanvasCaching::RetainedStatic
5116                        painter: paint_search_desk
5117                    }
5118                    text {
5119                        bind_style: search_lbl_style
5120                        { search_pill_lbl }
5121                    }
5122                }
5123                text {
5124                    bind_style: kbd_badge_style
5125                    { DOCS_SEARCH_SHORTCUT_HINT }
5126                }
5127            }
5128            if has_multi_locales {
5129                row {
5130                    node_ref: locale_btn_desk
5131                    bind_style: icon_btn_style_desk
5132                    role: A11yRole::Button
5133                    a11y_label: BTN_LOCALE_A11Y.to_string()
5134                    on_click: on_toggle_locale_desk
5135                    canvas {
5136                        style: canvas_tertiary_style
5137                        caching: CanvasCaching::RetainedStatic
5138                        painter: paint_globe_desk
5139                    }
5140                }
5141            }
5142            row {
5143                node_ref: scheme_btn_desk
5144                bind_style: icon_btn_style_desk
5145                role: A11yRole::Button
5146                a11y_label: BTN_SCHEME_A11Y.to_string()
5147                on_click: on_toggle_scheme_desk
5148                canvas {
5149                    style: canvas_tertiary_style
5150                    caching: CanvasCaching::RetainedStatic
5151                    painter: paint_scheme_desk
5152                }
5153            }
5154            row {
5155                bind_style: icon_btn_style_desk
5156                role: A11yRole::Button
5157                a11y_label: BTN_MODE_A11Y.to_string()
5158                on_click: on_toggle_mode_desk
5159                canvas {
5160                    style: canvas_tertiary_style
5161                    caching: CanvasCaching::RetainedStatic
5162                    painter: paint_mode_desk
5163                }
5164            }
5165        }
5166    };
5167    let row_secondary_style: Style = style! {
5168        Gap(SPACE_XS)
5169        AlignItems::Center
5170    };
5171    let canvas_style: Style = style! {
5172        Width(Length::Px(DOCS_TOPBAR_ICON_SIZE))
5173        Height(Length::Px(DOCS_TOPBAR_ICON_SIZE))
5174    };
5175    let mobile_actions: NodeId = view! {
5176        row {
5177            style: row_secondary_style
5178            row {
5179                bind_style: icon_btn_style_mob
5180                role: A11yRole::Button
5181                a11y_label: BTN_SEARCH_A11Y.to_string()
5182                on_click: on_open_cmd_mob
5183                canvas {
5184                    style: canvas_style
5185                    caching: CanvasCaching::RetainedStatic
5186                    painter: paint_search_mob
5187                }
5188            }
5189            if has_multi_locales {
5190                row {
5191                    node_ref: locale_btn_mob
5192                    bind_style: icon_btn_style_mob
5193                    role: A11yRole::Button
5194                    a11y_label: BTN_LOCALE_A11Y.to_string()
5195                    on_click: on_toggle_locale_mob
5196                    canvas {
5197                        style: canvas_style
5198                        caching: CanvasCaching::RetainedStatic
5199                        painter: paint_globe_mob
5200                    }
5201                }
5202            }
5203            row {
5204                node_ref: scheme_btn_mob
5205                bind_style: icon_btn_style_mob
5206                role: A11yRole::Button
5207                a11y_label: BTN_SCHEME_A11Y.to_string()
5208                on_click: on_toggle_scheme_mob
5209                canvas {
5210                    style: canvas_style
5211                    caching: CanvasCaching::RetainedStatic
5212                    painter: paint_scheme_mob
5213                }
5214            }
5215            row {
5216                bind_style: icon_btn_style_mob
5217                role: A11yRole::Button
5218                a11y_label: BTN_MODE_A11Y.to_string()
5219                on_click: on_toggle_mode_mob
5220                canvas {
5221                    style: canvas_style
5222                    caching: CanvasCaching::RetainedStatic
5223                    painter: paint_mode_mob
5224                }
5225            }
5226        }
5227    };
5228    let bottom_items: Vec<EuvNavItem> = state.bottom_nav_items();
5229    let home_route_path: String = state.home_route();
5230    let catalog_open: Signal<bool> = state.get_catalog_drawer_open();
5231    let bnav_route: Signal<String> =
5232        Signal::new(if active_route.get_untracked() == home_route_path {
5233            home_route_path.clone()
5234        } else {
5235            DOCS_BNAV_CATALOG_ROUTE.to_string()
5236        });
5237    let home_for_bnav: String = home_route_path.clone();
5238    let home_for_sync: String = home_route_path.clone();
5239    let home_for_brand: String = home_route_path;
5240    let vp_for_drawer: Signal<Size> = rctx.get_viewport_size();
5241    let init_mobile_auto_hide: bool =
5242        vp_for_drawer.get_untracked().get_width() < DESKTOP_LAYOUT_BREAKPOINT;
5243    let auto_hide_chrome_sig: Signal<bool> = Signal::new(init_mobile_auto_hide);
5244    let (bnav_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
5245        let _: Effect = Effect::new(move || {
5246            let picked: String = bnav_route.get();
5247            if picked == DOCS_BNAV_CATALOG_ROUTE {
5248                let _: bool = catalog_open.set_if_changed(true);
5249            } else if picked == home_for_bnav {
5250                let _: bool = catalog_open.set_if_changed(false);
5251                if active_route.get_untracked() != home_for_bnav {
5252                    let _: bool = active_route.set_if_changed(home_for_bnav.clone());
5253                }
5254            }
5255        });
5256        let _: Effect = Effect::new(move || {
5257            let cur: String = active_route.get();
5258            let _: bool = catalog_open.set_if_changed(false);
5259            let next_tab: String = if cur == home_for_sync {
5260                home_for_sync.clone()
5261            } else {
5262                String::new()
5263            };
5264            if bnav_route.get_untracked() != next_tab {
5265                let _: bool = bnav_route.set_if_changed(next_tab);
5266            }
5267        });
5268        let _: Effect = Effect::new(move || {
5269            let open_now: bool = catalog_open.get();
5270            if !open_now && bnav_route.get_untracked() == DOCS_BNAV_CATALOG_ROUTE {
5271                let cur: String = active_route.get_untracked();
5272                let _: bool = bnav_route.set_if_changed(cur);
5273            }
5274        });
5275        Effect::new(move || {
5276            let box_size: Size = vp_for_drawer.get();
5277            let is_desktop: bool = box_size.get_width() >= DESKTOP_LAYOUT_BREAKPOINT;
5278            let _: bool = auto_hide_chrome_sig.set_if_changed(!is_desktop);
5279            if is_desktop {
5280                let _: bool = catalog_open.set_if_changed(false);
5281            }
5282        })
5283    });
5284    let bottom_nav_opt: Option<NodeId> = if bottom_items.len() >= 2 {
5285        Some(view! {
5286            EuvBottomNav {
5287                items: bottom_items
5288                active_route: bnav_route
5289                tokens: tokens
5290            }
5291        })
5292    } else {
5293        None
5294    };
5295    let brand_scene: SceneHandle = rctx.get_scene().clone();
5296    let on_brand_home = move |_: &UiEvent| {
5297        let _: bool = catalog_open.set_if_changed(false);
5298        let _: bool = locale_open.set_if_changed(false);
5299        let _: bool = scheme_open.set_if_changed(false);
5300        let _: bool = active_route.set_if_changed(home_for_brand.clone());
5301        brand_scene.with_write(
5302            |tree: &mut SceneTree| {
5303                reset_active_scroll_in_subtree(tree, outlet_node);
5304            },
5305            (),
5306        );
5307    };
5308    let mut shell: EuvAppShell = EuvAppShell::new(
5309        state.get_site().get_title().clone(),
5310        sidebar_node,
5311        outlet_node,
5312        tokens,
5313    )
5314    .route(active_route)
5315    .drawer_open(catalog_open)
5316    .brand_logo(euv_brand_logo_image())
5317    .auto_hide_chrome_on_scroll(init_mobile_auto_hide)
5318    .auto_hide_chrome_signal(auto_hide_chrome_sig)
5319    .on_brand_click(on_brand_home)
5320    .top_bar_actions(top_actions)
5321    .mobile_header_actions(mobile_actions)
5322    .breadcrumb(breadcrumb_sig)
5323    .swipe_routes(swipe_routes)
5324    .theme(state.get_theme().clone())
5325    .page_padding(page_pad_sig);
5326    if let Some(bnav) = bottom_nav_opt {
5327        shell = shell.bottom_nav(bnav);
5328    }
5329    state.get_outlet_root().set(outlet_node);
5330    let scroll_tick_sig: Signal<u64> = state.get_scroll_tick();
5331    let shell_node: NodeId = shell.mount();
5332    let hooked_page_scrolls: Rc<RefCell<Vec<NodeId>>> = Rc::new(RefCell::new(Vec::new()));
5333    let hook_scene: SceneHandle = rctx.get_scene().clone();
5334    let sync_state: DocsViewerState = state.clone();
5335    let sync_scene: SceneHandle = rctx.get_scene().clone();
5336    hook_outlet_page_scrolls(
5337        &hook_scene,
5338        outlet_node,
5339        &hooked_page_scrolls,
5340        scroll_tick_sig,
5341    );
5342    let (scroll_hook_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
5343        Effect::new(move || {
5344            let _: String = active_route.get();
5345            let _: bool = catalog_open.get();
5346            hook_outlet_page_scrolls(
5347                &hook_scene,
5348                outlet_node,
5349                &hooked_page_scrolls,
5350                scroll_tick_sig,
5351            );
5352            sync_state.get_pending_post_layout_sync().set(true);
5353            sync_docs_post_layout_positions(&sync_state, &sync_scene);
5354            notify_frame_needed();
5355        })
5356    });
5357    let locale_portal_opt: Option<NodeId> = if has_multi_locales {
5358        Some(mount_docs_locale_dropdown_portal(
5359            state,
5360            tokens,
5361            vec![locale_btn_desk, locale_btn_mob],
5362        ))
5363    } else {
5364        None
5365    };
5366    let scheme_portal: NodeId =
5367        mount_docs_scheme_dropdown_portal(state, tokens, vec![scheme_btn_desk, scheme_btn_mob]);
5368    rctx.get_scene().with_write(
5369        |tree: &mut SceneTree| {
5370            tree.attach_scope(shell_node, bnav_scope);
5371            tree.attach_scope(shell_node, scroll_hook_scope);
5372        },
5373        (),
5374    );
5375    let column_style: Style = style! {
5376        Width(Length::Percent(100.0))
5377        Height(Length::Percent(100.0))
5378    };
5379    let viewer_root: NodeId = view! {
5380        column {
5381            style: column_style
5382            { shell_node }
5383            { cmd_modal }
5384            if let Some(lp) = locale_portal_opt {
5385                { lp }
5386            }
5387            { scheme_portal }
5388        }
5389    };
5390    rctx.on_key(viewer_root, move |ui_event: &UiEvent| {
5391        if let UiEventKind::KeyDown(KeyCode::Character(ch), mods) = ui_event.get_kind()
5392            && (mods.get_meta() || mods.get_ctrl())
5393            && (*ch == 'k' || *ch == 'K')
5394        {
5395            let _: bool = locale_open.set_if_changed(false);
5396            let _: bool = scheme_open.set_if_changed(false);
5397            let _: bool = cmd_open.set_if_changed(true);
5398        }
5399    });
5400    viewer_root
5401}
5402
5403/// Mounts the cross-platform reactive showcase-parity documentation viewer for `site` using `euv-ui`.
5404///
5405/// # Arguments
5406///
5407/// - `&DocSite` - Parsed documentation site.
5408/// - `Signal<String>` - Active route path signal.
5409/// - `Signal<String>` - Search query input signal.
5410/// - `ThemeTokens` - Active design tokens.
5411///
5412/// # Returns
5413///
5414/// - `NodeId` - Mounted reactive documentation shell node.
5415pub fn mount_docs_viewer(
5416    site: &DocSite,
5417    active_route: Signal<String>,
5418    search_query: Signal<String>,
5419    tokens: ThemeTokens,
5420) -> NodeId {
5421    let state: DocsViewerState =
5422        DocsViewerState::new(site.clone(), active_route, search_query, tokens);
5423    mount_docs_viewer_with_state(&state)
5424}
5425
5426/// Launches the documentation viewer app and steps one headless or native frame.
5427///
5428/// # Arguments
5429///
5430/// - `&DocSite` - Loaded documentation site.
5431/// - `bool` - When `true`, renders headlessly via `HeadlessPlatform`.
5432///
5433/// # Returns
5434///
5435/// - `Result<FrameStats, PlatformError>` - Frame render telemetry.
5436pub fn render_docs_smoke(site: &DocSite, headless: bool) -> Result<FrameStats, PlatformError> {
5437    render_docs_app(site, headless, false)
5438}
5439
5440/// Resolves the default `RenderConfig` for the documentation viewer (`Software` for deterministic headless captures; hardware-first direct GPU `Adaptive` with WebGL2/WebGPU fallback for live native & Web targets).
5441///
5442/// # Arguments
5443///
5444/// - `bool` - When `true`, returns the deterministic CPU software reference configuration.
5445///
5446/// # Returns
5447///
5448/// - `RenderConfig` - Selected documentation viewer rendering configuration.
5449#[must_use]
5450pub fn docs_default_render_config(headless: bool) -> RenderConfig {
5451    if headless {
5452        RenderConfig::software()
5453    } else {
5454        let mut config_spec: RenderConfig = RenderConfig::adaptive();
5455        config_spec.set_max_fps(0);
5456        config_spec
5457    }
5458}
5459
5460/// Launches the documentation viewer app in either single-frame or interactive event-loop mode.
5461///
5462/// # Arguments
5463///
5464/// - `&DocSite` - Loaded documentation site.
5465/// - `bool` - When `true`, renders headlessly via `HeadlessPlatform`.
5466/// - `bool` - When `true` and not headless, runs the interactive frame loop until window close.
5467///
5468/// # Returns
5469///
5470/// - `Result<FrameStats, PlatformError>` - Final rendered frame telemetry.
5471pub fn render_docs_app(
5472    site: &DocSite,
5473    headless: bool,
5474    interactive: bool,
5475) -> Result<FrameStats, PlatformError> {
5476    EuvOverlayStack::clear();
5477    reset_fullscreen_state();
5478    clear_provided_theme();
5479    let mut window_cfg: WindowConfig = WindowConfig::default();
5480    window_cfg
5481        .set_title(DOCS_WINDOW_TITLE.to_string())
5482        .set_size(DOCS_WINDOW_WIDTH, DOCS_WINDOW_HEIGHT)
5483        .set_render(docs_default_render_config(headless))
5484        .set_icon(Some(euv_brand_logo_image()));
5485    let mut app_cfg: AppConfig = AppConfig::default();
5486    app_cfg.set_window(window_cfg);
5487    let mut app: App = if headless {
5488        App::headless(app_cfg)?
5489    } else {
5490        App::new(app_cfg)?
5491    };
5492    let initial_route: String = site
5493        .get_pages()
5494        .first()
5495        .map(|point_val: &DocPage| point_val.get_route().clone())
5496        .unwrap_or_else(|| "/".to_string());
5497    let active_route: Signal<String> = Signal::new(initial_route);
5498    let search_query: Signal<String> = Signal::new(String::new());
5499    let tokens: ThemeTokens = ThemeTokens::resolve(active_feature_scheme(), ThemeMode::Light);
5500    let state: DocsViewerState =
5501        DocsViewerState::new(site.clone(), active_route, search_query, tokens);
5502    let mount_state: DocsViewerState = state.clone();
5503    let _: NodeId = app.mount(move || mount_docs_viewer_with_state(&mount_state));
5504    let limit: Option<u64> = if interactive && !headless {
5505        None
5506    } else {
5507        Some(1)
5508    };
5509    app.run_frames(limit)
5510}
5511
5512/// Resolves a candidate path or locale-prefixed path against `site` pages, normalizing duplicate slashes and `.html` suffixes.
5513///
5514/// # Arguments
5515///
5516/// - `&DocSite` - Loaded documentation site.
5517/// - `&str` - Raw path fragment or URL pathname candidate.
5518///
5519/// # Returns
5520///
5521/// - `Option<String>` - Matching canonical page route when found.
5522fn resolve_docs_candidate_path(site: &DocSite, raw_path: &str) -> Option<String> {
5523    let without_query: &str = raw_path.split(['?', '#']).next().unwrap_or("").trim();
5524    let mut segments: Vec<&str> = without_query
5525        .split('/')
5526        .filter(|seg: &&str| !seg.is_empty())
5527        .collect();
5528    if segments
5529        .last()
5530        .is_some_and(|last: &&str| last.eq_ignore_ascii_case(DOCS_SUFFIX_INDEX_HTML))
5531    {
5532        let _: Option<&str> = segments.pop();
5533    }
5534    let normalized_segments: Vec<String> = segments
5535        .into_iter()
5536        .map(|seg: &str| {
5537            seg.strip_suffix(DOCS_SUFFIX_HTML)
5538                .unwrap_or(seg)
5539                .to_string()
5540        })
5541        .filter(|seg: &String| !seg.is_empty())
5542        .collect();
5543    let candidate: String = if normalized_segments.is_empty() {
5544        "/".to_string()
5545    } else {
5546        format!("/{}", normalized_segments.join("/"))
5547    };
5548    if let Some(found) = site.resolve_readable_route(&candidate) {
5549        return Some(found);
5550    }
5551    if let Some(first_seg) = normalized_segments.first() {
5552        let active_locale: &str = site.get_locale_prefix().trim_matches('/');
5553        let matches_builtin: bool = DOCS_KNOWN_LOCALE_SEGMENTS
5554            .iter()
5555            .any(|loc: &&str| loc.eq_ignore_ascii_case(first_seg));
5556        let matches_active: bool =
5557            !active_locale.is_empty() && active_locale.eq_ignore_ascii_case(first_seg);
5558        let matches_configured: bool = site.get_locales().iter().any(|loc: &DocLocaleConfig| {
5559            let dir_match: bool = loc.get_dir().eq_ignore_ascii_case(first_seg);
5560            let pref_match: bool = loc
5561                .get_prefix()
5562                .trim_matches('/')
5563                .eq_ignore_ascii_case(first_seg);
5564            dir_match || pref_match
5565        });
5566        let is_known_locale: bool = [matches_builtin, matches_active, matches_configured]
5567            .into_iter()
5568            .any(|matched: bool| matched);
5569        if is_known_locale {
5570            let rest: &[String] = &normalized_segments[1..];
5571            let stripped: String = if rest.is_empty() {
5572                "/".to_string()
5573            } else {
5574                format!("/{}", rest.join("/"))
5575            };
5576            if let Some(found) = site.resolve_readable_route(&stripped) {
5577                return Some(found);
5578            }
5579        }
5580    }
5581    None
5582}
5583
5584/// Normalizes browser `location.hash` and `location.pathname` into a valid `DocSite` route and optional heading anchor slug.
5585///
5586/// # Arguments
5587///
5588/// - `&DocSite` - Loaded documentation site.
5589/// - `&str` - Raw `window.location.hash` value.
5590/// - `&str` - Raw `window.location.pathname` value.
5591///
5592/// # Returns
5593///
5594/// - `(String, Option<String>)` - Resolved canonical route path and optional heading anchor slug.
5595#[must_use]
5596pub fn normalize_docs_history_target(
5597    site: &DocSite,
5598    raw_hash: &str,
5599    raw_pathname: &str,
5600) -> (String, Option<String>) {
5601    let default_route: String = site
5602        .find_by_route("/")
5603        .or_else(|| site.get_pages().first())
5604        .map(|point_val: &DocPage| point_val.get_route().clone())
5605        .unwrap_or_else(|| "/".to_string());
5606    let path_fallback: String =
5607        resolve_docs_candidate_path(site, raw_pathname).unwrap_or_else(|| default_route.clone());
5608    let trimmed_hash: &str = raw_hash.trim().trim_start_matches('#').trim();
5609    if trimmed_hash.is_empty() {
5610        return (path_fallback, None);
5611    }
5612    if trimmed_hash.starts_with('/') {
5613        let (route_part, anchor_raw): (&str, Option<&str>) = match trimmed_hash.split_once('#') {
5614            Some((red_val, alpha_val)) => (red_val, Some(alpha_val)),
5615            None => (trimmed_hash, None),
5616        };
5617        let anchor: Option<String> = anchor_raw
5618            .map(str::trim)
5619            .filter(|first_val: &&str| !first_val.is_empty())
5620            .map(str::to_string);
5621        if route_part.trim_matches('/').is_empty() {
5622            return (path_fallback, anchor);
5623        }
5624        if let Some(found) = resolve_docs_candidate_path(site, route_part) {
5625            return (found, anchor);
5626        }
5627        return (default_route, None);
5628    }
5629    let (head_part, anchor_raw): (&str, Option<&str>) = match trimmed_hash.split_once('#') {
5630        Some((height_val, area_val)) => (height_val, Some(area_val)),
5631        None => (trimmed_hash, None),
5632    };
5633    let tail_anchor: Option<String> = anchor_raw
5634        .map(str::trim)
5635        .filter(|alpha_val_primary: &&str| !alpha_val_primary.is_empty())
5636        .map(str::to_string);
5637    if head_part.contains('/') {
5638        if let Some(found) = resolve_docs_candidate_path(site, head_part) {
5639            return (found, tail_anchor);
5640        }
5641        return (default_route, None);
5642    }
5643    (path_fallback, Some(head_part.to_string()))
5644}
5645
5646/// Applies an incoming browser history location (`popstate` / `hashchange`) to `app` and `state`, dismissing overlays and exiting fullscreen first.
5647///
5648/// # Arguments
5649///
5650/// - `&mut App` - Running documentation viewer application instance.
5651/// - `&DocsViewerState` - Shared reactive documentation viewer state.
5652/// - `&str` - Raw `window.location.hash` value.
5653/// - `&str` - Raw `window.location.pathname` value.
5654///
5655/// # Returns
5656///
5657/// - `String` - Normalized canonical documentation route applied to `state`.
5658pub fn apply_docs_history_navigation(
5659    app: &mut App,
5660    state: &DocsViewerState,
5661    raw_hash: &str,
5662    raw_pathname: &str,
5663) -> String {
5664    let (target_route, anchor): (String, Option<String>) =
5665        normalize_docs_history_target(state.get_site(), raw_hash, raw_pathname);
5666    let _: usize = EuvOverlayStack::dismiss_all();
5667    let _: bool = state.get_cmd_open().set_if_changed(false);
5668    if app.is_immersive_fullscreen() || is_fullscreen_active() || EuvOverlayStack::has_fullscreen()
5669    {
5670        let _: usize = sync_external_fullscreen_exit();
5671        app.set_immersive_fullscreen(false);
5672    }
5673    let _: bool = state
5674        .get_active_route()
5675        .set_if_changed(target_route.clone());
5676    let resolved_slug: String = anchor.clone().unwrap_or_else(|| {
5677        state
5678            .get_site()
5679            .find_by_route(&target_route)
5680            .and_then(|point_val: &DocPage| point_val.get_toc().first())
5681            .map(|it: &DocTocItem| it.get_slug().clone())
5682            .unwrap_or_default()
5683    });
5684    if let Ok(mut guard) = state.get_toc_click_lock().try_borrow_mut() {
5685        *guard = None;
5686    }
5687    let _: bool = state.get_active_toc_slug().set_if_changed(resolved_slug);
5688    let _: bool = state.get_pending_anchor_scroll().set_if_changed(anchor);
5689    let _: bool = state.get_pending_scroll_restore().set_if_changed(None);
5690    state.get_pending_post_layout_sync().set(true);
5691    target_route
5692}
5693
5694/// Synchronizes browser URL hash (`#<route>` or `#<route>#<anchor>`) without pushing redundant history entries or triggering reload loops.
5695///
5696/// # Arguments
5697///
5698/// - `&str` - Active canonical documentation route path.
5699/// - `Option<&str>` - Optional active TOC heading anchor slug.
5700pub(crate) fn sync_docs_browser_hash(route: &str, anchor: Option<&str>) {
5701    #[cfg(target_arch = "wasm32")]
5702    {
5703        if WEB_DOCS_SYNCING_FROM_HISTORY.with(Cell::get) {
5704            return;
5705        }
5706        let Some(win) = window() else {
5707            return;
5708        };
5709        let norm_route: String = if route.is_empty() || route == "/" {
5710            "/".to_string()
5711        } else if route.starts_with('/') {
5712            route.to_string()
5713        } else {
5714            format!("/{route}")
5715        };
5716        let clean_anchor: Option<&str> = anchor
5717            .map(|text_value: &str| text_value.trim().trim_start_matches('#').trim())
5718            .filter(|alpha_val: &&str| !alpha_val.is_empty());
5719        let target_hash: String = match clean_anchor {
5720            Some(slug) => format!("#{norm_route}#{slug}"),
5721            None => format!("#{norm_route}"),
5722        };
5723        if win.location().hash().ok().as_deref() == Some(target_hash.as_str()) {
5724            return;
5725        }
5726        let replaced: bool = win
5727            .history()
5728            .ok()
5729            .and_then(|hist: History| {
5730                hist.replace_state_with_url(&JsValue::NULL, "", Some(&target_hash))
5731                    .ok()
5732            })
5733            .is_some();
5734        if !replaced {
5735            let prev: bool =
5736                WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
5737            let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
5738            WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev));
5739        }
5740    }
5741    #[cfg(not(target_arch = "wasm32"))]
5742    let _: (&str, Option<&str>) = (route, anchor);
5743}
5744
5745/// Persists `(route, scroll_y, active_slug)` into browser `sessionStorage` (`DOCS_SCROLL_STORAGE_KEY`) so refreshing preserves reading position.
5746///
5747/// # Arguments
5748///
5749/// - `&str` - Active canonical route path.
5750/// - `f32` - Current vertical scroll offset in logical pixels.
5751/// - `&str` - Active TOC heading anchor slug.
5752pub(crate) fn persist_docs_scroll_state(route: &str, scroll_y: f32, active_slug: &str) {
5753    #[cfg(target_arch = "wasm32")]
5754    {
5755        if let Some(win) = window()
5756            && let Ok(Some(storage)) = win.session_storage()
5757        {
5758            let payload: String = format_docs_scroll_snapshot(route, scroll_y, active_slug);
5759            let _: Result<(), JsValue> = storage.set_item(DOCS_SCROLL_STORAGE_KEY, &payload);
5760        }
5761    }
5762    #[cfg(not(target_arch = "wasm32"))]
5763    let _: (&str, f32, &str) = (route, scroll_y, active_slug);
5764}
5765
5766/// Loads a previously persisted `(scroll_y, slug)` snapshot for `expected_route` from browser `sessionStorage`.
5767///
5768/// # Arguments
5769///
5770/// - `&str` - Canonical documentation route being restored.
5771///
5772/// # Returns
5773///
5774/// - `Option<(f32, Option<String>)>` - Saved scroll position and optional TOC slug when available.
5775#[cfg(target_arch = "wasm32")]
5776pub(crate) fn load_persisted_docs_scroll_state(
5777    expected_route: &str,
5778) -> Option<(f32, Option<String>)> {
5779    let win: Window = window()?;
5780    let storage: Storage = win.session_storage().ok()??;
5781    let raw: String = storage.get_item(DOCS_SCROLL_STORAGE_KEY).ok()??;
5782    parse_docs_scroll_snapshot(&raw, expected_route)
5783}
5784
5785/// Loads persisted unlocked documentation password secrets from browser `localStorage` (`"euv_docs_unlocked_v1"`).
5786///
5787/// # Returns
5788///
5789/// - `Vec<String>` - Previously unlocked password secrets, or an empty vector when unavailable.
5790pub(crate) fn load_persisted_unlocked_passwords() -> Vec<String> {
5791    #[cfg(target_arch = "wasm32")]
5792    {
5793        if let Some(win) = window()
5794            && let Ok(Some(storage)) = win.local_storage()
5795            && let Ok(Some(raw)) = storage.get_item(DOCS_UNLOCKED_STORAGE_KEY)
5796            && let Ok(parsed) = serde_json::from_str::<Vec<String>>(&raw)
5797        {
5798            return parsed;
5799        }
5800    }
5801    Vec::new()
5802}
5803
5804/// Persists unlocked documentation password secrets into browser `localStorage` (`"euv_docs_unlocked_v1"`).
5805///
5806/// # Arguments
5807///
5808/// - `&[String]` - Active list of unlocked password secrets.
5809pub(crate) fn persist_unlocked_passwords(list: &[String]) {
5810    #[cfg(target_arch = "wasm32")]
5811    {
5812        if let Some(win) = window()
5813            && let Ok(Some(storage)) = win.local_storage()
5814            && let Ok(encoded) = serde_json::to_string(list)
5815        {
5816            let _: Result<(), JsValue> = storage.set_item(DOCS_UNLOCKED_STORAGE_KEY, &encoded);
5817        }
5818    }
5819    #[cfg(not(target_arch = "wasm32"))]
5820    let _: usize = list.len();
5821}
5822
5823/// Synchronizes the running WebAssembly documentation viewer from browser `popstate` or `hashchange` and immediately repaints.
5824///
5825/// # Arguments
5826///
5827/// - `&Window` - Active browser `Window`.
5828#[cfg(target_arch = "wasm32")]
5829fn web_docs_sync_from_browser_history(win: &Window) {
5830    let raw_hash: String = win.location().hash().unwrap_or_default();
5831    let raw_pathname: String = win.location().pathname().unwrap_or_default();
5832    let prev_guard: bool =
5833        WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
5834    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5835        if let Ok(mut borrow) = slot.try_borrow_mut()
5836            && let Some((app, state)) = borrow.as_mut()
5837        {
5838            let _: String = apply_docs_history_navigation(app, state, &raw_hash, &raw_pathname);
5839            let _: Result<FrameStats, PlatformError> = app.step_frame();
5840            state.get_pending_post_layout_sync().set(false);
5841            state.sync_post_layout_positions(app.get_scene());
5842            let _: Result<FrameStats, PlatformError> = app.step_frame();
5843        }
5844    });
5845    WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
5846}
5847
5848/// Extracts plain UTF-8 clipboard text from a browser `paste` DOM event.
5849///
5850/// # Arguments
5851///
5852/// - `&web_sys::Event` - Browser DOM `paste` event.
5853///
5854/// # Returns
5855///
5856/// - `Option<String>` - Non-empty pasted text when available.
5857#[cfg(target_arch = "wasm32")]
5858fn web_docs_extract_paste_text(ui_event: &web_sys::Event) -> Option<String> {
5859    let data: JsValue = Reflect::get(
5860        ui_event.as_ref(),
5861        &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA),
5862    )
5863    .ok()?;
5864    if data.is_null() || data.is_undefined() {
5865        return None;
5866    }
5867    let get_fn_val: JsValue = Reflect::get(&data, &JsValue::from_str(WEB_PROP_GET_DATA)).ok()?;
5868    let get_fn: Function = get_fn_val.dyn_into::<Function>().ok()?;
5869    let result: JsValue = get_fn
5870        .call1(&data, &JsValue::from_str(WEB_MIME_TEXT_PLAIN))
5871        .ok()?;
5872    result
5873        .as_string()
5874        .filter(|text_value: &String| !text_value.is_empty())
5875}
5876
5877/// Returns `true` when the browser document currently has a standard or WebKit fullscreen element active.
5878///
5879/// # Arguments
5880///
5881/// - `&Document` - Active browser `Document`.
5882///
5883/// # Returns
5884///
5885/// - `bool` - `true` while browser fullscreen mode is active.
5886#[cfg(target_arch = "wasm32")]
5887fn web_docs_doc_is_fullscreen(doc: &Document) -> bool {
5888    if doc.fullscreen_element().is_some() {
5889        return true;
5890    }
5891    Reflect::get(
5892        doc.as_ref(),
5893        &JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
5894    )
5895    .ok()
5896    .map(|item_val: JsValue| !item_val.is_null() && !item_val.is_undefined())
5897    .unwrap_or(false)
5898}
5899
5900/// Attaches browser `popstate`, `hashchange`, `pageshow`, `blur`, `touchcancel`, `paste`, `fullscreenchange`, and color-scheme listeners once for the docs viewer.
5901///
5902/// # Arguments
5903///
5904/// - `&Window` - Active browser `Window`.
5905#[cfg(target_arch = "wasm32")]
5906fn web_docs_attach_browser_listeners(win: &Window) {
5907    let already_attached: bool =
5908        WEB_DOCS_LISTENERS_ATTACHED.with(|flag: &Cell<bool>| flag.replace(true));
5909    if already_attached {
5910        return;
5911    }
5912    let win_hist: Window = win.clone();
5913    let on_history: Closure<dyn FnMut(web_sys::Event)> =
5914        Closure::wrap(Box::new(move |_: web_sys::Event| {
5915            web_docs_sync_from_browser_history(&win_hist);
5916        }) as Box<dyn FnMut(web_sys::Event)>);
5917    drop(win.add_event_listener_with_callback(
5918        WEB_EVENT_POP_STATE,
5919        on_history.as_ref().unchecked_ref(),
5920    ));
5921    drop(win.add_event_listener_with_callback(
5922        WEB_EVENT_HASH_CHANGE,
5923        on_history.as_ref().unchecked_ref(),
5924    ));
5925    drop(win.add_event_listener_with_callback(
5926        WEB_EVENT_PAGE_SHOW,
5927        on_history.as_ref().unchecked_ref(),
5928    ));
5929    on_history.forget();
5930    let on_cancel: Closure<dyn FnMut(web_sys::Event)> =
5931        Closure::wrap(Box::new(move |_: web_sys::Event| {
5932            WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5933                if let Ok(mut borrow) = slot.try_borrow_mut()
5934                    && let Some((app, _)) = borrow.as_mut()
5935                {
5936                    let wid: WindowId = app.get_window_state().get_id();
5937                    app.dispatch_window_event(WindowEvent::PointerCancel(wid, 0));
5938                    let _: Result<FrameStats, PlatformError> = app.step_frame();
5939                }
5940            });
5941        }) as Box<dyn FnMut(web_sys::Event)>);
5942    drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_cancel.as_ref().unchecked_ref()));
5943    drop(win.add_event_listener_with_callback(
5944        WEB_EVENT_TOUCH_CANCEL,
5945        on_cancel.as_ref().unchecked_ref(),
5946    ));
5947    on_cancel.forget();
5948    let on_paste: Closure<dyn FnMut(web_sys::Event)> =
5949        Closure::wrap(Box::new(move |ui_event: web_sys::Event| {
5950            if let Some(pasted) = web_docs_extract_paste_text(&ui_event) {
5951                ui_event.prevent_default();
5952                WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5953                    if let Ok(mut borrow) = slot.try_borrow_mut()
5954                        && let Some((app, _)) = borrow.as_mut()
5955                    {
5956                        let wid: WindowId = app.get_window_state().get_id();
5957                        app.dispatch_window_event(WindowEvent::TextInput(wid, pasted));
5958                        let _: Result<FrameStats, PlatformError> = app.step_frame();
5959                    }
5960                });
5961            }
5962        }) as Box<dyn FnMut(web_sys::Event)>);
5963    drop(win.add_event_listener_with_callback(WEB_EVENT_PASTE, on_paste.as_ref().unchecked_ref()));
5964    on_paste.forget();
5965    if let Some(doc) = win.document() {
5966        let doc_fs: Document = doc.clone();
5967        let on_fs: Closure<dyn FnMut(web_sys::Event)> =
5968            Closure::wrap(Box::new(move |_: web_sys::Event| {
5969                if !web_docs_doc_is_fullscreen(&doc_fs) {
5970                    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
5971                        if let Ok(mut borrow) = slot.try_borrow_mut()
5972                            && let Some((app, _)) = borrow.as_mut()
5973                            && (app.is_immersive_fullscreen()
5974                                || is_fullscreen_active()
5975                                || EuvOverlayStack::has_fullscreen())
5976                        {
5977                            let _: usize = sync_external_fullscreen_exit();
5978                            app.set_immersive_fullscreen(false);
5979                            let wid: WindowId = app.get_window_state().get_id();
5980                            let measured: SafeAreaInsets = web_query_safe_area_insets();
5981                            app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, measured));
5982                            web_docs_wake_raf();
5983                        }
5984                    });
5985                }
5986            }) as Box<dyn FnMut(web_sys::Event)>);
5987        drop(doc.add_event_listener_with_callback(
5988            WEB_EVENT_FULLSCREEN_CHANGE,
5989            on_fs.as_ref().unchecked_ref(),
5990        ));
5991        drop(doc.add_event_listener_with_callback(
5992            WEB_EVENT_WEBKIT_FULLSCREEN_CHANGE,
5993            on_fs.as_ref().unchecked_ref(),
5994        ));
5995        on_fs.forget();
5996    }
5997    if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
5998        let mql_cb: MediaQueryList = mql.clone();
5999        let on_theme: Closure<dyn FnMut(web_sys::Event)> =
6000            Closure::wrap(Box::new(move |_: web_sys::Event| {
6001                let next_theme: ThemeMode = if mql_cb.matches() {
6002                    ThemeMode::Dark
6003                } else {
6004                    ThemeMode::Light
6005                };
6006                WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6007                    if let Ok(mut borrow) = slot.try_borrow_mut()
6008                        && let Some((app, _)) = borrow.as_mut()
6009                    {
6010                        let wid: WindowId = app.get_window_state().get_id();
6011                        app.dispatch_window_event(WindowEvent::ThemeChanged(wid, next_theme));
6012                        web_docs_wake_raf();
6013                    }
6014                });
6015            }) as Box<dyn FnMut(web_sys::Event)>);
6016        drop(
6017            mql.add_event_listener_with_callback(
6018                WEB_EVENT_CHANGE,
6019                on_theme.as_ref().unchecked_ref(),
6020            ),
6021        );
6022        on_theme.forget();
6023    }
6024}
6025
6026/// Boots the persistent WebAssembly showcase-parity documentation viewer from a serialized `DocSite` JSON bundle.
6027///
6028/// # Arguments
6029///
6030/// - `&str` - Compact UTF-8 JSON payload produced for the active locale bundle.
6031///
6032/// # Returns
6033///
6034/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
6035#[cfg(target_arch = "wasm32")]
6036pub fn boot_wasm_docs_bundle(bundle_json: &str) -> u64 {
6037    let site: DocSite = serde_json::from_str::<DocSite>(bundle_json).unwrap_or_else(|_| {
6038        DocSite::new(
6039            DOCS_SITE_TITLE.to_string(),
6040            DOCS_SITE_TAGLINE.to_string(),
6041            Vec::new(),
6042        )
6043    });
6044    boot_wasm_docs_site(site)
6045}
6046
6047/// Boots the persistent WebAssembly showcase-parity documentation viewer from a split plaintext shell and `EUVZ`-compressed bodies.
6048///
6049/// # Arguments
6050///
6051/// - `&str` - Compact plaintext `DocSite` shell JSON carrying metadata and TOC headings.
6052/// - `&[u8]` - `EUVZ`-compressed page body payload bytes.
6053///
6054/// # Returns
6055///
6056/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
6057#[cfg(target_arch = "wasm32")]
6058pub fn boot_wasm_docs_compressed_bundle(shell_json: &str, compressed_bodies: &[u8]) -> u64 {
6059    let site: DocSite = unpack_site_bundle(shell_json, compressed_bodies).unwrap_or_else(|_| {
6060        DocSite::new(
6061            DOCS_SITE_TITLE.to_string(),
6062            DOCS_SITE_TAGLINE.to_string(),
6063            Vec::new(),
6064        )
6065    });
6066    boot_wasm_docs_site(site)
6067}
6068
6069/// Mounts the hydrated `DocSite` into the persistent WebAssembly viewer runtime and renders the initial frame.
6070///
6071/// # Arguments
6072///
6073/// - `DocSite` - Hydrated documentation site for the active locale.
6074///
6075/// # Returns
6076///
6077/// - `u64` - Deterministic initial frame hash, or `0` on startup failure.
6078#[cfg(target_arch = "wasm32")]
6079fn boot_wasm_docs_site(site: DocSite) -> u64 {
6080    console_error_panic_hook::set_once();
6081    reset_reactive_runtime();
6082    register_frame_wakeup(web_docs_wake_raf);
6083    EuvOverlayStack::clear();
6084    reset_fullscreen_state();
6085    clear_provided_theme();
6086    let mut window_cfg: WindowConfig = WindowConfig::default();
6087    window_cfg
6088        .set_title(format!("{} · {EUV_DOCS_RELEASE_MARKER}", site.get_title()))
6089        .set_size(DOCS_WINDOW_WIDTH, DOCS_WINDOW_HEIGHT)
6090        .set_render(docs_default_render_config(false));
6091    let mut app_cfg: AppConfig = AppConfig::default();
6092    app_cfg.set_window(window_cfg);
6093    let mut app: App = match App::new(app_cfg) {
6094        Ok(alpha_val) => alpha_val,
6095        Err(_) => return 0,
6096    };
6097    let (initial_route, initial_anchor): (String, Option<String>) = if let Some(win) = window() {
6098        let raw_hash: String = win.location().hash().unwrap_or_default();
6099        let raw_pathname: String = win.location().pathname().unwrap_or_default();
6100        normalize_docs_history_target(&site, &raw_hash, &raw_pathname)
6101    } else {
6102        let fallback: String = site
6103            .get_pages()
6104            .first()
6105            .map(|point_val: &DocPage| point_val.get_route().clone())
6106            .unwrap_or_else(|| "/".to_string());
6107        (fallback, None)
6108    };
6109    let active_route: Signal<String> = Signal::new(initial_route.clone());
6110    let search_query: Signal<String> = Signal::new(String::new());
6111    let tokens: ThemeTokens = ThemeTokens::resolve(active_feature_scheme(), ThemeMode::Light);
6112    let state: DocsViewerState = DocsViewerState::new(site, active_route, search_query, tokens);
6113    if let Some(anchor) = initial_anchor {
6114        let _: bool = state.get_active_toc_slug().set_if_changed(anchor.clone());
6115        let _: bool = state
6116            .get_pending_anchor_scroll()
6117            .set_if_changed(Some(anchor));
6118    } else if let Some((saved_y, saved_slug)) =
6119        load_persisted_docs_scroll_state(initial_route.as_str())
6120    {
6121        if let Some(ref slug) = saved_slug {
6122            let _: bool = state.get_active_toc_slug().set_if_changed(slug.clone());
6123        }
6124        let _: bool = state
6125            .get_pending_scroll_restore()
6126            .set_if_changed(Some((saved_y, saved_slug)));
6127    }
6128    let has_home: bool = state
6129        .get_site()
6130        .get_pages()
6131        .iter()
6132        .any(|palette_val: &DocPage| palette_val.get_is_home());
6133    let mount_state: DocsViewerState = state.clone();
6134    let _: NodeId = app.mount(move || mount_docs_viewer_with_state(&mount_state));
6135    let route_watch: Signal<String> = state.get_active_route();
6136    let site_watch: Rc<DocSite> = state.get_site().clone();
6137    let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
6138        Effect::new(move || {
6139            let text_value: String = route_watch.get();
6140            if WEB_DOCS_SYNCING_FROM_HISTORY.with(Cell::get) {
6141                return;
6142            }
6143            if let Some(win) = window() {
6144                let raw_hash: String = win.location().hash().unwrap_or_default();
6145                let raw_pathname: String = win.location().pathname().unwrap_or_default();
6146                let (cur_route, _): (String, Option<String>) =
6147                    normalize_docs_history_target(&site_watch, &raw_hash, &raw_pathname);
6148                if cur_route != text_value {
6149                    let target_hash: String = format!("#{text_value}");
6150                    let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
6151                }
6152            }
6153        })
6154    });
6155    let root_id: NodeId = app
6156        .get_scene()
6157        .with_read(SceneTree::get_root, NodeId::default());
6158    app.get_scene().with_write(
6159        |tree: &mut SceneTree| {
6160            tree.attach_scope(root_id, hash_scope);
6161        },
6162        (),
6163    );
6164    let first_hash: u64 = app
6165        .step_frame()
6166        .map(|stats: FrameStats| stats.get_frame_hash())
6167        .unwrap_or(0);
6168    state.get_pending_post_layout_sync().set(false);
6169    state.sync_post_layout_positions(app.get_scene());
6170    let hash: u64 = app
6171        .step_frame()
6172        .map(|stats: FrameStats| stats.get_frame_hash())
6173        .unwrap_or(first_hash);
6174    let fetch_state: DocsViewerState = state.clone();
6175    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6176        if let Ok(mut borrow) = slot.try_borrow_mut() {
6177            *borrow = Some((app, state));
6178        }
6179    });
6180    if let Some(win) = window() {
6181        web_docs_attach_browser_listeners(&win);
6182    }
6183    if has_home {
6184        trigger_wasm_catalog_fetch(&fetch_state);
6185    }
6186    hash
6187}
6188
6189/// Switches the active route in the running WebAssembly documentation viewer and renders immediately.
6190///
6191/// # Arguments
6192///
6193/// - `&str` - Canonical route path.
6194///
6195/// # Returns
6196///
6197/// - `u64` - Rendered frame hash.
6198#[cfg(target_arch = "wasm32")]
6199pub fn wasm_docs_render_route(route: &str) -> u64 {
6200    let prev_guard: bool =
6201        WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
6202    let raw_pathname: String = window()
6203        .and_then(|win: Window| win.location().pathname().ok())
6204        .unwrap_or_default();
6205    let frame_hash: u64 =
6206        WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6207            let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut()
6208            {
6209                Ok(guard) => guard,
6210                Err(_) => return 0,
6211            };
6212            let Some((app, state)) = borrow.as_mut() else {
6213                return 0;
6214            };
6215            let _: String = apply_docs_history_navigation(app, state, route, &raw_pathname);
6216            let _: Result<FrameStats, PlatformError> = app.step_frame();
6217            state.get_pending_post_layout_sync().set(false);
6218            state.sync_post_layout_positions(app.get_scene());
6219            app.step_frame()
6220                .map(|stats: FrameStats| stats.get_frame_hash())
6221                .unwrap_or(0)
6222        });
6223    WEB_DOCS_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
6224    frame_hash
6225}
6226
6227/// Marks the WebAssembly documentation viewer dirty and wakes the demand-driven browser `requestAnimationFrame` driver when parked.
6228#[cfg(target_arch = "wasm32")]
6229fn web_docs_wake_raf() {
6230    WEB_DOCS_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.set(true));
6231    if let Some(win) = window()
6232        && let Ok(wake_val) = Reflect::get(&win, &JsValue::from_str(WEB_PROP_DOCS_WAKE))
6233        && let Ok(wake_fn) = wake_val.dyn_into::<Function>()
6234    {
6235        drop(wake_fn.call0(&win));
6236    }
6237}
6238
6239/// Returns the most recently rendered frame hash from the running WebAssembly documentation viewer without stepping a synchronous frame.
6240///
6241/// # Returns
6242///
6243/// - `u64` - Last rendered frame hash, or `0` when uninitialized.
6244#[cfg(target_arch = "wasm32")]
6245fn web_docs_last_frame_hash() -> u64 {
6246    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6247        let borrow: Ref<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow() {
6248            Ok(guard) => guard,
6249            Err(_) => return 0,
6250        };
6251        borrow
6252            .as_ref()
6253            .map(|(app, _): &(App, DocsViewerState)| {
6254                app.get_renderer().get_last_stats().get_frame_hash()
6255            })
6256            .unwrap_or(0)
6257    })
6258}
6259
6260/// Flushes coalesced resize, pointer-move, and scroll slots into `app` once at the start of an animation frame or before a discrete event.
6261///
6262/// # Arguments
6263///
6264/// - `&mut App` - Active WebAssembly documentation viewer application.
6265/// - `&DocsViewerState` - Shared reactive viewer state.
6266///
6267/// # Returns
6268///
6269/// - `bool` - `true` when at least one pending resize, move, or scroll input was applied.
6270#[cfg(target_arch = "wasm32")]
6271fn web_docs_flush_pending_inputs(app: &mut App, state: &DocsViewerState) -> bool {
6272    let mut applied: bool = false;
6273    let pending_resize: Option<(u32, u32, f32)> =
6274        WEB_DOCS_PENDING_RESIZE.with(|cell: &Cell<Option<(u32, u32, f32)>>| cell.take());
6275    if let Some((phys_w, phys_h, dpr)) = pending_resize {
6276        let scale: f32 = clamp_viewport_scale(dpr);
6277        let pw: u32 = phys_w.max(64);
6278        let ph: u32 = phys_h.max(64);
6279        if let Some(win) = window()
6280            && let Some(doc) = win.document()
6281            && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
6282            && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
6283        {
6284            if canvas.width() != pw {
6285                canvas.set_width(pw);
6286            }
6287            if canvas.height() != ph {
6288                canvas.set_height(ph);
6289            }
6290        }
6291        app.set_exact_physical_viewport(pw, ph, scale);
6292        app.get_scene().with_write(
6293            |tree: &mut SceneTree| {
6294                let root: NodeId = tree.get_root();
6295                let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
6296                tree.mark_dirty(root, dirty_l | DIRTY_PAINT);
6297            },
6298            (),
6299        );
6300        let measured_safe: SafeAreaInsets = web_query_safe_area_insets();
6301        let effective_safe: SafeAreaInsets = if app.is_immersive_fullscreen() {
6302            SafeAreaInsets::default()
6303        } else {
6304            measured_safe
6305        };
6306        let current_safe: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
6307        if current_safe != effective_safe {
6308            let wid: WindowId = app.get_window_state().get_id();
6309            app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective_safe));
6310        }
6311        state.get_pending_post_layout_sync().set(true);
6312        applied = true;
6313    }
6314    let pending_move: Option<(u32, bool, f32, f32, f32)> =
6315        WEB_DOCS_PENDING_MOVE.with(|cell: &Cell<Option<(u32, bool, f32, f32, f32)>>| cell.take());
6316    if let Some((pointer_id, is_touch, pos_x, pos_y, pressure)) = pending_move {
6317        let wid: WindowId = app.get_window_state().get_id();
6318        let device: PointerDevice = if is_touch {
6319            PointerDevice::Touch
6320        } else {
6321            PointerDevice::Mouse
6322        };
6323        let ptr: PointerEvent = PointerEvent::new(
6324            u64::from(pointer_id),
6325            device,
6326            Point::new(pos_x, pos_y),
6327            PointerButton::Primary,
6328            pressure.clamp(0.0, 1.0),
6329            Modifiers::default(),
6330        );
6331        app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr));
6332        applied = true;
6333    }
6334    let pending_scroll: Option<(f32, f32, f32, f32)> =
6335        WEB_DOCS_PENDING_SCROLL.with(|cell: &Cell<Option<(f32, f32, f32, f32)>>| cell.take());
6336    if let Some((pos_x, pos_y, dx, dy)) = pending_scroll {
6337        let wid: WindowId = app.get_window_state().get_id();
6338        if pos_x.is_finite() && pos_y.is_finite() {
6339            app.dispatch_window_event(WindowEvent::PointerMove(
6340                wid,
6341                PointerEvent::mouse(pos_x, pos_y),
6342            ));
6343        }
6344        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
6345        applied = true;
6346    }
6347    applied
6348}
6349
6350/// Coalesces a browser pointer move event into the single rAF-drained pending slot for the running WebAssembly documentation viewer.
6351///
6352/// # Arguments
6353///
6354/// - `f32` - Logical X coordinate inside the canvas.
6355/// - `f32` - Logical Y coordinate inside the canvas.
6356///
6357/// # Returns
6358///
6359/// - `u64` - Latest rendered frame hash.
6360#[cfg(target_arch = "wasm32")]
6361pub fn wasm_docs_pointer_move(pos_x: f32, pos_y: f32) -> u64 {
6362    WEB_DOCS_PENDING_MOVE.with(|cell: &Cell<Option<(u32, bool, f32, f32, f32)>>| {
6363        cell.set(Some((1, false, pos_x, pos_y, 0.0)));
6364    });
6365    web_docs_wake_raf();
6366    web_docs_last_frame_hash()
6367}
6368
6369/// Dispatches a browser pointer press event into the running WebAssembly documentation viewer and schedules the next animation frame.
6370///
6371/// # Arguments
6372///
6373/// - `f32` - Logical X coordinate inside the canvas.
6374/// - `f32` - Logical Y coordinate inside the canvas.
6375///
6376/// # Returns
6377///
6378/// - `u64` - Latest rendered frame hash.
6379#[cfg(target_arch = "wasm32")]
6380pub fn wasm_docs_pointer_down(pos_x: f32, pos_y: f32) -> u64 {
6381    let hash: u64 = WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6382        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6383            Ok(guard) => guard,
6384            Err(_) => return 0,
6385        };
6386        let Some((app, state)) = borrow.as_mut() else {
6387            return 0;
6388        };
6389        let _: bool = web_docs_flush_pending_inputs(app, state);
6390        let wid: WindowId = app.get_window_state().get_id();
6391        app.dispatch_window_event(WindowEvent::PointerDown(
6392            wid,
6393            PointerEvent::mouse(pos_x, pos_y),
6394        ));
6395        app.get_renderer().get_last_stats().get_frame_hash()
6396    });
6397    web_docs_wake_raf();
6398    hash
6399}
6400
6401/// Dispatches a browser pointer release event into the running WebAssembly documentation viewer and schedules the next animation frame.
6402///
6403/// # Arguments
6404///
6405/// - `f32` - Logical X coordinate inside the canvas.
6406/// - `f32` - Logical Y coordinate inside the canvas.
6407///
6408/// # Returns
6409///
6410/// - `u64` - Latest rendered frame hash.
6411#[cfg(target_arch = "wasm32")]
6412pub fn wasm_docs_pointer_up(pos_x: f32, pos_y: f32) -> u64 {
6413    let hash: u64 = WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6414        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6415            Ok(guard) => guard,
6416            Err(_) => return 0,
6417        };
6418        let Some((app, state)) = borrow.as_mut() else {
6419            return 0;
6420        };
6421        let _: bool = web_docs_flush_pending_inputs(app, state);
6422        let wid: WindowId = app.get_window_state().get_id();
6423        app.dispatch_window_event(WindowEvent::PointerUp(
6424            wid,
6425            PointerEvent::mouse(pos_x, pos_y),
6426        ));
6427        app.get_renderer().get_last_stats().get_frame_hash()
6428    });
6429    web_docs_wake_raf();
6430    hash
6431}
6432
6433/// Dispatches or coalesces a browser pointer event (`0=move`, `1=down`, `2=up`, `3=cancel`) with full touch/mouse device metadata into the running WebAssembly documentation viewer without synchronous off-rAF rendering.
6434///
6435/// # Arguments
6436///
6437/// - `u8` - Event kind (`0` move, `1` down, `2` up, `3` cancel).
6438/// - `u32` - Browser DOM `PointerEvent.pointerId`.
6439/// - `bool` - Whether the source pointer is a touch contact (`PointerDevice::Touch`).
6440/// - `f32` - Logical X coordinate inside the canvas.
6441/// - `f32` - Logical Y coordinate inside the canvas.
6442/// - `f32` - Normalized contact pressure (`0.0..=1.0`).
6443///
6444/// # Returns
6445///
6446/// - `u64` - Latest rendered frame hash.
6447#[cfg(target_arch = "wasm32")]
6448pub fn wasm_docs_pointer_event(
6449    kind: u8,
6450    pointer_id: u32,
6451    is_touch: bool,
6452    pos_x: f32,
6453    pos_y: f32,
6454    pressure: f32,
6455) -> u64 {
6456    if kind == 0 {
6457        WEB_DOCS_PENDING_MOVE.with(|cell: &Cell<Option<(u32, bool, f32, f32, f32)>>| {
6458            cell.set(Some((pointer_id, is_touch, pos_x, pos_y, pressure)));
6459        });
6460        web_docs_wake_raf();
6461        return web_docs_last_frame_hash();
6462    }
6463    let hash: u64 = WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6464        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6465            Ok(guard) => guard,
6466            Err(_) => return 0,
6467        };
6468        let Some((app, state)) = borrow.as_mut() else {
6469            return 0;
6470        };
6471        let _: bool = web_docs_flush_pending_inputs(app, state);
6472        let wid: WindowId = app.get_window_state().get_id();
6473        let pid: u64 = u64::from(pointer_id);
6474        let device: PointerDevice = if is_touch {
6475            PointerDevice::Touch
6476        } else {
6477            PointerDevice::Mouse
6478        };
6479        let ptr: PointerEvent = PointerEvent::new(
6480            pid,
6481            device,
6482            Point::new(pos_x, pos_y),
6483            PointerButton::Primary,
6484            pressure.clamp(0.0, 1.0),
6485            Modifiers::default(),
6486        );
6487        match kind {
6488            1 => app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr)),
6489            2 => app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr)),
6490            3 => app.dispatch_window_event(WindowEvent::PointerCancel(wid, pid)),
6491            _ => app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr)),
6492        }
6493        app.get_renderer().get_last_stats().get_frame_hash()
6494    });
6495    web_docs_wake_raf();
6496    hash
6497}
6498
6499/// Coalesces a browser wheel scroll delta into the rAF-drained scroll accumulator for the running WebAssembly documentation viewer.
6500///
6501/// # Arguments
6502///
6503/// - `f32` - Horizontal scroll delta.
6504/// - `f32` - Vertical scroll delta.
6505///
6506/// # Returns
6507///
6508/// - `u64` - Latest rendered frame hash.
6509#[cfg(target_arch = "wasm32")]
6510pub fn wasm_docs_scroll(dx: f32, dy: f32) -> u64 {
6511    WEB_DOCS_PENDING_SCROLL.with(|cell: &Cell<Option<(f32, f32, f32, f32)>>| {
6512        let next: (f32, f32, f32, f32) = match cell.get() {
6513            Some((prev_x, prev_y, prev_dx, prev_dy)) => {
6514                (prev_x, prev_y, prev_dx + dx, prev_dy + dy)
6515            }
6516            None => (f32::NAN, f32::NAN, dx, dy),
6517        };
6518        cell.set(Some(next));
6519    });
6520    web_docs_wake_raf();
6521    web_docs_last_frame_hash()
6522}
6523
6524/// Coalesces a browser wheel scroll delta anchored at logical pointer `(pos_x, pos_y)` into the single rAF-drained pending slot without synchronous off-rAF rendering.
6525///
6526/// # Arguments
6527///
6528/// - `f32` - Logical pointer X coordinate inside the canvas.
6529/// - `f32` - Logical pointer Y coordinate inside the canvas.
6530/// - `f32` - Horizontal scroll delta in CSS pixels.
6531/// - `f32` - Vertical scroll delta in CSS pixels.
6532///
6533/// # Returns
6534///
6535/// - `u64` - Latest rendered frame hash.
6536#[cfg(target_arch = "wasm32")]
6537pub fn wasm_docs_scroll_at(pos_x: f32, pos_y: f32, dx: f32, dy: f32) -> u64 {
6538    WEB_DOCS_PENDING_SCROLL.with(|cell: &Cell<Option<(f32, f32, f32, f32)>>| {
6539        let next: (f32, f32, f32, f32) = match cell.get() {
6540            Some((_, _, prev_dx, prev_dy)) => (pos_x, pos_y, prev_dx + dx, prev_dy + dy),
6541            None => (pos_x, pos_y, dx, dy),
6542        };
6543        cell.set(Some(next));
6544    });
6545    web_docs_wake_raf();
6546    web_docs_last_frame_hash()
6547}
6548
6549/// Re-queries real browser CSS `env(safe-area-inset-*)` values and dispatches `WindowEvent::SafeAreaChanged` only when insets actually change.
6550///
6551/// # Returns
6552///
6553/// - `u64` - Latest rendered frame hash.
6554#[cfg(target_arch = "wasm32")]
6555pub fn wasm_docs_sync_safe_area() -> u64 {
6556    let measured: SafeAreaInsets = web_query_safe_area_insets();
6557    let (changed, hash): (bool, u64) =
6558        WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6559            let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut()
6560            {
6561                Ok(guard) => guard,
6562                Err(_) => return (false, 0),
6563            };
6564            let Some((app, _)) = borrow.as_mut() else {
6565                return (false, 0);
6566            };
6567            let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
6568                SafeAreaInsets::default()
6569            } else {
6570                measured
6571            };
6572            let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
6573            let last_hash: u64 = app.get_renderer().get_last_stats().get_frame_hash();
6574            if current == effective {
6575                return (false, last_hash);
6576            }
6577            let wid: WindowId = app.get_window_state().get_id();
6578            app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
6579            (true, last_hash)
6580        });
6581    if changed {
6582        web_docs_wake_raf();
6583    }
6584    hash
6585}
6586
6587/// Dispatches a browser keyboard event with full modifier flags into the running WebAssembly documentation viewer and schedules the next animation frame.
6588///
6589/// # Arguments
6590///
6591/// - `&str` - DOM `KeyboardEvent.key` string.
6592/// - `bool` - Whether Control is pressed.
6593/// - `bool` - Whether Shift is pressed.
6594/// - `bool` - Whether Alt / Option is pressed.
6595/// - `bool` - Whether Meta / Command is pressed.
6596///
6597/// # Returns
6598///
6599/// - `u64` - Latest rendered frame hash.
6600#[cfg(target_arch = "wasm32")]
6601pub fn wasm_docs_key_down_mods(key: &str, ctrl: bool, shift: bool, alt: bool, meta: bool) -> u64 {
6602    let hash: u64 = WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6603        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6604            Ok(guard) => guard,
6605            Err(_) => return 0,
6606        };
6607        let Some((app, state)) = borrow.as_mut() else {
6608            return 0;
6609        };
6610        let _: bool = web_docs_flush_pending_inputs(app, state);
6611        let wid: WindowId = app.get_window_state().get_id();
6612        let code: KeyCode = match key {
6613            WEB_KEY_ENTER => KeyCode::Enter,
6614            WEB_KEY_BACKSPACE => KeyCode::Backspace,
6615            WEB_KEY_DELETE => KeyCode::Delete,
6616            WEB_KEY_ESCAPE => KeyCode::Escape,
6617            WEB_KEY_TAB => KeyCode::Tab,
6618            WEB_KEY_SPACE => KeyCode::Space,
6619            WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
6620            WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
6621            WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
6622            WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
6623            WEB_KEY_PAGE_UP => KeyCode::PageUp,
6624            WEB_KEY_PAGE_DOWN => KeyCode::PageDown,
6625            WEB_KEY_HOME => KeyCode::Home,
6626            WEB_KEY_END => KeyCode::End,
6627            other => other
6628                .chars()
6629                .next()
6630                .map(KeyCode::Character)
6631                .unwrap_or(KeyCode::Unknown),
6632        };
6633        let mods: Modifiers = Modifiers::new(shift, ctrl, alt, meta);
6634        app.dispatch_window_event(WindowEvent::KeyDown(wid, KeyEvent::new(code, mods, false)));
6635        if !ctrl && !alt && !meta && key.chars().count() == 1 {
6636            app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
6637        }
6638        app.get_renderer().get_last_stats().get_frame_hash()
6639    });
6640    web_docs_wake_raf();
6641    hash
6642}
6643
6644/// Copies and returns the currently selected text from the running WebAssembly documentation viewer (`""` when nothing is selected).
6645///
6646/// # Returns
6647///
6648/// - `String` - Selected UTF-8 text copied to the clipboard, or empty string.
6649#[cfg(target_arch = "wasm32")]
6650pub fn wasm_docs_copy_selected() -> String {
6651    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6652        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6653            Ok(guard) => guard,
6654            Err(_) => return String::new(),
6655        };
6656        let Some((app, _)) = borrow.as_mut() else {
6657            return String::new();
6658        };
6659        app.copy_selection()
6660            .or_else(|| app.get_scene().get_selected_text())
6661            .unwrap_or_default()
6662    })
6663}
6664
6665/// Dispatches UTF-8 text input (including composed IME/CJK text) into the running WebAssembly documentation viewer and schedules the next animation frame.
6666///
6667/// # Arguments
6668///
6669/// - `&str` - Composed or typed UTF-8 text string.
6670///
6671/// # Returns
6672///
6673/// - `u64` - Latest rendered frame hash.
6674#[cfg(target_arch = "wasm32")]
6675pub fn wasm_docs_text_input(text: &str) -> u64 {
6676    if text.is_empty() {
6677        return 0;
6678    }
6679    let hash: u64 = WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6680        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6681            Ok(guard) => guard,
6682            Err(_) => return 0,
6683        };
6684        let Some((app, _)) = borrow.as_mut() else {
6685            return 0;
6686        };
6687        let wid: WindowId = app.get_window_state().get_id();
6688        app.dispatch_window_event(WindowEvent::TextInput(wid, text.to_string()));
6689        app.get_renderer().get_last_stats().get_frame_hash()
6690    });
6691    web_docs_wake_raf();
6692    hash
6693}
6694
6695/// Returns `true` when the running WebAssembly documentation viewer currently has a focused `NodeKind::Input` text field.
6696///
6697/// # Returns
6698///
6699/// - `bool` - Whether an interactive text input (for example Search modal or Password gate) currently holds focus.
6700#[cfg(target_arch = "wasm32")]
6701#[must_use]
6702pub fn wasm_docs_has_focused_input() -> bool {
6703    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6704        let borrow: Ref<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow() {
6705            Ok(guard) => guard,
6706            Err(_) => return false,
6707        };
6708        let Some((app, _)) = borrow.as_ref() else {
6709            return false;
6710        };
6711        app.get_scene().with_read(
6712            |tree: &SceneTree| {
6713                tree.get_focus()
6714                    .focused_node()
6715                    .and_then(|id: NodeId| tree.get_node(id))
6716                    .is_some_and(|scene_node: &SceneNode| {
6717                        matches!(scene_node.get_kind(), NodeKind::Input(_))
6718                    })
6719            },
6720            false,
6721        )
6722    })
6723}
6724
6725/// Dispatches a browser keyboard event into the running WebAssembly documentation viewer.
6726///
6727/// # Arguments
6728///
6729/// - `&str` - DOM `KeyboardEvent.key` string.
6730///
6731/// # Returns
6732///
6733/// - `u64` - Latest rendered frame hash.
6734#[cfg(target_arch = "wasm32")]
6735pub fn wasm_docs_key_down(key: &str) -> u64 {
6736    wasm_docs_key_down_mods(key, false, false, false, false)
6737}
6738
6739/// Returns whether the WebAssembly documentation viewer has pending coalesced input, resize, dirty scene state, or active animations requiring another `requestAnimationFrame` tick.
6740///
6741/// # Returns
6742///
6743/// - `bool` - `true` when another rAF tick is required; `false` when the host may park at 0 rAF/s.
6744#[cfg(target_arch = "wasm32")]
6745#[must_use]
6746pub fn wasm_docs_needs_frame() -> bool {
6747    let pending_flag: bool = WEB_DOCS_NEEDS_FRAME.with(Cell::get)
6748        || WEB_DOCS_PENDING_MOVE
6749            .with(|cell: &Cell<Option<(u32, bool, f32, f32, f32)>>| cell.get().is_some())
6750        || WEB_DOCS_PENDING_SCROLL
6751            .with(|cell: &Cell<Option<(f32, f32, f32, f32)>>| cell.get().is_some())
6752        || WEB_DOCS_PENDING_RESIZE
6753            .with(|cell: &Cell<Option<(u32, u32, f32)>>| cell.get().is_some())
6754        || is_frame_needed();
6755    if pending_flag {
6756        return true;
6757    }
6758    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6759        let borrow: Ref<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow() {
6760            Ok(guard) => guard,
6761            Err(_) => return false,
6762        };
6763        let Some((app, state)) = borrow.as_ref() else {
6764            return false;
6765        };
6766        state.get_pending_post_layout_sync().get() || app.has_active_animations()
6767    })
6768}
6769
6770/// Drains coalesced input/resize state and advances at most one frame per browser `requestAnimationFrame` callback.
6771///
6772/// # Arguments
6773///
6774/// - `f32` - Elapsed seconds since the previous animation frame.
6775///
6776/// # Returns
6777///
6778/// - `u64` - Rendered frame hash.
6779#[cfg(target_arch = "wasm32")]
6780pub fn wasm_docs_tick(dt_secs: f32) -> u64 {
6781    let safe_dt: f32 = if dt_secs.is_finite() && dt_secs > 0.0 {
6782        dt_secs
6783    } else {
6784        0.0
6785    };
6786    WEB_DOCS_RUNTIME.with(|slot: &RefCell<Option<(App, DocsViewerState)>>| {
6787        let mut borrow: RefMut<'_, Option<(App, DocsViewerState)>> = match slot.try_borrow_mut() {
6788            Ok(guard) => guard,
6789            Err(_) => return 0,
6790        };
6791        let Some((app, state)) = borrow.as_mut() else {
6792            return 0;
6793        };
6794        let had_inputs: bool = web_docs_flush_pending_inputs(app, state);
6795        let dirty_flag: bool = WEB_DOCS_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.replace(false));
6796        let needs_post_sync: bool = state.get_pending_post_layout_sync().replace(false);
6797        let frame_requested: bool = take_frame_needed();
6798        let active_step: bool = needs_post_sync
6799            || had_inputs
6800            || dirty_flag
6801            || frame_requested
6802            || app.has_active_animations();
6803        if active_step && safe_dt > 0.0 && f64::from(safe_dt) <= WEB_DOCS_RAF_MAX_MEASURE_DT_SECS {
6804            let next_secs: f64 = WEB_DOCS_RAF_ACCUM_SECS.with(Cell::get) + f64::from(safe_dt);
6805            let next_frames: u32 = WEB_DOCS_RAF_ACCUM_FRAMES.with(Cell::get).saturating_add(1);
6806            if next_secs >= WEB_DOCS_RAF_SAMPLE_WINDOW_SECS
6807                && next_frames >= WEB_DOCS_RAF_MIN_SAMPLE_FRAMES
6808            {
6809                let measured_hz: f32 = (f64::from(next_frames) / next_secs) as f32;
6810                WEB_DOCS_RAF_ACCUM_SECS.with(|s_cell: &Cell<f64>| s_cell.set(0.0));
6811                WEB_DOCS_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
6812                app.report_host_refresh_rate(measured_hz);
6813            } else {
6814                WEB_DOCS_RAF_ACCUM_SECS.with(|s_cell: &Cell<f64>| s_cell.set(next_secs));
6815                WEB_DOCS_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(next_frames));
6816            }
6817        } else if !active_step {
6818            WEB_DOCS_RAF_ACCUM_SECS.with(|s_cell: &Cell<f64>| s_cell.set(0.0));
6819            WEB_DOCS_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
6820        }
6821        if needs_post_sync {
6822            let hash: u64 = app
6823                .step_game_frame(safe_dt)
6824                .map(|stats: FrameStats| stats.get_frame_hash())
6825                .unwrap_or(0);
6826            let rev_before: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
6827            state.sync_post_layout_positions(app.get_scene());
6828            let rev_after: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
6829            if rev_after != rev_before || is_frame_needed() {
6830                WEB_DOCS_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.set(true));
6831            }
6832            return hash;
6833        }
6834        if active_step || dt_secs <= 0.0 {
6835            return app
6836                .step_game_frame(safe_dt)
6837                .map(|stats: FrameStats| stats.get_frame_hash())
6838                .unwrap_or(0);
6839        }
6840        app.get_renderer().get_last_stats().get_frame_hash()
6841    })
6842}
6843
6844/// Coalesces a logical CSS viewport resize into exact physical pixels for the next animation frame.
6845///
6846/// # Arguments
6847///
6848/// - `u32` - Logical viewport width in CSS pixels.
6849/// - `u32` - Logical viewport height in CSS pixels.
6850/// - `f32` - Active browser `window.devicePixelRatio`.
6851///
6852/// # Returns
6853///
6854/// - `u64` - Latest rendered frame hash.
6855#[cfg(target_arch = "wasm32")]
6856pub fn wasm_docs_resize(width: u32, height: u32, dpr: f32) -> u64 {
6857    let width_val: u32 = width.max(64);
6858    let height_val: u32 = height.max(64);
6859    let scale: f32 = clamp_viewport_scale(dpr);
6860    let metrics: ViewportMetrics =
6861        ViewportMetrics::from_logical(f64::from(width_val), f64::from(height_val), scale);
6862    wasm_docs_resize_physical(
6863        metrics.get_physical_width(),
6864        metrics.get_physical_height(),
6865        scale,
6866    )
6867}
6868
6869/// Coalesces an exact physical surface resize `(phys_w, phys_h)` at `dpr` to be applied once inside the next animation frame without synchronous double-stepping.
6870///
6871/// # Arguments
6872///
6873/// - `u32` - Exact physical surface width in device pixels.
6874/// - `u32` - Exact physical surface height in device pixels.
6875/// - `f32` - Active browser `window.devicePixelRatio`.
6876///
6877/// # Returns
6878///
6879/// - `u64` - Latest rendered frame hash.
6880#[cfg(target_arch = "wasm32")]
6881pub fn wasm_docs_resize_physical(phys_w: u32, phys_h: u32, dpr: f32) -> u64 {
6882    let scale: f32 = clamp_viewport_scale(dpr);
6883    let pw: u32 = phys_w.max(64);
6884    let ph: u32 = phys_h.max(64);
6885    WEB_DOCS_PENDING_RESIZE.with(|cell: &Cell<Option<(u32, u32, f32)>>| {
6886        cell.set(Some((pw, ph, scale)));
6887    });
6888    web_docs_wake_raf();
6889    web_docs_last_frame_hash()
6890}