lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
//! `InlineEdit`: one value shown as text, edited in place with Save and Cancel.
//!
//! The behavior follows `@santi020k/lumen-react` and the `InlineEdit` contract in lumen-core: Edit
//! opens a labelled field with the committed value, Save trims and validates it, and the host
//! accepts or rejects the change through `on_value_change`. Persistence stays in the application.

// cspell:words feff

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.";

/// Tests a value against an `<input pattern>` the way the browser does: the whole value must
/// match, with the `v` flag where the browser supports it, and a pattern that does not compile
/// sets no constraint. Values travel through the eval channel, never through the script text.
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);";

/// Selects the text of a single-line field, or puts the caret at the end of a multiline field,
/// after the editor opens.
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;";

/// Text of an [`InlineEdit`]. Unset or blank fields keep the English default, and `{label}`
/// becomes the field label, like `resolveLumenInlineEditLabels` in lumen-core.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct InlineEditLabels {
    /// Edit button text, also its accessible name. Default: "Edit {label}".
    pub edit: Option<String>,
    /// Save button text. Default: "Save".
    pub save: Option<String>,
    /// Cancel button text. Default: "Cancel".
    pub cancel: Option<String>,
    /// Polite announcement after a saved change. Default: "{label} saved."
    pub saved: Option<String>,
}

/// [`InlineEditLabels`] with the defaults filled in.
#[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."),
        }
    }
}

/// A change the person saved in an [`InlineEdit`], passed to `on_value_change` before the editor
/// closes.
///
/// Call [`prevent_default`](Self::prevent_default) while the handler runs to keep the editor open
/// with focus in the field, like `preventDefault()` in lumen-react. A later call, for example
/// from a spawned task, has no effect.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InlineEditChangeDetail {
    /// The trimmed value to save.
    pub value: String,
    /// The `name` prop, or an empty string.
    pub name: String,
    /// The committed value before this change.
    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)),
        }
    }

    /// Keeps the editor open with focus in the field instead of saving.
    pub fn prevent_default(&self) {
        self.prevented.set(true);
    }

    /// Whether a handler called [`prevent_default`](Self::prevent_default).
    pub fn default_prevented(&self) -> bool {
        self.prevented.get()
    }
}

/// Props for [`InlineEdit`].
#[derive(Props, Clone, PartialEq)]
pub struct InlineEditProps {
    /// Names the field, its Edit button, and the saved announcement.
    #[props(into)]
    pub label: String,
    /// The committed value. Setting it makes the component controlled.
    #[props(into)]
    pub value: Option<String>,
    /// The initial committed value when `value` is not set.
    #[props(default, into)]
    pub default_value: String,
    /// Called with the trimmed value after a valid save that changed it. Call
    /// `prevent_default()` on the detail to keep the editor open.
    pub on_value_change: Option<EventHandler<InlineEditChangeDetail>>,
    /// The field's form name, also passed to `on_value_change` as `name`.
    #[props(into)]
    pub name: Option<String>,
    /// Rejects an empty value, after trimming.
    #[props(default)]
    pub required: bool,
    /// Most UTF-16 code units the field accepts, like the native `maxlength`.
    pub max_length: Option<u32>,
    /// A regular expression the whole single-line value must match, like the native `pattern`.
    /// Ignored when `multiline` is set.
    #[props(into)]
    pub pattern: Option<String>,
    /// Hint in the empty field, also shown muted in read mode while the value is empty.
    #[props(into)]
    pub placeholder: Option<String>,
    /// Edits with a textarea. Enter adds a line; Control or Command with Enter saves.
    #[props(default)]
    pub multiline: bool,
    /// Renders the read-mode value as a heading of this level. Values outside 1-6 clamp.
    pub heading_level: Option<i64>,
    /// Button text and the saved announcement.
    #[props(default)]
    pub labels: InlineEditLabels,
    /// Root id. The field id becomes `{id}-control` and the error id `{id}-error`; generated when
    /// unset or empty.
    #[props(into)]
    pub id: Option<String>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. `data-error-required`, `data-error-pattern`, and
    /// `data-error-too-long` replace the default validation messages, as in lumen-react.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
}

