Skip to main content

sandbox_quant/
ui_docs.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3
4use anyhow::{anyhow, bail, Context, Result};
5use ratatui::backend::TestBackend;
6use ratatui::Terminal;
7use serde::Deserialize;
8
9use crate::model::candle::Candle;
10use crate::ui::{self, AppState, GridTab};
11
12const DEFAULT_SCENARIO_DIR: &str = "docs/ui/scenarios";
13const DEFAULT_INDEX_PATH: &str = "docs/ui/INDEX.md";
14const DEFAULT_README_PATH: &str = "README.md";
15const DEFAULT_SYMBOLS: [&str; 5] = ["BTCUSDT", "ETHUSDT", "SOLUSDT", "BNBUSDT", "XRPUSDT"];
16
17#[derive(Debug, Clone, Deserialize)]
18pub struct Scenario {
19    pub id: String,
20    pub title: String,
21    #[serde(default = "default_width")]
22    pub width: u16,
23    #[serde(default = "default_height")]
24    pub height: u16,
25    #[serde(default)]
26    pub profiles: Vec<String>,
27    #[serde(default, alias = "step")]
28    pub steps: Vec<Step>,
29}
30
31#[derive(Debug, Clone, Deserialize)]
32#[serde(tag = "type", rename_all = "snake_case")]
33pub enum Step {
34    Key { value: String },
35    Wait { ms: u64 },
36    AssertText { value: String },
37    Snapshot { path: String },
38}
39
40#[derive(Debug, Clone)]
41pub struct RenderedScenario {
42    pub id: String,
43    pub title: String,
44    pub snapshot_paths: Vec<SnapshotArtifact>,
45}
46
47#[derive(Debug, Clone)]
48pub struct SnapshotArtifact {
49    pub raw_path: String,
50    pub image_path: Option<String>,
51}
52
53fn default_width() -> u16 {
54    180
55}
56
57fn default_height() -> u16 {
58    50
59}
60
61pub fn run_cli(args: &[String]) -> Result<()> {
62    if args.is_empty() {
63        return run_mode("full");
64    }
65    match args[0].as_str() {
66        "smoke" => run_mode("smoke"),
67        "full" => run_mode("full"),
68        "scenario" => {
69            let id = args
70                .get(1)
71                .ok_or_else(|| anyhow!("`scenario` requires an id argument"))?;
72            run_single_scenario(id)
73        }
74        "readme-only" => {
75            let rendered = collect_existing_rendered(DEFAULT_INDEX_PATH)?;
76            update_readme(DEFAULT_README_PATH, &rendered)
77        }
78        "help" | "--help" | "-h" => {
79            print_usage();
80            Ok(())
81        }
82        other => bail!(
83            "unknown subcommand `{}`. expected one of: smoke|full|scenario|readme-only",
84            other
85        ),
86    }
87}
88
89fn run_mode(profile: &str) -> Result<()> {
90    let scenarios = load_scenarios_from_dir(DEFAULT_SCENARIO_DIR)?;
91    let filtered: Vec<Scenario> = if profile == "full" {
92        scenarios
93    } else {
94        scenarios
95            .into_iter()
96            .filter(|s| s.profiles.iter().any(|p| p == profile))
97            .collect()
98    };
99    if filtered.is_empty() {
100        bail!("no scenarios found for profile `{}`", profile);
101    }
102    run_scenarios_and_write(&filtered, DEFAULT_INDEX_PATH, DEFAULT_README_PATH)?;
103    Ok(())
104}
105
106fn run_single_scenario(id: &str) -> Result<()> {
107    let scenarios = load_scenarios_from_dir(DEFAULT_SCENARIO_DIR)?;
108    let scenario = scenarios
109        .into_iter()
110        .find(|s| s.id == id)
111        .ok_or_else(|| anyhow!("scenario `{}` not found", id))?;
112    run_scenarios_and_write(&[scenario], DEFAULT_INDEX_PATH, DEFAULT_README_PATH)?;
113    Ok(())
114}
115
116pub fn run_scenarios_and_write<P: AsRef<Path>, R: AsRef<Path>>(
117    scenarios: &[Scenario],
118    index_path: P,
119    readme_path: R,
120) -> Result<Vec<RenderedScenario>> {
121    let rendered = run_scenarios(scenarios)?;
122    write_index(index_path, &rendered)?;
123    update_readme(readme_path, &rendered)?;
124    Ok(rendered)
125}
126
127pub fn load_scenarios_from_dir<P: AsRef<Path>>(dir: P) -> Result<Vec<Scenario>> {
128    let mut paths: Vec<PathBuf> = fs::read_dir(dir.as_ref())
129        .with_context(|| format!("failed to read {}", dir.as_ref().display()))?
130        .filter_map(|entry| entry.ok().map(|e| e.path()))
131        .filter(|path| path.extension().map(|ext| ext == "toml").unwrap_or(false))
132        .collect();
133    paths.sort();
134
135    let mut scenarios = Vec::with_capacity(paths.len());
136    for path in paths {
137        let raw = fs::read_to_string(&path)
138            .with_context(|| format!("failed to read scenario {}", path.display()))?;
139        let scenario: Scenario = toml::from_str(&raw)
140            .with_context(|| format!("failed to parse scenario {}", path.display()))?;
141        scenarios.push(scenario);
142    }
143    Ok(scenarios)
144}
145
146fn run_scenarios(scenarios: &[Scenario]) -> Result<Vec<RenderedScenario>> {
147    scenarios.iter().map(run_scenario).collect()
148}
149
150fn run_scenario(s: &Scenario) -> Result<RenderedScenario> {
151    let mut state = seed_state();
152    let mut snapshots = Vec::new();
153
154    for step in &s.steps {
155        match step {
156            Step::Key { value } => apply_key_action(&mut state, value)?,
157            Step::Wait { ms } => {
158                let _ = ms;
159            }
160            Step::AssertText { value } => {
161                let text = render_to_text(&state, s.width, s.height)?;
162                if !text.contains(value) {
163                    bail!(
164                        "scenario `{}` assert_text failed: missing `{}`",
165                        s.id,
166                        value
167                    );
168                }
169            }
170            Step::Snapshot { path } => {
171                let text = render_to_text(&state, s.width, s.height)?;
172                let snapshot_path = PathBuf::from(path);
173                if let Some(parent) = snapshot_path.parent() {
174                    fs::create_dir_all(parent).with_context(|| {
175                        format!("failed to create snapshot dir {}", parent.display())
176                    })?;
177                }
178                fs::write(&snapshot_path, text).with_context(|| {
179                    format!("failed to write snapshot {}", snapshot_path.display())
180                })?;
181                let image_path = write_svg_preview(&snapshot_path)?;
182                snapshots.push(SnapshotArtifact {
183                    raw_path: snapshot_path.to_string_lossy().to_string(),
184                    image_path,
185                });
186            }
187        }
188    }
189
190    if snapshots.is_empty() {
191        let default_path = format!("docs/ui/screenshots/{}.txt", s.id);
192        let text = render_to_text(&state, s.width, s.height)?;
193        let default_path_buf = PathBuf::from(&default_path);
194        if let Some(parent) = default_path_buf.parent() {
195            fs::create_dir_all(parent)
196                .with_context(|| format!("failed to create {}", parent.display()))?;
197        }
198        fs::write(&default_path_buf, text)
199            .with_context(|| format!("failed to write {}", default_path_buf.display()))?;
200        let image_path = write_svg_preview(&default_path_buf)?;
201        snapshots.push(SnapshotArtifact {
202            raw_path: default_path,
203            image_path,
204        });
205    }
206
207    Ok(RenderedScenario {
208        id: s.id.clone(),
209        title: s.title.clone(),
210        snapshot_paths: snapshots,
211    })
212}
213
214pub fn render_to_text(state: &AppState, width: u16, height: u16) -> Result<String> {
215    let backend = TestBackend::new(width, height);
216    let mut terminal = Terminal::new(backend).context("failed to init test terminal")?;
217    terminal
218        .draw(|frame| ui::render(frame, state))
219        .context("failed to render frame")?;
220    let buf = terminal.backend().buffer();
221    let area = buf.area;
222    let mut out = String::new();
223    for y in 0..area.height {
224        for x in 0..area.width {
225            out.push_str(buf[(x, y)].symbol());
226        }
227        out.push('\n');
228    }
229    Ok(out)
230}
231
232pub fn seed_state() -> AppState {
233    let mut state = AppState::new("BTCUSDT", "MA(Config)", 120, 60_000, "1m");
234    let now_ms = chrono::Utc::now().timestamp_millis() as u64;
235    state.ws_connected = true;
236    state.current_equity_usdt = Some(10_000.0);
237    state.initial_equity_usdt = Some(9_800.0);
238    state.candles = seed_candles(now_ms, state.candle_interval_ms, 100, 67_000.0);
239    state.last_price_update_ms = Some(now_ms);
240    state.last_price_event_ms = Some(now_ms.saturating_sub(180));
241    state.last_price_latency_ms = Some(180);
242    state.last_order_history_update_ms = Some(now_ms.saturating_sub(1_100));
243    state.last_order_history_event_ms = Some(now_ms.saturating_sub(1_950));
244    state.last_order_history_latency_ms = Some(850);
245    state.symbol_items = DEFAULT_SYMBOLS.iter().map(|v| v.to_string()).collect();
246    state.strategy_item_symbols = vec![
247        "BTCUSDT".to_string(),
248        "ETHUSDT".to_string(),
249        "SOLUSDT".to_string(),
250    ];
251    state.strategy_item_active = vec![true, false, true];
252    state.strategy_item_total_running_ms = vec![3_600_000, 0, 7_200_000];
253    state.network_reconnect_count = 1;
254    state.network_tick_drop_count = 2;
255    state.network_tick_latencies_ms = vec![120, 160, 170, 210, 300];
256    state.network_fill_latencies_ms = vec![400, 600, 1200];
257    state.network_order_sync_latencies_ms = vec![100, 130, 170];
258    state.network_last_fill_ms = Some(now_ms.saturating_sub(4_500));
259    state.fast_sma = state.candles.last().map(|c| c.close * 0.9992);
260    state.slow_sma = state.candles.last().map(|c| c.close * 0.9985);
261    state
262}
263
264fn seed_candles(now_ms: u64, interval_ms: u64, count: usize, base_price: f64) -> Vec<Candle> {
265    let count = count.max(8);
266    let bucket_close = now_ms - (now_ms % interval_ms);
267    let mut candles = Vec::with_capacity(count);
268    for i in 0..count {
269        let remaining = (count - i) as u64;
270        let open_time = bucket_close.saturating_sub(remaining * interval_ms);
271        let close_time = open_time.saturating_add(interval_ms);
272        let drift = (i as f64) * 2.1;
273        let wave = ((i as f64) * 0.24).sin() * 18.0;
274        let open = base_price + drift + wave;
275        let close = open + (((i % 6) as f64) - 2.0) * 1.7;
276        let high = open.max(close) + 6.5;
277        let low = open.min(close) - 6.0;
278        candles.push(Candle {
279            open,
280            high,
281            low,
282            close,
283            open_time,
284            close_time,
285        });
286    }
287    candles
288}
289
290fn apply_key_action(state: &mut AppState, key: &str) -> Result<()> {
291    match key.to_ascii_lowercase().as_str() {
292        "g" => {
293            state.grid_open = !state.grid_open;
294            if !state.grid_open {
295                state.strategy_editor_open = false;
296            }
297        }
298        "1" => {
299            if state.grid_open {
300                state.grid_tab = GridTab::Assets;
301            }
302        }
303        "2" => {
304            if state.grid_open {
305                state.grid_tab = GridTab::Strategies;
306            }
307        }
308        "3" => {
309            if state.grid_open {
310                state.grid_tab = GridTab::Risk;
311            }
312        }
313        "4" => {
314            if state.grid_open {
315                state.grid_tab = GridTab::Network;
316            }
317        }
318        "5" => {
319            if state.grid_open {
320                state.grid_tab = GridTab::SystemLog;
321            }
322        }
323        "tab" => {
324            if state.grid_open && state.grid_tab == GridTab::Strategies {
325                state.grid_select_on_panel = !state.grid_select_on_panel;
326            }
327        }
328        "c" => {
329            if state.grid_open && state.grid_tab == GridTab::Strategies {
330                state.strategy_editor_open = true;
331            }
332        }
333        "esc" => {
334            if state.strategy_editor_open {
335                state.strategy_editor_open = false;
336            } else if state.grid_open {
337                state.grid_open = false;
338            } else if state.symbol_selector_open {
339                state.symbol_selector_open = false;
340            } else if state.strategy_selector_open {
341                state.strategy_selector_open = false;
342            } else if state.account_popup_open {
343                state.account_popup_open = false;
344            } else if state.history_popup_open {
345                state.history_popup_open = false;
346            }
347        }
348        "t" => {
349            if !state.grid_open {
350                state.symbol_selector_open = true;
351            }
352        }
353        "y" => {
354            if !state.grid_open {
355                state.strategy_selector_open = true;
356            }
357        }
358        "a" => {
359            if !state.grid_open {
360                state.account_popup_open = true;
361            }
362        }
363        "i" => {
364            if !state.grid_open {
365                state.history_popup_open = true;
366            }
367        }
368        other => bail!("unsupported key action `{}`", other),
369    }
370    Ok(())
371}
372
373fn write_index<P: AsRef<Path>>(path: P, rendered: &[RenderedScenario]) -> Result<()> {
374    if let Some(parent) = path.as_ref().parent() {
375        fs::create_dir_all(parent)
376            .with_context(|| format!("failed to create {}", parent.display()))?;
377    }
378    let mut out = String::new();
379    out.push_str("# UI Snapshot Index\n\n");
380    out.push_str("Generated by `cargo run --bin ui_docs -- <mode>`.\n\n");
381    for item in rendered {
382        out.push_str(&format!("## {} (`{}`)\n\n", item.title, item.id));
383        for snapshot in &item.snapshot_paths {
384            if let Some(image_path) = &snapshot.image_path {
385                let rel_image = image_path
386                    .strip_prefix("docs/ui/")
387                    .unwrap_or(image_path.as_str());
388                out.push_str(&format!("![{}]({})\n\n", item.id, xml_escape(rel_image)));
389            }
390            out.push_str(&format!("- raw: `{}`\n", snapshot.raw_path));
391        }
392        out.push('\n');
393    }
394    fs::write(path.as_ref(), out)
395        .with_context(|| format!("failed to write {}", path.as_ref().display()))?;
396    Ok(())
397}
398
399fn collect_existing_rendered<P: AsRef<Path>>(index_path: P) -> Result<Vec<RenderedScenario>> {
400    let raw = fs::read_to_string(index_path.as_ref())
401        .with_context(|| format!("failed to read {}", index_path.as_ref().display()))?;
402    let mut rendered = Vec::new();
403    let mut current: Option<RenderedScenario> = None;
404
405    for line in raw.lines() {
406        if let Some(rest) = line.strip_prefix("## ") {
407            if let Some(prev) = current.take() {
408                rendered.push(prev);
409            }
410            let (title, id) = if let Some((lhs, rhs)) = rest.rsplit_once(" (`") {
411                let id = rhs.trim_end_matches("`)");
412                (lhs.trim().to_string(), id.to_string())
413            } else {
414                (rest.to_string(), "unknown".to_string())
415            };
416            current = Some(RenderedScenario {
417                id,
418                title,
419                snapshot_paths: Vec::new(),
420            });
421        } else if let Some(path) = line
422            .trim()
423            .strip_prefix("- raw: `")
424            .and_then(|v| v.strip_suffix('`'))
425        {
426            if let Some(curr) = current.as_mut() {
427                let image_path = infer_svg_path(Path::new(path));
428                curr.snapshot_paths.push(SnapshotArtifact {
429                    raw_path: path.to_string(),
430                    image_path,
431                });
432            }
433        }
434    }
435    if let Some(prev) = current.take() {
436        rendered.push(prev);
437    }
438    Ok(rendered)
439}
440
441pub fn update_readme<P: AsRef<Path>>(readme_path: P, rendered: &[RenderedScenario]) -> Result<()> {
442    let start_marker = "<!-- UI_DOCS:START -->";
443    let end_marker = "<!-- UI_DOCS:END -->";
444    let raw = fs::read_to_string(readme_path.as_ref())
445        .with_context(|| format!("failed to read {}", readme_path.as_ref().display()))?;
446    let start = raw
447        .find(start_marker)
448        .ok_or_else(|| anyhow!("README start marker not found"))?;
449    let end = raw
450        .find(end_marker)
451        .ok_or_else(|| anyhow!("README end marker not found"))?;
452    if start >= end {
453        bail!("README marker order invalid");
454    }
455    let mut block = String::new();
456    block.push_str(start_marker);
457    block.push('\n');
458    block.push_str("### UI Docs (Auto)\n\n");
459    block.push_str("- Generated by `cargo run --bin ui_docs -- smoke|full`\n");
460    block.push_str("- Full index: `docs/ui/INDEX.md`\n\n");
461    for item in rendered.iter().take(4) {
462        if let Some(snapshot) = item.snapshot_paths.first() {
463            if let Some(image_path) = &snapshot.image_path {
464                block.push_str(&format!(
465                    "![{}]({})\n\n",
466                    item.title,
467                    xml_escape(image_path)
468                ));
469            }
470            block.push_str(&format!("- {} raw: `{}`\n", item.title, snapshot.raw_path));
471        }
472    }
473    block.push('\n');
474    block.push_str(end_marker);
475    let next = format!(
476        "{}{}{}",
477        &raw[..start],
478        block,
479        &raw[end + end_marker.len()..]
480    );
481    fs::write(readme_path.as_ref(), next)
482        .with_context(|| format!("failed to write {}", readme_path.as_ref().display()))?;
483    Ok(())
484}
485
486fn print_usage() {
487    eprintln!("usage:");
488    eprintln!("  cargo run --bin ui-docs");
489    eprintln!("  cargo run --bin ui_docs -- smoke");
490    eprintln!("  cargo run --bin ui_docs -- full");
491    eprintln!("  cargo run --bin ui_docs -- scenario <id>");
492    eprintln!("  cargo run --bin ui_docs -- readme-only");
493}
494
495fn write_svg_preview(raw_snapshot_path: &Path) -> Result<Option<String>> {
496    let raw = fs::read_to_string(raw_snapshot_path)
497        .with_context(|| format!("failed to read {}", raw_snapshot_path.display()))?;
498    let svg_path = raw_snapshot_path.with_extension("svg");
499    let lines: Vec<&str> = raw.lines().collect();
500    let width_chars = lines
501        .iter()
502        .map(|line| line.chars().count())
503        .max()
504        .unwrap_or(0);
505    let height_chars = lines.len();
506    if width_chars == 0 || height_chars == 0 {
507        return Ok(None);
508    }
509    let cell_w = 9usize;
510    let cell_h = 18usize;
511    let px_w = (width_chars * cell_w + 24) as u32;
512    let px_h = (height_chars * cell_h + 24) as u32;
513
514    let mut svg = String::new();
515    svg.push_str(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
516    svg.push('\n');
517    svg.push_str(&format!(
518        r#"<svg xmlns="http://www.w3.org/2000/svg" width="{}" height="{}" viewBox="0 0 {} {}">"#,
519        px_w, px_h, px_w, px_h
520    ));
521    svg.push('\n');
522    svg.push_str(&format!(
523        r##"<rect x="0" y="0" width="{}" height="{}" fill="#0f111a"/>"##,
524        px_w, px_h
525    ));
526    svg.push('\n');
527    svg.push_str(r##"<g font-family="Menlo, Monaco, 'Courier New', monospace" font-size="14" fill="#d8dee9">"##);
528    svg.push('\n');
529
530    for (i, line) in lines.iter().enumerate() {
531        let y = 18 + (i as u32) * (cell_h as u32);
532        svg.push_str(&format!(
533            r#"<text x="12" y="{}" xml:space="preserve">{}</text>"#,
534            y,
535            xml_escape(line)
536        ));
537        svg.push('\n');
538    }
539    svg.push_str("</g>\n</svg>\n");
540
541    fs::write(&svg_path, svg).with_context(|| format!("failed to write {}", svg_path.display()))?;
542    Ok(Some(svg_path.to_string_lossy().to_string()))
543}
544
545fn infer_svg_path(raw_path: &Path) -> Option<String> {
546    let svg = raw_path.with_extension("svg");
547    if svg.exists() {
548        Some(svg.to_string_lossy().to_string())
549    } else {
550        None
551    }
552}
553
554fn xml_escape(input: &str) -> String {
555    input
556        .replace('&', "&amp;")
557        .replace('<', "&lt;")
558        .replace('>', "&gt;")
559        .replace('"', "&quot;")
560        .replace('\'', "&apos;")
561}