Skip to main content

euv_example/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/// - `F` - Closure executing the benchmarked workload.
8///
9/// # Returns
10///
11/// - `f64` - Elapsed duration in milliseconds.
12#[cfg(not(target_arch = "wasm32"))]
13fn measure_ms<F>(work: F) -> f64
14where
15    F: 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/// - `F` - Closure executing the benchmarked workload.
27///
28/// # Returns
29///
30/// - `f64` - Elapsed duration in milliseconds.
31#[cfg(target_arch = "wasm32")]
32fn measure_ms<F>(work: F) -> f64
33where
34    F: FnOnce(),
35{
36    let perf: Option<Performance> = window().and_then(|w: Window| w.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 p: ThemePalette = tokens.get_palette();
258        let g: ThemeGeometry = tokens.get_geometry();
259        let mut win: WindowConfig = WindowConfig::default();
260        win.set_size(360, 640).set_render(RenderConfig::software());
261        let mut cfg: AppConfig = AppConfig::default();
262        cfg.set_window(win);
263        let Ok(mut app) = App::headless(cfg) 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                view! {
272                    row {
273                        width: Length::Percent(100.0)
274                        height: Length::Px(36.0)
275                        padding: Edges::symmetric(SPACE_XS, SPACE_MD)
276                        align: AlignItems::Center
277                        border: (g.get_border_width(), p.get_border())
278                        text {
279                            font_size: 13.0
280                            color: p.get_foreground()
281                            { format!("{STRESS_ROW_PREFIX} #{idx}") }
282                        }
283                    }
284                }
285            })
286        });
287        let _: Result<FrameStats, PlatformError> = app.step_frame();
288        let mut samples: Vec<f64> = Vec::with_capacity(24);
289        let mut last_shaded: usize = 0;
290        let mut mounted_nodes: usize = 0;
291        for step in 1..=24usize {
292            let next_y: f32 = ((step as f32) * 144.0) % 3_500_000.0;
293            let dt: f64 = measure_ms(|| {
294                let _: bool = scroll_y.set_if_changed(next_y);
295                if let Ok(stats) = app.step_frame() {
296                    last_shaded = stats.get_pixels_shaded();
297                }
298            });
299            samples.push(dt);
300        }
301        mounted_nodes = app.get_scene().with_read(
302            |tree: &SceneTree| {
303                tree.get_nodes()
304                    .iter()
305                    .filter(|n: &&SceneNode| n.get_alive())
306                    .count()
307            },
308            mounted_nodes,
309        );
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_node: NodeId = view! {
334                grid {
335                    columns: 4
336                    width: Length::Percent(100.0)
337                    gap: SPACE_SM
338                    for card_idx in 0..8usize {
339                        column {
340                            width: Length::Percent(100.0)
341                            padding: Edges::all(SPACE_SM)
342                            gap: SPACE_XS
343                            row {
344                                width: Length::Percent(100.0)
345                                justify: JustifyContent::SpaceBetween
346                                if card_idx == 0 {
347                                    text {
348                                        node_ref: first_title
349                                        font_size: 13.0
350                                        { format!("{STRESS_CELL_PREFIX} {section_idx}-{card_idx}") }
351                                    }
352                                } else {
353                                    text {
354                                        font_size: 13.0
355                                        { format!("{STRESS_CELL_PREFIX} {section_idx}-{card_idx}") }
356                                    }
357                                }
358                                text {
359                                    font_size: 11.0
360                                    { format!("{section_idx}") }
361                                }
362                            }
363                        }
364                    }
365                }
366            };
367            leaves.push(first_title);
368            sections.push(grid_node);
369        }
370        let p_node: NodeId = view! {
371            column {
372                width: Length::Px(1280.0)
373                padding: Edges::all(SPACE_MD)
374                gap: SPACE_SM
375                ..sections
376            }
377        };
378        (leaves, p_node)
379    });
380    scene.with_write(
381        |tree: &mut SceneTree| {
382            let root: NodeId = tree.get_root();
383            tree.replace_children(root, vec![page]);
384        },
385        (),
386    );
387    let mut engine: LayoutEngine = LayoutEngine::default();
388    let viewport: Size = Size::new(1280.0, 800.0);
389    let mut init_nodes: usize = 0;
390    let init_ms: f64 = measure_ms(|| {
391        let st: LayoutStats = scene.with_write(
392            |tree: &mut SceneTree| engine.compute(tree, viewport),
393            LayoutStats::default(),
394        );
395        init_nodes = st.get_nodes_computed();
396    });
397    let mut samples: Vec<f64> = Vec::with_capacity(40);
398    let mut total_computed: usize = 0;
399    let mut total_skipped: usize = 0;
400    for step in 0..40usize {
401        let target: NodeId = leaf_nodes[step % leaf_nodes.len()];
402        let dt: f64 = measure_ms(|| {
403            scene.with_write(
404                |tree: &mut SceneTree| {
405                    tree.set_text(target, format!("{STRESS_CELL_PREFIX} #{step}"));
406                    let stats: LayoutStats = engine.compute(tree, viewport);
407                    total_computed += stats.get_nodes_computed();
408                    total_skipped += stats.get_subtrees_skipped();
409                },
410                (),
411            );
412        });
413        samples.push(dt);
414    }
415    let details: String = format!(
416        "nodes={init_nodes} init={init_ms:.2}ms avg_recomputed={} skipped={}",
417        total_computed / 40,
418        total_skipped / 40
419    );
420    finalize_case(entry, &samples, false, details);
421}
422
423/// Runs Scenario 3: bulk batched reactive signal and memo updates across 1,000 live components.
424///
425/// # Arguments
426///
427/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
428fn run_stress_reactive_1000(entry: &mut StressCaseResult) {
429    let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
430        let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
431        let p: ThemePalette = tokens.get_palette();
432        let mut win: WindowConfig = WindowConfig::default();
433        win.set_size(800, 600).set_render(RenderConfig::hardware());
434        let mut cfg: AppConfig = AppConfig::default();
435        cfg.set_window(win);
436        let Ok(mut app) = App::headless(cfg) else {
437            return (Vec::new(), STRESS_UNIT_NA.to_string());
438        };
439        let mut signals: Vec<Signal<u32>> = Vec::with_capacity(1_000);
440        for idx in 0..1_000u32 {
441            signals.push(Signal::new(idx));
442        }
443        let signals_mount: Vec<Signal<u32>> = signals.clone();
444        let _: NodeId = app.mount(move || {
445            let derived_memos: Vec<Memo<u32>> = signals_mount
446                .into_iter()
447                .map(|sig: Signal<u32>| {
448                    Memo::new(move || sig.get().wrapping_mul(3).wrapping_add(1))
449                })
450                .collect();
451            view! {
452                scroll {
453                    width: Length::Percent(100.0)
454                    height: Length::Percent(100.0)
455                    gap: 2.0
456                    for derived in derived_memos.into_iter() {
457                        text {
458                            font_size: 12.0
459                            color: p.get_foreground()
460                            { move || format!("{STRESS_CELL_PREFIX} {}", derived.get()) }
461                        }
462                    }
463                }
464            }
465        });
466        let _: Result<FrameStats, PlatformError> = app.step_frame();
467        let mut samples: Vec<f64> = Vec::with_capacity(16);
468        let mut last_rev: u64 = 0;
469        for tick in 1..=16u32 {
470            let dt: f64 = measure_ms(|| {
471                batch(|| {
472                    for (idx, sig) in signals.iter().enumerate() {
473                        let _: bool = sig.set_if_changed(tick.wrapping_add(idx as u32));
474                    }
475                });
476                flush_effects();
477                if app.step_frame().is_ok() {
478                    last_rev = app.get_last_rendered_revision();
479                }
480            });
481            samples.push(dt);
482        }
483        let info: String = format!("signals=1000 memos=1000 rev={last_rev}");
484        (samples, info)
485    });
486    scope.dispose();
487    finalize_case(entry, &samples, false, details);
488}
489
490/// Runs Scenario 4: dynamic `.wasm` binary verification, sandbox execution, hot-swap, and rollback.
491///
492/// # Arguments
493///
494/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
495fn run_stress_wasm_hotswap(entry: &mut StressCaseResult) {
496    let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
497        let mut win: WindowConfig = WindowConfig::default();
498        win.set_size(640, 480).set_render(RenderConfig::hardware());
499        let mut cfg: AppConfig = AppConfig::default();
500        cfg.set_window(win);
501        let Ok(mut app) = App::headless(cfg) else {
502            return (Vec::new(), STRESS_UNIT_NA.to_string());
503        };
504        let hub: DynamicUpdateHub = app.get_dynamic_hub().clone();
505        let registry: RegistryWasmFetcher = RegistryWasmFetcher::default();
506        let wasm_v1: Vec<u8> = build_partial_widget_wasm(STRESS_WASM_TITLE_V1, 1, 0x2563EB);
507        let wasm_v2: Vec<u8> = build_partial_widget_wasm(STRESS_WASM_TITLE_V2, 2, 0x7C3AED);
508        let csum_v1: u64 = compute_wasm_checksum(&wasm_v1);
509        let csum_v2: u64 = compute_wasm_checksum(&wasm_v2);
510        registry.register(
511            STRESS_WASM_URL_V1.to_string(),
512            wasm_v1,
513            STRESS_WASM_ETAG_V1.to_string(),
514            WasmFaultKind::None,
515        );
516        registry.register(
517            STRESS_WASM_URL_V2.to_string(),
518            wasm_v2,
519            STRESS_WASM_ETAG_V2.to_string(),
520            WasmFaultKind::None,
521        );
522        let manager: WasmDynamicManager =
523            WasmDynamicManager::new(hub.clone(), Rc::new(registry), WasmSandboxConfig::default());
524        let hub_slot: DynamicUpdateHub = hub;
525        let _: NodeId = app.mount(move || {
526            view! {
527                slot {
528                    id: STRESS_WASM_SLOT
529                    hub: hub_slot
530                    text {
531                        font_size: 14.0
532                        { STRESS_WASM_FALLBACK }
533                    }
534                }
535            }
536        });
537        let _: Result<FrameStats, PlatformError> = app.step_frame();
538        let mut samples: Vec<f64> = Vec::with_capacity(12);
539        let mut completed: usize = 0;
540        for cycle in 0..12usize {
541            let base_ver: u64 = ((cycle as u64) * 2) + 1;
542            let dt: f64 = measure_ms(|| {
543                let req_v1: WasmDownloadRequest = WasmDownloadRequest::partial(
544                    STRESS_WASM_URL_V1.to_string(),
545                    STRESS_WASM_SLOT.to_string(),
546                    base_ver,
547                )
548                .with_checksum(csum_v1)
549                .with_allow_downgrade(true);
550                let req_v2: WasmDownloadRequest = WasmDownloadRequest::partial(
551                    STRESS_WASM_URL_V2.to_string(),
552                    STRESS_WASM_SLOT.to_string(),
553                    base_ver + 1,
554                )
555                .with_checksum(csum_v2)
556                .with_allow_downgrade(true);
557                if manager.load_and_mount(req_v1, STRESS_WASM_KEY).is_ok()
558                    && manager.load_and_mount(req_v2, STRESS_WASM_KEY).is_ok()
559                    && manager
560                        .rollback_partial(STRESS_WASM_SLOT, STRESS_WASM_RB_REASON)
561                        .is_ok()
562                {
563                    let _: Result<FrameStats, PlatformError> = app.step_frame();
564                    completed += 1;
565                }
566            });
567            samples.push(dt);
568        }
569        let info: String = format!("cycles={completed}/12 cache={}", manager.cache_len());
570        (samples, info)
571    });
572    scope.dispose();
573    finalize_case(entry, &samples, false, details);
574}
575
576/// Runs Scenario 5: 30-frame mobile sidebar drawer slide-in & scrim animation over shadowed cards.
577///
578/// # Arguments
579///
580/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
581fn run_stress_drawer_anim(entry: &mut StressCaseResult) {
582    let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
583        let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
584        let p: ThemePalette = tokens.get_palette();
585        let mut win: WindowConfig = WindowConfig::default();
586        win.set_size(360, 780).set_render(RenderConfig::software());
587        let mut cfg: AppConfig = AppConfig::default();
588        cfg.set_window(win);
589        let Ok(mut app) = App::headless(cfg) else {
590            return (Vec::new(), STRESS_UNIT_NA.to_string());
591        };
592        let drawer_open: Signal<bool> = Signal::new(false);
593        let _: NodeId = app.mount(|| {
594            let drawer_body: NodeId = view! {
595                column {
596                    width: Length::Percent(100.0)
597                    gap: SPACE_SM
598                    for idx in 0..8usize {
599                        text {
600                            font_size: 14.0
601                            color: p.get_foreground()
602                            { format!("{STRESS_DRAWER_ITEM} {idx}") }
603                        }
604                    }
605                }
606            };
607            view! {
608                column {
609                    width: Length::Percent(100.0)
610                    height: Length::Percent(100.0)
611                    padding: Edges::all(SPACE_MD)
612                    gap: SPACE_MD
613                    background: p.get_background()
614                    for idx in 0..6usize {
615                        EuvCard(format!("{STRESS_CARD_PREFIX} #{idx}"), tokens) {
616                            subtitle: STRESS_CARD_SUB
617                            EuvBadge(STRESS_BADGE_TXT.to_string(), EuvTone::Primary, tokens)
618                        }
619                    }
620                    EuvDrawer(drawer_open, STRESS_DRAWER_TITLE.to_string(), drawer_body, tokens)
621                }
622            }
623        });
624        app.set_exact_physical_viewport(720, 1560, 2.0);
625        let _: Result<FrameStats, PlatformError> = app.step_frame();
626        let _: bool = drawer_open.set_if_changed(true);
627        let mut samples: Vec<f64> = Vec::with_capacity(30);
628        let mut active_frames: usize = 0;
629        for step in 0..30usize {
630            if step == 16 {
631                let _: bool = drawer_open.set_if_changed(false);
632            }
633            let dt: f64 = measure_ms(|| {
634                if app.step_game_frame(1.0 / 120.0).is_ok() && app.has_active_animations() {
635                    active_frames += 1;
636                }
637            });
638            samples.push(dt);
639        }
640        let info: String = format!("720x1560@2x anim_frames={active_frames} backdrop_cache=on");
641        (samples, info)
642    });
643    scope.dispose();
644    finalize_case(entry, &samples, true, details);
645}
646
647/// Runs Scenario 6: 240Hz multi-touch pan, 1,000-node hit-test, and tap-jitter drift verification.
648///
649/// # Arguments
650///
651/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
652fn run_stress_touch_hittest(entry: &mut StressCaseResult) {
653    let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
654        let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
655        let p: ThemePalette = tokens.get_palette();
656        let mut win: WindowConfig = WindowConfig::default();
657        win.set_size(400, 800).set_render(RenderConfig::hardware());
658        let mut cfg: AppConfig = AppConfig::default();
659        cfg.set_window(win);
660        let Ok(mut app) = App::headless(cfg) else {
661            return (Vec::new(), STRESS_UNIT_NA.to_string());
662        };
663        let mut scroll_id: NodeId = NodeId::default();
664        let _: NodeId = app.mount(|| {
665            view! {
666                scroll {
667                    node_ref: scroll_id
668                    width: Length::Percent(100.0)
669                    height: Length::Percent(100.0)
670                    gap: SPACE_XS
671                    padding: Edges::all(SPACE_SM)
672                    for idx in 0..250usize {
673                        row {
674                            width: Length::Percent(100.0)
675                            height: Length::Px(32.0)
676                            gap: SPACE_XS
677                            text { font_size: 12.0 color: p.get_foreground() { format!("{STRESS_ROW_PREFIX} {idx}") } }
678                            text { font_size: 11.0 color: p.get_muted_foreground() { STRESS_BADGE_TXT } }
679                            text { font_size: 11.0 color: p.get_primary() { format!("#{idx}") } }
680                        }
681                    }
682                }
683            }
684        });
685        let _: Result<FrameStats, PlatformError> = app.step_frame();
686        let wid: WindowId = app.get_window_state().get_id();
687        app.dispatch_window_event(WindowEvent::PointerDown(
688            wid,
689            PointerEvent::touch(99, 200.0, 400.0),
690        ));
691        app.dispatch_window_event(WindowEvent::PointerMove(
692            wid,
693            PointerEvent::touch(99, 204.0, 406.0),
694        ));
695        app.dispatch_window_event(WindowEvent::PointerUp(
696            wid,
697            PointerEvent::touch(99, 204.0, 406.0),
698        ));
699        let _: Result<FrameStats, PlatformError> = app.step_frame();
700        let tap_drift: f32 = app.get_scene().with_read(
701            |tree: &SceneTree| {
702                tree.get_node(scroll_id)
703                    .map(|n: &SceneNode| n.get_layout_box().get_scroll_offset().get_y())
704                    .unwrap_or(0.0)
705            },
706            0.0,
707        );
708        let mut samples: Vec<f64> = Vec::with_capacity(120);
709        for step in 0..120usize {
710            let y: f32 = 120.0 + ((step * 19) % 580) as f32;
711            let dt: f64 = measure_ms(|| {
712                app.dispatch_window_event(WindowEvent::PointerMove(
713                    wid,
714                    PointerEvent::mouse(200.0, y),
715                ));
716                app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 14.0)));
717                let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
718            });
719            samples.push(dt);
720        }
721        let final_scroll: f32 = app.get_scene().with_read(
722            |tree: &SceneTree| {
723                tree.get_node(scroll_id)
724                    .map(|n: &SceneNode| n.get_layout_box().get_scroll_offset().get_y())
725                    .unwrap_or(0.0)
726            },
727            0.0,
728        );
729        let info: String =
730            format!("nodes=1000 tap_drift={tap_drift:.2}px scrolled={final_scroll:.0}px");
731        (samples, info)
732    });
733    scope.dispose();
734    finalize_case(entry, &samples, false, details);
735}
736
737/// Runs Scenario 7: HiDPI 3x (`1080x1920`) Gaussian shadow and SDF rounded-rect rasterization.
738///
739/// # Arguments
740///
741/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
742fn run_stress_hidpi_shadow(entry: &mut StressCaseResult) {
743    let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
744        let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
745        let mut win: WindowConfig = WindowConfig::default();
746        win.set_size(360, 640).set_render(RenderConfig::software());
747        let mut cfg: AppConfig = AppConfig::default();
748        cfg.set_window(win);
749        let Ok(mut app) = App::headless(cfg) else {
750            return (Vec::new(), STRESS_UNIT_NA.to_string());
751        };
752        let mut scroll_id: NodeId = NodeId::default();
753        let _: NodeId = app.mount(|| {
754            view! {
755                scroll {
756                    node_ref: scroll_id
757                    width: Length::Percent(100.0)
758                    height: Length::Percent(100.0)
759                    padding: Edges::all(SPACE_MD)
760                    gap: SPACE_MD
761                    background: tokens.get_palette().get_background()
762                    for idx in 0..12usize {
763                        EuvCard(format!("{STRESS_CARD_PREFIX} #{idx}"), tokens) {
764                            subtitle: STRESS_CARD_SUB
765                            EuvBadge(STRESS_BADGE_TXT.to_string(), EuvTone::Primary, tokens)
766                            EuvProgress(((idx % 9) as f32 + 1.0) * 0.1, tokens)
767                        }
768                    }
769                }
770            }
771        });
772        app.set_exact_physical_viewport(1080, 1920, 3.0);
773        let _: Result<FrameStats, PlatformError> = app.step_frame();
774        let mut samples: Vec<f64> = Vec::with_capacity(12);
775        let mut last_shaded: usize = 0;
776        for step in 1..=12usize {
777            let offset_y: f32 = ((step as f32) * 24.0) % 600.0;
778            let dt: f64 = measure_ms(|| {
779                app.get_scene().with_write(
780                    |tree: &mut SceneTree| {
781                        tree.set_scroll_offset(scroll_id, Point::new(0.0, offset_y));
782                    },
783                    (),
784                );
785                if let Ok(stats) = app.step_frame() {
786                    last_shaded = stats.get_pixels_shaded();
787                }
788            });
789            samples.push(dt);
790        }
791        let info: String = format!("1080x1920@3x shaded={last_shaded}px/f");
792        (samples, info)
793    });
794    scope.dispose();
795    finalize_case(entry, &samples, true, details);
796}
797
798/// Runs Scenario 8: Unicode + CJK glyph rasterization and RGBA8 atlas shelf-packing.
799///
800/// # Arguments
801///
802/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
803fn run_stress_cjk_atlas(entry: &mut StressCaseResult) {
804    let sample_chars: [char; 16] = [
805        'A', 'W', 'g', '9', '跨', '端', '原', '生', '框', '架', '高', '性', '能', '渲', '染', '器',
806    ];
807    let provider: NativeSystemFont = NativeSystemFont::deterministic();
808    let mut samples: Vec<f64> = Vec::with_capacity(16);
809    let mut packed_regions: usize = 0;
810    let mut atlas_w: u32 = 0;
811    let mut atlas_h: u32 = 0;
812    for _ in 0..16usize {
813        let dt: f64 = measure_ms(|| {
814            let mut atlas: GlyphAtlas = GlyphAtlas::default();
815            for sz in [120u16, 160u16, 220u16].into_iter() {
816                for ch in sample_chars.iter() {
817                    let key: GlyphKey = GlyphKey::new(*ch, sz, sz >= 220);
818                    let _: &RasterizedGlyph = atlas.get_or_rasterize_with(key, &provider);
819                }
820            }
821            let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
822            packed_regions = packed.get_regions().len();
823            atlas_w = packed.get_width();
824            atlas_h = packed.get_height();
825        });
826        samples.push(dt);
827    }
828    let details: String = format!("glyphs={packed_regions} atlas={atlas_w}x{atlas_h}");
829    finalize_case(entry, &samples, false, details);
830}
831
832/// Runs Scenario 9: 2D rigid-body physics (256 bodies + 1,024 particles) and 3D BVH ray-tracing.
833///
834/// # Arguments
835///
836/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
837fn run_stress_game_2d_3d(entry: &mut StressCaseResult) {
838    let mut world2d: GameWorld = GameWorld::with_capacity(256);
839    for idx in 0..256usize {
840        let col: f32 = (idx % 16) as f32;
841        let row: f32 = (idx / 16) as f32;
842        let eid: EntityId = world2d.spawn(
843            EntityTag::Enemy,
844            Point::new(40.0 + col * 52.0, 40.0 + row * 40.0),
845        );
846        if let Some(ent) = world2d.get_entity_mut(eid) {
847            ent.set_velocity(Velocity2D::new(
848                if idx % 2 == 0 { 110.0 } else { -95.0 },
849                if idx % 3 == 0 { 85.0 } else { -75.0 },
850                0.0,
851            ));
852            ent.set_body(Some(RigidBody2D::dynamic(1.0, 0.9, 0.02)));
853            ent.set_collider(Some(Collider2D::circle(
854                10.0,
855                COLLISION_LAYER_ENEMY,
856                COLLISION_LAYER_ALL,
857                false,
858            )));
859        }
860    }
861    let mut phys_cfg: PhysicsConfig = PhysicsConfig::default();
862    phys_cfg.set_arena_bounds(Some(Rect::new(0.0, 0.0, 960.0, 720.0)));
863    let mut physics: PhysicsWorld2D = PhysicsWorld2D::with_config(phys_cfg);
864    let mut particles: ParticleSystem = ParticleSystem::with_capacity(1024);
865    let mut emit_cfg: ParticleEmitterConfig = ParticleEmitterConfig::default();
866    emit_cfg.set_min_life(10.0).set_max_life(20.0);
867    particles.emit_burst(Point::new(400.0, 300.0), 1024, emit_cfg);
868    let mut collisions: usize = 0;
869    let phys_ms: f64 = measure_ms(|| {
870        for _ in 0..60usize {
871            collisions += physics.step(&mut world2d, 1.0 / 60.0).len();
872            let _: usize = particles.update(1.0 / 60.0);
873        }
874    });
875    let mut world3d: World3D = World3D::create_open_world_city();
876    let mut renderer3d: Renderer3D = Renderer3D::default();
877    let cfg3d: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::High);
878    let mut samples: Vec<f64> = Vec::with_capacity(4);
879    let mut last_tris: usize = 0;
880    let mut last_rays: usize = 0;
881    for _ in 0..4usize {
882        let dt: f64 = measure_ms(|| {
883            let _: ImageBuffer = renderer3d.render_world(&mut world3d, 320, 180, &cfg3d);
884            let st: RenderStats3D = renderer3d.get_last_stats();
885            last_tris = st.get_triangles_drawn();
886            last_rays = st.get_rays_traced();
887        });
888        samples.push(dt);
889    }
890    let details: String =
891        format!("2d_60t={phys_ms:.2}ms col={collisions} 3d_tris={last_tris} rays={last_rays}");
892    finalize_case(entry, &samples, true, details);
893}
894
895/// Runs Scenario 10: declarative `view!` macro component tree mount, layout, and disposal.
896///
897/// # Arguments
898///
899/// - `&mut StressCaseResult` - Result slot populated with live timing metrics.
900fn run_stress_macro_mount(entry: &mut StressCaseResult) {
901    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
902    let p: ThemePalette = tokens.get_palette();
903    let mut samples: Vec<f64> = Vec::with_capacity(8);
904    let mut last_nodes: usize = 0;
905    for _ in 0..8usize {
906        let dt: f64 = measure_ms(|| {
907            let scene: SceneHandle = SceneHandle::new_tree();
908            let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
909            let tree_root: NodeId = with_context(ctx, || {
910                view! {
911                    column {
912                        width: Length::Px(1000.0)
913                        gap: SPACE_XS
914                        for idx in 0..160usize {
915                            row {
916                                width: Length::Percent(100.0)
917                                justify: JustifyContent::SpaceBetween
918                                align: AlignItems::Center
919                                padding: Edges::symmetric(SPACE_XS, SPACE_SM)
920                                background: p.get_card()
921                                text {
922                                    font_size: 13.0
923                                    color: p.get_foreground()
924                                    { format!("{STRESS_CARD_PREFIX} {idx}") }
925                                }
926                                EuvBadge(STRESS_BADGE_TXT.to_string(), EuvTone::Primary, tokens)
927                            }
928                        }
929                    }
930                }
931            });
932            let mut engine: LayoutEngine = LayoutEngine::default();
933            scene.with_write(
934                |tree: &mut SceneTree| {
935                    let root: NodeId = tree.get_root();
936                    tree.replace_children(root, vec![tree_root]);
937                    let st: LayoutStats = engine.compute(tree, Size::new(1000.0, 800.0));
938                    last_nodes = st.get_nodes_computed();
939                },
940                (),
941            );
942        });
943        samples.push(dt);
944    }
945    let details: String = format!("cards=160 nodes={last_nodes} zero_alloc_macro=ok");
946    finalize_case(entry, &samples, false, details);
947}
948
949/// Executes a single interactive stress scenario by `scenario_id` and updates `state` signals immediately.
950///
951/// # Arguments
952///
953/// - `&ShowcaseState` - Reactive showcase state storing stress telemetry.
954/// - `&str` - Stable scenario identifier (`STRESS_ID_*`).
955pub fn execute_stress_case(state: &ShowcaseState, scenario_id: &str) {
956    let results_sig: Signal<Vec<StressCaseResult>> = state.get_stress_results();
957    let summary_sig: Signal<String> = state.get_stress_summary();
958    let mut rows: Vec<StressCaseResult> = results_sig.get_untracked();
959    let Some(entry) = rows
960        .iter_mut()
961        .find(|item: &&mut StressCaseResult| item.get_id().as_str() == scenario_id)
962    else {
963        return;
964    };
965    match scenario_id {
966        STRESS_ID_VLIST_100K => run_stress_vlist_100k(entry),
967        STRESS_ID_LAYOUT_2000 => run_stress_layout_2000(entry),
968        STRESS_ID_REACTIVE_1000 => run_stress_reactive_1000(entry),
969        STRESS_ID_WASM_HOTSWAP => run_stress_wasm_hotswap(entry),
970        STRESS_ID_DRAWER_ANIM => run_stress_drawer_anim(entry),
971        STRESS_ID_TOUCH_HITTEST => run_stress_touch_hittest(entry),
972        STRESS_ID_HIDPI_SHADOW => run_stress_hidpi_shadow(entry),
973        STRESS_ID_CJK_ATLAS => run_stress_cjk_atlas(entry),
974        STRESS_ID_GAME_2D_3D => run_stress_game_2d_3d(entry),
975        STRESS_ID_MACRO_MOUNT => run_stress_macro_mount(entry),
976        _ => return,
977    }
978    let summary: String = format!(
979        "{} -> {} | avg={:.2}ms p95={:.2}ms max={:.2}ms ({}) [{}]",
980        entry.get_title(),
981        entry.get_status(),
982        entry.get_avg_ms(),
983        entry.get_p95_ms(),
984        entry.get_max_ms(),
985        entry.get_throughput(),
986        entry.get_details()
987    );
988    batch(|| {
989        let _: bool = results_sig.set(rows);
990        let _: bool = summary_sig.set_if_changed(summary);
991    });
992}
993
994/// Executes a slice of stress scenario identifiers sequentially and updates live summary telemetry.
995///
996/// # Arguments
997///
998/// - `&ShowcaseState` - Reactive showcase state storing stress telemetry.
999/// - `&[&str]` - Ordered list of scenario IDs to run.
1000pub fn execute_stress_batch(state: &ShowcaseState, ids: &[&str]) {
1001    let mut total_ms: f64 = 0.0;
1002    for scenario_id in ids.iter() {
1003        let dt: f64 = measure_ms(|| execute_stress_case(state, scenario_id));
1004        total_ms += dt;
1005    }
1006    let rows: Vec<StressCaseResult> = state.get_stress_results().get_untracked();
1007    let completed: usize = rows
1008        .iter()
1009        .filter(|r: &&StressCaseResult| r.get_runs() > 0)
1010        .count();
1011    let passed: usize = rows
1012        .iter()
1013        .filter(|r: &&StressCaseResult| r.get_status().as_str() == STRESS_STATUS_PASS)
1014        .count();
1015    let summary: String = format!(
1016        "Completed {completed}/{} scenarios ({passed}/{completed} within budget) in {total_ms:.1}ms total.",
1017        rows.len()
1018    );
1019    let _: bool = state.get_stress_summary().set_if_changed(summary);
1020}
1021
1022/// Mounts the declarative Interactive UI Stress & Performance Lab page (`/stress`).
1023///
1024/// # Arguments
1025///
1026/// - `&ShowcaseState` - Reactive showcase state.
1027/// - `ThemeTokens` - Active resolved design tokens.
1028///
1029/// # Returns
1030///
1031/// - `NodeId` - Mounted stress lab page handle.
1032pub fn mount_stress_page(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
1033    let p: ThemePalette = tokens.get_palette();
1034    let g: ThemeGeometry = tokens.get_geometry();
1035    let results_sig: Signal<Vec<StressCaseResult>> = state.get_stress_results();
1036    let summary_sig: Signal<String> = state.get_stress_summary();
1037    let st_all: ShowcaseState = state.clone();
1038    let st_core: ShowcaseState = state.clone();
1039    let st_reset: ShowcaseState = state.clone();
1040    let st_list: ShowcaseState = state.clone();
1041    view! {
1042        EuvPage(STRESS_PAGE_TITLE.to_string(), STRESS_PAGE_SUBTITLE.to_string(), tokens) {
1043            column {
1044                width: Length::Percent(100.0)
1045                bind_children: move || {
1046                    let rows: Vec<StressCaseResult> = results_sig.get();
1047                    let total: usize = rows.len();
1048                    let done: usize = rows.iter().filter(|r: &&StressCaseResult| r.get_runs() > 0).count();
1049                    let passed: usize = rows
1050                    .iter()
1051                    .filter(|r: &&StressCaseResult| r.get_status().as_str() == STRESS_STATUS_PASS)
1052                    .count();
1053                    let latest_opt: Option<&StressCaseResult> = rows
1054                    .iter()
1055                    .filter(|r: &&StressCaseResult| r.get_runs() > 0)
1056                    .max_by_key(|r: &&StressCaseResult| r.get_runs());
1057                    let (latest_val, latest_cap): (String, String) = match latest_opt {
1058                        Some(item) => (
1059                            format!("{:.2} ms", item.get_avg_ms()),
1060                            format!("{} ({})", item.get_title(), item.get_throughput()),
1061                        ),
1062                        None => (
1063                            STRESS_KPI_IDLE_VAL.to_string(),
1064                            STRESS_KPI_IDLE_CAP.to_string(),
1065                        ),
1066                    };
1067                    let kpi_grid: NodeId = view! {
1068                        EuvStatGrid() {
1069                            EuvStatCard(
1070                                STRESS_KPI_COMPLETED_LABEL.to_string(),
1071                                format!("{done} / {total}"),
1072                                format!("{total} interactive workloads ready"),
1073                                tokens
1074                            )
1075                            EuvStatCard(
1076                                STRESS_KPI_BUDGET_LABEL.to_string(),
1077                                if done == 0 {
1078                                    STRESS_KPI_IDLE_VAL.to_string()
1079                                } else {
1080                                    format!("{passed} / {done} {STRESS_STATUS_PASS}")
1081                                },
1082                                STRESS_KPI_BUDGET_CAP.to_string(),
1083                                tokens
1084                            )
1085                            EuvStatCard(
1086                                STRESS_KPI_LATEST_LABEL.to_string(),
1087                                latest_val,
1088                                latest_cap,
1089                                tokens
1090                            )
1091                        }
1092                    };
1093                    vec![kpi_grid]
1094                }
1095            }
1096            EuvCard(STRESS_CTRL_TITLE.to_string(), tokens) {
1097                subtitle: STRESS_CTRL_SUBTITLE
1098                EuvActionRow() {
1099                    EuvButton(STRESS_BTN_RUN_ALL.to_string(), tokens) {
1100                        on_click: move |_: &UiEvent| {
1101                            let all_ids: [&str; 10] = [
1102                                STRESS_ID_VLIST_100K,
1103                                STRESS_ID_LAYOUT_2000,
1104                                STRESS_ID_REACTIVE_1000,
1105                                STRESS_ID_WASM_HOTSWAP,
1106                                STRESS_ID_DRAWER_ANIM,
1107                                STRESS_ID_TOUCH_HITTEST,
1108                                STRESS_ID_HIDPI_SHADOW,
1109                                STRESS_ID_CJK_ATLAS,
1110                                STRESS_ID_GAME_2D_3D,
1111                                STRESS_ID_MACRO_MOUNT,
1112                            ];
1113                            execute_stress_batch(&st_all, &all_ids);
1114                        }
1115                    }
1116                    EuvButton(STRESS_BTN_RUN_CORE.to_string(), tokens) {
1117                        secondary()
1118                        on_click: move |_: &UiEvent| {
1119                            let core_ids: [&str; 5] = [
1120                                STRESS_ID_VLIST_100K,
1121                                STRESS_ID_LAYOUT_2000,
1122                                STRESS_ID_REACTIVE_1000,
1123                                STRESS_ID_WASM_HOTSWAP,
1124                                STRESS_ID_DRAWER_ANIM,
1125                            ];
1126                            execute_stress_batch(&st_core, &core_ids);
1127                        }
1128                    }
1129                    EuvButton(STRESS_BTN_RESET.to_string(), tokens) {
1130                        outline()
1131                        on_click: move |_: &UiEvent| {
1132                            batch(|| {
1133                                let _: bool = st_reset
1134                                .get_stress_results()
1135                                .set(default_stress_results());
1136                                let _: bool = st_reset
1137                                .get_stress_summary()
1138                                .set_if_changed(STRESS_SUMMARY_READY.to_string());
1139                            });
1140                        }
1141                    }
1142                }
1143                text {
1144                    font_size: 13.0
1145                    color: p.get_primary()
1146                    { move || summary_sig.get() }
1147                }
1148            }
1149            EuvCard(STRESS_SCENARIOS_TITLE.to_string(), tokens) {
1150                subtitle: STRESS_SCENARIOS_SUB
1151                column {
1152                    width: Length::Percent(100.0)
1153                    gap: SPACE_MD
1154                    bind_children: move || {
1155                        let rows: Vec<StressCaseResult> = results_sig.get();
1156                        let mut cards: Vec<NodeId> = Vec::with_capacity(rows.len());
1157                        for item in rows.into_iter() {
1158                            let sid: String = item.get_id().clone();
1159                            let st_run: ShowcaseState = st_list.clone();
1160                            let status_tone: EuvTone = match item.get_status().as_str() {
1161                                STRESS_STATUS_PASS => EuvTone::Success,
1162                                STRESS_STATUS_WARN => EuvTone::Warning,
1163                                _ => EuvTone::Neutral,
1164                            };
1165                            let metric_line: String = if item.get_runs() == 0 {
1166                                format!(
1167                                    "Budget <= {:.2}ms | Status: {} | Click button to run",
1168                                    item.get_budget_ms(),
1169                                    item.get_status()
1170                                )
1171                            } else {
1172                                format!(
1173                                    "Avg: {:.2}ms | P95: {:.2}ms | Max: {:.2}ms | Budget <= {:.2}ms | {} (runs={})",
1174                                    item.get_avg_ms(),
1175                                    item.get_p95_ms(),
1176                                    item.get_max_ms(),
1177                                    item.get_budget_ms(),
1178                                    item.get_throughput(),
1179                                    item.get_runs()
1180                                )
1181                            };
1182                            let detail_line: String = if item.get_runs() == 0 {
1183                                item.get_description().clone()
1184                            } else {
1185                                format!("{} | {}", item.get_description(), item.get_details())
1186                            };
1187                            let item_card: NodeId = view! {
1188                                column {
1189                                    width: Length::Percent(100.0)
1190                                    padding: Edges::all(SPACE_MD)
1191                                    gap: SPACE_SM
1192                                    background: p.get_card()
1193                                    border: (g.get_border_width(), p.get_border())
1194                                    radius: g.get_radius_md()
1195                                    row {
1196                                        width: Length::Percent(100.0)
1197                                        flex_wrap: FlexWrap::Wrap
1198                                        justify: JustifyContent::SpaceBetween
1199                                        align: AlignItems::Center
1200                                        gap: SPACE_SM
1201                                        text {
1202                                            font_size: 14.0
1203                                            font_weight: FontWeight::Bold
1204                                            color: p.get_foreground()
1205                                            { item.get_title().clone() }
1206                                        }
1207                                        row {
1208                                            gap: SPACE_XS
1209                                            align: AlignItems::Center
1210                                            EuvBadge(item.get_category().clone(), EuvTone::Primary, tokens)
1211                                            EuvBadge(item.get_status().clone(), status_tone, tokens)
1212                                        }
1213                                    }
1214                                    text {
1215                                        font_size: 12.5
1216                                        color: p.get_muted_foreground()
1217                                        { detail_line }
1218                                    }
1219                                    text {
1220                                        font_size: 12.5
1221                                        font_weight: FontWeight::SemiBold
1222                                        color: p.get_foreground()
1223                                        { metric_line }
1224                                    }
1225                                    EuvActionRow() {
1226                                        EuvButton(item.get_button_label().clone(), tokens) {
1227                                            secondary()
1228                                            sm()
1229                                            on_click: move |_: &UiEvent| {
1230                                                execute_stress_case(&st_run, &sid);
1231                                            }
1232                                        }
1233                                    }
1234                                }
1235                            };
1236                            cards.push(item_card);
1237                        }
1238                        cards
1239                    }
1240                }
1241            }
1242        }
1243    }
1244}