Skip to main content

euv_docs/viewer/
fn.rs

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