mod support;
use std::any::Any;
use std::cell::RefCell;
use std::future::{Future, ready};
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use dioxus::dioxus_core::{
AttributeValue, DynamicNode, ElementId, Mutation, Mutations, VNode, current_owner,
};
use dioxus::document::{Document, Eval, EvalError, Evaluator};
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, KeyboardData, Location, MediaData, Modifiers, MountedData,
MountedResult, MouseData, PlatformEventData, PointerData, RenderedElementBacking, ResizeData,
ScrollData, SelectionData, ToggleData, TouchData, TransitionData, VisibleData, WheelData,
set_event_converter,
};
use dioxus::prelude::*;
use dioxus::signals::UnsyncStorage;
use lumen_dioxus::prelude::*;
use support::{Token, attribute, tokenize};
const TRIGGER: &str = "ui-button ui-button--outline ui-button--sm ui-inline-edit__trigger";
const SAVE: &str = "ui-button ui-button--default ui-button--default-size";
const CANCEL: &str = "ui-button ui-button--outline ui-button--default-size";
thread_local! {
static LOG: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
static FOCUS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
static SCRIPTS: 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| std::mem::take(&mut *log.borrow_mut()))
}
fn take_focus_log() -> Vec<String> {
FOCUS.with(|log| std::mem::take(&mut *log.borrow_mut()))
}
fn take_scripts() -> Vec<String> {
SCRIPTS.with(|log| std::mem::take(&mut *log.borrow_mut()))
}
#[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)]
struct KeyPress {
key: Key,
modifiers: Modifiers,
composing: bool,
}
fn press(key: Key) -> KeyPress {
KeyPress {
key,
modifiers: Modifiers::empty(),
composing: false,
}
}
fn press_with(key: Key, modifiers: Modifiers) -> KeyPress {
KeyPress {
modifiers,
..press(key)
}
}
fn press_composing(key: Key) -> KeyPress {
KeyPress {
composing: true,
..press(key)
}
}
impl ModifiersInteraction for KeyPress {
fn modifiers(&self) -> Modifiers {
self.modifiers
}
}
impl HasKeyboardData for KeyPress {
fn key(&self) -> Key {
self.key.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 {
self.composing
}
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
}
}
#[derive(Clone)]
struct TestNode(String);
impl RenderedElementBacking for TestNode {
fn as_any(&self) -> &dyn Any {
self
}
fn set_focus(&self, focus: bool) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
if focus {
let label = self.0.clone();
FOCUS.with(|log| log.borrow_mut().push(label));
}
Box::pin(ready(Ok(())))
}
}
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, event: &PlatformEventData) -> MountedData {
MountedData::new(data::<TestNode>(event))
}
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 TestDocument;
impl Document for TestDocument {
fn eval(&self, js: String) -> Eval {
let evaluator: Box<dyn Evaluator> = Box::new(TestEval {
js,
sent: RefCell::new(None),
});
Eval::new(current_owner::<UnsyncStorage>().insert(evaluator))
}
}
struct TestEval {
js: String,
sent: RefCell<Option<serde_json::Value>>,
}
impl TestEval {
fn kind(&self) -> &'static str {
if self.js.contains("RegExp") {
"pattern"
} else if self.js.contains("setSelectionRange") {
"select"
} else {
"other"
}
}
}
impl Evaluator for TestEval {
fn send(&self, data: serde_json::Value) -> Result<(), EvalError> {
let entry = format!("{}:{data}", self.kind());
SCRIPTS.with(|log| log.borrow_mut().push(entry));
*self.sent.borrow_mut() = Some(data);
Ok(())
}
fn poll_recv(&mut self, _: &mut Context<'_>) -> Poll<Result<serde_json::Value, EvalError>> {
Poll::Ready(Err(EvalError::Finished))
}
fn poll_join(&mut self, _: &mut Context<'_>) -> Poll<Result<serde_json::Value, EvalError>> {
let sent = self.sent.borrow();
let text = |index: usize| {
sent.as_ref()
.and_then(|data| data.get(index))
.and_then(serde_json::Value::as_str)
.unwrap_or_default()
.to_string()
};
let value = if self.kind() == "pattern" {
let matches = text(0) != "[A-Z]+" || text(1).chars().all(|c| c.is_ascii_uppercase());
serde_json::json!(matches)
} else {
serde_json::json!(true)
};
Poll::Ready(Ok(value))
}
}
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);
}
}
_ => {}
}
}
}
struct Harness {
dom: VirtualDom,
}
impl Harness {
fn new(app: fn() -> Element) -> Self {
set_event_converter(Box::new(TestConverter));
take_log();
take_focus_log();
take_scripts();
let mut dom = VirtualDom::new(app);
let mut mutations = Mutations::default();
dom.rebuild(&mut mutations);
let mut harness = Self { dom };
harness.apply(mutations);
harness.settle();
harness
}
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
}
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 control(&self) -> ElementId {
self.find("oninput", None)
}
fn button(&self, class: &str) -> ElementId {
self.find("onclick", Some(("class", class)))
}
fn apply(&mut self, mutations: Mutations) {
let mounted: Vec<ElementId> = mutations
.edits
.into_iter()
.filter_map(|edit| match edit {
Mutation::NewEventListener { name, id } if name == "mounted" => Some(id),
_ => None,
})
.collect();
if mounted.is_empty() {
return;
}
let elements = self.mounted();
for id in mounted {
let control = elements
.iter()
.any(|entry| entry.id == id && entry.listeners.contains(&"oninput"));
let label = if control { "control" } else { "trigger" };
self.dispatch("mounted", TestNode(label.to_string()), id, false);
}
}
fn dispatch<T: Any>(&mut self, name: &str, data: T, target: ElementId, bubbles: bool) -> bool {
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);
!event.default_action_enabled()
}
fn settle(&mut self) {
for _ in 0..12 {
let mut mutations = Mutations::default();
self.dom.render_immediate(&mut mutations);
self.apply(mutations);
}
}
fn send<T: Any>(&mut self, name: &str, data: T, target: ElementId, bubbles: bool) -> bool {
let prevented = self.dispatch(name, data, target, bubbles);
self.settle();
prevented
}
fn input(&mut self, target: ElementId, value: &str) {
self.send("input", TestForm(value.to_string()), target, true);
}
fn click(&mut self, target: ElementId) {
self.send("click", TestPointer, target, true);
}
fn key(&mut self, target: ElementId, press: KeyPress) -> bool {
self.send("keydown", press, target, true)
}
fn open(&mut self) {
let trigger = self.button(TRIGGER);
self.click(trigger);
take_focus_log();
take_scripts();
}
}
fn part(html: &str, slot: &str) -> Vec<(String, String)> {
tokenize(html)
.into_iter()
.find_map(|token| match token {
Token::Open(_, attributes)
if attribute(&attributes, "data-slot").as_deref() == Some(slot) =>
{
Some(attributes)
}
_ => None,
})
.unwrap_or_else(|| panic!("no data-slot=\"{slot}\" in {html}"))
}
fn slot_text(html: &str, slot: &str) -> String {
let tokens = tokenize(html);
let position = tokens
.iter()
.position(|token| {
matches!(token, Token::Open(_, attributes) if attribute(attributes, "data-slot").as_deref() == Some(slot))
})
.unwrap_or_else(|| panic!("no data-slot=\"{slot}\" in {html}"));
match tokens.get(position + 1) {
Some(Token::Text(text)) => text.clone(),
_ => String::new(),
}
}
fn state(html: &str) -> String {
attribute(&part(html, "inline-edit"), "data-state").unwrap_or_default()
}
fn is_hidden(html: &str, slot: &str) -> bool {
attribute(&part(html, slot), "hidden").is_some()
}
fn log_change(change: &InlineEditChangeDetail) {
log(format!(
"change:{}|{}|{}",
change.value, change.name, change.previous_value
));
}
fn title_app() -> Element {
use_context_provider(|| Rc::new(TestDocument) as Rc<dyn Document>);
rsx! {
div {
onkeydown: move |event: KeyboardEvent| log(format!("outer:{}", event.key())),
InlineEdit {
default_value: "Atlas",
id: "title",
label: "Title",
name: "title",
on_value_change: move |change: InlineEditChangeDetail| log_change(&change),
}
}
}
}
fn required_app() -> Element {
rsx! {
InlineEdit {
id: "summary",
label: "Summary",
on_value_change: move |change: InlineEditChangeDetail| log_change(&change),
required: true,
}
}
}
fn required_message_app() -> Element {
rsx! {
InlineEdit {
"data-error-required": "Write a summary.",
id: "summary",
label: "Summary",
required: true,
}
}
}
fn max_length_app() -> Element {
rsx! {
InlineEdit {
default_value: "Quarterly",
id: "code",
label: "Code",
max_length: 3,
on_value_change: move |change: InlineEditChangeDetail| log_change(&change),
}
}
}
fn max_length_message_app() -> Element {
rsx! {
InlineEdit {
"data-error-too-long": "Use three letters.",
id: "code",
label: "Code",
max_length: 3,
}
}
}
fn pattern_app() -> Element {
use_context_provider(|| Rc::new(TestDocument) as Rc<dyn Document>);
rsx! {
InlineEdit {
default_value: "ABC",
id: "code",
label: "Code",
name: "code",
on_value_change: move |change: InlineEditChangeDetail| log_change(&change),
pattern: "[A-Z]+",
}
}
}
fn pattern_message_app() -> Element {
use_context_provider(|| Rc::new(TestDocument) as Rc<dyn Document>);
rsx! {
InlineEdit {
"data-error-pattern": "Use capital letters.",
default_value: "ABC",
id: "code",
label: "Code",
pattern: "[A-Z]+",
}
}
}
fn pattern_without_scripting_app() -> Element {
rsx! {
InlineEdit {
default_value: "ABC",
id: "code",
label: "Code",
on_value_change: move |change: InlineEditChangeDetail| log_change(&change),
pattern: "[A-Z]+",
}
}
}
fn veto_app() -> Element {
rsx! {
InlineEdit {
default_value: "Atlas",
id: "title",
label: "Title",
on_value_change: move |change: InlineEditChangeDetail| {
log_change(&change);
change.prevent_default();
},
}
}
}
fn controlled_app() -> Element {
let mut title = use_signal(|| "Atlas".to_string());
rsx! {
InlineEdit {
id: "title",
label: "Title",
on_value_change: move |change: InlineEditChangeDetail| {
log_change(&change);
title.set(change.value);
},
value: title(),
}
}
}
fn fixed_value_app() -> Element {
rsx! {
InlineEdit {
id: "title",
label: "Title",
on_value_change: move |change: InlineEditChangeDetail| log_change(&change),
value: "Atlas",
}
}
}
fn multiline_app() -> Element {
use_context_provider(|| Rc::new(TestDocument) as Rc<dyn Document>);
rsx! {
InlineEdit {
default_value: "First line",
id: "notes",
label: "Notes",
labels: InlineEditLabels {
saved: Some("Saved {label}.".to_string()),
..InlineEditLabels::default()
},
multiline: true,
on_value_change: move |change: InlineEditChangeDetail| log_change(&change),
}
}
}
#[test]
fn edit_shows_the_enhanced_trigger_and_opens_a_focused_selected_field() {
let mut harness = Harness::new(title_app);
let html = harness.html();
assert_eq!(state(&html), "reading");
assert!(!is_hidden(&html, "inline-edit-trigger"));
assert!(is_hidden(&html, "inline-edit-editor"));
assert_eq!(slot_text(&html, "inline-edit-value"), "Atlas");
assert!(html.contains("Edit Title"), "{html}");
let trigger = harness.button(TRIGGER);
harness.click(trigger);
let html = harness.html();
assert_eq!(state(&html), "editing");
assert!(is_hidden(&html, "inline-edit-view"));
assert!(!is_hidden(&html, "inline-edit-editor"));
assert_eq!(
attribute(&part(&html, "inline-edit-control"), "value").as_deref(),
Some("Atlas")
);
assert_eq!(take_focus_log(), ["control"]);
assert_eq!(take_scripts(), [r#"select:["title-control",false]"#]);
}
#[test]
fn enter_saves_the_trimmed_value_announces_it_and_returns_focus_to_edit() {
let mut harness = Harness::new(title_app);
harness.open();
let control = harness.control();
harness.input(control, " Atlas 2 \u{feff}");
let prevented = harness.key(control, press(Key::Enter));
let html = harness.html();
assert!(prevented);
assert_eq!(take_log(), ["change:Atlas 2|title|Atlas", "outer:Enter"]);
assert_eq!(state(&html), "reading");
assert_eq!(slot_text(&html, "inline-edit-value"), "Atlas 2");
assert_eq!(slot_text(&html, "inline-edit-status"), "Title saved.");
assert_eq!(take_focus_log(), ["trigger"]);
harness.open();
let html = harness.html();
assert_eq!(
attribute(&part(&html, "inline-edit-control"), "value").as_deref(),
Some("Atlas 2")
);
assert_eq!(slot_text(&html, "inline-edit-status"), "");
}
#[test]
fn save_button_saves_like_enter() {
let mut harness = Harness::new(title_app);
harness.open();
let control = harness.control();
harness.input(control, "Borealis");
let save = harness.button(SAVE);
harness.click(save);
let html = harness.html();
assert_eq!(take_log(), ["change:Borealis|title|Atlas"]);
assert_eq!(slot_text(&html, "inline-edit-value"), "Borealis");
assert_eq!(slot_text(&html, "inline-edit-status"), "Title saved.");
assert_eq!(take_focus_log(), ["trigger"]);
}
#[test]
fn an_unchanged_value_closes_without_an_event_or_announcement() {
let mut harness = Harness::new(title_app);
harness.open();
let control = harness.control();
harness.input(control, " Atlas ");
harness.key(control, press(Key::Enter));
let html = harness.html();
assert_eq!(take_log(), ["outer:Enter"]);
assert_eq!(state(&html), "reading");
assert_eq!(slot_text(&html, "inline-edit-status"), "");
assert_eq!(take_focus_log(), ["trigger"]);
}
#[test]
fn escape_restores_the_value_and_stays_inside_the_editor() {
let mut harness = Harness::new(title_app);
harness.open();
let control = harness.control();
harness.input(control, "Changed");
let prevented = harness.key(control, press(Key::Escape));
let html = harness.html();
assert!(prevented);
assert_eq!(take_log(), Vec::<String>::new());
assert_eq!(state(&html), "reading");
assert_eq!(slot_text(&html, "inline-edit-value"), "Atlas");
assert_eq!(
attribute(&part(&html, "inline-edit-control"), "value").as_deref(),
Some("Atlas")
);
assert_eq!(take_focus_log(), ["trigger"]);
}
#[test]
fn escape_on_an_editor_button_cancels_too() {
let mut harness = Harness::new(title_app);
harness.open();
let control = harness.control();
harness.input(control, "Changed");
let save = harness.button(SAVE);
harness.key(save, press(Key::Escape));
assert_eq!(take_log(), Vec::<String>::new());
assert_eq!(state(&harness.html()), "reading");
}
#[test]
fn cancel_restores_the_value() {
let mut harness = Harness::new(title_app);
harness.open();
let control = harness.control();
harness.input(control, "Changed");
let cancel = harness.button(CANCEL);
harness.click(cancel);
let html = harness.html();
assert_eq!(take_log(), Vec::<String>::new());
assert_eq!(slot_text(&html, "inline-edit-value"), "Atlas");
assert_eq!(take_focus_log(), ["trigger"]);
harness.open();
let html = harness.html();
assert_eq!(
attribute(&part(&html, "inline-edit-control"), "value").as_deref(),
Some("Atlas")
);
}
#[test]
fn keys_during_composition_do_nothing() {
let mut harness = Harness::new(title_app);
harness.open();
let control = harness.control();
harness.input(control, "Changed");
let enter = harness.key(control, press_composing(Key::Enter));
let escape = harness.key(control, press_composing(Key::Escape));
assert!(!enter);
assert!(!escape);
assert_eq!(take_log(), ["outer:Enter", "outer:Escape"]);
assert_eq!(state(&harness.html()), "editing");
}
#[test]
fn required_from_save_shows_the_message_and_focuses_the_field() {
let mut harness = Harness::new(required_app);
harness.open();
let save = harness.button(SAVE);
harness.click(save);
let html = harness.html();
let control = part(&html, "inline-edit-control");
assert_eq!(take_log(), Vec::<String>::new());
assert_eq!(state(&html), "editing");
assert_eq!(
slot_text(&html, "inline-edit-error"),
"Please fill out this field."
);
assert!(!is_hidden(&html, "inline-edit-error"));
assert_eq!(attribute(&control, "aria-invalid").as_deref(), Some("true"));
assert_eq!(
attribute(&control, "aria-describedby").as_deref(),
Some("summary-error")
);
assert_eq!(
attribute(&part(&html, "inline-edit-editor"), "data-invalid").as_deref(),
Some("true")
);
assert_eq!(slot_text(&html, "inline-edit-status"), "");
assert_eq!(take_focus_log(), ["control"]);
}
#[test]
fn required_from_enter_announces_the_message_and_typing_clears_it() {
let mut harness = Harness::new(required_app);
harness.open();
let control = harness.control();
harness.input(control, " ");
harness.key(control, press(Key::Enter));
let html = harness.html();
assert_eq!(
slot_text(&html, "inline-edit-status"),
"Please fill out this field."
);
assert_eq!(
attribute(&part(&html, "inline-edit-control"), "value").as_deref(),
Some("")
);
assert_eq!(take_focus_log(), Vec::<String>::new());
harness.input(control, "A");
let html = harness.html();
assert!(is_hidden(&html, "inline-edit-error"));
assert!(attribute(&part(&html, "inline-edit-control"), "aria-invalid").is_none());
assert!(attribute(&part(&html, "inline-edit-editor"), "data-invalid").is_none());
harness.key(control, press(Key::Enter));
assert_eq!(take_log(), ["change:A||"]);
}
#[test]
fn data_error_required_replaces_the_message() {
let mut harness = Harness::new(required_message_app);
harness.open();
let save = harness.button(SAVE);
harness.click(save);
assert_eq!(
slot_text(&harness.html(), "inline-edit-error"),
"Write a summary."
);
}
#[test]
fn max_length_counts_utf16_units_after_an_edit() {
let mut harness = Harness::new(max_length_app);
harness.open();
let save = harness.button(SAVE);
harness.click(save);
assert_eq!(state(&harness.html()), "reading");
assert_eq!(take_log(), Vec::<String>::new());
harness.open();
let control = harness.control();
harness.input(control, "\u{1f600}\u{1f600}");
harness.click(save);
let html = harness.html();
assert_eq!(state(&html), "editing");
assert_eq!(
slot_text(&html, "inline-edit-error"),
"Please shorten this text to 3 characters or less (you are currently using 4 characters)."
);
assert_eq!(take_log(), Vec::<String>::new());
harness.input(control, "abc");
harness.click(save);
assert_eq!(take_log(), ["change:abc||Quarterly"]);
}
#[test]
fn data_error_too_long_replaces_the_message() {
let mut harness = Harness::new(max_length_message_app);
harness.open();
let control = harness.control();
harness.input(control, "four");
let save = harness.button(SAVE);
harness.click(save);
assert_eq!(
slot_text(&harness.html(), "inline-edit-error"),
"Use three letters."
);
}
#[test]
fn pattern_checks_the_trimmed_value_through_the_document() {
let mut harness = Harness::new(pattern_app);
harness.open();
let control = harness.control();
harness.input(control, "abc");
let save = harness.button(SAVE);
harness.click(save);
let html = harness.html();
assert_eq!(take_scripts(), [r#"pattern:["[A-Z]+","abc"]"#]);
assert_eq!(
slot_text(&html, "inline-edit-error"),
"Please match the requested format."
);
assert_eq!(take_focus_log(), ["control"]);
assert_eq!(take_log(), Vec::<String>::new());
harness.input(control, " XYZ ");
harness.key(control, press(Key::Enter));
assert_eq!(take_scripts(), [r#"pattern:["[A-Z]+","XYZ"]"#]);
assert_eq!(take_log(), ["change:XYZ|code|ABC"]);
assert_eq!(state(&harness.html()), "reading");
}
#[test]
fn pattern_skips_an_empty_value() {
let mut harness = Harness::new(pattern_app);
harness.open();
let control = harness.control();
harness.input(control, "");
harness.key(control, press(Key::Enter));
assert_eq!(take_scripts(), Vec::<String>::new());
assert_eq!(take_log(), ["change:|code|ABC"]);
}
#[test]
fn data_error_pattern_replaces_the_message() {
let mut harness = Harness::new(pattern_message_app);
harness.open();
let control = harness.control();
harness.input(control, "abc");
harness.key(control, press(Key::Enter));
let html = harness.html();
assert_eq!(
slot_text(&html, "inline-edit-error"),
"Use capital letters."
);
assert_eq!(
slot_text(&html, "inline-edit-status"),
"Use capital letters."
);
}
#[test]
fn pattern_is_not_checked_without_scripting() {
let mut harness = Harness::new(pattern_without_scripting_app);
harness.open();
let control = harness.control();
harness.input(control, "abc");
harness.key(control, press(Key::Enter));
assert_eq!(take_log(), ["change:abc||ABC"]);
assert_eq!(state(&harness.html()), "reading");
}
#[test]
fn prevent_default_keeps_the_editor_open_with_focus_in_the_field() {
let mut harness = Harness::new(veto_app);
harness.open();
let control = harness.control();
harness.input(control, "Borealis");
harness.key(control, press(Key::Enter));
let html = harness.html();
assert_eq!(take_log(), ["change:Borealis||Atlas"]);
assert_eq!(state(&html), "editing");
assert_eq!(slot_text(&html, "inline-edit-value"), "Atlas");
assert_eq!(slot_text(&html, "inline-edit-status"), "");
assert_eq!(take_focus_log(), ["control"]);
}
#[test]
fn a_controlled_value_follows_the_host() {
let mut harness = Harness::new(controlled_app);
harness.open();
let control = harness.control();
harness.input(control, "Borealis");
harness.key(control, press(Key::Enter));
let html = harness.html();
assert_eq!(take_log(), ["change:Borealis||Atlas"]);
assert_eq!(slot_text(&html, "inline-edit-value"), "Borealis");
assert_eq!(slot_text(&html, "inline-edit-status"), "Title saved.");
}
#[test]
fn a_controlled_value_the_host_keeps_stays() {
let mut harness = Harness::new(fixed_value_app);
harness.open();
let control = harness.control();
harness.input(control, "Borealis");
harness.key(control, press(Key::Enter));
let html = harness.html();
assert_eq!(take_log(), ["change:Borealis||Atlas"]);
assert_eq!(state(&html), "reading");
assert_eq!(slot_text(&html, "inline-edit-value"), "Atlas");
assert_eq!(
attribute(&part(&html, "inline-edit-control"), "value").as_deref(),
Some("Atlas")
);
}
#[test]
fn multiline_keeps_enter_for_new_lines_and_saves_with_control_or_command() {
let mut harness = Harness::new(multiline_app);
let trigger = harness.button(TRIGGER);
harness.click(trigger);
assert_eq!(take_focus_log(), ["control"]);
assert_eq!(take_scripts(), [r#"select:["notes-control",true]"#]);
let control = harness.control();
harness.input(control, "First line\nSecond line\n");
let enter = harness.key(control, press(Key::Enter));
assert!(!enter);
assert_eq!(state(&harness.html()), "editing");
let saved = harness.key(control, press_with(Key::Enter, Modifiers::CONTROL));
let html = harness.html();
assert!(saved);
assert_eq!(take_log(), ["change:First line\nSecond line||First line"]);
assert_eq!(slot_text(&html, "inline-edit-status"), "Saved Notes.");
harness.open();
harness.input(control, "Third");
harness.key(control, press_with(Key::Enter, Modifiers::META));
assert_eq!(take_log(), ["change:Third||First line\nSecond line"]);
}