1use std::cell::Cell;
10use std::rc::Rc;
11
12use dioxus::core::AttributeValue;
13use dioxus::prelude::*;
14
15use super::number_field_host::use_scripting;
16use super::number_field_locale::js_trim;
17use crate::class::compose;
18use crate::hooks::{Controllable, use_controllable, use_unique_id};
19use crate::overlay::{focus_element, is_escape};
20
21const TRIGGER_CLASS: &str = "ui-button ui-button--outline ui-button--sm ui-inline-edit__trigger";
22const SAVE_CLASS: &str = "ui-button ui-button--default ui-button--default-size";
23const CANCEL_CLASS: &str = "ui-button ui-button--outline ui-button--default-size";
24
25const VALUE_MISSING_MESSAGE: &str = "Please fill out this field.";
26const PATTERN_MISMATCH_MESSAGE: &str = "Please match the requested format.";
27
28const PATTERN_SCRIPT: &str = r"const [pattern, value] = await dioxus.recv();
32let flags = 'v';
33try { new RegExp('', flags); } catch { flags = 'u'; }
34let expression;
35try { expression = new RegExp('^(?:' + pattern + ')$', flags); } catch { return true; }
36return expression.test(value);";
37
38const SELECT_SCRIPT: &str = r"const [id, multiline] = await dioxus.recv();
41const field = document.getElementById(id);
42if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement)) return false;
43field.focus();
44if (multiline) field.setSelectionRange(field.value.length, field.value.length);
45else field.select();
46return true;";
47
48#[derive(Clone, Debug, Default, PartialEq, Eq)]
51pub struct InlineEditLabels {
52 pub edit: Option<String>,
54 pub save: Option<String>,
56 pub cancel: Option<String>,
58 pub saved: Option<String>,
60}
61
62#[derive(Clone, Debug, PartialEq, Eq)]
64struct ResolvedInlineEditLabels {
65 edit: String,
66 save: String,
67 cancel: String,
68 saved: String,
69}
70
71impl InlineEditLabels {
72 fn resolve(&self) -> ResolvedInlineEditLabels {
73 let pick = |value: Option<&str>, fallback: &str| {
74 value
75 .filter(|text| !is_blank(text))
76 .unwrap_or(fallback)
77 .to_string()
78 };
79
80 ResolvedInlineEditLabels {
81 edit: pick(self.edit.as_deref(), "Edit {label}"),
82 save: pick(self.save.as_deref(), "Save"),
83 cancel: pick(self.cancel.as_deref(), "Cancel"),
84 saved: pick(self.saved.as_deref(), "{label} saved."),
85 }
86 }
87}
88
89#[derive(Clone, Debug, PartialEq, Eq)]
96pub struct InlineEditChangeDetail {
97 pub value: String,
99 pub name: String,
101 pub previous_value: String,
103 prevented: Rc<Cell<bool>>,
104}
105
106impl InlineEditChangeDetail {
107 fn new(value: String, name: String, previous_value: String) -> Self {
108 Self {
109 value,
110 name,
111 previous_value,
112 prevented: Rc::new(Cell::new(false)),
113 }
114 }
115
116 pub fn prevent_default(&self) {
118 self.prevented.set(true);
119 }
120
121 pub fn default_prevented(&self) -> bool {
123 self.prevented.get()
124 }
125}
126
127#[derive(Props, Clone, PartialEq)]
129pub struct InlineEditProps {
130 #[props(into)]
132 pub label: String,
133 #[props(into)]
135 pub value: Option<String>,
136 #[props(default, into)]
138 pub default_value: String,
139 pub on_value_change: Option<EventHandler<InlineEditChangeDetail>>,
142 #[props(into)]
144 pub name: Option<String>,
145 #[props(default)]
147 pub required: bool,
148 pub max_length: Option<u32>,
150 #[props(into)]
153 pub pattern: Option<String>,
154 #[props(into)]
156 pub placeholder: Option<String>,
157 #[props(default)]
159 pub multiline: bool,
160 pub heading_level: Option<i64>,
162 #[props(default)]
164 pub labels: InlineEditLabels,
165 #[props(into)]
168 pub id: Option<String>,
169 #[props(into)]
171 pub class: Option<String>,
172 #[props(extends = GlobalAttributes, extends = div)]
175 pub attributes: Vec<Attribute>,
176}
177
178#[component]
187pub fn InlineEdit(props: InlineEditProps) -> Element {
188 let generated = use_unique_id();
189 let base_id = props
190 .id
191 .clone()
192 .filter(|id| !id.is_empty())
193 .unwrap_or(generated);
194 let control_id = format!("{base_id}-control");
195 let error_id = format!("{base_id}-error");
196 let labels = props.labels.resolve();
197 let scripting = use_scripting();
198 let committed = use_controllable(props.value.clone(), || props.default_value.clone(), None);
199 let editing = use_signal(|| false);
200 let draft = use_signal(String::new);
201 let edited = use_signal(|| false);
202 let error = use_signal(|| None::<String>);
203 let status = use_signal(String::new);
204 let focus = use_signal(|| None::<FocusTarget>);
205 let attempt = use_hook(|| CopyValue::new(0_u64));
206 let mut enhanced = use_signal(|| false);
207 let mut trigger_node = use_signal(|| None::<Rc<MountedData>>);
208 let mut control_node = use_signal(|| None::<Rc<MountedData>>);
209 let config = InlineEditConfig {
210 control_id: control_id.clone(),
211 multiline: props.multiline,
212 name: props.name.clone().unwrap_or_default(),
213 required: props.required,
214 max_length: props.max_length,
215 pattern: props.pattern.clone().filter(|_| !props.multiline),
216 messages: ValidityMessages::from_attributes(&props.attributes),
217 saved: format_label(&labels.saved, &props.label),
218 scripting,
219 on_value_change: props.on_value_change,
220 };
221 let mut config_store = use_hook(|| CopyValue::new(config.clone()));
222 config_store.set(config);
223
224 let machine = InlineEditMachine {
225 committed,
226 editing,
227 draft,
228 edited,
229 error,
230 status,
231 focus,
232 attempt,
233 config: config_store,
234 trigger_node,
235 control_node,
236 };
237
238 use_effect(move || enhanced.set(true));
239 use_effect(move || {
242 let request = machine.focus;
243
244 if let Some(target) = request() {
245 machine.move_focus(target);
246 }
247 });
248
249 let committed_value = committed.get();
250 let is_editing = editing();
251 let draft_value = draft();
252 let current_error = error();
253 let status_text = status();
254 let invalid = current_error.is_some();
255 let field_value = if is_editing {
256 draft_value
257 } else {
258 committed_value.clone()
259 };
260 let empty = committed_value.is_empty();
261 let display = if empty {
262 props.placeholder.clone().unwrap_or_default()
263 } else {
264 committed_value
265 };
266 let value_node = value_element(heading_level(props.heading_level), empty, display);
267 let edit_text = format_label(&labels.edit, &props.label);
268 let max_length = props.max_length.map(|max| max.to_string());
269 let error_hidden = current_error.as_deref().is_none_or(str::is_empty);
270 let class = compose([Some("ui-inline-edit"), props.class.as_deref()]);
271 let state = if is_editing { "editing" } else { "reading" };
272
273 rsx! {
274 div {
275 class,
276 "data-slot": "inline-edit",
277 "data-state": state,
278 "data-ui-inline-edit": "",
279 "data-ui-owner": "dioxus",
280 id: "{base_id}",
281 ..props.attributes,
282 div { class: "ui-inline-edit__view", "data-slot": "inline-edit-view", hidden: is_editing,
283 {value_node}
284 button {
285 class: TRIGGER_CLASS,
286 "data-slot": "inline-edit-trigger",
287 hidden: !enhanced(),
288 r#type: "button",
289 onclick: move |_| machine.open(),
290 onmounted: move |event| trigger_node.set(Some(event.data())),
291 span { class: "ui-button__content", "{edit_text}" }
292 }
293 }
294 div {
295 class: "ui-field ui-inline-edit__editor",
296 "data-invalid": invalid.then_some("true"),
297 "data-slot": "inline-edit-editor",
298 "data-ui-field": "true",
299 "data-ui-field-control": "{control_id}",
300 hidden: !is_editing,
301 onkeydown: move |event: KeyboardEvent| {
302 if !is_escape(&event) || event.is_composing() || !machine.is_editing() {
303 return;
304 }
305
306 event.prevent_default();
308 event.stop_propagation();
309 machine.cancel();
310 },
311 label { class: "ui-label", "data-slot": "inline-edit-label", r#for: "{control_id}", "{props.label}" }
312 if props.multiline {
313 textarea {
314 aria_describedby: "{error_id}",
315 aria_invalid: invalid.then_some("true"),
316 class: "ui-textarea",
317 "data-slot": "inline-edit-control",
318 id: "{control_id}",
319 maxlength: max_length.clone(),
320 name: props.name.clone(),
321 placeholder: props.placeholder.clone(),
322 required: props.required,
323 rows: "3",
324 value: (!field_value.is_empty()).then(|| field_value.clone()),
327 oninput: move |event: FormEvent| machine.update(event.value()),
328 onkeydown: move |event: KeyboardEvent| {
329 let modifiers = event.modifiers();
330
331 if event.key() != Key::Enter
333 || event.is_composing()
334 || !(modifiers.ctrl() || modifiers.meta())
335 || !machine.is_editing()
336 {
337 return;
338 }
339
340 event.prevent_default();
341 machine.save(SaveSource::Field);
342 },
343 onmounted: move |event| control_node.set(Some(event.data())),
344 }
345 } else {
346 input {
347 aria_describedby: "{error_id}",
348 aria_invalid: invalid.then_some("true"),
349 class: "ui-input",
350 "data-slot": "inline-edit-control",
351 id: "{control_id}",
352 maxlength: max_length.clone(),
353 name: props.name.clone(),
354 pattern: props.pattern.clone(),
355 placeholder: props.placeholder.clone(),
356 required: props.required,
357 r#type: "text",
358 value: "{field_value}",
359 oninput: move |event: FormEvent| machine.update(event.value()),
360 onkeydown: move |event: KeyboardEvent| {
361 if event.key() != Key::Enter || event.is_composing() || !machine.is_editing() {
362 return;
363 }
364
365 event.prevent_default();
366 machine.save(SaveSource::Field);
367 },
368 onmounted: move |event| control_node.set(Some(event.data())),
369 }
370 }
371 p {
372 class: "ui-field-error",
373 "data-slot": "inline-edit-error",
374 "data-ui-field-error": "true",
375 hidden: error_hidden,
376 id: "{error_id}",
377 if let Some(message) = current_error {
378 "{message}"
379 }
380 }
381 div { class: "ui-inline-edit__actions", "data-slot": "inline-edit-actions",
382 button {
383 class: SAVE_CLASS,
384 "data-slot": "inline-edit-save",
385 r#type: "button",
386 onclick: move |_| machine.save(SaveSource::Button),
387 span { class: "ui-button__content", "{labels.save}" }
388 }
389 button {
390 class: CANCEL_CLASS,
391 "data-slot": "inline-edit-cancel",
392 r#type: "button",
393 onclick: move |_| machine.cancel(),
394 span { class: "ui-button__content", "{labels.cancel}" }
395 }
396 }
397 }
398 span {
399 aria_atomic: "true",
400 aria_live: "polite",
401 class: "ui-sr-only",
402 "data-slot": "inline-edit-status",
403 role: "status",
404 "{status_text}"
405 }
406 }
407 }
408}
409
410fn value_element(level: Option<u8>, empty: bool, text: String) -> Element {
412 let empty = empty.then_some("");
413
414 match level {
415 None => rsx! {
416 span { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
417 },
418 Some(1) => rsx! {
419 h1 { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
420 },
421 Some(2) => rsx! {
422 h2 { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
423 },
424 Some(3) => rsx! {
425 h3 { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
426 },
427 Some(4) => rsx! {
428 h4 { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
429 },
430 Some(5) => rsx! {
431 h5 { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
432 },
433 Some(_) => rsx! {
434 h6 { class: "ui-inline-edit__value", "data-empty": empty, "data-slot": "inline-edit-value", {text} }
435 },
436 }
437}
438
439fn heading_level(value: Option<i64>) -> Option<u8> {
441 value.map(|level| u8::try_from(level.clamp(1, 6)).unwrap_or(2))
442}
443
444fn is_blank(text: &str) -> bool {
445 js_trim(text).is_empty()
446}
447
448fn normalize_value(value: &str) -> String {
451 js_trim(value).to_string()
452}
453
454fn format_label(template: &str, label: &str) -> String {
456 template.replace("{label}", label)
457}
458
459fn attribute_text(attributes: &[Attribute], name: &str) -> Option<String> {
461 attributes
462 .iter()
463 .rev()
464 .find(|attribute| attribute.name == name)
465 .and_then(|attribute| match &attribute.value {
466 AttributeValue::Text(text) => Some(text.clone()),
467 _ => None,
468 })
469}
470
471#[derive(Clone, Copy, Debug, PartialEq, Eq)]
473enum Violation {
474 ValueMissing,
475 PatternMismatch,
476 TooLong { length: usize, max: u32 },
477}
478
479fn too_long(value: &str, max_length: Option<u32>) -> Option<Violation> {
481 let max = max_length?;
482 let length = value.encode_utf16().count();
483
484 (length > usize::try_from(max).unwrap_or(usize::MAX))
485 .then_some(Violation::TooLong { length, max })
486}
487
488#[derive(Clone, Debug, Default, PartialEq, Eq)]
490struct ValidityMessages {
491 required: Option<String>,
492 pattern: Option<String>,
493 too_long: Option<String>,
494}
495
496impl ValidityMessages {
497 fn from_attributes(attributes: &[Attribute]) -> Self {
498 Self {
499 required: attribute_text(attributes, "data-error-required"),
500 pattern: attribute_text(attributes, "data-error-pattern"),
501 too_long: attribute_text(attributes, "data-error-too-long"),
502 }
503 }
504
505 fn message(&self, violation: Violation) -> String {
506 match violation {
507 Violation::ValueMissing => self
508 .required
509 .clone()
510 .unwrap_or_else(|| VALUE_MISSING_MESSAGE.to_string()),
511 Violation::PatternMismatch => self
512 .pattern
513 .clone()
514 .unwrap_or_else(|| PATTERN_MISMATCH_MESSAGE.to_string()),
515 Violation::TooLong { length, max } => self.too_long.clone().unwrap_or_else(|| {
516 format!(
517 "Please shorten this text to {max} characters or less (you are currently using {length} characters)."
518 )
519 }),
520 }
521 }
522}
523
524#[derive(Clone, Copy, Debug, PartialEq, Eq)]
526enum FocusTarget {
527 Control,
529 Trigger,
531}
532
533#[derive(Clone, Copy, Debug, PartialEq, Eq)]
536enum SaveSource {
537 Field,
538 Button,
539}
540
541#[derive(Clone)]
543struct InlineEditConfig {
544 control_id: String,
545 multiline: bool,
546 name: String,
547 required: bool,
548 max_length: Option<u32>,
549 pattern: Option<String>,
550 messages: ValidityMessages,
551 saved: String,
552 scripting: Option<bool>,
553 on_value_change: Option<EventHandler<InlineEditChangeDetail>>,
554}
555
556#[derive(Clone, Copy)]
558struct InlineEditMachine {
559 committed: Controllable<String>,
560 editing: Signal<bool>,
561 draft: Signal<String>,
562 edited: Signal<bool>,
565 error: Signal<Option<String>>,
566 status: Signal<String>,
567 focus: Signal<Option<FocusTarget>>,
568 attempt: CopyValue<u64>,
570 config: CopyValue<InlineEditConfig>,
571 trigger_node: Signal<Option<Rc<MountedData>>>,
572 control_node: Signal<Option<Rc<MountedData>>>,
573}
574
575impl InlineEditMachine {
576 fn is_editing(&self) -> bool {
577 *self.editing.peek()
578 }
579
580 fn next_attempt(&self) -> u64 {
581 let mut attempt = self.attempt;
582 let next = (*attempt.peek()).wrapping_add(1);
583
584 attempt.set(next);
585 next
586 }
587
588 fn open(&self) {
589 if self.is_editing() {
590 return;
591 }
592
593 let Self {
594 mut draft,
595 mut edited,
596 mut error,
597 mut status,
598 mut editing,
599 mut focus,
600 ..
601 } = *self;
602
603 self.next_attempt();
604 draft.set(self.committed.peek());
605 edited.set(false);
606 error.set(None);
607 status.set(String::new());
608 editing.set(true);
609 focus.set(Some(FocusTarget::Control));
610 }
611
612 fn close(&self) {
613 let Self {
614 mut editing,
615 mut error,
616 mut focus,
617 ..
618 } = *self;
619
620 self.next_attempt();
621 editing.set(false);
622 error.set(None);
623 focus.set(Some(FocusTarget::Trigger));
624 }
625
626 fn cancel(&self) {
627 if self.is_editing() {
628 self.close();
629 }
630 }
631
632 fn update(&self, next: String) {
634 let Self {
635 mut draft,
636 mut edited,
637 mut error,
638 ..
639 } = *self;
640
641 self.next_attempt();
642 draft.set(next);
643 edited.set(true);
644
645 let has_error = error.peek().is_some();
646
647 if has_error {
648 error.set(None);
649 }
650 }
651
652 fn report_invalid(&self, violation: Violation, source: SaveSource) {
653 let Self {
654 mut error,
655 mut status,
656 ..
657 } = *self;
658 let message = self.config.peek().messages.message(violation);
659
660 error.set(Some(message.clone()));
661
662 match source {
665 SaveSource::Field => status.set(message),
666 SaveSource::Button => self.focus_field(),
667 }
668 }
669
670 fn save(&self, source: SaveSource) {
671 if !self.is_editing() {
672 return;
673 }
674
675 let mut draft = self.draft;
676 let attempt = self.next_attempt();
677 let current = draft.peek().clone();
678 let next = normalize_value(¤t);
679
680 if current != next {
682 draft.set(next.clone());
683 }
684
685 let config = self.config.peek().clone();
686
687 if config.required && next.is_empty() {
688 self.report_invalid(Violation::ValueMissing, source);
689 return;
690 }
691
692 let too_long = if *self.edited.peek() {
693 too_long(&next, config.max_length)
694 } else {
695 None
696 };
697 let pattern = config
700 .pattern
701 .filter(|_| !next.is_empty() && config.scripting != Some(false));
702
703 let Some(pattern) = pattern else {
704 self.finish(next, too_long, source);
705 return;
706 };
707
708 let eval = document::eval(PATTERN_SCRIPT);
709 let sent = eval.send((pattern, next.clone())).is_ok();
710 let machine = *self;
711
712 spawn(async move {
713 let matches = !sent || eval.join::<bool>().await.unwrap_or(true);
715
716 if *machine.attempt.peek() != attempt || !machine.is_editing() {
718 return;
719 }
720
721 if matches {
722 machine.finish(next, too_long, source);
723 } else {
724 machine.report_invalid(Violation::PatternMismatch, source);
725 }
726 });
727 }
728
729 fn finish(&self, next: String, too_long: Option<Violation>, source: SaveSource) {
732 if let Some(violation) = too_long {
733 self.report_invalid(violation, source);
734 return;
735 }
736
737 let previous = self.committed.peek();
738
739 if next == previous {
740 self.close();
741 return;
742 }
743
744 let config = self.config.peek().clone();
745
746 if let Some(handler) = config.on_value_change {
747 let detail = InlineEditChangeDetail::new(next.clone(), config.name, previous);
748
749 handler.call(detail.clone());
750
751 if detail.default_prevented() {
752 self.focus_field();
753 return;
754 }
755 }
756
757 let mut status = self.status;
758
759 self.committed.set(next);
760 self.close();
761 status.set(config.saved);
762 }
763
764 fn focus_field(&self) {
766 focus_element(self.control_node.peek().clone());
767 }
768
769 fn move_focus(&self, target: FocusTarget) {
770 match target {
771 FocusTarget::Trigger => focus_element(self.trigger_node.peek().clone()),
772 FocusTarget::Control => {
773 let node = self.control_node.peek().clone();
774 let config = self.config.peek().clone();
775
776 spawn(async move {
777 if let Some(node) = node {
778 let _ = node.set_focus(true).await;
779 }
780
781 if config.scripting == Some(true) {
783 let eval = document::eval(SELECT_SCRIPT);
784 let _ = eval.send((config.control_id, config.multiline));
785 }
786 });
787 }
788 }
789 }
790}
791
792#[cfg(test)]
793mod tests {
794 use dioxus::prelude::*;
795
796 use super::{
797 InlineEditLabels, ValidityMessages, Violation, format_label, heading_level, is_blank,
798 normalize_value, too_long,
799 };
800
801 #[test]
802 fn values_trim_like_javascript() {
803 assert_eq!(normalize_value(" Atlas \n"), "Atlas");
804 assert_eq!(normalize_value("\u{feff}\u{3000}Atlas\u{a0}"), "Atlas");
805 assert_eq!(normalize_value("\u{85}Atlas"), "\u{85}Atlas");
806 assert_eq!(normalize_value(" \t "), "");
807 assert!(is_blank(" \u{2028}"));
808 assert!(!is_blank("a"));
809 }
810
811 #[test]
812 fn labels_resolve_blank_text_to_the_defaults() {
813 let labels = InlineEditLabels {
814 edit: Some("Change {label}".to_string()),
815 save: Some(" ".to_string()),
816 cancel: None,
817 saved: Some("{label} updated".to_string()),
818 }
819 .resolve();
820
821 assert_eq!(labels.edit, "Change {label}");
822 assert_eq!(labels.save, "Save");
823 assert_eq!(labels.cancel, "Cancel");
824 assert_eq!(format_label(&labels.saved, "Title"), "Title updated");
825 assert_eq!(format_label("{label}: {label}", "A"), "A: A");
826 assert_eq!(format_label("Saved", "Title"), "Saved");
827 }
828
829 #[test]
830 fn too_long_counts_utf16_code_units() {
831 assert_eq!(too_long("abc", Some(3)), None);
832 assert_eq!(
833 too_long("four", Some(3)),
834 Some(Violation::TooLong { length: 4, max: 3 })
835 );
836 assert_eq!(
837 too_long("\u{1f600}\u{1f600}", Some(3)),
838 Some(Violation::TooLong { length: 4, max: 3 })
839 );
840 assert_eq!(too_long("four", None), None);
841 assert!(too_long(&"a".repeat(10_000), Some(9_999)).is_some());
842 }
843
844 #[test]
845 fn heading_levels_clamp() {
846 assert_eq!(heading_level(None), None);
847 assert_eq!(heading_level(Some(0)), Some(1));
848 assert_eq!(heading_level(Some(4)), Some(4));
849 assert_eq!(heading_level(Some(9)), Some(6));
850 assert_eq!(heading_level(Some(i64::MIN)), Some(1));
851 }
852
853 #[test]
854 fn data_error_attributes_replace_the_default_messages() {
855 let attributes = vec![
856 Attribute::new("data-error-required", "Enter a code.", None, false),
857 Attribute::new("data-error-too-long", "Too long.", None, false),
858 ];
859 let messages = ValidityMessages::from_attributes(&attributes);
860
861 assert_eq!(messages.message(Violation::ValueMissing), "Enter a code.");
862 assert_eq!(
863 messages.message(Violation::TooLong { length: 5, max: 4 }),
864 "Too long."
865 );
866 assert_eq!(
867 messages.message(Violation::PatternMismatch),
868 "Please match the requested format."
869 );
870 assert_eq!(
871 ValidityMessages::default().message(Violation::TooLong { length: 5, max: 4 }),
872 "Please shorten this text to 4 characters or less (you are currently using 5 characters)."
873 );
874 }
875}