diff --git a/crates/thing-core/src/render/leaf.rs b/crates/thing-core/src/render/leaf.rs index a088976..611b99b 100644 --- a/crates/thing-core/src/render/leaf.rs +++ b/crates/thing-core/src/render/leaf.rs @@ -156,7 +156,7 @@ impl<'a> Painter<'a> { Some(Bound::Asset(entry)) if entry.width.get() > 0 && entry.height.get() > 0 => entry, _ => { self.placeholder(id, rect); - if !alt.is_empty() { + if !alt.is_empty() && rect.w > 0.0 { self.draw_text(id, alt, "thing.text", true, Some(1), rect, rect.h, text); } return; diff --git a/crates/thing-core/tests/goldens/layout-f07-plot.txt b/crates/thing-core/tests/goldens/layout-f07-plot.txt index 57315cb..c8080b9 100644 --- a/crates/thing-core/tests/goldens/layout-f07-plot.txt +++ b/crates/thing-core/tests/goldens/layout-f07-plot.txt @@ -1,5 +1,5 @@ surface thing:surface:provider.market.plot viewport 800x600 scale 1 pixels -root 0 0 800 20 -line 2 2 796 0 -bar 2 10 796 0 -area 2 18 796 0 +root 0 0 800 470 +line 2 2 300 150 +bar 2 160 300 150 +area 2 318 300 150 diff --git a/crates/thing-core/tests/goldens/render-f01-swarm-dashboard-cells.txt b/crates/thing-core/tests/goldens/render-f01-swarm-dashboard-cells.txt index edace37..01ca3e3 100644 --- a/crates/thing-core/tests/goldens/render-f01-swarm-dashboard-cells.txt +++ b/crates/thing-core/tests/goldens/render-f01-swarm-dashboard-cells.txt @@ -4,4 +4,6 @@ text 2 2 #ffffffff cells "42.0%" bold=false italic=false underline=false text 54 2 #eeeef4ff cells "Eureka" bold=false italic=false underline=false text 2 11 #eeeef4ff cells "Libby" bold=false italic=false underline=false text 54 11 #eeeef4ff cells "Kiko" bold=false italic=false underline=false +fill 2 20 48 1 r0 #2c2c3eff +stroke 2 20 48 1 r0 w1 #4a4a60ff text 2 20 #eeeef4ff cells "Restart" bold=false italic=false underline=false diff --git a/crates/thing-core/tests/goldens/render-f01-swarm-dashboard.txt b/crates/thing-core/tests/goldens/render-f01-swarm-dashboard.txt index 6b5c656..29807f6 100644 --- a/crates/thing-core/tests/goldens/render-f01-swarm-dashboard.txt +++ b/crates/thing-core/tests/goldens/render-f01-swarm-dashboard.txt @@ -4,4 +4,6 @@ text 2 2 #ffffffff font0 size16 [52@0,0 50@8,0 46@16,0 48@24,0 37@32,0] text 404 2 #eeeef4ff font0 size16 [69@0,0 117@8,0 114@16,0 101@24,0 107@32,0 97@40,0] text 2 26 #eeeef4ff font0 size16 [76@0,0 105@8,0 98@16,0 98@24,0 121@32,0] text 404 26 #eeeef4ff font0 size16 [75@0,0 105@8,0 107@16,0 111@24,0] +fill 2 50 398 16 r0 #2c2c3eff +stroke 2 50 398 16 r0 w1 #4a4a60ff text 2 50 #eeeef4ff font0 size16 [82@0,0 101@8,0 115@16,0 116@24,0 97@32,0 114@40,0 116@48,0] diff --git a/crates/thing-core/tests/goldens/render-f02-login-effect.txt b/crates/thing-core/tests/goldens/render-f02-login-effect.txt index 926e984..5f23298 100644 --- a/crates/thing-core/tests/goldens/render-f02-login-effect.txt +++ b/crates/thing-core/tests/goldens/render-f02-login-effect.txt @@ -1,2 +1,6 @@ surface thing:surface:provider.login.login viewport 800x600 scale 1 pixels +stroke 2 2 796 24 r0 w1 #4a4a60ff +text 4 4 #6e6e80ff font0 size16 [117@0,0 115@8,0 101@16,0 114@24,0 110@32,0 97@40,0 109@48,0 101@56,0] +fill 2 34 796 16 r0 #2c2c3eff +stroke 2 34 796 16 r0 w1 #4a4a60ff text 2 34 #eeeef4ff font0 size16 [83@0,0 105@8,0 103@16,0 110@24,0 32@32,0 105@40,0 110@48,0] diff --git a/crates/thing-core/tests/goldens/render-f03-input-target.txt b/crates/thing-core/tests/goldens/render-f03-input-target.txt index 042dd96..2891885 100644 --- a/crates/thing-core/tests/goldens/render-f03-input-target.txt +++ b/crates/thing-core/tests/goldens/render-f03-input-target.txt @@ -1,2 +1,3 @@ surface thing:surface:provider.muninn.input-target viewport 800x600 scale 1 pixels +image 82 3.125 636 357.75 "asset://provider.muninn/board.png" "The board the target sits on" text 282 122 #eeeef4ff font0 size16 [82@0,0 101@8,0 97@16,0 100@24,0 121@32,0] diff --git a/crates/thing-core/tests/goldens/render-f04-form.txt b/crates/thing-core/tests/goldens/render-f04-form.txt index e5be111..dad45d1 100644 --- a/crates/thing-core/tests/goldens/render-f04-form.txt +++ b/crates/thing-core/tests/goldens/render-f04-form.txt @@ -1 +1,9 @@ surface thing:surface:provider.settings.form viewport 800x600 scale 1 pixels +stroke 2 2 796 20 r0 w1 #4a4a60ff +fill 780 4 16 16 r0 #7c9cffff +fill 2 37.5 796 5 r0 #4a4a60ff +fill 778 30 20 20 r0 #7c9cffff +stroke 2 58 796 24 r0 w1 #4a4a60ff +text 4 60 #eeeef4ff font0 size16 [68@0,0 97@8,0 114@16,0 107@24,0] +stroke 2 90 796 24 r0 w1 #4a4a60ff +text 4 92 #eeeef4ff font0 size16 [56@0,0 48@8,0 56@16,0 48@24,0] diff --git a/crates/thing-core/tests/goldens/render-f05-modal-overlay-scale1.5.txt b/crates/thing-core/tests/goldens/render-f05-modal-overlay-scale1.5.txt index 23dbb9d..056a8d2 100644 --- a/crates/thing-core/tests/goldens/render-f05-modal-overlay-scale1.5.txt +++ b/crates/thing-core/tests/goldens/render-f05-modal-overlay-scale1.5.txt @@ -3,5 +3,9 @@ text 2 2 #eeeef4ff font0 size16 [84@0,0 104@8,0 101@16,0 32@24,0 97@32,0 114@40, fill 0 0 800 600 r0 #00000099 fill 0 266 800 68 r6 #2c2c3eff text 2 268 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0 32@48,0 116@56,0 104@64,0 101@72,0 32@80,0 97@88,0 114@96,0 99@104,0 104@112,0 105@120,0 118@128,0 101@136,0 63@144,0] +fill 2 292 796 16 r0 #2c2c3eff +stroke 2 292 796 16 r0 w1 #4a4a60ff text 2 292 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0] +fill 2 316 796 16 r0 #2c2c3eff +stroke 2 316 796 16 r0 w1 #4a4a60ff text 2 316 #eeeef4ff font0 size16 [67@0,0 97@8,0 110@16,0 99@24,0 101@32,0 108@40,0] diff --git a/crates/thing-core/tests/goldens/render-f05-modal-overlay.txt b/crates/thing-core/tests/goldens/render-f05-modal-overlay.txt index 85dfef5..3409c76 100644 --- a/crates/thing-core/tests/goldens/render-f05-modal-overlay.txt +++ b/crates/thing-core/tests/goldens/render-f05-modal-overlay.txt @@ -3,5 +3,9 @@ text 2 2 #eeeef4ff font0 size16 [84@0,0 104@8,0 101@16,0 32@24,0 97@32,0 114@40, fill 0 0 800 600 r0 #00000099 fill 0 266 800 68 r6 #2c2c3eff text 2 268 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0 32@48,0 116@56,0 104@64,0 101@72,0 32@80,0 97@88,0 114@96,0 99@104,0 104@112,0 105@120,0 118@128,0 101@136,0 63@144,0] +fill 2 292 796 16 r0 #2c2c3eff +stroke 2 292 796 16 r0 w1 #4a4a60ff text 2 292 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0] +fill 2 316 796 16 r0 #2c2c3eff +stroke 2 316 796 16 r0 w1 #4a4a60ff text 2 316 #eeeef4ff font0 size16 [67@0,0 97@8,0 110@16,0 99@24,0 101@32,0 108@40,0] diff --git a/crates/thing-core/tests/goldens/render-f07-plot.txt b/crates/thing-core/tests/goldens/render-f07-plot.txt index 4914890..4d00a56 100644 --- a/crates/thing-core/tests/goldens/render-f07-plot.txt +++ b/crates/thing-core/tests/goldens/render-f07-plot.txt @@ -1 +1,14 @@ surface thing:surface:provider.market.plot viewport 800x600 scale 1 pixels +clip-push 2 2 300 150 r0 +polyline w2 #7c9cffff 2,152 77,77 152,114.5 227,2 302,47 +clip-pop +clip-push 2 160 300 150 r0 +fill 2 253.75 60 56.25 r0 #7c9cffff +fill 62 206.875 60 103.125 r0 #7c9cffff +fill 122 230.3125 60 79.6875 r0 #7c9cffff +fill 182 160 60 150 r0 #7c9cffff +fill 242 188.125 60 121.875 r0 #7c9cffff +clip-pop +clip-push 2 318 300 150 r0 +polygon #7c9cffff 2,168 5.030303,-19.5 8.060606,74.25 11.090909,-207 14.121212,-94.5 14.121212,393 2,393 +clip-pop diff --git a/crates/thing-core/tests/goldens/render-f09-composition-stack.txt b/crates/thing-core/tests/goldens/render-f09-composition-stack.txt index e2a58fd..eca9bb0 100644 --- a/crates/thing-core/tests/goldens/render-f09-composition-stack.txt +++ b/crates/thing-core/tests/goldens/render-f09-composition-stack.txt @@ -1,8 +1,12 @@ surface thing:surface:provider.stack.stack viewport 800x600 scale 1 pixels text 2 2 #ff00ffff font0 size16 [76@0,0 111@8,0 97@16,0 100@24,0] text 4 48 #ffffffff font0 size16 [67@0,0 97@8,0 114@16,0 100@24,0] +fill 4 72 792 16 r0 #2c2c3eff +stroke 4 72 792 16 r0 w1 #4a4a60ff text 4 72 #eeeef4ff font0 size16 [79@0,0 112@8,0 101@16,0 110@24,0] text 6 98 #ffffffff font0 size16 [67@0,0 97@8,0 114@16,0 100@24,0] +fill 6 122 788 16 r0 #2c2c3eff +stroke 6 122 788 16 r0 w1 #4a4a60ff text 6 122 #eeeef4ff font0 size16 [79@0,0 112@8,0 101@16,0 110@24,0] text 6 146 #eeeef4ff font0 size16 [110@0,0 101@8,0 115@16,0 116@24,0 101@32,0 100@40,0] diagnostic ThemeTokenUnknown std-stat/stat-label caption diff --git a/crates/thing-core/tests/render.rs b/crates/thing-core/tests/render.rs index fc641c9..5cf56ac 100644 --- a/crates/thing-core/tests/render.rs +++ b/crates/thing-core/tests/render.rs @@ -593,7 +593,9 @@ fn random_documents_render_without_panic_balanced_and_equal() { let sizes = [0.0, 1.0, 7.5, 40.0, 100.0, 5000.0, 1e6, 1e7, -4.0, f64::NAN]; let overflows = [Overflow::Visible, Overflow::Clip, Overflow::Scroll]; let tokens = ["thing.surface", "thing.error", "unknown", "thing.scrim"]; - for round in 0..300u64 { + let mut refused = 0u32; + const ROUNDS: u64 = 300; + for round in 0..ROUNDS { let mut counter = 0u32; let mut generated: Vec = Vec::new(); fn grow(depth: u32, next: &mut dyn FnMut() -> u64, counter: &mut u32, generated: &mut Vec, sizes: &[f64], overflows: &[Overflow], tokens: &[&str]) -> Node { @@ -601,9 +603,29 @@ fn random_documents_render_without_panic_balanced_and_equal() { let id = format!("n{counter}"); generated.push(id.clone()); let pick = next(); - match (pick % 7, depth) { + match (pick % 13, depth) { (0, _) => embed(&id, sizes[(next() % 10) as usize], sizes[(next() % 10) as usize]), (1, _) => Node::Text(TextNode { common: common(&id), content: lit_text("some wrapping words"), style_token: tokens[(next() % 4) as usize].into(), wrap: next() % 2 == 0, max_lines: None, selectable: false }), + (3, _) => Node::Toggle(ToggleNode { common: common(&id), checked: lit_bool(next() % 2 == 0), on_change: command("dismiss") }), + (4, _) => Node::Slider(SliderNode { + common: common(&id), + min: sizes[(next() % 10) as usize], + max: sizes[(next() % 10) as usize], + step: 1.0, + value: lit_number(sizes[(next() % 10) as usize]), + commit: command("dismiss"), + }), + (5, _) => image(&id, "x", [ImageFit::Fill, ImageFit::Contain, ImageFit::Cover, ImageFit::Unscaled][(next() % 4) as usize].clone()), + (6, _) => Node::Button(ButtonNode { common: common(&id), content: vec![], on_activate: command("dismiss"), enabled: lit_bool(next() % 2 == 0) }), + (7, _) => Node::TextInput(TextInputNode { + common: common(&id), + multiline: next() % 2 == 0, + input_kind: InputKind::Text, + placeholder: lit_text("type here"), + initial: lit_text(["", "typed words"][(next() % 2) as usize]), + submit: command("dismiss"), + }), + (8, _) => Node::Plot(PlotNode { common: common(&id), series: series_bind("s"), mark: PlotMark::Bar, x_min: None, x_max: None, y_min: None, y_max: None }), (2, d) if d < 3 => { let anchor = if next() % 2 == 0 { Anchor::Viewport } else { at(&generated[(next() % generated.len() as u64) as usize]) }; let children = (0..(next() % 3)).map(|_| grow(depth + 1, next, counter, generated, sizes, overflows, tokens)).collect(); @@ -635,8 +657,14 @@ fn random_documents_render_without_panic_balanced_and_equal() { scroll.set(nid(id), ((next() % 400) as f32 - 100.0, [f32::NAN, 1e30, 30.0, 400.0][(next() % 4) as usize])); } let frame = [pixels(1.0), pixels(1.5), pixels(2.0), frame(80.0, 30.0, 1.0, Metrics::Cells)][(round % 4) as usize]; - let Ok(tree) = bind(&mut MemState::new(), &surface_of(root)) else { continue }; - let Ok(laid) = layout(&tree, &frame, &mut measure(&frame)) else { continue }; + let Ok(tree) = bind(&mut MemState::new(), &surface_of(root)) else { + refused += 1; + continue; + }; + let Ok(laid) = layout(&tree, &frame, &mut measure(&frame)) else { + refused += 1; + continue; + }; let theme = Theme::std(); let first = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut measure(&frame)); let second = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut measure(&frame)); @@ -644,6 +672,9 @@ fn random_documents_render_without_panic_balanced_and_equal() { assert!(balanced(&first.commands), "round {round}"); assert_eq!(first.placed.len(), laid.nodes.len()); } + // A round that layout refuses renders nothing: keep them few enough that render is exercised. + eprintln!("random documents: {refused} of {ROUNDS} refused"); + assert!(refused * 10 <= ROUNDS as u32, "{refused} of {ROUNDS} rounds were refused"); } #[test] @@ -683,3 +714,340 @@ fn a_scrollbar_is_one_cell_thick_in_cells_and_the_theme_thickness_in_pixels() { let (_, device) = inline(pane(), &pixels(2.0), &ScrollOffsets::default()); assert_eq!(fills(&device).iter().map(|f| f.2).collect::>(), [Theme::std().scrollbar]); } + +// ---- leaves ------------------------------------------------------------------------------ + +use thing_core::layout::Rect; +use thing_testkit::state::{Series, Swarm}; + +const PROVIDER: &str = "provider.render"; + +fn rect(x: f32, y: f32, w: f32, h: f32) -> Rect { + Rect { x, y, w, h } +} + +fn color(token: &str) -> Rgba { + Theme::std().color(token).unwrap() +} + +fn catalog(assets: &[(&str, i32, i32)]) -> AssetCatalog { + AssetCatalog { + provider_id: ProviderId::new(PROVIDER), + catalog_id: seg("icons"), + version: ver(1), + assets: assets + .iter() + .map(|(id, w, h)| AssetEntry { id: (*id).into(), media_type: "image/png".into(), uri: format!("asset://{id}"), width: count(*w), height: count(*h) }) + .collect(), + } +} + +fn image(id: &str, asset: &str, fit: ImageFit) -> Node { + Node::Image(ImageNode { common: common(id), catalog: "icons".into(), asset: asset.into(), fit, alt: lit_text("alt") }) +} + +fn with_state(state: &mut MemState, root: Node, frame: &LayoutFrame) -> Rendered { + let tree = bind(state, &surface_of(root)).expect("resolves"); + draw(&tree, frame, &ScrollOffsets::default()).1 +} + +fn rendered(root: Node) -> Rendered { + with_state(&mut MemState::new(), root, &pixels(1.0)) +} + +fn series_bind(key: &str) -> Bind { + Bind { + source: StateSource::Record(StateRef { provider: Some(ProviderId::new(PROVIDER)), schema: SchemaId::new("gamecult.thing.test.series.v1"), key: RecordKey::new(key) }), + member: path(&["Values"]), + format: None, + } +} + +fn plot_node(mark: PlotMark, bounds: [Option; 4]) -> Node { + Node::Plot(PlotNode { common: common("p"), series: series_bind("s"), mark, x_min: bounds[0], x_max: bounds[1], y_min: bounds[2], y_max: bounds[3] }) +} + +/// A plot over `values` in a root that is exactly the plot: its rect is (0, 0, 300, 150). +fn plotted(values: &[f64], mark: PlotMark, bounds: [Option; 4]) -> Rendered { + let mut state = MemState::new(); + state.put_state(&ProviderId::new(PROVIDER), "s", &Series { values: values.to_vec() }); + with_state(&mut state, flat("root", plain(), vec![plot_node(mark, bounds)]), &pixels(1.0)) +} + +fn polylines(rendered: &Rendered) -> Vec> { + rendered.commands.iter().filter_map(|c| if let RenderCommand::Polyline { points, .. } = c { Some(points.clone()) } else { None }).collect() +} + +fn invalid(rendered: &Rendered) -> Vec<&str> { + rendered.diagnostics.iter().filter(|d| d.code == Code::StyleValueInvalid).map(|d| d.detail.as_str()).collect() +} + +fn lines_of(rendered: &Rendered) -> Vec { + rendered + .commands + .iter() + .filter_map(|c| match c { + RenderCommand::Text { run: Run::Glyphs { glyphs, .. }, .. } => Some(glyphs.iter().filter_map(|g| char::from_u32(g.id)).collect()), + _ => None, + }) + .collect() +} + +fn fills_of(rendered: &Rendered, token: &str) -> Vec { + let want = color(token); + rendered.commands.iter().filter_map(|c| if let RenderCommand::FillRect { rect, color, .. } = c { (*color == want).then_some(*rect) } else { None }).collect() +} + +#[test] +fn fit_table() { + let provider = ProviderId::new(PROVIDER); + let run = |asset: &str, fit: ImageFit| { + let mut state = MemState::new(); + state.put(&provider, &catalog(&[("wide", 400, 200), ("tall", 100, 400)])); + // A 100x100 row: the image is squeezed to the row's height and width, so its rect is not its ratio. + let rendered = with_state(&mut state, flat("root", sized(100.0, 100.0), vec![image("pic", asset, fit)]), &pixels(1.0)); + assert_eq!(placed(&rendered, "pic").rect, rect(0.0, 0.0, 100.0, 100.0), "the image fills the row"); + rendered.commands + }; + let img = |r: Rect, uri: &str| RenderCommand::Image { rect: r, uri: format!("asset://{uri}"), alt: "alt".into() }; + let clip = |inner: Vec| { + let mut out = vec![RenderCommand::ClipPush { rect: rect(0.0, 0.0, 100.0, 100.0), radius: 0.0 }]; + out.extend(inner); + out.push(RenderCommand::ClipPop); + out + }; + assert_eq!(run("wide", ImageFit::Fill), [img(rect(0.0, 0.0, 100.0, 100.0), "wide")]); + assert_eq!(run("wide", ImageFit::Contain), [img(rect(0.0, 25.0, 100.0, 50.0), "wide")]); + assert_eq!(run("wide", ImageFit::Cover), clip(vec![img(rect(-50.0, 0.0, 200.0, 100.0), "wide")])); + assert_eq!(run("wide", ImageFit::Unscaled), clip(vec![img(rect(-150.0, -50.0, 400.0, 200.0), "wide")])); + assert_eq!(run("tall", ImageFit::Fill), [img(rect(0.0, 0.0, 100.0, 100.0), "tall")]); + assert_eq!(run("tall", ImageFit::Contain), [img(rect(37.5, 0.0, 25.0, 100.0), "tall")]); + assert_eq!(run("tall", ImageFit::Cover), clip(vec![img(rect(0.0, -150.0, 100.0, 400.0), "tall")])); + assert_eq!(run("tall", ImageFit::Unscaled), clip(vec![img(rect(0.0, -150.0, 100.0, 400.0), "tall")])); +} + +#[test] +fn a_missing_asset_is_one_placeholder_and_no_image_command() { + let provider = ProviderId::new(PROVIDER); + let mut state = MemState::new(); + // No catalog (Absent), an entry the catalog lacks (Error), and a 0x0 entry. + state.put(&provider, &catalog(&[("empty", 0, 0)])); + let mut root = vec![Node::Image(ImageNode { common: common("absent"), catalog: "nowhere".into(), asset: "x".into(), fit: ImageFit::Fill, alt: lit_text("alt") })]; + for (id, asset) in [("lacks", "nothing"), ("empty", "empty")] { + root.push(image(id, asset, ImageFit::Contain)); + } + let out = with_state(&mut state, flat("root", plain(), root), &pixels(1.0)); + let none = rect(0.0, 0.0, 0.0, 0.0); + let placeholder = || { + [ + RenderCommand::FillRect { rect: none, radius: 0.0, color: color("thing.placeholder") }, + RenderCommand::StrokeRect { rect: none, radius: 0.0, width: 1.0, color: color("thing.error") }, + ] + }; + let three: Vec<_> = (0..3).flat_map(|_| placeholder()).collect(); + assert_eq!(out.commands, three, "no catalog (Absent), a missing entry (Error) and a 0x0 entry"); +} + +#[test] +fn a_nan_splits_a_line_and_a_one_point_run_draws_nothing() { + let split = plotted(&[1.0, 2.0, f64::NAN, 3.0, 4.0], PlotMark::Line, [None; 4]); + assert_eq!( + polylines(&split), + [vec![(0.0, 150.0), (75.0, 100.0)], vec![(225.0, 50.0), (300.0, 0.0)]], + "y grows down, so the least value is the bottom" + ); + assert!(balanced(&split.commands)); + let lone = plotted(&[1.0, f64::NAN, 2.0, f64::INFINITY, 3.0], PlotMark::Line, [None; 4]); + assert_eq!(lone.commands, []); + assert_eq!(invalid(&lone), Vec::<&str>::new(), "a non-finite point is skipped, not a style fault"); + assert_eq!(plotted(&[], PlotMark::Line, [None; 4]).commands, []); + // Every point of one value: the equal ends widen by 1 and the line runs through the middle. + assert_eq!(polylines(&plotted(&[5.0, 5.0], PlotMark::Line, [None; 4])), [vec![(0.0, 75.0), (300.0, 75.0)]]); +} + +#[test] +fn explicit_bounds_clip_and_a_bad_bound_takes_the_data_and_is_named() { + let clipped = plotted(&[1.0, 2.0, 3.0], PlotMark::Line, [None, None, Some(0.0), Some(2.0)]); + assert_eq!(polylines(&clipped), [vec![(0.0, 75.0), (150.0, 0.0), (300.0, -75.0)]]); + assert!(matches!(clipped.commands.first(), Some(RenderCommand::ClipPush { rect: r, .. }) if *r == rect(0.0, 0.0, 300.0, 150.0))); + assert!(matches!(clipped.commands.last(), Some(RenderCommand::ClipPop))); + assert_eq!(invalid(&clipped), Vec::<&str>::new()); + let nan = plotted(&[1.0, 3.0], PlotMark::Line, [None, None, None, Some(f64::NAN)]); + assert_eq!(invalid(&nan), ["y_max"]); + assert_eq!(polylines(&nan), [vec![(0.0, 150.0), (300.0, 0.0)]], "the data's own max"); + let crossed = plotted(&[1.0, 3.0], PlotMark::Line, [None, None, Some(9.0), Some(2.0)]); + assert_eq!(invalid(&crossed), ["y_min", "y_max"]); + assert_eq!(polylines(&crossed), [vec![(0.0, 150.0), (300.0, 0.0)]]); + let past = plotted(&[1.0, 3.0], PlotMark::Line, [Some(7.0), None, None, None]); + assert_eq!(invalid(&past), ["x_min"]); +} + +#[test] +fn bars_rise_from_the_baseline_and_an_area_closes_to_it() { + let bars = plotted(&[2.0, -1.0, 4.0], PlotMark::Bar, [None; 4]); + let slots: Vec<_> = fills_of(&bars, "thing.plot.mark"); + // y domain [-1, 4]: the baseline (0) is at y 120; slot width is 300 / 3. + assert_eq!(slots, [rect(0.0, 60.0, 100.0, 60.0), rect(100.0, 120.0, 100.0, 30.0), rect(200.0, 0.0, 100.0, 120.0)]); + assert!(balanced(&bars.commands)); + let area = plotted(&[1.0, 2.0], PlotMark::Area, [None; 4]); + let polygons: Vec<_> = area.commands.iter().filter_map(|c| if let RenderCommand::Polygon { points, .. } = c { Some(points.clone()) } else { None }).collect(); + // The baseline 0 clamps into the domain [1, 2]: the bottom. + assert_eq!(polygons, [vec![(0.0, 150.0), (300.0, 0.0), (300.0, 150.0), (0.0, 150.0)]]); +} + +#[test] +fn a_plot_lowers_to_a_bounded_number_of_vertices() { + let mut seed = 0x2545_F491_4F6C_DD1Du64; + for round in 0..40 { + let n = 1 + round * 7; + let values: Vec = (0..n) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + match seed % 5 { + 0 => f64::NAN, + 1 => f64::NEG_INFINITY, + _ => (seed % 1000) as f64 - 500.0, + } + }) + .collect(); + for (mark, bound) in [(PlotMark::Line, 1), (PlotMark::Area, 2), (PlotMark::Bar, 1)] { + let out = plotted(&values, mark, [None; 4]); + let vertices: usize = out + .commands + .iter() + .map(|c| match c { + RenderCommand::Polyline { points, .. } | RenderCommand::Polygon { points, .. } => points.len(), + RenderCommand::FillRect { .. } => 1, + _ => 0, + }) + .sum(); + assert!(vertices <= bound * n, "{n} points gave {vertices}"); + assert!(balanced(&out.commands)); + } + } +} + +#[test] +fn a_plot_without_a_series_draws_nothing_and_a_refused_series_is_the_placeholder() { + let absent = rendered(flat("root", plain(), vec![plot_node(PlotMark::Line, [None; 4])])); + assert_eq!(absent.commands, []); + // The record is there but holds no Values: an Error site. + let mut state = MemState::new(); + state.put_state(&ProviderId::new(PROVIDER), "s", &Swarm { id: "s".into(), name: "n".into(), load: 0.0 }); + let mut node = plot_node(PlotMark::Line, [None; 4]); + if let Node::Plot(p) = &mut node { + if let StateSource::Record(r) = &mut p.series.source { + r.schema = SchemaId::new("gamecult.thing.test.swarm.v1"); + } + } + let out = with_state(&mut state, flat("root", plain(), vec![node]), &pixels(1.0)); + let whole = rect(0.0, 0.0, 300.0, 150.0); + assert_eq!( + out.commands, + [ + RenderCommand::FillRect { rect: whole, radius: 0.0, color: color("thing.placeholder") }, + RenderCommand::StrokeRect { rect: whole, radius: 0.0, width: 1.0, color: color("thing.error") }, + ] + ); +} + +#[test] +fn a_plot_is_sized_by_layout_to_the_default_object_size() { + let plot = || flat("root", plain(), vec![plot_node(PlotMark::Line, [None; 4])]); + let out = rendered(plot()); + assert_eq!(placed(&out, "p").rect, rect(0.0, 0.0, 300.0, 150.0)); + let scaled = with_state(&mut MemState::new(), plot(), &pixels(2.0)); + assert_eq!(placed(&scaled, "p").rect, rect(0.0, 0.0, 300.0, 150.0), "logical, whatever the scale"); + let cells = with_state(&mut MemState::new(), plot(), &frame(80.0, 30.0, 1.0, Metrics::Cells)); + assert_eq!(placed(&cells, "p").rect, rect(0.0, 0.0, 38.0, 10.0)); +} + +fn knob(rendered: &Rendered) -> Rect { + *fills_of(rendered, "thing.control.accent").last().expect("a knob") +} + +#[test] +fn a_toggle_knob_follows_checked_and_a_slider_thumb_is_clamped() { + let toggle = |checked: bool| { + let node = Node::Toggle(ToggleNode { common: common("t"), checked: lit_bool(checked), on_change: command("dismiss") }); + rendered(flat("root", plain(), vec![node])) + }; + // A 40x20 toggle inset by 2: a 16 knob at the left or at the right. + assert_eq!(knob(&toggle(false)), rect(2.0, 2.0, 16.0, 16.0)); + assert_eq!(knob(&toggle(true)), rect(22.0, 2.0, 16.0, 16.0)); + let slider = |min: f64, max: f64, value: f64| { + let node = Node::Slider(SliderNode { common: common("s"), min, max, step: 1.0, value: lit_number(value), commit: command("dismiss") }); + rendered(flat("root", plain(), vec![node])) + }; + // A 160x20 slider: the thumb is 20 wide and travels 140. + for (value, x) in [(5.0, 70.0), (-5.0, 0.0), (99.0, 140.0), (f64::NAN, 0.0)] { + let out = slider(0.0, 10.0, value); + assert_eq!(knob(&out), rect(x, 0.0, 20.0, 20.0), "value {value}"); + assert_eq!(invalid(&out), Vec::<&str>::new()); + } + for (min, max) in [(3.0, 3.0), (5.0, 1.0), (f64::NAN, 1.0), (0.0, f64::INFINITY)] { + let out = slider(min, max, 2.0); + assert_eq!(knob(&out).x, 0.0, "{min}..{max}: the thumb is at the start"); + assert_eq!(invalid(&out), ["max"]); + assert_eq!(out.diagnostics.last().unwrap().node, Some(nid("s"))); + } +} + +#[test] +fn a_disabled_button_is_the_disabled_token_and_its_content_follows_the_chrome() { + let button = |enabled: bool| { + let node = Node::Button(ButtonNode { common: common("b"), content: vec![text("label", "Go")], on_activate: command("dismiss"), enabled: lit_bool(enabled) }); + rendered(flat("root", plain(), vec![node])) + }; + let on = button(true); + let off = button(false); + assert_eq!(fills_of(&on, "thing.control.fill").len(), 1); + assert_eq!(fills_of(&on, "thing.control.disabled").len(), 0); + assert_eq!(fills_of(&off, "thing.control.fill").len(), 0); + assert_eq!(fills_of(&off, "thing.control.disabled").len(), 1); + assert!(matches!(on.commands.as_slice(), [RenderCommand::FillRect { .. }, RenderCommand::StrokeRect { .. }, RenderCommand::Text { .. }])); +} + +#[test] +fn a_placeholder_shows_only_while_the_input_is_empty_and_a_select_shows_its_label() { + let input = |initial: &str| { + let node = Node::TextInput(TextInputNode { + common: common("i"), + multiline: false, + input_kind: InputKind::Text, + placeholder: lit_text("type"), + initial: lit_text(initial), + submit: command("dismiss"), + }); + rendered(flat("root", plain(), vec![node])) + }; + let text_color = |r: &Rendered| match r.commands.iter().find(|c| matches!(c, RenderCommand::Text { .. })) { + Some(RenderCommand::Text { color, .. }) => color.clone(), + _ => panic!("no text"), + }; + let empty = input(""); + assert_eq!(lines_of(&empty), ["type"]); + assert_eq!(text_color(&empty), color("thing.placeholder")); + let filled = input("hi"); + assert_eq!(lines_of(&filled), ["hi"]); + assert_eq!(text_color(&filled), color("thing.control.text")); + + let select = |value: &str| { + let mut state = MemState::new(); + state.put_state(&ProviderId::new(PROVIDER), "row", &Swarm { id: "row".into(), name: value.into(), load: 0.0 }); + let options = OptionList::Literal(LiteralOptions { + options: vec![SelectOption { value: "a".into(), label: "Alpha".into() }, SelectOption { value: "b".into(), label: "Beta".into() }], + }); + let value = Bind { + source: StateSource::Record(StateRef { provider: Some(ProviderId::new(PROVIDER)), schema: SchemaId::new("gamecult.thing.test.swarm.v1"), key: RecordKey::new("row") }), + member: path(&["Name"]), + format: None, + }; + let node = Node::Select(SelectNode { common: common("sel"), options, value, on_change: command("dismiss") }); + with_state(&mut state, flat("root", plain(), vec![node]), &pixels(1.0)) + }; + assert_eq!(lines_of(&select("b")), ["Beta"]); + assert_eq!(lines_of(&select("zzz")), ["zzz"], "the value itself when no option matches"); +}