/// Shows one value as text with an Edit button that swaps in a labelled field with Save and
/// Cancel.
///
/// Save trims the value and checks `required`, `max_length`, and `pattern`. A failed check shows
/// the message under the field and keeps focus there. A changed value goes to `on_value_change`;
/// unless the handler prevents it, the editor closes, focus returns to Edit, and the saved label
/// is announced politely. Escape or Cancel restores the committed value. Server rendering keeps
/// Edit hidden until the component mounts, like lumen-react before hydration.
#[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));
    // Focus moves after the render that shows its target: the field on open, Edit on close.
    // Every request writes the signal, so asking for the same target again runs this again.
    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;
                    }

                    // Escape closes only the editor, not a dialog or popover around it.
                    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",
                        // An absent attribute is an empty field, which keeps server-rendered
                        // markup equal to lumen-react's, where the value is the element's text.
                        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();

                            // Enter adds a line; Control or Command with Enter saves.
                            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}"
            }
        }
    }
}

/// The read-mode value: a `span`, or `h1`-`h6` when a heading level is set.
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} }
        },
    }
}

/// Clamps a heading level to 1-6, like `resolveLumenHeadingLevel` in lumen-core.
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()
}

/// The value Lumen validates and saves: the typed text without surrounding white space, like
/// `normalizeLumenInlineEditValue`.
fn normalize_value(value: &str) -> String {
    js_trim(value).to_string()
}

/// Replaces every `{label}` in a label template, like `formatLumenInlineEditLabel`.
fn format_label(template: &str, label: &str) -> String {
    template.replace("{label}", label)
}

/// The text of an attribute the app passed to the component, if any.
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,
        })
}

/// A native constraint the saved value fails.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Violation {
    ValueMissing,
    PatternMismatch,
    TooLong { length: usize, max: u32 },
}

/// `TooLong` when `value` has more UTF-16 code units than `max_length`, as the browser counts.
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 })
}

/// Messages from `data-error-*` attributes, which replace the defaults for their constraint.
#[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)."
                )
            }),
        }
    }
}

/// What receives focus after the next render.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FocusTarget {
    /// The field of an editor that just opened, with its text selected.
    Control,
    /// The Edit button of an editor that just closed.
    Trigger,
}

/// Where a save started. Enter comes from the field, which already has focus; Save moves focus
/// back to the field when the value is invalid.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SaveSource {
    Field,
    Button,
}

/// The props the event handlers read, refreshed on every render.
#[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>>,
}

/// The editor state shared by the event handlers.
#[derive(Clone, Copy)]
struct InlineEditMachine {
    committed: Controllable<String>,
    editing: Signal<bool>,
    draft: Signal<String>,
    /// Whether the person typed since the editor opened; the browser only reports a value longer
    /// than `maxlength` after an edit.
    edited: Signal<bool>,
    error: Signal<Option<String>>,
    status: Signal<String>,
    focus: Signal<Option<FocusTarget>>,
    /// Counts opens, closes, edits, and saves, so a pattern check that finishes late is dropped.
    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();
        }
    }

    /// Typing replaces the draft and clears a shown error.
    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()));

        // Moving focus reads the field and its error; a field that already has focus needs the
        // status region.
        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(&current);

        // Validate the trimmed text, so white space alone fails `required`.
        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
        };
        // The browser skips `pattern` for an empty value. Dioxus Native runs no JavaScript, so
        // the pattern is not checked there.
        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 {
            // A check that cannot run leaves the pattern unchecked, as on Dioxus Native.
            let matches = !sent || eval.join::<bool>().await.unwrap_or(true);

            // Typing, closing, or saving again while the check ran makes this result stale.
            if *machine.attempt.peek() != attempt || !machine.is_editing() {
                return;
            }

            if matches {
                machine.finish(next, too_long, source);
            } else {
                machine.report_invalid(Violation::PatternMismatch, source);
            }
        });
    }

    /// Ends a save whose value passed the earlier checks, in the browser's order: a value that is
    /// too long fails after a pattern mismatch. An unchanged value closes without an event.
    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);
    }

    /// Focuses the visible field without changing its selection.
    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;
                    }

                    // Selection needs the DOM: a web and desktop enhancement.
                    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)."
        );
    }
}