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