//! Tests for `@burokku/react` on the test backend. They live in this example //! because it is the crate that bundles React: `tests/harness.ts` exposes //! `h` (React's `createElement`), `useState`, `Activity`, `createRoot`, //! `flushSync`, and `describe`, which prints a subtree as `tag(children)`. use burokku::{ test::{ElementState, InputEvent, MouseButton, PhysicalPosition}, Burokku, BurokkuError, TestApp, TestBackend, }; use std::future::Future; #[test] fn host_components_build_elements_and_text_nodes() -> Result<(), BurokkuError> { run(|mut app| async move { app.eval::<()>( r#" globalThis.root = createRoot(); flushSync(() => root.render( h("window", null, h("flex", null, h("text", null, "Hello, ", "world", h("text", null, "!")), h("div", null))))); "#, ) .await?; app.present().await?; assert_eq!( app.eval::("describe(app)").await?, r#"app(window(flex(text("Hello, ","world",text("!")),div())))"# ); Ok(()) }) } #[test] fn keyed_children_move_without_being_recreated() -> Result<(), BurokkuError> { run(|app| async move { app.eval::<()>( r#" globalThis.root = createRoot(); globalThis.list = keys => h("window", null, h("flex", null, keys.map(key => h("text", { key }, key)))); flushSync(() => root.render(list(["a", "b", "c"]))); globalThis.items = app.firstChild.firstChild; globalThis.before = [...items.childNodes]; flushSync(() => root.render(list(["c", "a"]))); "#, ) .await?; assert_eq!( app.eval::("describe(items)").await?, r#"flex(text("c"),text("a"))"# ); assert!( app.eval::( "items.childNodes[0] === before[2] && items.childNodes[1] === before[0] \ && before[1].parentNode === null" ) .await? ); Ok(()) }) } #[test] fn style_props_set_changed_keys_and_remove_dropped_ones() -> Result<(), BurokkuError> { run(|mut app| async move { app.eval::<()>( r#" globalThis.root = createRoot(); globalThis.boxed = style => h("window", null, h("div", { style })); flushSync(() => root.render(boxed({ width: "40px", height: "20px" }))); "#, ) .await?; app.present().await?; assert_eq!(box_size(&app).await?, [40.0, 20.0]); app.eval::<()>(r#"flushSync(() => root.render(boxed({ width: "60px" })))"#) .await?; app.present().await?; assert_eq!(box_size(&app).await?, [60.0, 0.0]); Ok(()) }) } #[test] fn other_props_set_attributes_and_nullish_values_remove_them() -> Result<(), BurokkuError> { run(|mut app| async move { app.eval::<()>( r#" globalThis.root = createRoot(); globalThis.titled = (title, tabindex) => h("window", { title }, h("div", { tabindex })); flushSync(() => root.render(titled("First", 0))); "#, ) .await?; app.present().await?; assert_eq!(app.window_title().as_deref(), Some("First")); assert_eq!( app.eval::("app.firstChild.firstChild.getAttribute('tabindex')") .await?, "0" ); app.eval::<()>(r#"flushSync(() => root.render(titled("Second", undefined)))"#) .await?; app.present().await?; assert_eq!(app.window_title().as_deref(), Some("Second")); assert!( !app.eval::("app.firstChild.firstChild.hasAttribute('tabindex')") .await? ); Ok(()) }) } #[test] fn clicks_call_the_handler_of_the_latest_props() -> Result<(), BurokkuError> { run(|mut app| async move { app.eval::<()>( r#" globalThis.root = createRoot(); globalThis.calls = []; globalThis.target = onClick => h("window", null, h("div", { style: { width: "100px", height: "100px" }, onClick })); flushSync(() => root.render(target(() => calls.push("first")))); "#, ) .await?; app.present().await?; click(&mut app, 50.0, 50.0)?; app.eval::<()>(r#"flushSync(() => root.render(target(() => calls.push("second"))))"#) .await?; click(&mut app, 50.0, 50.0)?; app.eval::<()>("flushSync(() => root.render(target(undefined)))") .await?; click(&mut app, 50.0, 50.0)?; assert_eq!(app.eval::("calls.join()").await?, "first,second"); Ok(()) }) } #[test] fn state_set_in_a_click_handler_commits_before_the_click_task_ends() -> Result<(), BurokkuError> { run(|mut app| async move { app.eval::<()>( r#" globalThis.seen = []; function Counter() { const [count, setCount] = useState(0); const onClick = () => { setCount(count + 1); // React queued its flush first, so this runs after the commit. queueMicrotask(() => seen.push(app.firstChild.textContent)); }; return h("window", null, h("flex", { style: { width: "100px", height: "100px" }, onClick }, h("text", null, `Clicked ${count}`))); } globalThis.root = createRoot(); flushSync(() => root.render(h(Counter))); "#, ) .await?; app.present().await?; click(&mut app, 50.0, 50.0)?; assert_eq!(app.eval::("seen.join()").await?, "Clicked 1"); Ok(()) }) } #[test] fn text_outside_a_text_element_is_an_uncaught_error() -> Result<(), BurokkuError> { run(|app| async move { app.eval::<()>( r#" globalThis.errors = []; globalThis.root = createRoot(app, { onUncaughtError: error => errors.push(error.message), }); flushSync(() => root.render(h("window", null, h("flex", null, "stray")))); "#, ) .await?; assert_eq!( app.eval::("errors.join()").await?, r#"Text must be inside a or element: "stray""# ); Ok(()) }) } #[test] fn a_root_in_an_element_replaces_its_children_and_unmounts() -> Result<(), BurokkuError> { run(|app| async move { app.eval::<()>( r#" const window = app.createElement("window"); globalThis.panel = app.createElement("flex"); panel.appendChild(app.createElement("div")); window.appendChild(panel); app.appendChild(window); globalThis.root = createRoot(panel); flushSync(() => root.render(h("text", null, "Inside"))); "#, ) .await?; assert_eq!( app.eval::("describe(panel)").await?, r#"flex(text("Inside"))"# ); app.eval::<()>("root.unmount()").await?; assert_eq!(app.eval::("describe(panel)").await?, "flex()"); Ok(()) }) } #[test] fn a_root_in_a_text_element_takes_strings() -> Result<(), BurokkuError> { run(|app| async move { app.eval::<()>( r#" const window = app.createElement("window"); globalThis.label = app.createElement("text"); window.appendChild(label); app.appendChild(window); flushSync(() => createRoot(label).render(["Count: ", 3])); "#, ) .await?; assert_eq!( app.eval::("describe(label)").await?, r#"text("Count: ","3")"# ); Ok(()) }) } #[test] fn text_inside_an_input_renders_as_its_value() -> Result<(), BurokkuError> { run(|app| async move { app.eval::<()>( r#" globalThis.errors = []; globalThis.root = createRoot(app, { onUncaughtError: error => errors.push(error.message), }); flushSync(() => root.render(h("window", null, h("input", null, "Hello")))); "#, ) .await?; assert_eq!(app.eval::("errors.join()").await?, ""); assert_eq!( app.eval::("describe(app)").await?, r#"app(window(input("Hello")))"# ); assert_eq!( app.eval::("app.firstChild.firstChild.value") .await?, "Hello" ); Ok(()) }) } /// Runs `body` on the test backend with the harness loaded and nothing rendered. #[test] fn a_hidden_activity_hides_the_text_inside_its_elements() -> Result<(), BurokkuError> { run(|mut app| async move { app.eval::<()>( r#" globalThis.root = createRoot(); globalThis.view = mode => h("window", null, h(Activity, { mode }, h("text", null, "Inside"))); flushSync(() => root.render(view("visible"))); flushSync(() => root.render(view("hidden"))); "#, ) .await?; app.present().await?; assert_eq!( app.eval::("describe(app)").await?, r#"app(window(text("")))"# ); Ok(()) }) } #[test] fn text_changed_or_added_while_an_activity_is_hidden_shows_once_it_is_visible( ) -> Result<(), BurokkuError> { run(|mut app| async move { app.eval::<()>( r#" globalThis.root = createRoot(); globalThis.view = (mode, labels) => h("window", null, h(Activity, { mode }, h("flex", null, labels.map(label => h("text", { key: label }, label))))); flushSync(() => root.render(view("visible", ["a"]))); flushSync(() => root.render(view("hidden", ["a"]))); root.render(view("hidden", ["b", "c"])); "#, ) .await?; // React renders a hidden subtree's updates when it is idle. for _ in 0..20 { app.run_host_turn().await?; std::thread::sleep(std::time::Duration::from_millis(5)); } app.present().await?; assert_eq!( app.eval::("describe(app)").await?, r#"app(window(flex(text(""),text(""))))"#, "the text stays hidden" ); app.eval::<()>(r#"flushSync(() => root.render(view("visible", ["b", "c"])))"#) .await?; assert_eq!( app.eval::("describe(app)").await?, r#"app(window(flex(text("b"),text("c"))))"# ); Ok(()) }) } fn run(body: F) -> Result<(), BurokkuError> where F: FnOnce(TestApp) -> Fut + 'static, Fut: Future> + 'static, { Burokku::builder() .with_backend::() .script(include_str!("../dist/harness.js")) .run_test(body) } /// The presented size of the window's first child. async fn box_size(app: &TestApp) -> Result<[f64; 2], BurokkuError> { let size: Vec = app .eval( "(() => { const r = app.firstChild.firstChild.getBoundingClientRect(); \ return [r.width, r.height]; })()", ) .await?; Ok([size[0], size[1]]) } /// Presses and releases the primary button at `x`, `y` in the window. fn click(app: &mut TestApp, x: f64, y: f64) -> Result<(), BurokkuError> { let window = app.window_id().unwrap(); let position = PhysicalPosition::new(x, y); for (state, buttons) in [(ElementState::Pressed, 1), (ElementState::Released, 0)] { app.send_input_event( window, InputEvent::MouseInput { state, button: MouseButton::Left, position, buttons, }, )?; } Ok(()) }