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