Skip to main content

euv_docs/viewer/
fn.rs

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