use std::cell::Cell;
use std::rc::Rc;
use dioxus::core::AttributeValue;
use dioxus::prelude::*;
use super::number_field_host::use_scripting;
use super::number_field_locale::js_trim;
use crate::class::compose;
use crate::hooks::{Controllable, use_controllable, use_unique_id};
use crate::overlay::{focus_element, is_escape};
const TRIGGER_CLASS: &str = "ui-button ui-button--outline ui-button--sm ui-inline-edit__trigger";
const SAVE_CLASS: &str = "ui-button ui-button--default ui-button--default-size";
const CANCEL_CLASS: &str = "ui-button ui-button--outline ui-button--default-size";
const VALUE_MISSING_MESSAGE: &str = "Please fill out this field.";
const PATTERN_MISMATCH_MESSAGE: &str = "Please match the requested format.";
const PATTERN_SCRIPT: &str = r"const [pattern, value] = await dioxus.recv();
let flags = 'v';
try { new RegExp('', flags); } catch { flags = 'u'; }
let expression;
try { expression = new RegExp('^(?:' + pattern + ')$', flags); } catch { return true; }
return expression.test(value);";
const SELECT_SCRIPT: &str = r"const [id, multiline] = await dioxus.recv();
const field = document.getElementById(id);
if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement)) return false;
field.focus();
if (multiline) field.setSelectionRange(field.value.length, field.value.length);
else field.select();
return true;";
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct InlineEditLabels {
pub edit: Option<String>,
pub save: Option<String>,
pub cancel: Option<String>,
pub saved: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct ResolvedInlineEditLabels {
edit: String,
save: String,
cancel: String,
saved: String,
}
impl InlineEditLabels {
fn resolve(&self) -> ResolvedInlineEditLabels {
let pick = |value: Option<&str>, fallback: &str| {
value
.filter(|text| !is_blank(text))
.unwrap_or(fallback)
.to_string()
};
ResolvedInlineEditLabels {
edit: pick(self.edit.as_deref(), "Edit {label}"),
save: pick(self.save.as_deref(), "Save"),
cancel: pick(self.cancel.as_deref(), "Cancel"),
saved: pick(self.saved.as_deref(), "{label} saved."),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InlineEditChangeDetail {
pub value: String,
pub name: String,
pub previous_value: String,
prevented: Rc<Cell<bool>>,
}
impl InlineEditChangeDetail {
fn new(value: String, name: String, previous_value: String) -> Self {
Self {
value,
name,
previous_value,
prevented: Rc::new(Cell::new(false)),
}
}
pub fn prevent_default(&self) {
self.prevented.set(true);
}
pub fn default_prevented(&self) -> bool {
self.prevented.get()
}
}
#[derive(Props, Clone, PartialEq)]
pub struct InlineEditProps {
#[props(into)]
pub label: String,
#[props(into)]
pub value: Option<String>,
#[props(default, into)]
pub default_value: String,
pub on_value_change: Option<EventHandler<InlineEditChangeDetail>>,
#[props(into)]
pub name: Option<String>,
#[props(default)]
pub required: bool,
pub max_length: Option<u32>,
#[props(into)]
pub pattern: Option<String>,
#[props(into)]
pub placeholder: Option<String>,
#[props(default)]
pub multiline: bool,
pub heading_level: Option<i64>,
#[props(default)]
pub labels: InlineEditLabels,
#[props(into)]
pub id: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
}
#[component]
pub fn InlineEdit(props: InlineEditProps) -> Element {
let generated = use_unique_id();
let base_id = props
.id
.clone()
.filter(|id| !id.is_empty())
.unwrap_or(generated);
let control_id = format!("{base_id}-control");
let error_id = format!("{base_id}-error");
let labels = props.labels.resolve();
let scripting = use_scripting();
let committed = use_controllable(props.value.clone(), || props.default_value.clone(), None);
let editing = use_signal(|| false);
let draft = use_signal(String::new);
let edited = use_signal(|| false);
let error = use_signal(|| None::<String>);
let status = use_signal(String::new);
let focus = use_signal(|| None::<FocusTarget>);
let attempt = use_hook(|| CopyValue::new(0_u64));
let mut enhanced = use_signal(|| false);
let mut trigger_node = use_signal(|| None::<Rc<MountedData>>);
let mut control_node = use_signal(|| None::<Rc<MountedData>>);
let config = InlineEditConfig {
control_id: control_id.clone(),
multiline: props.multiline,
name: props.name.clone().unwrap_or_default(),
required: props.required,
max_length: props.max_length,
pattern: props.pattern.clone().filter(|_| !props.multiline),
messages: ValidityMessages::from_attributes(&props.attributes),
saved: format_label(&labels.saved, &props.label),
scripting,
on_value_change: props.on_value_change,
};
let mut config_store = use_hook(|| CopyValue::new(config.clone()));
config_store.set(config);
let machine = InlineEditMachine {
committed,
editing,
draft,
edited,
error,
status,
focus,
attempt,
config: config_store,
trigger_node,
control_node,
};
use_effect(move || enhanced.set(true));
use_effect(move || {
let request = machine.focus;
if let Some(target) = request() {
machine.move_focus(target);
}
});
let committed_value = committed.get();
let is_editing = editing();
let draft_value = draft();
let current_error = error();
let status_text = status();
let invalid = current_error.is_some();
let field_value = if is_editing {
draft_value
} else {
committed_value.clone()
};
let empty = committed_value.is_empty();
let display = if empty {
props.placeholder.clone().unwrap_or_default()
} else {
committed_value
};
let value_node = value_element(heading_level(props.heading_level), empty, display);
let edit_text = format_label(&labels.edit, &props.label);
let max_length = props.max_length.map(|max| max.to_string());
let error_hidden = current_error.as_deref().is_none_or(str::is_empty);
let class = compose([Some("ui-inline-edit"), props.class.as_deref()]);
let state = if is_editing { "editing" } else { "reading" };
rsx! {
div {
class,
"data-slot": "inline-edit",
"data-state": state,
"data-ui-inline-edit": "",
"data-ui-owner": "dioxus",
id: "{base_id}",
..props.attributes,
div { class: "ui-inline-edit__view", "data-slot": "inline-edit-view", hidden: is_editing,
{value_node}
button {
class: TRIGGER_CLASS,
"data-slot": "inline-edit-trigger",
hidden: !enhanced(),
r#type: "button",
onclick: move |_| machine.open(),
onmounted: move |event| trigger_node.set(Some(event.data())),
span { class: "ui-button__content", "{edit_text}" }
}
}
div {
class: "ui-field ui-inline-edit__editor",
"data-invalid": invalid.then_some("true"),
"data-slot": "inline-edit-editor",
"data-ui-field": "true",
"data-ui-field-control": "{control_id}",
hidden: !is_editing,
onkeydown: move |event: KeyboardEvent| {
if !is_escape(&event) || event.is_composing() || !machine.is_editing() {
return;
}
event.prevent_default();
event.stop_propagation();
machine.cancel();
},
label { class: "ui-label", "data-slot": "inline-edit-label", r#for: "{control_id}", "{props.label}" }
if props.multiline {
textarea {
aria_describedby: "{error_id}",
aria_invalid: invalid.then_some("true"),
class: "ui-textarea",
"data-slot": "inline-edit-control",
id: "{control_id}",
maxlength: max_length.clone(),
name: props.name.clone(),
placeholder: props.placeholder.clone(),
required: props.required,
rows: "3",
value: (!field_value.is_empty()).then(|| field_value.clone()),
oninput: move |event: FormEvent| machine.update(event.value()),
onkeydown: move |event: KeyboardEvent| {
let modifiers = event.modifiers();
if event.key() != Key::Enter
|| event.is_composing()
|| !(modifiers.ctrl() || modifiers.meta())
|| !machine.is_editing()
{
return;
}
event.prevent_default();
machine.save(SaveSource::Field);
},
onmounted: move |event| control_node.set(Some(event.data())),
}
} else {
input {
aria_describedby: "{error_id}",
aria_invalid: invalid.then_some("true"),
class: "ui-input",
"data-slot": "inline-edit-control",
id: "{control_id}",
maxlength: max_length.clone(),
name: props.name.clone(),
pattern: props.pattern.clone(),
placeholder: props.placeholder.clone(),
required: props.required,
r#type: "text",
value: "{field_value}",
oninput: move |event: FormEvent| machine.update(event.value()),
onkeydown: move |event: KeyboardEvent| {
if event.key() != Key::Enter || event.is_composing() || !machine.is_editing() {
return;
}
event.prevent_default();
machine.save(SaveSource::Field);
},
onmounted: move |event| control_node.set(Some(event.data())),
}
}
p {
class: "ui-field-error",
"data-slot": "inline-edit-error",
"data-ui-field-error": "true",
hidden: error_hidden,
id: "{error_id}",
if let Some(message) = current_error {
"{message}"
}
}
div { class: "ui-inline-edit__actions", "data-slot": "inline-edit-actions",
button {
class: SAVE_CLASS,
"data-slot": "inline-edit-save",
r#type: "button",
onclick: move |_| machine.save(SaveSource::Button),
span { class: "ui-button__content", "{labels.save}" }
}
button {
class: CANCEL_CLASS,
"data-slot": "inline-edit-cancel",
r#type: "button",
onclick: move |_| machine.cancel(),
span { class: "ui-button__content", "{labels.cancel}" }
}
}
}
span {
aria_atomic: "true",
aria_live: "polite",
class: "ui-sr-only",
"data-slot": "inline-edit-status",
role: "status",
"{status_text}"
}
}
}
}
fn value_element(level: Option<u8>, empty: bool, text: String) -> Element {
let empty = empty.then_some("");
match level {
None => rsx! {
span { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
},
Some(1) => rsx! {
h1 { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
},
Some(2) => rsx! {
h2 { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
},
Some(3) => rsx! {
h3 { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
},
Some(4) => rsx! {
h4 { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
},
Some(5) => rsx! {
h5 { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
},
Some(_) => rsx! {
h6 { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
},
}
}
fn heading_level(value: Option<i64>) -> Option<u8> {
value.map(|level| u8::try_from(level.clamp(1, 6)).unwrap_or(2))
}
fn is_blank(text: &str) -> bool {
js_trim(text).is_empty()
}
fn normalize_value(value: &str) -> String {
js_trim(value).to_string()
}
fn format_label(template: &str, label: &str) -> String {
template.replace("{label}", label)
}
fn attribute_text(attributes: &[Attribute], name: &str) -> Option<String> {
attributes
.iter()
.rev()
.find(|attribute| attribute.name == name)
.and_then(|attribute| match &attribute.value {
AttributeValue::Text(text) => Some(text.clone()),
_ => None,
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Violation {
ValueMissing,
PatternMismatch,
TooLong { length: usize, max: u32 },
}
fn too_long(value: &str, max_length: Option<u32>) -> Option<Violation> {
let max = max_length?;
let length = value.encode_utf16().count();
(length > usize::try_from(max).unwrap_or(usize::MAX))
.then_some(Violation::TooLong { length, max })
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct ValidityMessages {
required: Option<String>,
pattern: Option<String>,
too_long: Option<String>,
}
impl ValidityMessages {
fn from_attributes(attributes: &[Attribute]) -> Self {
Self {
required: attribute_text(attributes, "data-error-required"),
pattern: attribute_text(attributes, "data-error-pattern"),
too_long: attribute_text(attributes, "data-error-too-long"),
}
}
fn message(&self, violation: Violation) -> String {
match violation {
Violation::ValueMissing => self
.required
.clone()
.unwrap_or_else(|| VALUE_MISSING_MESSAGE.to_string()),
Violation::PatternMismatch => self
.pattern
.clone()
.unwrap_or_else(|| PATTERN_MISMATCH_MESSAGE.to_string()),
Violation::TooLong { length, max } => self.too_long.clone().unwrap_or_else(|| {
format!(
"Please shorten this text to {max} characters or less (you are currently using {length} characters)."
)
}),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FocusTarget {
Control,
Trigger,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SaveSource {
Field,
Button,
}
#[derive(Clone)]
struct InlineEditConfig {
control_id: String,
multiline: bool,
name: String,
required: bool,
max_length: Option<u32>,
pattern: Option<String>,
messages: ValidityMessages,
saved: String,
scripting: Option<bool>,
on_value_change: Option<EventHandler<InlineEditChangeDetail>>,
}
#[derive(Clone, Copy)]
struct InlineEditMachine {
committed: Controllable<String>,
editing: Signal<bool>,
draft: Signal<String>,
edited: Signal<bool>,
error: Signal<Option<String>>,
status: Signal<String>,
focus: Signal<Option<FocusTarget>>,
attempt: CopyValue<u64>,
config: CopyValue<InlineEditConfig>,
trigger_node: Signal<Option<Rc<MountedData>>>,
control_node: Signal<Option<Rc<MountedData>>>,
}
impl InlineEditMachine {
fn is_editing(&self) -> bool {
*self.editing.peek()
}
fn next_attempt(&self) -> u64 {
let mut attempt = self.attempt;
let next = (*attempt.peek()).wrapping_add(1);
attempt.set(next);
next
}
fn open(&self) {
if self.is_editing() {
return;
}
let Self {
mut draft,
mut edited,
mut error,
mut status,
mut editing,
mut focus,
..
} = *self;
self.next_attempt();
draft.set(self.committed.peek());
edited.set(false);
error.set(None);
status.set(String::new());
editing.set(true);
focus.set(Some(FocusTarget::Control));
}
fn close(&self) {
let Self {
mut editing,
mut error,
mut focus,
..
} = *self;
self.next_attempt();
editing.set(false);
error.set(None);
focus.set(Some(FocusTarget::Trigger));
}
fn cancel(&self) {
if self.is_editing() {
self.close();
}
}
fn update(&self, next: String) {
let Self {
mut draft,
mut edited,
mut error,
..
} = *self;
self.next_attempt();
draft.set(next);
edited.set(true);
let has_error = error.peek().is_some();
if has_error {
error.set(None);
}
}
fn report_invalid(&self, violation: Violation, source: SaveSource) {
let Self {
mut error,
mut status,
..
} = *self;
let message = self.config.peek().messages.message(violation);
error.set(Some(message.clone()));
match source {
SaveSource::Field => status.set(message),
SaveSource::Button => self.focus_field(),
}
}
fn save(&self, source: SaveSource) {
if !self.is_editing() {
return;
}
let mut draft = self.draft;
let attempt = self.next_attempt();
let current = draft.peek().clone();
let next = normalize_value(¤t);
if current != next {
draft.set(next.clone());
}
let config = self.config.peek().clone();
if config.required && next.is_empty() {
self.report_invalid(Violation::ValueMissing, source);
return;
}
let too_long = if *self.edited.peek() {
too_long(&next, config.max_length)
} else {
None
};
let pattern = config
.pattern
.filter(|_| !next.is_empty() && config.scripting != Some(false));
let Some(pattern) = pattern else {
self.finish(next, too_long, source);
return;
};
let eval = document::eval(PATTERN_SCRIPT);
let sent = eval.send((pattern, next.clone())).is_ok();
let machine = *self;
spawn(async move {
let matches = !sent || eval.join::<bool>().await.unwrap_or(true);
if *machine.attempt.peek() != attempt || !machine.is_editing() {
return;
}
if matches {
machine.finish(next, too_long, source);
} else {
machine.report_invalid(Violation::PatternMismatch, source);
}
});
}
fn finish(&self, next: String, too_long: Option<Violation>, source: SaveSource) {
if let Some(violation) = too_long {
self.report_invalid(violation, source);
return;
}
let previous = self.committed.peek();
if next == previous {
self.close();
return;
}
let config = self.config.peek().clone();
if let Some(handler) = config.on_value_change {
let detail = InlineEditChangeDetail::new(next.clone(), config.name, previous);
handler.call(detail.clone());
if detail.default_prevented() {
self.focus_field();
return;
}
}
let mut status = self.status;
self.committed.set(next);
self.close();
status.set(config.saved);
}
fn focus_field(&self) {
focus_element(self.control_node.peek().clone());
}
fn move_focus(&self, target: FocusTarget) {
match target {
FocusTarget::Trigger => focus_element(self.trigger_node.peek().clone()),
FocusTarget::Control => {
let node = self.control_node.peek().clone();
let config = self.config.peek().clone();
spawn(async move {
if let Some(node) = node {
let _ = node.set_focus(true).await;
}
if config.scripting == Some(true) {
let eval = document::eval(SELECT_SCRIPT);
let _ = eval.send((config.control_id, config.multiline));
}
});
}
}
}
}
#[cfg(test)]
mod tests {
use dioxus::prelude::*;
use super::{
InlineEditLabels, ValidityMessages, Violation, format_label, heading_level, is_blank,
normalize_value, too_long,
};
#[test]
fn values_trim_like_javascript() {
assert_eq!(normalize_value(" Atlas \n"), "Atlas");
assert_eq!(normalize_value("\u{feff}\u{3000}Atlas\u{a0}"), "Atlas");
assert_eq!(normalize_value("\u{85}Atlas"), "\u{85}Atlas");
assert_eq!(normalize_value(" \t "), "");
assert!(is_blank(" \u{2028}"));
assert!(!is_blank("a"));
}
#[test]
fn labels_resolve_blank_text_to_the_defaults() {
let labels = InlineEditLabels {
edit: Some("Change {label}".to_string()),
save: Some(" ".to_string()),
cancel: None,
saved: Some("{label} updated".to_string()),
}
.resolve();
assert_eq!(labels.edit, "Change {label}");
assert_eq!(labels.save, "Save");
assert_eq!(labels.cancel, "Cancel");
assert_eq!(format_label(&labels.saved, "Title"), "Title updated");
assert_eq!(format_label("{label}: {label}", "A"), "A: A");
assert_eq!(format_label("Saved", "Title"), "Saved");
}
#[test]
fn too_long_counts_utf16_code_units() {
assert_eq!(too_long("abc", Some(3)), None);
assert_eq!(
too_long("four", Some(3)),
Some(Violation::TooLong { length: 4, max: 3 })
);
assert_eq!(
too_long("\u{1f600}\u{1f600}", Some(3)),
Some(Violation::TooLong { length: 4, max: 3 })
);
assert_eq!(too_long("four", None), None);
assert!(too_long(&"a".repeat(10_000), Some(9_999)).is_some());
}
#[test]
fn heading_levels_clamp() {
assert_eq!(heading_level(None), None);
assert_eq!(heading_level(Some(0)), Some(1));
assert_eq!(heading_level(Some(4)), Some(4));
assert_eq!(heading_level(Some(9)), Some(6));
assert_eq!(heading_level(Some(i64::MIN)), Some(1));
}
#[test]
fn data_error_attributes_replace_the_default_messages() {
let attributes = vec![
Attribute::new("data-error-required", "Enter a code.", None, false),
Attribute::new("data-error-too-long", "Too long.", None, false),
];
let messages = ValidityMessages::from_attributes(&attributes);
assert_eq!(messages.message(Violation::ValueMissing), "Enter a code.");
assert_eq!(
messages.message(Violation::TooLong { length: 5, max: 4 }),
"Too long."
);
assert_eq!(
messages.message(Violation::PatternMismatch),
"Please match the requested format."
);
assert_eq!(
ValidityMessages::default().message(Violation::TooLong { length: 5, max: 4 }),
"Please shorten this text to 4 characters or less (you are currently using 5 characters)."
);
}
}