mod support;
use std::cell::RefCell;
use dioxus::dioxus_core::ElementId;
use dioxus::prelude::*;
use harness::{Harness, KeyPress};
use lumen_dioxus::prelude::*;
use support::{Token, attribute, opening_tags, tokenize};
mod harness {
use std::any::Any;
use std::rc::Rc;
use dioxus::dioxus_core::{AttributeValue, DynamicNode, ElementId, NoOpMutations, VNode};
use dioxus::html::geometry::{ClientPoint, ElementPoint, PagePoint, ScreenPoint};
use dioxus::html::input_data::{MouseButton, MouseButtonSet};
use dioxus::html::point_interaction::{
InteractionElementOffset, InteractionLocation, ModifiersInteraction, PointerInteraction,
};
use dioxus::html::{
AnimationData, CancelData, ClipboardData, Code, CompositionData, DragData, FileData,
FocusData, FormData, FormValue, HasFileData, HasFormData, HasKeyboardData, HasMouseData,
HtmlEventConverter, ImageData, Key, KeyboardData, Location, MediaData, Modifiers,
MountedData, MouseData, PlatformEventData, PointerData, ResizeData, ScrollData,
SelectionData, ToggleData, TouchData, TransitionData, VisibleData, WheelData,
set_event_converter,
};
use dioxus::prelude::*;
#[derive(Clone)]
struct TestForm(String);
impl HasFileData for TestForm {
fn files(&self) -> Vec<FileData> {
Vec::new()
}
}
impl HasFormData for TestForm {
fn value(&self) -> String {
self.0.clone()
}
fn valid(&self) -> bool {
true
}
fn values(&self) -> Vec<(String, FormValue)> {
Vec::new()
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Clone)]
pub struct KeyPress(pub Key);
impl ModifiersInteraction for KeyPress {
fn modifiers(&self) -> Modifiers {
Modifiers::empty()
}
}
impl HasKeyboardData for KeyPress {
fn key(&self) -> Key {
self.0.clone()
}
fn code(&self) -> Code {
Code::Unidentified
}
fn location(&self) -> Location {
Location::Standard
}
fn is_auto_repeating(&self) -> bool {
false
}
fn is_composing(&self) -> bool {
false
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Clone)]
struct TestPointer;
impl InteractionLocation for TestPointer {
fn client_coordinates(&self) -> ClientPoint {
ClientPoint::new(0.0, 0.0)
}
fn screen_coordinates(&self) -> ScreenPoint {
ScreenPoint::new(0.0, 0.0)
}
fn page_coordinates(&self) -> PagePoint {
PagePoint::new(0.0, 0.0)
}
}
impl InteractionElementOffset for TestPointer {
fn element_coordinates(&self) -> ElementPoint {
ElementPoint::new(0.0, 0.0)
}
}
impl ModifiersInteraction for TestPointer {
fn modifiers(&self) -> Modifiers {
Modifiers::empty()
}
}
impl PointerInteraction for TestPointer {
fn trigger_button(&self) -> Option<MouseButton> {
Some(MouseButton::Primary)
}
fn held_buttons(&self) -> MouseButtonSet {
MouseButtonSet::empty()
}
}
impl HasMouseData for TestPointer {
fn as_any(&self) -> &dyn Any {
self
}
}
struct TestConverter;
fn unsupported(kind: &str) -> ! {
unreachable!("the test harness does not dispatch {kind} events")
}
fn data<T: Clone + 'static>(event: &PlatformEventData) -> T {
event
.downcast::<T>()
.cloned()
.unwrap_or_else(|| unreachable!("unexpected event data type"))
}
impl HtmlEventConverter for TestConverter {
fn convert_animation_data(&self, _: &PlatformEventData) -> AnimationData {
unsupported("animation")
}
fn convert_cancel_data(&self, _: &PlatformEventData) -> CancelData {
unsupported("cancel")
}
fn convert_clipboard_data(&self, _: &PlatformEventData) -> ClipboardData {
unsupported("clipboard")
}
fn convert_composition_data(&self, _: &PlatformEventData) -> CompositionData {
unsupported("composition")
}
fn convert_drag_data(&self, _: &PlatformEventData) -> DragData {
unsupported("drag")
}
fn convert_focus_data(&self, _: &PlatformEventData) -> FocusData {
unsupported("focus")
}
fn convert_form_data(&self, event: &PlatformEventData) -> FormData {
FormData::new(data::<TestForm>(event))
}
fn convert_image_data(&self, _: &PlatformEventData) -> ImageData {
unsupported("image")
}
fn convert_keyboard_data(&self, event: &PlatformEventData) -> KeyboardData {
KeyboardData::new(data::<KeyPress>(event))
}
fn convert_media_data(&self, _: &PlatformEventData) -> MediaData {
unsupported("media")
}
fn convert_mounted_data(&self, _: &PlatformEventData) -> MountedData {
unsupported("mounted")
}
fn convert_mouse_data(&self, event: &PlatformEventData) -> MouseData {
MouseData::new(data::<TestPointer>(event))
}
fn convert_pointer_data(&self, _: &PlatformEventData) -> PointerData {
unsupported("pointer")
}
fn convert_resize_data(&self, _: &PlatformEventData) -> ResizeData {
unsupported("resize")
}
fn convert_scroll_data(&self, _: &PlatformEventData) -> ScrollData {
unsupported("scroll")
}
fn convert_selection_data(&self, _: &PlatformEventData) -> SelectionData {
unsupported("selection")
}
fn convert_toggle_data(&self, _: &PlatformEventData) -> ToggleData {
unsupported("toggle")
}
fn convert_touch_data(&self, _: &PlatformEventData) -> TouchData {
unsupported("touch")
}
fn convert_transition_data(&self, _: &PlatformEventData) -> TransitionData {
unsupported("transition")
}
fn convert_visible_data(&self, _: &PlatformEventData) -> VisibleData {
unsupported("visible")
}
fn convert_wheel_data(&self, _: &PlatformEventData) -> WheelData {
unsupported("wheel")
}
}
struct Mounted {
id: ElementId,
attributes: Vec<(&'static str, String)>,
listeners: Vec<&'static str>,
}
fn collect(dom: &VirtualDom, node: &VNode, out: &mut Vec<Mounted>) {
for (index, attributes) in node.dynamic_attrs.iter().enumerate() {
let Some(id) = node.mounted_dynamic_attribute(index, dom) else {
continue;
};
let position = out
.iter()
.position(|entry| entry.id == id)
.unwrap_or_else(|| {
out.push(Mounted {
id,
attributes: Vec::new(),
listeners: Vec::new(),
});
out.len() - 1
});
for attribute in attributes {
match &attribute.value {
AttributeValue::Listener(_) => out[position].listeners.push(attribute.name),
AttributeValue::Text(text) => {
out[position]
.attributes
.push((attribute.name, text.clone()));
}
_ => {}
}
}
}
for (index, dynamic) in node.dynamic_nodes.iter().enumerate() {
match dynamic {
DynamicNode::Component(component) => {
if let Some(scope) = component.mounted_scope(index, node, dom) {
collect(dom, scope.root_node(), out);
}
}
DynamicNode::Fragment(children) => {
for child in children {
collect(dom, child, out);
}
}
_ => {}
}
}
}
pub struct Harness {
dom: VirtualDom,
}
impl Harness {
pub fn new(app: fn() -> Element) -> Self {
set_event_converter(Box::new(TestConverter));
let mut dom = VirtualDom::new(app);
dom.rebuild_in_place();
let mut harness = Self { dom };
harness.settle();
harness
}
pub fn html(&self) -> String {
dioxus_ssr::render(&self.dom)
}
fn mounted(&self) -> Vec<Mounted> {
let mut out = Vec::new();
collect(&self.dom, self.dom.base_scope().root_node(), &mut out);
out
}
pub fn find(&self, listener: &str, attribute: Option<(&str, &str)>) -> ElementId {
self.mounted()
.into_iter()
.find(|entry| {
entry.listeners.contains(&listener)
&& attribute.is_none_or(|(name, value)| {
entry
.attributes
.iter()
.any(|(key, text)| *key == name && text == value)
})
})
.map_or_else(
|| panic!("no element listens for {listener} with {attribute:?}"),
|entry| entry.id,
)
}
fn send<T: Any>(
&mut self,
name: &str,
data: T,
target: ElementId,
bubbles: bool,
) -> Event<dyn Any> {
let payload: Rc<dyn Any> = Rc::new(PlatformEventData::new(Box::new(data)));
let event = Event::new(payload, bubbles);
self.dom.runtime().handle_event(name, event.clone(), target);
self.settle();
event
}
fn settle(&mut self) {
for _ in 0..8 {
self.dom.render_immediate(&mut NoOpMutations);
self.dom.process_events();
}
self.dom.render_immediate(&mut NoOpMutations);
}
pub fn input(&mut self, target: ElementId, value: &str) {
self.send("input", TestForm(value.to_string()), target, true);
}
pub fn key(&mut self, target: ElementId, press: KeyPress) -> bool {
!self
.send("keydown", press, target, true)
.default_action_enabled()
}
pub fn click(&mut self, target: ElementId) -> bool {
!self
.send("click", TestPointer, target, true)
.default_action_enabled()
}
pub fn form_event(&mut self, target: ElementId, name: &str) {
self.send(name, TestForm(String::new()), target, true);
}
}
}
thread_local! {
static LOG: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
fn log(entry: impl Into<String>) {
LOG.with(|log| log.borrow_mut().push(entry.into()));
}
fn take_log() -> Vec<String> {
LOG.with(|log| log.borrow_mut().drain(..).collect())
}
fn test_id(name: &'static str) -> &'static str {
name
}
fn tag_with(html: &str, tag: &str, name: &str, value: &str) -> Vec<(String, String)> {
opening_tags(html, tag)
.into_iter()
.find(|attributes| attribute(attributes, name).as_deref() == Some(value))
.unwrap_or_else(|| panic!("no <{tag} {name}=\"{value}\"> in {html}"))
}
fn text_after(html: &str, name: &str, value: &str) -> String {
let tokens = tokenize(html);
let position = tokens
.iter()
.position(|token| {
matches!(token, Token::Open(_, attributes) if attribute(attributes, name).as_deref() == Some(value))
})
.unwrap_or_else(|| panic!("no element with {name}=\"{value}\" in {html}"));
match tokens.get(position + 1) {
Some(Token::Text(text)) => text.clone(),
_ => String::new(),
}
}
struct PasswordView {
input_type: String,
toggle_label: String,
pressed: String,
}
fn password_view(harness: &Harness) -> PasswordView {
let html = harness.html();
let input = tag_with(&html, "input", "id", "pw");
let toggle = tag_with(&html, "button", "data-ui-password-toggle", "true");
assert_eq!(
opening_tags(&html, "span")
.iter()
.filter(|span| attribute(span, "data-ui-password-icon").is_some())
.count(),
2,
"both icons stay mounted: {html}"
);
PasswordView {
input_type: attribute(&input, "type").unwrap_or_default(),
toggle_label: attribute(&toggle, "aria-label").unwrap_or_default(),
pressed: attribute(&toggle, "aria-pressed").unwrap_or_default(),
}
}
fn toggle(harness: &Harness) -> ElementId {
harness.find("onclick", Some(("data-ui-password-toggle", "true")))
}
fn password_app() -> Element {
rsx! {
PasswordField {
hide_label: "Ocultar",
id: "pw",
oninput: move |event: FormEvent| log(format!("input {}", event.value())),
show_label: "Mostrar",
}
}
}
#[test]
fn password_toggle_switches_the_input_type_name_and_pressed_state() {
let mut harness = Harness::new(password_app);
let view = password_view(&harness);
assert_eq!(view.input_type, "password");
assert_eq!(view.toggle_label, "Mostrar");
assert_eq!(view.pressed, "false");
let target = toggle(&harness);
assert!(
harness.click(target),
"the click keeps focus in the input on Native"
);
let view = password_view(&harness);
assert_eq!(view.input_type, "text");
assert_eq!(view.toggle_label, "Ocultar");
assert_eq!(view.pressed, "true");
harness.click(toggle(&harness));
let view = password_view(&harness);
assert_eq!(view.input_type, "password");
assert_eq!(view.toggle_label, "Mostrar");
assert_eq!(view.pressed, "false");
let input = harness.find("oninput", Some(("id", "pw")));
harness.input(input, "hunter2");
assert_eq!(take_log(), vec!["input hunter2".to_string()]);
}
fn password_form_app() -> Element {
let mut status = use_signal(|| FormStatus::Idle);
rsx! {
Form {
onreset: move |_| log("reset"),
onsubmit: move |event: FormEvent| {
event.prevent_default();
log("submit");
status.set(FormStatus::Success);
},
status: status(),
PasswordField { id: "pw" }
button { "data-test": test_id("edit"), onclick: move |_| status.set(FormStatus::Idle), "Edit" }
}
}
}
#[test]
fn password_hides_again_after_a_form_reset_or_success() {
let mut harness = Harness::new(password_form_app);
let form = harness.find("onreset", None);
harness.click(toggle(&harness));
assert_eq!(password_view(&harness).input_type, "text");
harness.form_event(form, "reset");
assert_eq!(take_log(), vec!["reset".to_string()]);
assert_eq!(password_view(&harness).input_type, "password");
assert_eq!(password_view(&harness).pressed, "false");
harness.click(toggle(&harness));
assert_eq!(password_view(&harness).input_type, "text");
harness.form_event(form, "submit");
assert_eq!(take_log(), vec!["submit".to_string()]);
assert_eq!(
attribute(&first(&harness.html(), "form"), "data-status").as_deref(),
Some("success")
);
assert_eq!(password_view(&harness).input_type, "password");
let edit = harness.find("onclick", Some(("data-test", "edit")));
harness.click(edit);
harness.click(toggle(&harness));
assert_eq!(password_view(&harness).input_type, "text");
}
fn password_success_form_app() -> Element {
rsx! {
Form { status: FormStatus::Success,
PasswordField { id: "pw" }
}
}
}
#[test]
fn a_form_that_mounts_successful_does_not_block_the_toggle() {
let mut harness = Harness::new(password_success_form_app);
harness.click(toggle(&harness));
assert_eq!(password_view(&harness).input_type, "text");
}
fn first(html: &str, tag: &str) -> Vec<(String, String)> {
opening_tags(html, tag)
.into_iter()
.next()
.unwrap_or_else(|| panic!("no <{tag}> in {html}"))
}
fn count_app() -> Element {
let mut bio = use_signal(String::new);
let mut composing = use_signal(|| false);
rsx! {
Textarea {
aria_describedby: "bio-count",
id: "bio",
oninput: move |event: FormEvent| bio.set(event.value()),
value: "{bio}",
}
CharacterCount {
announce_at: vec![10, 0],
composing: composing(),
max: 12,
value: bio(),
value_id: "bio-count",
}
button { "data-test": test_id("compose"), onclick: move |_| composing.toggle(), "Compose" }
}
}
struct CountView {
state: String,
text: String,
announcement: String,
}
fn count_view(harness: &Harness) -> CountView {
let html = harness.html();
let root = first(&html, "p");
assert_eq!(
attribute(
&tag_with(&html, "span", "data-slot", "character-count-value"),
"id"
)
.as_deref(),
Some("bio-count")
);
CountView {
state: attribute(&root, "data-state").unwrap_or_default(),
text: text_after(&html, "data-slot", "character-count-value"),
announcement: text_after(&html, "data-slot", "character-count-announcer"),
}
}
#[test]
fn character_count_follows_the_control_and_announces_at_thresholds() {
let mut harness = Harness::new(count_app);
let bio = harness.find("oninput", Some(("id", "bio")));
let view = count_view(&harness);
assert_eq!(
(view.state.as_str(), view.text.as_str()),
("within", "12 characters left")
);
assert_eq!(view.announcement, "");
harness.input(bio, "a");
assert_eq!(count_view(&harness).announcement, "");
harness.input(bio, "ab");
let view = count_view(&harness);
assert_eq!(view.state, "near");
assert_eq!(view.announcement, "10 characters left");
harness.input(bio, "abc");
assert_eq!(count_view(&harness).announcement, "10 characters left");
harness.input(bio, "a");
harness.input(bio, "ab");
assert_eq!(
count_view(&harness).announcement,
"10 characters left\u{a0}"
);
harness.input(bio, &"a".repeat(13));
let view = count_view(&harness);
assert_eq!(view.state, "over");
assert_eq!(view.text, "1 character over the limit");
assert_eq!(view.announcement, "1 character over the limit");
harness.input(bio, &"a".repeat(12));
assert_eq!(count_view(&harness).announcement, "0 characters left");
}
#[test]
fn character_count_waits_for_composition_to_end() {
let mut harness = Harness::new(count_app);
let bio = harness.find("oninput", Some(("id", "bio")));
let compose = harness.find("onclick", Some(("data-test", "compose")));
harness.input(bio, "a");
harness.click(compose);
harness.input(bio, "ab");
let view = count_view(&harness);
assert_eq!(view.text, "10 characters left", "the count still updates");
assert_eq!(
view.announcement, "",
"announcements wait for the composition"
);
harness.click(compose);
assert_eq!(count_view(&harness).announcement, "10 characters left");
}
#[test]
fn character_count_never_truncates_and_counts_graphemes() {
let mut harness = Harness::new(count_app);
let bio = harness.find("oninput", Some(("id", "bio")));
let long = "👍🏽".repeat(14);
harness.input(bio, &long);
let html = harness.html();
assert_eq!(count_view(&harness).text, "2 characters over the limit");
assert!(
html.contains(&long),
"the control keeps every character: {html}"
);
}
fn form_app() -> Element {
let mut status = use_signal(|| FormStatus::Idle);
rsx! {
Form {
enhance: true,
onchange: move |event: FormEvent| log(format!("change {}", event.value())),
oninput: move |event: FormEvent| log(format!("input {}", event.value())),
onsubmit: move |event: FormEvent| {
event.prevent_default();
log("submit");
status.set(FormStatus::Submitting);
},
status: status(),
SearchField { aria_label: "Query", name: "q" }
}
}
}
#[test]
fn form_reports_events_and_reflects_its_status() {
let mut harness = Harness::new(form_app);
let html = harness.html();
let form = first(&html, "form");
assert_eq!(attribute(&form, "data-status").as_deref(), Some("idle"));
assert_eq!(attribute(&form, "aria-busy"), None);
assert_eq!(attribute(&form, "data-ui-form").as_deref(), Some("true"));
let query = harness.find("oninput", Some(("name", "q")));
harness.input(query, "lumen");
let target = harness.find("onsubmit", None);
harness.form_event(target, "submit");
assert_eq!(
take_log(),
vec!["input lumen".to_string(), "submit".to_string()]
);
let form = first(&harness.html(), "form");
assert_eq!(
attribute(&form, "data-status").as_deref(),
Some("submitting")
);
assert_eq!(attribute(&form, "aria-busy").as_deref(), Some("true"));
}
fn search_app() -> Element {
let mut query = use_signal(String::new);
rsx! {
SearchField {
aria_label: "Search",
oninput: move |event: FormEvent| query.set(event.value()),
onkeydown: move |event: KeyboardEvent| {
if event.key() == Key::Escape {
query.set(String::new());
log("cleared");
}
},
value: "{query}",
}
p { "data-test": test_id("query"), "{query}" }
}
}
#[test]
fn search_field_reports_edits_and_keys() {
let mut harness = Harness::new(search_app);
let field = harness.find("oninput", Some(("aria-label", "Search")));
harness.input(field, "tokens");
assert_eq!(text_after(&harness.html(), "data-test", "query"), "tokens");
assert_eq!(
attribute(&first(&harness.html(), "input"), "type").as_deref(),
Some("search")
);
harness.key(field, KeyPress(Key::Escape));
assert_eq!(take_log(), vec!["cleared".to_string()]);
assert_eq!(text_after(&harness.html(), "data-test", "query"), "");
}
fn settings_app() -> Element {
let mut dark = use_signal(|| false);
rsx! {
SettingsRow {
control: move |control: SettingsRowControlProps| rsx! {
Switch {
aria_describedby: control.aria_describedby,
aria_labelledby: control.aria_labelledby,
checked: dark(),
id: control.id,
onchange: move |next: bool| dark.set(next),
}
},
control_id: "dark-mode",
description: "Use dark colors everywhere.",
label: "Dark mode",
}
}
}
#[test]
fn settings_row_names_and_describes_an_aria_button_control() {
let mut harness = Harness::new(settings_app);
let html = harness.html();
let switch = tag_with(&html, "button", "role", "switch");
let label = first(&html, "label");
assert_eq!(attribute(&switch, "id").as_deref(), Some("dark-mode"));
assert_eq!(
attribute(&switch, "aria-labelledby").as_deref(),
Some("dark-mode-label")
);
assert_eq!(
attribute(&switch, "aria-describedby").as_deref(),
Some("dark-mode-description")
);
assert_eq!(attribute(&label, "for").as_deref(), Some("dark-mode"));
assert_eq!(attribute(&label, "id").as_deref(), Some("dark-mode-label"));
let target = harness.find("onclick", Some(("role", "switch")));
harness.click(target);
assert_eq!(
attribute(
&tag_with(&harness.html(), "button", "role", "switch"),
"aria-checked"
)
.as_deref(),
Some("true")
);
}
fn summary_app() -> Element {
let mut errors = use_signal(FormErrors::default);
rsx! {
ErrorSummary { errors: errors(), id: "checkout-errors" }
button {
"data-test": test_id("validate"),
onclick: move |_| {
errors.set(FormErrors::from(vec![
FormFieldError::new("card", "Enter a card number.").control_id("card"),
]));
},
"Validate"
}
}
}
#[test]
fn error_summary_appears_with_linked_errors() {
let mut harness = Harness::new(summary_app);
let section = first(&harness.html(), "section");
assert_eq!(attribute(§ion, "hidden").as_deref(), Some(""));
assert_eq!(
attribute(§ion, "aria-labelledby").as_deref(),
Some("checkout-errors-heading")
);
let validate = harness.find("onclick", Some(("data-test", "validate")));
harness.click(validate);
let html = harness.html();
assert_eq!(attribute(&first(&html, "section"), "hidden"), None);
assert_eq!(
attribute(&first(&html, "a"), "href").as_deref(),
Some("#card")
);
assert_eq!(text_after(&html, "href", "#card"), "Enter a card number.");
}