Skip to main content

euv_docs/viewer/
fn.rs

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