Skip to main content

euv_example/pages/stress/
fn.rs

1use super::*;
2
3/// Measures the wall-clock execution duration of `work` in milliseconds on native targets.
4///
5/// # Arguments
6///
7/// - `CallbackFn` - Closure executing the benchmarked workload.
8///
9/// # Returns
10///
11/// - `f64` - Elapsed duration in milliseconds.
12#[cfg(not(target_arch = "wasm32"))]
13fn measure_ms<CallbackFn>(work: CallbackFn) -> f64
14where
15    CallbackFn: FnOnce(),
16{
17    let start: Instant = Instant::now();
18    work();
19    start.elapsed().as_secs_f64() * 1000.0
20}
21
22/// Measures the wall-clock execution duration of `work` in milliseconds in WebAssembly via `Performance.now()`.
23///
24/// # Arguments
25///
26/// - `CallbackFn` - Closure executing the benchmarked workload.
27///
28/// # Returns
29///
30/// - `f64` - Elapsed duration in milliseconds.
31#[cfg(target_arch = "wasm32")]
32fn measure_ms<CallbackFn>(work: CallbackFn) -> f64
33where
34    CallbackFn: FnOnce(),
35{
36    let perf: Option<Performance> = window().and_then(|width_val: Window| width_val.performance());
37    let t0: f64 = perf.as_ref().map(Performance::now).unwrap_or(0.0);
38    work();
39    let t1: f64 = perf.as_ref().map(Performance::now).unwrap_or(t0);
40    (t1 - t0).max(0.0)
41}
42
43/// Computes `(avg_ms, p95_ms, max_ms)` from a slice of per-iteration millisecond timings.
44///
45/// # Arguments
46///
47/// - `&[f64]` - Per-iteration millisecond sample slice.
48///
49/// # Returns
50///
51/// - `(f64, f64, f64)` - Tuple containing mean, 95th percentile, and maximum latency in milliseconds.
52fn summarize_samples(samples: &[f64]) -> (f64, f64, f64) {
53    if samples.is_empty() {
54        return (0.0, 0.0, 0.0);
55    }
56    let mut sorted: Vec<f64> = samples.to_vec();
57    sorted.sort_by(f64::total_cmp);
58    let sum: f64 = sorted.iter().copied().sum();
59    let len: usize = sorted.len();
60    let avg: f64 = sum / (len as f64);
61    let p95_idx: usize = ((len * 95) / 100).min(len - 1);
62    let p95: f64 = sorted[p95_idx];
63    let max: f64 = sorted[len - 1];
64    (avg, p95, max)
65}
66
67/// Formats an iteration rate string (FPS or ops/s) from a mean per-iteration latency in milliseconds.
68///
69/// # Arguments
70///
71/// - `f64` - Mean latency per iteration in milliseconds.
72/// - `bool` - When `true`, formats as `FPS`; otherwise formats as `ops/s`.
73///
74/// # Returns
75///
76/// - `String` - Human-readable throughput string.
77fn format_rate(avg_ms: f64, is_fps: bool) -> String {
78    let rate: f64 = if avg_ms > 0.0001 {
79        1000.0 / avg_ms
80    } else {
81        999_999.0
82    };
83    if is_fps {
84        format!("{rate:.0} FPS")
85    } else {
86        format!("{rate:.0} ops/s")
87    }
88}
89
90/// Constructs an idle `StressCaseResult` descriptor ready for interactive execution.
91///
92/// # Arguments
93///
94/// - `&str` - Stable scenario identifier.
95/// - `&str` - Human-readable title.
96/// - `&str` - Short category label.
97/// - `&str` - Workload description.
98/// - `&str` - Action button label.
99/// - `f64` - Per-iteration budget threshold in milliseconds.
100///
101/// # Returns
102///
103/// - `StressCaseResult` - Idle scenario entry.
104fn make_idle_case(
105    id: &str,
106    title: &str,
107    category: &str,
108    description: &str,
109    button_label: &str,
110    budget_ms: f64,
111) -> StressCaseResult {
112    StressCaseResult {
113        id: id.to_string(),
114        title: title.to_string(),
115        category: category.to_string(),
116        description: description.to_string(),
117        button_label: button_label.to_string(),
118        status: STRESS_STATUS_IDLE.to_string(),
119        budget_ms,
120        iterations: 0,
121        avg_ms: 0.0,
122        p95_ms: 0.0,
123        max_ms: 0.0,
124        throughput: STRESS_UNIT_NA.to_string(),
125        details: STRESS_UNIT_NA.to_string(),
126        runs: 0,
127    }
128}
129
130/// Returns the default list of 10 interactive UI stress benchmark scenarios in `IDLE` state.
131///
132/// # Returns
133///
134/// - `Vec<StressCaseResult>` - Ordered list of 10 ready stress benchmark scenarios.
135#[must_use]
136pub fn default_stress_results() -> Vec<StressCaseResult> {
137    vec![
138        make_idle_case(
139            STRESS_ID_VLIST_100K,
140            STRESS_TITLE_VLIST,
141            STRESS_CAT_LIST,
142            STRESS_DESC_VLIST,
143            STRESS_BTN_VLIST,
144            8.33,
145        ),
146        make_idle_case(
147            STRESS_ID_LAYOUT_2000,
148            STRESS_TITLE_LAYOUT,
149            STRESS_CAT_LAYOUT,
150            STRESS_DESC_LAYOUT,
151            STRESS_BTN_LAYOUT,
152            2.0,
153        ),
154        make_idle_case(
155            STRESS_ID_REACTIVE_1000,
156            STRESS_TITLE_REACTIVE,
157            STRESS_CAT_REACTIVE,
158            STRESS_DESC_REACTIVE,
159            STRESS_BTN_REACTIVE,
160            6.0,
161        ),
162        make_idle_case(
163            STRESS_ID_WASM_HOTSWAP,
164            STRESS_TITLE_WASM,
165            STRESS_CAT_WASM,
166            STRESS_DESC_WASM,
167            STRESS_BTN_WASM,
168            5.0,
169        ),
170        make_idle_case(
171            STRESS_ID_DRAWER_ANIM,
172            STRESS_TITLE_ANIM,
173            STRESS_CAT_ANIM,
174            STRESS_DESC_ANIM,
175            STRESS_BTN_ANIM,
176            8.33,
177        ),
178        make_idle_case(
179            STRESS_ID_TOUCH_HITTEST,
180            STRESS_TITLE_TOUCH,
181            STRESS_CAT_INPUT,
182            STRESS_DESC_TOUCH,
183            STRESS_BTN_TOUCH,
184            1.5,
185        ),
186        make_idle_case(
187            STRESS_ID_HIDPI_SHADOW,
188            STRESS_TITLE_HIDPI,
189            STRESS_CAT_RASTER,
190            STRESS_DESC_HIDPI,
191            STRESS_BTN_HIDPI,
192            16.67,
193        ),
194        make_idle_case(
195            STRESS_ID_CJK_ATLAS,
196            STRESS_TITLE_CJK,
197            STRESS_CAT_TEXT,
198            STRESS_DESC_CJK,
199            STRESS_BTN_CJK,
200            4.0,
201        ),
202        make_idle_case(
203            STRESS_ID_GAME_2D_3D,
204            STRESS_TITLE_GAME,
205            STRESS_CAT_ENGINE,
206            STRESS_DESC_GAME,
207            STRESS_BTN_GAME,
208            16.67,
209        ),
210        make_idle_case(
211            STRESS_ID_MACRO_MOUNT,
212            STRESS_TITLE_MACRO,
213            STRESS_CAT_MACRO,
214            STRESS_DESC_MACRO,
215            STRESS_BTN_MACRO,
216            6.0,
217        ),
218    ]
219}
220
221/// Applies measured samples and diagnostic metadata to a `StressCaseResult` and evaluates budget compliance.
222///
223/// # Arguments
224///
225/// - `&mut StressCaseResult` - Target result entry to update.
226/// - `&[f64]` - Per-iteration millisecond timing samples.
227/// - `bool` - Whether throughput should be displayed in `FPS` (`true`) or `ops/s` (`false`).
228/// - `String` - Scenario-specific telemetry details.
229fn finalize_case(entry: &mut StressCaseResult, samples: &[f64], is_fps: bool, details: String) {
230    let (avg_ms, p95_ms, max_ms): (f64, f64, f64) = summarize_samples(samples);
231    let pass: bool = avg_ms <= entry.get_budget_ms();
232    let status: String = if pass {
233        STRESS_STATUS_PASS.to_string()
234    } else {
235        STRESS_STATUS_WARN.to_string()
236    };
237    let next_runs: u32 = entry.get_runs().saturating_add(1);
238    entry
239        .set_status(status)
240        .set_iterations(samples.len())
241        .set_avg_ms(avg_ms)
242        .set_p95_ms(p95_ms)
243        .set_max_ms(max_ms)
244        .set_throughput(format_rate(avg_ms, is_fps))
245        .set_details(details)
246        .set_runs(next_runs);
247}
248
249/// Runs Scenario 1: continuous scrolling across a 100,000-row virtualized list.
250///
251/// # Arguments
252///
253/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
254fn run_stress_vlist_100k(entry: &mut StressCaseResult) {
255    let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
256        let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
257        let palette: ThemePalette = tokens.get_palette();
258        let geometry: ThemeGeometry = tokens.get_geometry();
259        let mut win: WindowConfig = WindowConfig::default();
260        win.set_size(360, 640).set_render(RenderConfig::software());
261        let mut config_spec: AppConfig = AppConfig::default();
262        config_spec.set_window(win);
263        let Ok(mut app) = App::headless(config_spec) else {
264            return (Vec::new(), STRESS_UNIT_NA.to_string());
265        };
266        let scroll_y: Signal<f32> = Signal::new(0.0);
267        let _: NodeId = app.mount(|| {
268            let vlist: EuvVirtualList =
269                EuvVirtualList::new(100_000, 36.0, scroll_y, tokens).viewport_height(600.0);
270            vlist.mount_with(move |idx: usize| {
271                let row_sixth_style: Style = style! {
272                    Width(Length::Percent(100.0))
273                    Height(Length::Px(36.0))
274                    Padding(Edges::symmetric(SPACE_XS, SPACE_MD))
275                    AlignItems::Center
276                    Border::new(geometry.get_border_width(), palette.get_border())
277                };
278                let text_thirteenth_style: Style = style! {
279                    FontSize(13.0)
280                    TextColor(palette.get_foreground())
281                };
282                view! {
283                    row {
284                        style: row_sixth_style
285                        text {
286                            style: text_thirteenth_style
287                            { format!("{STRESS_ROW_PREFIX} #{idx}") }
288                        }
289                    }
290                }
291            })
292        });
293        let _: Result<FrameStats, PlatformError> = app.step_frame();
294        let mut samples: Vec<f64> = Vec::with_capacity(24);
295        let mut last_shaded: usize = 0;
296        let mut mounted_nodes: usize = 0;
297        for step in 1..=24usize {
298            let next_y: f32 = ((step as f32) * 144.0) % 3_500_000.0;
299            let dt: f64 = measure_ms(|| {
300                let _: bool = scroll_y.set_if_changed(next_y);
301                if let Ok(stats) = app.step_frame() {
302                    last_shaded = stats.get_pixels_shaded();
303                }
304            });
305            samples.push(dt);
306        }
307        mounted_nodes = app
308            .get_scene()
309            .with_read(SceneTree::live_node_count, mounted_nodes);
310        let info: String = format!(
311            "rows=100k mounted_nodes={mounted_nodes} scroll={:.0}px shaded={last_shaded}",
312            scroll_y.get_untracked()
313        );
314        (samples, info)
315    });
316    scope.dispose();
317    finalize_case(entry, &samples, true, details);
318}
319
320/// Runs Scenario 2: 2,000-node nested Flex/Grid layout and surgical dirty-subtree relayout passes.
321///
322/// # Arguments
323///
324/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
325fn run_stress_layout_2000(entry: &mut StressCaseResult) {
326    let scene: SceneHandle = SceneHandle::new_tree();
327    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
328    let (leaf_nodes, page): (Vec<NodeId>, NodeId) = with_context(ctx, || {
329        let mut leaves: Vec<NodeId> = Vec::with_capacity(50);
330        let mut sections: Vec<NodeId> = Vec::with_capacity(50);
331        for section_idx in 0..50usize {
332            let mut first_title: NodeId = NodeId::default();
333            let grid_style: Style = style! {
334                GridColumns(4)
335                Width(Length::Percent(100.0))
336                Gap(SPACE_SM)
337            };
338            let column_seventh_style: Style = style! {
339                Width(Length::Percent(100.0))
340                Padding(Edges::all(SPACE_SM))
341                Gap(SPACE_XS)
342            };
343            let row_fifth_style: Style = style! {
344                Width(Length::Percent(100.0))
345                JustifyContent::SpaceBetween
346            };
347            let text_eleventh_style: Style = style! {
348                FontSize(13.0)
349            };
350            let text_twelfth_style: Style = style! {
351                FontSize(11.0)
352            };
353            let grid_node: NodeId = view! {
354                grid {
355                    style: grid_style
356                    for card_idx in 0..8usize {
357                        column {
358                            style: column_seventh_style
359                            row {
360                                style: row_fifth_style
361                                if card_idx == 0 {
362                                    text {
363                                        node_ref: first_title
364                                        style: text_eleventh_style
365                                        { format!("{STRESS_CELL_PREFIX} {section_idx}-{card_idx}") }
366                                    }
367                                } else {
368                                    text {
369                                        style: text_eleventh_style
370                                        { format!("{STRESS_CELL_PREFIX} {section_idx}-{card_idx}") }
371                                    }
372                                }
373                                text {
374                                    style: text_twelfth_style
375                                    { format!("{section_idx}") }
376                                }
377                            }
378                        }
379                    }
380                }
381            };
382            leaves.push(first_title);
383            sections.push(grid_node);
384        }
385        let column_sixth_style: Style = style! {
386            Width(Length::Px(1280.0))
387            Padding(Edges::all(SPACE_MD))
388            Gap(SPACE_SM)
389        };
390        let p_node: NodeId = view! {
391            column {
392                style: column_sixth_style
393                ..sections
394            }
395        };
396        (leaves, p_node)
397    });
398    scene.with_write(
399        |tree: &mut SceneTree| {
400            let root: NodeId = tree.get_root();
401            tree.replace_children(root, vec![page]);
402        },
403        (),
404    );
405    let mut engine: LayoutEngine = LayoutEngine::default();
406    let viewport: Size = Size::new(1280.0, 800.0);
407    let mut init_nodes: usize = 0;
408    let init_ms: f64 = measure_ms(|| {
409        let node_style: LayoutStats = scene.with_write(
410            |tree: &mut SceneTree| engine.compute(tree, viewport),
411            LayoutStats::default(),
412        );
413        init_nodes = node_style.get_nodes_computed();
414    });
415    let mut samples: Vec<f64> = Vec::with_capacity(40);
416    let mut total_computed: usize = 0;
417    let mut total_skipped: usize = 0;
418    for step in 0..40usize {
419        let target: NodeId = leaf_nodes[step % leaf_nodes.len()];
420        let dt: f64 = measure_ms(|| {
421            scene.with_write(
422                |tree: &mut SceneTree| {
423                    tree.set_text(target, format!("{STRESS_CELL_PREFIX} #{step}"));
424                    let stats: LayoutStats = engine.compute(tree, viewport);
425                    total_computed += stats.get_nodes_computed();
426                    total_skipped += stats.get_subtrees_skipped();
427                },
428                (),
429            );
430        });
431        samples.push(dt);
432    }
433    let details: String = format!(
434        "nodes={init_nodes} init={init_ms:.2}ms avg_recomputed={} skipped={}",
435        total_computed / 40,
436        total_skipped / 40
437    );
438    finalize_case(entry, &samples, false, details);
439}
440
441/// Runs Scenario 3: bulk batched reactive signal and memo updates across 1,000 live components.
442///
443/// # Arguments
444///
445/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
446fn run_stress_reactive_1000(entry: &mut StressCaseResult) {
447    let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
448        let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
449        let palette: ThemePalette = tokens.get_palette();
450        let mut win: WindowConfig = WindowConfig::default();
451        win.set_size(800, 600).set_render(RenderConfig::hardware());
452        let mut config_spec: AppConfig = AppConfig::default();
453        config_spec.set_window(win);
454        let Ok(mut app) = App::headless(config_spec) else {
455            return (Vec::new(), STRESS_UNIT_NA.to_string());
456        };
457        let mut signals: Vec<Signal<u32>> = Vec::with_capacity(1_000);
458        for idx in 0..1_000u32 {
459            signals.push(Signal::new(idx));
460        }
461        let signals_mount: Vec<Signal<u32>> = signals.clone();
462        let _: NodeId = app.mount(move || {
463            let derived_memos: Vec<Memo<u32>> = signals_mount
464                .into_iter()
465                .map(|sig: Signal<u32>| {
466                    Memo::new(move || sig.get().wrapping_mul(3).wrapping_add(1))
467                })
468                .collect();
469            let scroll_tertiary_style: Style = style! {
470                Width(Length::Percent(100.0))
471                Height(Length::Percent(100.0))
472                Gap(2.0)
473            };
474            let text_tenth_style: Style = style! {
475                FontSize(12.0)
476                TextColor(palette.get_foreground())
477            };
478            view! {
479                scroll {
480                    style: scroll_tertiary_style
481                    for derived in derived_memos.into_iter() {
482                        text {
483                            style: text_tenth_style
484                            { move || format!("{STRESS_CELL_PREFIX} {}", derived.get()) }
485                        }
486                    }
487                }
488            }
489        });
490        let _: Result<FrameStats, PlatformError> = app.step_frame();
491        let mut samples: Vec<f64> = Vec::with_capacity(16);
492        let mut last_rev: u64 = 0;
493        for tick in 1..=16u32 {
494            let dt: f64 = measure_ms(|| {
495                batch(|| {
496                    for (idx, sig) in signals.iter().enumerate() {
497                        let _: bool = sig.set_if_changed(tick.wrapping_add(idx as u32));
498                    }
499                });
500                flush_effects();
501                if app.step_frame().is_ok() {
502                    last_rev = app.get_last_rendered_revision();
503                }
504            });
505            samples.push(dt);
506        }
507        let info: String = format!("signals=1000 memos=1000 rev={last_rev}");
508        (samples, info)
509    });
510    scope.dispose();
511    finalize_case(entry, &samples, false, details);
512}
513
514/// Runs Scenario 4: dynamic `.wasm` binary verification, sandbox execution, hot-swap, and rollback.
515///
516/// # Arguments
517///
518/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
519fn run_stress_wasm_hotswap(entry: &mut StressCaseResult) {
520    let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
521        let mut win: WindowConfig = WindowConfig::default();
522        win.set_size(640, 480).set_render(RenderConfig::hardware());
523        let mut config_spec: AppConfig = AppConfig::default();
524        config_spec.set_window(win);
525        let Ok(mut app) = App::headless(config_spec) else {
526            return (Vec::new(), STRESS_UNIT_NA.to_string());
527        };
528        let hub: DynamicUpdateHub = app.get_dynamic_hub().clone();
529        let registry: RegistryWasmFetcher = RegistryWasmFetcher::default();
530        let wasm_v1: Vec<u8> = build_partial_widget_wasm(STRESS_WASM_TITLE_V1, 1, 0x2563EB);
531        let wasm_v2: Vec<u8> = build_partial_widget_wasm(STRESS_WASM_TITLE_V2, 2, 0x7C3AED);
532        let csum_v1: u64 = compute_wasm_checksum(&wasm_v1);
533        let csum_v2: u64 = compute_wasm_checksum(&wasm_v2);
534        registry.register(
535            STRESS_WASM_URL_V1.to_string(),
536            wasm_v1,
537            STRESS_WASM_ETAG_V1.to_string(),
538            WasmFaultKind::None,
539        );
540        registry.register(
541            STRESS_WASM_URL_V2.to_string(),
542            wasm_v2,
543            STRESS_WASM_ETAG_V2.to_string(),
544            WasmFaultKind::None,
545        );
546        let manager: WasmDynamicManager =
547            WasmDynamicManager::new(hub.clone(), Rc::new(registry), WasmSandboxConfig::default());
548        let hub_slot: DynamicUpdateHub = hub;
549        let _: NodeId = app.mount(move || {
550            let text_ninth_style: Style = style! {
551                FontSize(14.0)
552            };
553            view! {
554                slot {
555                    id: STRESS_WASM_SLOT
556                    hub: hub_slot
557                    text {
558                        style: text_ninth_style
559                        { STRESS_WASM_FALLBACK }
560                    }
561                }
562            }
563        });
564        let _: Result<FrameStats, PlatformError> = app.step_frame();
565        let mut samples: Vec<f64> = Vec::with_capacity(12);
566        let mut completed: usize = 0;
567        for cycle in 0..12usize {
568            let base_ver: u64 = ((cycle as u64) * 2) + 1;
569            let dt: f64 = measure_ms(|| {
570                let req_v1: WasmDownloadRequest = WasmDownloadRequest::partial(
571                    STRESS_WASM_URL_V1.to_string(),
572                    STRESS_WASM_SLOT.to_string(),
573                    base_ver,
574                )
575                .with_checksum(csum_v1)
576                .with_allow_downgrade(true);
577                let req_v2: WasmDownloadRequest = WasmDownloadRequest::partial(
578                    STRESS_WASM_URL_V2.to_string(),
579                    STRESS_WASM_SLOT.to_string(),
580                    base_ver + 1,
581                )
582                .with_checksum(csum_v2)
583                .with_allow_downgrade(true);
584                if manager.load_and_mount(req_v1, STRESS_WASM_KEY).is_ok()
585                    && manager.load_and_mount(req_v2, STRESS_WASM_KEY).is_ok()
586                    && manager
587                        .rollback_partial(STRESS_WASM_SLOT, STRESS_WASM_RB_REASON)
588                        .is_ok()
589                {
590                    let _: Result<FrameStats, PlatformError> = app.step_frame();
591                    completed += 1;
592                }
593            });
594            samples.push(dt);
595        }
596        let info: String = format!("cycles={completed}/12 cache={}", manager.cache_len());
597        (samples, info)
598    });
599    scope.dispose();
600    finalize_case(entry, &samples, false, details);
601}
602
603/// Runs Scenario 5: 30-frame mobile sidebar drawer slide-in & scrim animation over shadowed cards.
604///
605/// # Arguments
606///
607/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
608fn run_stress_drawer_anim(entry: &mut StressCaseResult) {
609    let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
610        let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
611        let palette: ThemePalette = tokens.get_palette();
612        let mut win: WindowConfig = WindowConfig::default();
613        win.set_size(360, 780).set_render(RenderConfig::software());
614        let mut config_spec: AppConfig = AppConfig::default();
615        config_spec.set_window(win);
616        let Ok(mut app) = App::headless(config_spec) else {
617            return (Vec::new(), STRESS_UNIT_NA.to_string());
618        };
619        let drawer_open: Signal<bool> = Signal::new(false);
620        let _: NodeId = app.mount(|| {
621            let column_fifth_style: Style = style! {
622                Width(Length::Percent(100.0))
623                Gap(SPACE_SM)
624            };
625            let text_eighth_style: Style = style! {
626                FontSize(14.0)
627                TextColor(palette.get_foreground())
628            };
629            let drawer_body: NodeId = view! {
630                column {
631                    style: column_fifth_style
632                    for idx in 0..8usize {
633                        text {
634                            style: text_eighth_style
635                            { format!("{STRESS_DRAWER_ITEM} {idx}") }
636                        }
637                    }
638                }
639            };
640            let column_quaternary_style: Style = style! {
641                Width(Length::Percent(100.0))
642                Height(Length::Percent(100.0))
643                Padding(Edges::all(SPACE_MD))
644                Gap(SPACE_MD)
645                Background(palette.get_background())
646            };
647            view! {
648                column {
649                    style: column_quaternary_style
650                    for idx in 0..6usize {
651                        EuvCard {
652                            title: format!("{STRESS_CARD_PREFIX} #{idx}")
653                            tokens: tokens
654                            subtitle: STRESS_CARD_SUB
655                            EuvBadge {
656                                label: STRESS_BADGE_TXT.to_string()
657                                tone: EuvTone::Primary
658                                tokens: tokens
659                            }
660                        }
661                    }
662                    EuvDrawer {
663                        open: drawer_open
664                        title: STRESS_DRAWER_TITLE.to_string()
665                        body: drawer_body
666                        tokens: tokens
667                    }
668                }
669            }
670        });
671        app.set_exact_physical_viewport(720, 1560, 2.0);
672        let _: Result<FrameStats, PlatformError> = app.step_frame();
673        let _: bool = drawer_open.set_if_changed(true);
674        let mut samples: Vec<f64> = Vec::with_capacity(30);
675        let mut active_frames: usize = 0;
676        for step in 0..30usize {
677            if step == 16 {
678                let _: bool = drawer_open.set_if_changed(false);
679            }
680            let dt: f64 = measure_ms(|| {
681                if app.step_game_frame(1.0 / 120.0).is_ok() && app.has_active_animations() {
682                    active_frames += 1;
683                }
684            });
685            samples.push(dt);
686        }
687        let info: String = format!("720x1560@2x anim_frames={active_frames} backdrop_cache=on");
688        (samples, info)
689    });
690    scope.dispose();
691    finalize_case(entry, &samples, true, details);
692}
693
694/// Runs Scenario 6: 240Hz multi-touch pan, 1,000-node hit-test, and tap-jitter drift verification.
695///
696/// # Arguments
697///
698/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
699fn run_stress_touch_hittest(entry: &mut StressCaseResult) {
700    let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
701        let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
702        let palette: ThemePalette = tokens.get_palette();
703        let mut win: WindowConfig = WindowConfig::default();
704        win.set_size(400, 800).set_render(RenderConfig::hardware());
705        let mut config_spec: AppConfig = AppConfig::default();
706        config_spec.set_window(win);
707        let Ok(mut app) = App::headless(config_spec) else {
708            return (Vec::new(), STRESS_UNIT_NA.to_string());
709        };
710        let mut scroll_id: NodeId = NodeId::default();
711        let _: NodeId = app.mount(|| {
712            let scroll_secondary_style: Style = style! {
713                Width(Length::Percent(100.0))
714                Height(Length::Percent(100.0))
715                Gap(SPACE_XS)
716                Padding(Edges::all(SPACE_SM))
717            };
718            let row_quaternary_style: Style = style! {
719                Width(Length::Percent(100.0))
720                Height(Length::Px(32.0))
721                Gap(SPACE_XS)
722            };
723            let text_fifth_style: Style = style! {
724                FontSize(12.0)
725                TextColor(palette.get_foreground())
726            };
727            let text_sixth_style: Style = style! {
728                FontSize(11.0)
729                TextColor(palette.get_muted_foreground())
730            };
731            let text_seventh_style: Style = style! {
732                FontSize(11.0)
733                TextColor(palette.get_primary())
734            };
735            view! {
736                scroll {
737                    node_ref: scroll_id
738                    style: scroll_secondary_style
739                    for idx in 0..250usize {
740                        row {
741                            style: row_quaternary_style
742                            text { style: text_fifth_style
743                                { format!("{STRESS_ROW_PREFIX} {idx}") } }
744                            text { style: text_sixth_style
745                                { STRESS_BADGE_TXT } }
746                            text { style: text_seventh_style
747                                { format!("#{idx}") } }
748                        }
749                    }
750                }
751            }
752        });
753        let _: Result<FrameStats, PlatformError> = app.step_frame();
754        let wid: WindowId = app.get_window_state().get_id();
755        app.dispatch_window_event(WindowEvent::PointerDown(
756            wid,
757            PointerEvent::touch(99, 200.0, 400.0),
758        ));
759        app.dispatch_window_event(WindowEvent::PointerMove(
760            wid,
761            PointerEvent::touch(99, 204.0, 406.0),
762        ));
763        app.dispatch_window_event(WindowEvent::PointerUp(
764            wid,
765            PointerEvent::touch(99, 204.0, 406.0),
766        ));
767        let _: Result<FrameStats, PlatformError> = app.step_frame();
768        let tap_drift: f32 = app.get_scene().with_read(
769            |tree: &SceneTree| {
770                tree.get_node(scroll_id)
771                    .map(|scene_node: &SceneNode| {
772                        scene_node.get_layout_box().get_scroll_offset().get_y()
773                    })
774                    .unwrap_or(0.0)
775            },
776            0.0,
777        );
778        let mut samples: Vec<f64> = Vec::with_capacity(120);
779        for step in 0..120usize {
780            let pos_y: f32 = 120.0 + ((step * 19) % 580) as f32;
781            let dt: f64 = measure_ms(|| {
782                app.dispatch_window_event(WindowEvent::PointerMove(
783                    wid,
784                    PointerEvent::mouse(200.0, pos_y),
785                ));
786                app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 14.0)));
787                let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
788            });
789            samples.push(dt);
790        }
791        let final_scroll: f32 = app.get_scene().with_read(
792            |tree: &SceneTree| {
793                tree.get_node(scroll_id)
794                    .map(|target_node: &SceneNode| {
795                        target_node.get_layout_box().get_scroll_offset().get_y()
796                    })
797                    .unwrap_or(0.0)
798            },
799            0.0,
800        );
801        let info: String =
802            format!("nodes=1000 tap_drift={tap_drift:.2}px scrolled={final_scroll:.0}px");
803        (samples, info)
804    });
805    scope.dispose();
806    finalize_case(entry, &samples, false, details);
807}
808
809/// Runs Scenario 7: HiDPI 3x (`1080x1920`) Gaussian shadow and SDF rounded-rect rasterization.
810///
811/// # Arguments
812///
813/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
814fn run_stress_hidpi_shadow(entry: &mut StressCaseResult) {
815    let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
816        let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
817        let mut win: WindowConfig = WindowConfig::default();
818        win.set_size(360, 640).set_render(RenderConfig::software());
819        let mut config_spec: AppConfig = AppConfig::default();
820        config_spec.set_window(win);
821        let Ok(mut app) = App::headless(config_spec) else {
822            return (Vec::new(), STRESS_UNIT_NA.to_string());
823        };
824        let mut scroll_id: NodeId = NodeId::default();
825        let _: NodeId = app.mount(|| {
826            let scroll_style: Style = style! {
827                Width(Length::Percent(100.0))
828                Height(Length::Percent(100.0))
829                Padding(Edges::all(SPACE_MD))
830                Gap(SPACE_MD)
831                Background(tokens.get_palette().get_background())
832            };
833            view! {
834                scroll {
835                    node_ref: scroll_id
836                    style: scroll_style
837                    for idx in 0..12usize {
838                        EuvCard {
839                            title: format!("{STRESS_CARD_PREFIX} #{idx}")
840                            tokens: tokens
841                            subtitle: STRESS_CARD_SUB
842                            EuvBadge {
843                                label: STRESS_BADGE_TXT.to_string()
844                                tone: EuvTone::Primary
845                                tokens: tokens
846                            }
847                            EuvProgress {
848                                value: ((idx % 9) as f32 + 1.0) * 0.1
849                                tokens: tokens
850                            }
851                        }
852                    }
853                }
854            }
855        });
856        app.set_exact_physical_viewport(1080, 1920, 3.0);
857        let _: Result<FrameStats, PlatformError> = app.step_frame();
858        let mut samples: Vec<f64> = Vec::with_capacity(12);
859        let mut last_shaded: usize = 0;
860        for step in 1..=12usize {
861            let offset_y: f32 = ((step as f32) * 24.0) % 600.0;
862            let dt: f64 = measure_ms(|| {
863                app.get_scene().with_write(
864                    |tree: &mut SceneTree| {
865                        tree.set_scroll_offset(scroll_id, Point::new(0.0, offset_y));
866                    },
867                    (),
868                );
869                if let Ok(stats) = app.step_frame() {
870                    last_shaded = stats.get_pixels_shaded();
871                }
872            });
873            samples.push(dt);
874        }
875        let info: String = format!("1080x1920@3x shaded={last_shaded}px/f");
876        (samples, info)
877    });
878    scope.dispose();
879    finalize_case(entry, &samples, true, details);
880}
881
882/// Runs Scenario 8: Unicode + CJK glyph rasterization and RGBA8 atlas shelf-packing.
883///
884/// # Arguments
885///
886/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
887fn run_stress_cjk_atlas(entry: &mut StressCaseResult) {
888    let sample_chars: [char; 16] = [
889        'A', 'W', 'g', '9', '跨', '端', '原', '生', '框', '架', '高', '性', '能', '渲', '染', '器',
890    ];
891    let provider: NativeSystemFont = NativeSystemFont::deterministic();
892    let mut samples: Vec<f64> = Vec::with_capacity(16);
893    let mut packed_regions: usize = 0;
894    let mut atlas_w: u32 = 0;
895    let mut atlas_h: u32 = 0;
896    for _ in 0..16usize {
897        let dt: f64 = measure_ms(|| {
898            let mut atlas: GlyphAtlas = GlyphAtlas::default();
899            for sz in [120u16, 160u16, 220u16].into_iter() {
900                for ch in sample_chars.iter() {
901                    let key: GlyphKey = GlyphKey::new(*ch, sz, sz >= 220);
902                    let _: &RasterizedGlyph = atlas.get_or_rasterize_with(key, &provider);
903                }
904            }
905            let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
906            packed_regions = packed.get_regions().len();
907            atlas_w = packed.get_width();
908            atlas_h = packed.get_height();
909        });
910        samples.push(dt);
911    }
912    let details: String = format!("glyphs={packed_regions} atlas={atlas_w}x{atlas_h}");
913    finalize_case(entry, &samples, false, details);
914}
915
916/// Runs Scenario 9: 2D rigid-body physics (256 bodies + 1,024 particles) and 3D BVH ray-tracing.
917///
918/// # Arguments
919///
920/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
921fn run_stress_game_2d_3d(entry: &mut StressCaseResult) {
922    let mut world2d: GameWorld = GameWorld::with_capacity(256);
923    for idx in 0..256usize {
924        let col: f32 = (idx % 16) as f32;
925        let row: f32 = (idx / 16) as f32;
926        let eid: EntityId = world2d.spawn(
927            EntityTag::Enemy,
928            Point::new(40.0 + col * 52.0, 40.0 + row * 40.0),
929        );
930        if let Some(ent) = world2d.get_entity_mut(eid) {
931            ent.set_velocity(Velocity2D::new(
932                if idx % 2 == 0 { 110.0 } else { -95.0 },
933                if idx % 3 == 0 { 85.0 } else { -75.0 },
934                0.0,
935            ));
936            ent.set_body(Some(RigidBody2D::dynamic(1.0, 0.9, 0.02)));
937            ent.set_collider(Some(Collider2D::circle(
938                10.0,
939                COLLISION_LAYER_ENEMY,
940                COLLISION_LAYER_ALL,
941                false,
942            )));
943        }
944    }
945    let mut phys_cfg: PhysicsConfig = PhysicsConfig::default();
946    phys_cfg.set_arena_bounds(Some(Rect::new(0.0, 0.0, 960.0, 720.0)));
947    let mut physics: PhysicsWorld2D = PhysicsWorld2D::with_config(phys_cfg);
948    let mut particles: ParticleSystem = ParticleSystem::with_capacity(1024);
949    let mut emit_cfg: ParticleEmitterConfig = ParticleEmitterConfig::default();
950    emit_cfg.set_min_life(10.0).set_max_life(20.0);
951    particles.emit_burst(Point::new(400.0, 300.0), 1024, emit_cfg);
952    let mut collisions: usize = 0;
953    let phys_ms: f64 = measure_ms(|| {
954        for _ in 0..60usize {
955            collisions += physics.step(&mut world2d, 1.0 / 60.0).len();
956            let _: usize = particles.update(1.0 / 60.0);
957        }
958    });
959    let mut world3d: World3D = World3D::create_open_world_city();
960    let mut renderer3d: Renderer3D = Renderer3D::default();
961    let cfg3d: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::High);
962    let mut samples: Vec<f64> = Vec::with_capacity(4);
963    let mut last_tris: usize = 0;
964    let mut last_rays: usize = 0;
965    for _ in 0..4usize {
966        let dt: f64 = measure_ms(|| {
967            let _: ImageBuffer = renderer3d.render_world(&mut world3d, 320, 180, &cfg3d);
968            let node_style: RenderStats3D = renderer3d.get_last_stats();
969            last_tris = node_style.get_triangles_drawn();
970            last_rays = node_style.get_rays_traced();
971        });
972        samples.push(dt);
973    }
974    let details: String =
975        format!("2d_60t={phys_ms:.2}ms col={collisions} 3d_tris={last_tris} rays={last_rays}");
976    finalize_case(entry, &samples, true, details);
977}
978
979/// Runs Scenario 10: declarative `view!` macro component tree mount, layout, and disposal.
980///
981/// # Arguments
982///
983/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
984fn run_stress_macro_mount(entry: &mut StressCaseResult) {
985    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
986    let palette: ThemePalette = tokens.get_palette();
987    let mut samples: Vec<f64> = Vec::with_capacity(8);
988    let mut last_nodes: usize = 0;
989    for _ in 0..8usize {
990        let dt: f64 = measure_ms(|| {
991            let scene: SceneHandle = SceneHandle::new_tree();
992            let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
993            let tree_root: NodeId = with_context(ctx, || {
994                let column_tertiary_style: Style = style! {
995                    Width(Length::Px(1000.0))
996                    Gap(SPACE_XS)
997                };
998                let row_tertiary_style: Style = style! {
999                    Width(Length::Percent(100.0))
1000                    JustifyContent::SpaceBetween
1001                    AlignItems::Center
1002                    Padding(Edges::symmetric(SPACE_XS, SPACE_SM))
1003                    Background(palette.get_card())
1004                };
1005                let text_quaternary_style: Style = style! {
1006                    FontSize(13.0)
1007                    TextColor(palette.get_foreground())
1008                };
1009                view! {
1010                    column {
1011                        style: column_tertiary_style
1012                        for idx in 0..160usize {
1013                            row {
1014                                style: row_tertiary_style
1015                                text {
1016                                    style: text_quaternary_style
1017                                    { format!("{STRESS_CARD_PREFIX} {idx}") }
1018                                }
1019                                EuvBadge {
1020                                    label: STRESS_BADGE_TXT.to_string()
1021                                    tone: EuvTone::Primary
1022                                    tokens: tokens
1023                                }
1024                            }
1025                        }
1026                    }
1027                }
1028            });
1029            let mut engine: LayoutEngine = LayoutEngine::default();
1030            scene.with_write(
1031                |tree: &mut SceneTree| {
1032                    let root: NodeId = tree.get_root();
1033                    tree.replace_children(root, vec![tree_root]);
1034                    let node_style: LayoutStats = engine.compute(tree, Size::new(1000.0, 800.0));
1035                    last_nodes = node_style.get_nodes_computed();
1036                },
1037                (),
1038            );
1039        });
1040        samples.push(dt);
1041    }
1042    let details: String = format!("cards=160 nodes={last_nodes} zero_alloc_macro=ok");
1043    finalize_case(entry, &samples, false, details);
1044}
1045
1046/// Executes a single interactive stress scenario by `scenario_id` and updates `state` signals immediately.
1047///
1048/// # Arguments
1049///
1050/// - `&ShowcaseState` - Reactive showcase state storing stress telemetry.
1051/// - `&str` - Stable scenario identifier (`STRESS_ID_*`).
1052pub fn execute_stress_case(state: &ShowcaseState, scenario_id: &str) {
1053    let results_sig: Signal<Vec<StressCaseResult>> = state.get_stress_results();
1054    let summary_sig: Signal<String> = state.get_stress_summary();
1055    let mut rows: Vec<StressCaseResult> = results_sig.get_untracked();
1056    let Some(entry) = rows
1057        .iter_mut()
1058        .find(|item: &&mut StressCaseResult| item.get_id().as_str() == scenario_id)
1059    else {
1060        return;
1061    };
1062    match scenario_id {
1063        STRESS_ID_VLIST_100K => run_stress_vlist_100k(entry),
1064        STRESS_ID_LAYOUT_2000 => run_stress_layout_2000(entry),
1065        STRESS_ID_REACTIVE_1000 => run_stress_reactive_1000(entry),
1066        STRESS_ID_WASM_HOTSWAP => run_stress_wasm_hotswap(entry),
1067        STRESS_ID_DRAWER_ANIM => run_stress_drawer_anim(entry),
1068        STRESS_ID_TOUCH_HITTEST => run_stress_touch_hittest(entry),
1069        STRESS_ID_HIDPI_SHADOW => run_stress_hidpi_shadow(entry),
1070        STRESS_ID_CJK_ATLAS => run_stress_cjk_atlas(entry),
1071        STRESS_ID_GAME_2D_3D => run_stress_game_2d_3d(entry),
1072        STRESS_ID_MACRO_MOUNT => run_stress_macro_mount(entry),
1073        _ => return,
1074    }
1075    let summary: String = format!(
1076        "{} -> {} | avg={:.2}ms p95={:.2}ms max={:.2}ms ({}) [{}]",
1077        entry.get_title(),
1078        entry.get_status(),
1079        entry.get_avg_ms(),
1080        entry.get_p95_ms(),
1081        entry.get_max_ms(),
1082        entry.get_throughput(),
1083        entry.get_details()
1084    );
1085    batch(|| {
1086        let _: bool = results_sig.set(rows);
1087        let _: bool = summary_sig.set_if_changed(summary);
1088    });
1089}
1090
1091/// Executes a slice of stress scenario identifiers sequentially and updates live summary telemetry.
1092///
1093/// # Arguments
1094///
1095/// - `&ShowcaseState` - Reactive showcase state storing stress telemetry.
1096/// - `&[&str]` - Ordered list of scenario IDs to run.
1097pub fn execute_stress_batch(state: &ShowcaseState, ids: &[&str]) {
1098    let mut total_ms: f64 = 0.0;
1099    for scenario_id in ids.iter() {
1100        let dt: f64 = measure_ms(|| execute_stress_case(state, scenario_id));
1101        total_ms += dt;
1102    }
1103    let rows: Vec<StressCaseResult> = state.get_stress_results().get_untracked();
1104    let completed: usize = rows
1105        .iter()
1106        .filter(|red_val: &&StressCaseResult| red_val.get_runs() > 0)
1107        .count();
1108    let passed: usize = rows
1109        .iter()
1110        .filter(|radius_val: &&StressCaseResult| {
1111            radius_val.get_status().as_str() == STRESS_STATUS_PASS
1112        })
1113        .count();
1114    let summary: String = format!(
1115        "Completed {completed}/{} scenarios ({passed}/{completed} within budget) in {total_ms:.1}ms total.",
1116        rows.len()
1117    );
1118    let _: bool = state.get_stress_summary().set_if_changed(summary);
1119}
1120
1121/// Mounts the declarative Interactive UI Stress & Performance Lab page (`/stress`).
1122///
1123/// # Arguments
1124///
1125/// - `&ShowcaseState` - Reactive showcase state.
1126/// - `ThemeTokens` - Active resolved design tokens.
1127///
1128/// # Returns
1129///
1130/// - `NodeId` - Mounted stress lab page handle.
1131pub fn mount_stress_page(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
1132    state.ensure_stress_loaded();
1133    let results_sig: Signal<Vec<StressCaseResult>> = state.get_stress_results();
1134    let summary_sig: Signal<String> = state.get_stress_summary();
1135    let st_all: ShowcaseState = state.clone();
1136    let st_core: ShowcaseState = state.clone();
1137    let st_reset: ShowcaseState = state.clone();
1138    let st_list: ShowcaseState = state.clone();
1139    let build_kpi_grid = move || -> Vec<NodeId> {
1140        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
1141        let rows: Vec<StressCaseResult> = results_sig.get();
1142        let total: usize = rows.len();
1143        let done: usize = rows
1144            .iter()
1145            .filter(|red_val: &&StressCaseResult| red_val.get_runs() > 0)
1146            .count();
1147        let passed: usize = rows
1148            .iter()
1149            .filter(|radius_val: &&StressCaseResult| {
1150                radius_val.get_status().as_str() == STRESS_STATUS_PASS
1151            })
1152            .count();
1153        let latest_opt: Option<&StressCaseResult> = rows
1154            .iter()
1155            .filter(|rect_val: &&StressCaseResult| rect_val.get_runs() > 0)
1156            .max_by_key(|row_val: &&StressCaseResult| row_val.get_runs());
1157        let (latest_val, latest_cap): (String, String) = match latest_opt {
1158            Some(item) => (
1159                format!("{:.2} ms", item.get_avg_ms()),
1160                format!("{} ({})", item.get_title(), item.get_throughput()),
1161            ),
1162            None => (
1163                STRESS_KPI_IDLE_VAL.to_string(),
1164                STRESS_KPI_IDLE_CAP.to_string(),
1165            ),
1166        };
1167        let budget_val: String = if done == 0 {
1168            STRESS_KPI_IDLE_VAL.to_string()
1169        } else {
1170            format!("{passed} / {done} {STRESS_STATUS_PASS}")
1171        };
1172        let kpi_grid: NodeId = view! {
1173            EuvStatGrid {
1174                EuvStatCard {
1175                    label: STRESS_KPI_COMPLETED_LABEL.to_string()
1176                    value: format!("{done} / {total}")
1177                    caption: format!("{total} interactive workloads ready")
1178                    tokens: live_tok
1179                }
1180                EuvStatCard {
1181                    label: STRESS_KPI_BUDGET_LABEL.to_string()
1182                    value: budget_val
1183                    caption: STRESS_KPI_BUDGET_CAP.to_string()
1184                    tokens: live_tok
1185                }
1186                EuvStatCard {
1187                    label: STRESS_KPI_LATEST_LABEL.to_string()
1188                    value: latest_val
1189                    caption: latest_cap
1190                    tokens: live_tok
1191                }
1192            }
1193        };
1194        vec![kpi_grid]
1195    };
1196    let on_run_all = move |_: &UiEvent| {
1197        let all_ids: [&str; 10] = [
1198            STRESS_ID_VLIST_100K,
1199            STRESS_ID_LAYOUT_2000,
1200            STRESS_ID_REACTIVE_1000,
1201            STRESS_ID_WASM_HOTSWAP,
1202            STRESS_ID_DRAWER_ANIM,
1203            STRESS_ID_TOUCH_HITTEST,
1204            STRESS_ID_HIDPI_SHADOW,
1205            STRESS_ID_CJK_ATLAS,
1206            STRESS_ID_GAME_2D_3D,
1207            STRESS_ID_MACRO_MOUNT,
1208        ];
1209        execute_stress_batch(&st_all, &all_ids);
1210    };
1211    let on_run_core = move |_: &UiEvent| {
1212        let core_ids: [&str; 5] = [
1213            STRESS_ID_VLIST_100K,
1214            STRESS_ID_LAYOUT_2000,
1215            STRESS_ID_REACTIVE_1000,
1216            STRESS_ID_WASM_HOTSWAP,
1217            STRESS_ID_DRAWER_ANIM,
1218        ];
1219        execute_stress_batch(&st_core, &core_ids);
1220    };
1221    let on_reset = move |_: &UiEvent| {
1222        batch(|| {
1223            let _: bool = st_reset.get_stress_results().set(default_stress_results());
1224            let _: bool = st_reset
1225                .get_stress_summary()
1226                .set_if_changed(STRESS_SUMMARY_READY.to_string());
1227        });
1228    };
1229    let summary_text = move || -> String { summary_sig.get() };
1230    let summary_style = move || -> Style {
1231        let live: ThemeTokens = use_live_tokens(tokens);
1232        style! {
1233            Width(Length::Percent(100.0))
1234            FontSize(13.0)
1235            TextColor(live.get_palette().get_primary())
1236        }
1237    };
1238    let build_scenario_grid = move || -> Vec<NodeId> {
1239        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
1240        let live_p: ThemePalette = live_tok.get_palette();
1241        let live_g: ThemeGeometry = live_tok.get_geometry();
1242        let rows: Vec<StressCaseResult> = results_sig.get();
1243        let mut cards: Vec<NodeId> = Vec::with_capacity(rows.len());
1244        for item in rows.into_iter() {
1245            let sid: String = item.get_id().clone();
1246            let st_run: ShowcaseState = st_list.clone();
1247            let status_tone: EuvTone = match item.get_status().as_str() {
1248                STRESS_STATUS_PASS => EuvTone::Success,
1249                STRESS_STATUS_WARN => EuvTone::Warning,
1250                _ => EuvTone::Neutral,
1251            };
1252            let metric_line: String = if item.get_runs() == 0 {
1253                format!(
1254                    "Budget <= {:.2}ms | Status: {} | Click button to run",
1255                    item.get_budget_ms(),
1256                    item.get_status()
1257                )
1258            } else {
1259                format!(
1260                    "Avg: {:.2}ms | P95: {:.2}ms | Max: {:.2}ms | Budget <= {:.2}ms | {} (runs={})",
1261                    item.get_avg_ms(),
1262                    item.get_p95_ms(),
1263                    item.get_max_ms(),
1264                    item.get_budget_ms(),
1265                    item.get_throughput(),
1266                    item.get_runs()
1267                )
1268            };
1269            let detail_line: String = if item.get_runs() == 0 {
1270                item.get_description().clone()
1271            } else {
1272                format!("{} | {}", item.get_description(), item.get_details())
1273            };
1274            let title_str: String = item.get_title().clone();
1275            let cat_str: String = item.get_category().clone();
1276            let status_str: String = item.get_status().clone();
1277            let btn_label: String = item.get_button_label().clone();
1278            let on_run_case = move |_: &UiEvent| {
1279                execute_stress_case(&st_run, &sid);
1280            };
1281            let column_secondary_style: Style = style! {
1282                Width(Length::Percent(100.0))
1283                Padding(Edges::all(SPACE_MD))
1284                Gap(SPACE_SM)
1285                Overflow::Hidden
1286                Background(live_p.get_card())
1287                Border::new(live_g.get_border_width(), live_p.get_border())
1288                Radius(live_g.get_radius_md())
1289            };
1290            let row_style: Style = style! {
1291                Width(Length::Percent(100.0))
1292                FlexWrap::Wrap
1293                JustifyContent::SpaceBetween
1294                AlignItems::Center
1295                Gap(SPACE_SM)
1296            };
1297            let text_style: Style = style! {
1298                FlexShrink(1.0)
1299                MinWidth(Length::Px(0.0))
1300                FontSize(14.0)
1301                FontWeight::Bold
1302                TextColor(live_p.get_card_foreground())
1303            };
1304            let row_secondary_style: Style = style! {
1305                Gap(SPACE_XS)
1306                AlignItems::Center
1307            };
1308            let text_secondary_style: Style = style! {
1309                Width(Length::Percent(100.0))
1310                FontSize(12.5)
1311                TextColor(live_p.get_muted_foreground())
1312            };
1313            let text_tertiary_style: Style = style! {
1314                Width(Length::Percent(100.0))
1315                FontSize(12.5)
1316                FontWeight::SemiBold
1317                TextColor(live_p.get_card_foreground())
1318            };
1319            let item_card: NodeId = view! {
1320                column {
1321                    style: column_secondary_style
1322                    row {
1323                        style: row_style
1324                        text {
1325                            style: text_style
1326                            { title_str }
1327                        }
1328                        row {
1329                            style: row_secondary_style
1330                            EuvBadge {
1331                                label: cat_str
1332                                tone: EuvTone::Primary
1333                                tokens: live_tok
1334                            }
1335                            EuvBadge {
1336                                label: status_str
1337                                tone: status_tone
1338                                tokens: live_tok
1339                            }
1340                        }
1341                    }
1342                    text {
1343                        style: text_secondary_style
1344                        { detail_line }
1345                    }
1346                    text {
1347                        style: text_tertiary_style
1348                        { metric_line }
1349                    }
1350                    EuvActionRow {
1351                        EuvButton {
1352                            label: btn_label
1353                            tokens: live_tok
1354                            outline()
1355                            small()
1356                            on_click: on_run_case
1357                        }
1358                    }
1359                }
1360            };
1361            cards.push(item_card);
1362        }
1363        vec![mount_responsive_grid(cards, 3)]
1364    };
1365    let column_style: Style = style! {
1366        Width(Length::Percent(100.0))
1367    };
1368    view! {
1369        EuvPage {
1370            title: STRESS_PAGE_TITLE.to_string()
1371            subtitle: STRESS_PAGE_SUBTITLE.to_string()
1372            tokens: tokens
1373            column {
1374                style: column_style
1375                bind_children: build_kpi_grid
1376            }
1377            EuvCard {
1378                title: STRESS_CTRL_TITLE.to_string()
1379                tokens: tokens
1380                subtitle: STRESS_CTRL_SUBTITLE
1381                EuvActionRow {
1382                    EuvButton {
1383                        label: STRESS_BTN_RUN_ALL.to_string()
1384                        tokens: tokens
1385                        small()
1386                        on_click: on_run_all
1387                    }
1388                    EuvButton {
1389                        label: STRESS_BTN_RUN_CORE.to_string()
1390                        tokens: tokens
1391                        outline()
1392                        small()
1393                        on_click: on_run_core
1394                    }
1395                    EuvButton {
1396                        label: STRESS_BTN_RESET.to_string()
1397                        tokens: tokens
1398                        outline()
1399                        small()
1400                        on_click: on_reset
1401                    }
1402                }
1403                text {
1404                    bind_style: summary_style
1405                    { summary_text }
1406                }
1407            }
1408            EuvCard {
1409                title: STRESS_SCENARIOS_TITLE.to_string()
1410                tokens: tokens
1411                subtitle: STRESS_SCENARIOS_SUB
1412                column {
1413                    style: column_style
1414                    bind_children: build_scenario_grid
1415                }
1416            }
1417        }
1418    }
1419}