1
//! Text Input Manager
2
//!
3
//! Centralizes all text editing logic for contenteditable nodes.
4
//!
5
//! This manager handles text input from multiple sources:
6
//!
7
//! - Keyboard input (character insertion, backspace, etc.)
8
//! - IME composition (multi-character input for Asian languages)
9
//! - Accessibility actions (screen readers, voice control)
10
//! - Programmatic edits (from callbacks)
11
//!
12
//! ## Architecture
13
//!
14
//! The text input system uses a two-phase approach:
15
//!
16
//! 1. **Record Phase**: When text input occurs, record what changed (`old_text` + `inserted_text`)
17
//!
18
//!    - Append to `pending_changesets`, a FIFO queue — several edits can be recorded before the
19
//!      pass that applies them runs, and they may target different nodes and come from different
20
//!      sources
21
//!    - Do NOT modify any caches yet
22
//!    - Return affected nodes so callbacks can be invoked
23
//!
24
//! 2. **Apply Phase**: After callbacks, if preventDefault was not set:
25
//!
26
//!    - Compute new text using `text3::edit`
27
//!    - Update cursor position
28
//!    - Update text cache
29
//!    - Mark nodes dirty for re-layout
30
//!
31
//! This separation allows:
32
//!
33
//! - User callbacks to inspect the changeset before it's applied
34
//! - preventDefault to cancel the edit
35
//! - Consistent behavior across keyboard/IME/A11y sources
36

            
37
use azul_core::{
38
    dom::DomNodeId,
39
    events::{
40
        EventData, EventProvider, EventSource as CoreEventSource, EventType, SyntheticEvent,
41
        TextInputEventData,
42
    },
43
    task::Instant,
44
};
45
use azul_css::corety::AzString;
46

            
47
/// Information about a pending text edit that hasn't been applied yet
48
#[derive(Debug, Clone)]
49
#[repr(C)]
50
pub struct PendingTextEdit {
51
    /// The node that was edited
52
    pub node: DomNodeId,
53
    /// The text that was inserted
54
    pub inserted_text: AzString,
55
    /// The old text before the edit (plain text extracted from `InlineContent`)
56
    pub old_text: AzString,
57
}
58

            
59
impl PendingTextEdit {
60
    /// Preview the resulting text by appending `inserted_text` to `old_text`.
61
    ///
62
    /// NOTE: Actual cursor-based insertion is handled by `apply_text_changeset()`
63
    /// in window.rs via `text3::edit::insert_text()`.
64
    #[must_use]
65
202
    pub fn resulting_text(&self) -> AzString {
66
202
        let mut result = self.old_text.as_str().to_string();
67
202
        result.push_str(self.inserted_text.as_str());
68
202
        result.into()
69
202
    }
70
}
71
#[allow(variant_size_differences)]
72
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
73
// disparity accepted
74
/// C-compatible Option type for `PendingTextEdit`
75
#[derive(Debug, Clone)]
76
#[repr(C, u8)]
77
pub enum OptionPendingTextEdit {
78
    None,
79
    Some(PendingTextEdit),
80
}
81

            
82
impl OptionPendingTextEdit {
83
    #[must_use]
84
17
    pub fn into_option(self) -> Option<PendingTextEdit> {
85
17
        match self {
86
3
            Self::None => None,
87
14
            Self::Some(t) => Some(t),
88
        }
89
17
    }
90
}
91

            
92
impl From<Option<PendingTextEdit>> for OptionPendingTextEdit {
93
14
    fn from(o: Option<PendingTextEdit>) -> Self {
94
14
        o.map_or_else(|| Self::None, Self::Some)
95
14
    }
96
}
97

            
98
impl<'a> From<Option<&'a PendingTextEdit>> for OptionPendingTextEdit {
99
2
    fn from(o: Option<&'a PendingTextEdit>) -> Self {
100
2
        o.map_or_else(|| Self::None, |v| Self::Some(v.clone()))
101
2
    }
102
}
103

            
104
/// Source of a text input event
105
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106
pub enum TextInputSource {
107
    /// Regular keyboard input
108
    Keyboard,
109
    /// IME composition (multi-character input)
110
    Ime,
111
    /// Accessibility action from assistive technology
112
    Accessibility,
113
    /// Programmatic edit from user callback
114
    Programmatic,
115
}
116

            
117
/// One recorded-but-not-yet-applied edit, together with where it came from.
118
///
119
/// The source is stored PER ENTRY: a queue can hold a keyboard edit and an
120
/// accessibility edit at the same time, so one manager-wide "current source"
121
/// cannot describe it (it would relabel the older entries' `EventSource` with
122
/// whatever arrived last).
123
#[derive(Debug, Clone)]
124
pub struct QueuedTextEdit {
125
    /// What was recorded.
126
    pub edit: PendingTextEdit,
127
    /// Where this particular edit came from.
128
    pub source: TextInputSource,
129
    /// Which SEAT typed it (9b-ii-a-i-d-ii): the edit is applied at that
130
    /// seat's caret. Seat 0 is the primary.
131
    pub seat_id: u64,
132
}
133

            
134
/// FIFO of recorded-but-not-yet-applied text edits, oldest first.
135
///
136
/// The head is stored out of line from the tail so [`Self::front`] can be a
137
/// `const fn`: a `Vec` cannot be dereferenced in const context, and
138
/// `LayoutWindow::get_last_text_changeset` (which reaches the front through
139
/// [`TextInputManager::get_pending_changeset`]) is const. The split is an
140
/// implementation detail — `head.is_none()` always means the whole queue is
141
/// empty, which is why both fields are private and every mutation goes through
142
/// a method here.
143
#[derive(Debug, Clone, Default)]
144
pub struct PendingTextEditQueue {
145
    head: Option<QueuedTextEdit>,
146
    tail: Vec<QueuedTextEdit>,
147
}
148

            
149
impl PendingTextEditQueue {
150
    /// An empty queue.
151
    #[must_use]
152
7625
    pub const fn new() -> Self {
153
7625
        Self {
154
7625
            head: None,
155
7625
            tail: Vec::new(),
156
7625
        }
157
7625
    }
158

            
159
    /// Append an edit; the oldest entry stays at the front.
160
2994
    pub fn push(&mut self, entry: QueuedTextEdit) {
161
2994
        if self.head.is_none() {
162
2912
            self.head = Some(entry);
163
2912
        } else {
164
82
            self.tail.push(entry);
165
82
        }
166
2994
    }
167

            
168
    /// The oldest queued edit — the one the next apply pass consumes.
169
    #[must_use]
170
2060
    pub const fn front(&self) -> Option<&QueuedTextEdit> {
171
2060
        match &self.head {
172
2036
            Some(q) => Some(q),
173
24
            None => None,
174
        }
175
2060
    }
176

            
177
    /// Mutable access to the oldest queued edit.
178
72
    pub const fn front_mut(&mut self) -> Option<&mut QueuedTextEdit> {
179
72
        self.head.as_mut()
180
72
    }
181

            
182
    /// The most recently recorded edit.
183
    #[must_use]
184
21
    pub fn back(&self) -> Option<&QueuedTextEdit> {
185
21
        self.tail.last().or(self.head.as_ref())
186
21
    }
187

            
188
    /// Remove and return the oldest queued edit.
189
5781
    pub fn pop_front(&mut self) -> Option<QueuedTextEdit> {
190
5781
        let popped = self.head.take()?;
191
2853
        if !self.tail.is_empty() {
192
52
            self.head = Some(self.tail.remove(0));
193
2802
        }
194
2853
        Some(popped)
195
5781
    }
196

            
197
    /// Drop the whole queue.
198
5
    pub fn clear(&mut self) {
199
5
        self.head = None;
200
5
        self.tail.clear();
201
5
    }
202

            
203
    /// Every queued edit, oldest first.
204
201
    pub fn iter(&self) -> impl Iterator<Item = &QueuedTextEdit> {
205
201
        self.head.iter().chain(self.tail.iter())
206
201
    }
207

            
208
    /// Number of queued edits.
209
    #[must_use]
210
11
    pub fn len(&self) -> usize {
211
11
        usize::from(self.head.is_some()) + self.tail.len()
212
11
    }
213

            
214
    /// Whether nothing is queued.
215
    #[must_use]
216
5
    pub const fn is_empty(&self) -> bool {
217
5
        self.head.is_none()
218
5
    }
219

            
220
    /// Rewrite every entry with `f`, dropping the entries for which it returns
221
    /// `false`. Order is preserved and the head/tail invariant is restored.
222
459
    pub fn retain_mut<F: FnMut(&mut QueuedTextEdit) -> bool>(&mut self, mut f: F) {
223
459
        let mut kept: Vec<QueuedTextEdit> = self
224
459
            .head
225
459
            .take()
226
459
            .into_iter()
227
459
            .chain(core::mem::take(&mut self.tail))
228
462
            .filter_map(|mut e| f(&mut e).then_some(e))
229
459
            .collect();
230
459
        if kept.is_empty() {
231
451
            return;
232
8
        }
233
8
        self.tail = kept.split_off(1);
234
8
        self.head = kept.pop();
235
459
    }
236
}
237

            
238
impl<'a> IntoIterator for &'a PendingTextEditQueue {
239
    type Item = &'a QueuedTextEdit;
240
    type IntoIter = core::iter::Chain<
241
        core::option::Iter<'a, QueuedTextEdit>,
242
        core::slice::Iter<'a, QueuedTextEdit>,
243
    >;
244

            
245
    fn into_iter(self) -> Self::IntoIter {
246
        self.head.iter().chain(self.tail.iter())
247
    }
248
}
249

            
250
/// Text Input Manager
251
///
252
/// Centralizes all text editing logic. This is the single source of truth
253
/// for text input state.
254
#[derive(Debug)]
255
pub struct TextInputManager {
256
    /// Text changesets that have been recorded but not applied yet, oldest
257
    /// first.
258
    ///
259
    /// This is a QUEUE, not a slot: the record phase runs per OS text event
260
    /// while the apply phase runs per event pass, so two keystrokes arriving
261
    /// inside one pass both have to survive. A single slot silently dropped
262
    /// the older one.
263
    pub pending_changesets: PendingTextEditQueue,
264
}
265

            
266
impl TextInputManager {
267
    /// Create a new `TextInputManager`
268
    #[must_use]
269
7625
    pub const fn new() -> Self {
270
7625
        Self {
271
7625
            pending_changesets: PendingTextEditQueue::new(),
272
7625
        }
273
7625
    }
274

            
275
    /// Record a text input event (Phase 1)
276
    ///
277
    /// This ONLY records what text was inserted. It does NOT apply the changes yet.
278
    /// The changes are applied later in `apply_changeset()` if preventDefault is not set.
279
    ///
280
    /// Appends to the queue — recording twice before one apply keeps BOTH
281
    /// edits, in the order they arrived, each with its own source.
282
    ///
283
    /// # Arguments
284
    ///
285
    /// - `node` - The DOM node being edited
286
    /// - `inserted_text` - The text being inserted
287
    /// - `old_text` - The current text before the edit
288
    /// - `source` - Where the input came from (keyboard, IME, A11y, etc.)
289
    ///
290
    /// Returns the affected node for event generation.
291
72
    pub fn record_input(
292
72
        &mut self,
293
72
        node: DomNodeId,
294
72
        inserted_text: String,
295
72
        old_text: String,
296
72
        source: TextInputSource,
297
72
    ) -> DomNodeId {
298
72
        self.record_input_for_seat(
299
            azul_core::window::PRIMARY_POINTER_SEAT,
300
72
            node,
301
72
            inserted_text,
302
72
            old_text,
303
72
            source,
304
        )
305
72
    }
306

            
307
    /// `record_input` for the text seat `seat_id` typed (9b-ii-a-i-d-ii).
308
2922
    pub fn record_input_for_seat(
309
2922
        &mut self,
310
2922
        seat_id: u64,
311
2922
        node: DomNodeId,
312
2922
        inserted_text: String,
313
2922
        old_text: String,
314
2922
        source: TextInputSource,
315
2922
    ) -> DomNodeId {
316
2922
        self.pending_changesets.push(QueuedTextEdit {
317
2922
            seat_id,
318
2922
            edit: PendingTextEdit {
319
2922
                node,
320
2922
                inserted_text: inserted_text.into(),
321
2922
                old_text: old_text.into(),
322
2922
            },
323
2922
            source,
324
2922
        });
325

            
326
2922
        node
327
2922
    }
328

            
329
    /// Get the changeset the next apply pass will consume — the OLDEST queued
330
    /// one, so applying in this order matches the order the edits were typed.
331
    ///
332
    /// Callers that want the most recent edit instead want
333
    /// [`Self::get_newest_changeset`]; callers that want all of them iterate
334
    /// `pending_changesets`.
335
    #[must_use]
336
2045
    pub const fn get_pending_changeset(&self) -> Option<&PendingTextEdit> {
337
2045
        match self.pending_changesets.front() {
338
2029
            Some(q) => Some(&q.edit),
339
16
            None => None,
340
        }
341
2045
    }
342

            
343
    /// The source of the changeset [`Self::get_pending_changeset`] returns.
344
    #[must_use]
345
15
    pub const fn get_pending_source(&self) -> Option<TextInputSource> {
346
15
        match self.pending_changesets.front() {
347
7
            Some(q) => Some(q.source),
348
8
            None => None,
349
        }
350
15
    }
351

            
352
    /// The MOST RECENTLY recorded changeset — for callers that report "what was
353
    /// just typed" rather than "what is applied next".
354
    #[must_use]
355
20
    pub fn get_newest_changeset(&self) -> Option<&PendingTextEdit> {
356
20
        self.pending_changesets.back().map(|q| &q.edit)
357
20
    }
358

            
359
    /// The source of the changeset [`Self::get_newest_changeset`] returns.
360
    #[must_use]
361
1
    pub fn get_newest_source(&self) -> Option<TextInputSource> {
362
1
        self.pending_changesets.back().map(|q| q.source)
363
1
    }
364

            
365
    /// Remove and return the oldest queued edit — the apply phase's cursor
366
    /// through the queue. Applying one edit must NOT discard the rest.
367
5781
    pub fn take_next_changeset(&mut self) -> Option<QueuedTextEdit> {
368
5781
        self.pending_changesets.pop_front()
369
5781
    }
370

            
371
    /// Replace the changeset currently at the front of the queue (the one about
372
    /// to be applied), keeping its source. With an empty queue this records a
373
    /// new `Programmatic` entry.
374
    ///
375
    /// This is what `CallbackInfo::set_text_changeset` rewrites: a callback
376
    /// overriding "the text that is about to be inserted" means the in-flight
377
    /// edit, not the whole queue.
378
72
    pub fn set_changeset(&mut self, changeset: PendingTextEdit) {
379
72
        if let Some(front) = self.pending_changesets.front_mut() {
380
1
            front.edit = changeset;
381
71
        } else {
382
71
            self.pending_changesets.push(QueuedTextEdit {
383
71
                seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
384
71
                edit: changeset,
385
71
                source: TextInputSource::Programmatic,
386
71
            });
387
71
        }
388
72
    }
389

            
390
    /// Drop EVERY pending changeset.
391
    ///
392
    /// This is called when preventDefault vetoes the input, when focus moves
393
    /// away, and after the apply phase has drained the queue. A veto kills the
394
    /// whole batch — leaving later entries queued would land them a pass later,
395
    /// which is exactly what the veto forbade.
396
5
    pub fn clear_changeset(&mut self) {
397
5
        self.pending_changesets.clear();
398
5
    }
399
}
400

            
401
impl Default for TextInputManager {
402
1
    fn default() -> Self {
403
1
        Self::new()
404
1
    }
405
}
406

            
407
/// The `EventSource` an edit recorded from `source` is dispatched with.
408
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
409
                                  // (or cross-type bindings that can't merge)
410
33
const fn event_source_of(source: TextInputSource) -> CoreEventSource {
411
33
    match source {
412
28
        TextInputSource::Keyboard | TextInputSource::Ime => CoreEventSource::User,
413
        // A11y is still user input
414
2
        TextInputSource::Accessibility => CoreEventSource::User,
415
3
        TextInputSource::Programmatic => CoreEventSource::Programmatic,
416
    }
417
33
}
418

            
419
impl EventProvider for TextInputManager {
420
    /// Get pending text input events: one Input event per QUEUED changeset, in
421
    /// the order they were recorded.
422
    ///
423
    /// The event data includes the old text and inserted text so callbacks can
424
    /// query the changeset. Each event is labelled with the source of ITS OWN
425
    /// edit, so a keyboard edit and an accessibility edit queued in the same
426
    /// pass keep their own `EventSource`.
427
172
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent> {
428
172
        self.pending_changesets
429
172
            .iter()
430
176
            .map(|queued| {
431
                // Generate Input event (fires on every keystroke).
432
                // Carry the edit details on the event itself (inserted/old text) so
433
                // callbacks read them straight off the event — like other event
434
                // types — without having to query `get_pending_changeset()`. The
435
                // edited node is available via `SyntheticEvent.target`.
436
                //
437
                // Note: We don't generate Change events here - those are generated
438
                // when focus is lost or Enter is pressed (handled elsewhere)
439
33
                SyntheticEvent::new(
440
33
                    EventType::Input,
441
33
                    event_source_of(queued.source),
442
33
                    queued.edit.node,
443
33
                    timestamp.clone(),
444
33
                    EventData::TextInput(TextInputEventData {
445
33
                        inserted_text: queued.edit.inserted_text.as_str().to_string(),
446
33
                        old_text: queued.edit.old_text.as_str().to_string(),
447
33
                    }),
448
                )
449
33
            })
450
172
            .collect()
451
172
    }
452
}
453

            
454
impl crate::managers::NodeIdRemap for TextInputManager {
455
    /// Remap every pending (recorded, not-yet-applied) text edit.
456
    ///
457
    /// An entry whose target node was unmounted between "record" and "apply" is
458
    /// dropped — applying it would insert the text into whichever node inherited
459
    /// the index — while the entries around it keep their place in the queue.
460
459
    fn remap_node_ids(&mut self, dom: azul_core::dom::DomId, map: &crate::managers::NodeIdMap) {
461
462
        self.pending_changesets.retain_mut(|queued| {
462
16
            match map.resolve_dom_node_id(dom, queued.edit.node) {
463
9
                Some(new_id) => {
464
9
                    queued.edit.node = new_id;
465
9
                    true
466
                }
467
7
                None => false,
468
            }
469
16
        });
470
459
    }
471
}
472

            
473
#[cfg(test)]
474
mod autotest_generated {
475
    use azul_core::{
476
        dom::{DomId, DomNodeId, NodeId},
477
        styled_dom::NodeHierarchyItemId,
478
        task::SystemTick,
479
    };
480

            
481
    use super::*;
482
    use crate::managers::{NodeIdMap, NodeIdRemap};
483

            
484
    /// A `DomNodeId` for `(dom, node_index)` using the safe 1-based encoder.
485
    fn dom_node(dom: usize, index: usize) -> DomNodeId {
486
        DomNodeId {
487
            dom: DomId { inner: dom },
488
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(index))),
489
        }
490
    }
491

            
492
    fn ts() -> Instant {
493
        Instant::Tick(SystemTick::new(0))
494
    }
495

            
496
    fn edit(old: &str, inserted: &str) -> PendingTextEdit {
497
        PendingTextEdit {
498
            node: dom_node(0, 0),
499
            inserted_text: inserted.to_string().into(),
500
            old_text: old.to_string().into(),
501
        }
502
    }
503

            
504
    /// Strings chosen to break naive byte/char slicing: combining marks, ZWJ
505
    /// sequences, regional-indicator flags, bidi overrides, NUL and control
506
    /// bytes, lone replacement chars.
507
    fn adversarial_strings() -> Vec<String> {
508
        vec![
509
            String::new(),
510
            "a".to_string(),
511
            "héllo".to_string(),
512
            "e\u{0301}\u{0300}\u{0327}".to_string(),
513
            "👨‍👩‍👧‍👦".to_string(),
514
            "🇩🇪🇫🇷".to_string(),
515
            "مرحبا بالعالم".to_string(),
516
            "\u{202E}override\u{202C}".to_string(),
517
            "\0nul\0inside\0".to_string(),
518
            "\r\n\t\u{0b}\u{0c}".to_string(),
519
            "\u{FFFD}\u{FEFF}".to_string(),
520
            "𝕥𝕖𝕩𝕥".to_string(),
521
            "a".repeat(1024),
522
        ]
523
    }
524

            
525
    fn text_input_data(ev: &SyntheticEvent) -> &TextInputEventData {
526
        match &ev.data {
527
            EventData::TextInput(d) => d,
528
            other => panic!("expected EventData::TextInput, got {other:?}"),
529
        }
530
    }
531

            
532
    // ---------------------------------------------------------------------
533
    // PendingTextEdit::resulting_text  (getter / round-trip)
534
    // ---------------------------------------------------------------------
535

            
536
    #[test]
537
    fn resulting_text_basic_append() {
538
        assert_eq!(
539
            edit("Hello", " World").resulting_text().as_str(),
540
            "Hello World"
541
        );
542
    }
543

            
544
    #[test]
545
    fn resulting_text_empty_instance_is_empty() {
546
        assert_eq!(edit("", "").resulting_text().as_str(), "");
547
    }
548

            
549
    #[test]
550
    fn resulting_text_pure_deletion_keeps_old_text() {
551
        // A pure deletion records an empty `inserted_text`; the preview must be
552
        // the untouched old text, not an empty string.
553
        assert_eq!(edit("abc", "").resulting_text().as_str(), "abc");
554
    }
555

            
556
    #[test]
557
    fn resulting_text_is_exact_byte_concatenation_for_unicode() {
558
        for old in adversarial_strings() {
559
            for inserted in adversarial_strings() {
560
                let result = edit(&old, &inserted).resulting_text();
561
                let expected = format!("{old}{inserted}");
562
                assert_eq!(
563
                    result.as_str(),
564
                    expected.as_str(),
565
                    "concat mismatch for old={old:?} inserted={inserted:?}"
566
                );
567
                assert_eq!(
568
                    result.as_str().len(),
569
                    old.len() + inserted.len(),
570
                    "byte length must be additive (no normalization / no truncation)"
571
                );
572
            }
573
        }
574
    }
575

            
576
    #[test]
577
    fn resulting_text_preserves_interior_nul_bytes() {
578
        // AzString is length-prefixed, not NUL-terminated: an embedded NUL must
579
        // survive the String -> AzString -> &str round-trip untruncated.
580
        let result = edit("a\0b", "c\0d").resulting_text();
581
        assert_eq!(result.as_str(), "a\0bc\0d");
582
        assert_eq!(result.as_str().len(), 6);
583
        assert_eq!(result.as_str().matches('\0').count(), 2);
584
    }
585

            
586
    #[test]
587
    fn resulting_text_round_trips_every_adversarial_string() {
588
        // encode == decode: String -> AzString -> &str must be the identity.
589
        for s in adversarial_strings() {
590
            assert_eq!(edit(&s, "").resulting_text().as_str(), s.as_str());
591
            assert_eq!(edit("", &s).resulting_text().as_str(), s.as_str());
592
        }
593
    }
594

            
595
    #[test]
596
    fn resulting_text_huge_strings_do_not_panic_or_truncate() {
597
        let old = "a".repeat(300_000);
598
        let inserted = "b".repeat(200_000);
599
        let result = edit(&old, &inserted).resulting_text();
600
        assert_eq!(result.as_str().len(), 500_000);
601
        assert!(result.as_str().starts_with("aaaa"));
602
        assert!(result.as_str().ends_with("bbbb"));
603
    }
604

            
605
    #[test]
606
    fn resulting_text_is_pure_and_repeatable() {
607
        let e = edit("old", "new");
608
        let first = e.resulting_text();
609
        let second = e.resulting_text();
610
        assert_eq!(first.as_str(), second.as_str());
611
        // The receiver must be untouched by the preview.
612
        assert_eq!(e.old_text.as_str(), "old");
613
        assert_eq!(e.inserted_text.as_str(), "new");
614
    }
615

            
616
    // ---------------------------------------------------------------------
617
    // OptionPendingTextEdit::into_option  (round-trip)
618
    // ---------------------------------------------------------------------
619

            
620
    #[test]
621
    fn option_pending_text_edit_none_round_trip() {
622
        assert!(OptionPendingTextEdit::None.into_option().is_none());
623
        // Both `From<Option<T>>` and `From<Option<&T>>` exist — pin the owned one.
624
        assert!(OptionPendingTextEdit::from(None::<PendingTextEdit>)
625
            .into_option()
626
            .is_none());
627
        assert!(OptionPendingTextEdit::from(None::<&PendingTextEdit>)
628
            .into_option()
629
            .is_none());
630
    }
631

            
632
    #[test]
633
    fn option_pending_text_edit_some_round_trip_preserves_fields() {
634
        for s in adversarial_strings() {
635
            let original = PendingTextEdit {
636
                node: dom_node(7, 13),
637
                inserted_text: s.clone().into(),
638
                old_text: s.clone().into(),
639
            };
640
            let recovered = OptionPendingTextEdit::from(Some(original.clone()))
641
                .into_option()
642
                .expect("Some must round-trip to Some");
643
            assert_eq!(recovered.node, original.node);
644
            assert_eq!(recovered.inserted_text.as_str(), s.as_str());
645
            assert_eq!(recovered.old_text.as_str(), s.as_str());
646
        }
647
    }
648

            
649
    #[test]
650
    fn option_pending_text_edit_from_ref_deep_clones() {
651
        let original = edit("old", "ins");
652
        let cloned = OptionPendingTextEdit::from(Some(&original))
653
            .into_option()
654
            .expect("Some(&T) must map to Some");
655
        // Deep clone: the borrow is over, and both sides still hold their text.
656
        assert_eq!(cloned.old_text.as_str(), "old");
657
        assert_eq!(cloned.inserted_text.as_str(), "ins");
658
        assert_eq!(original.old_text.as_str(), "old");
659
    }
660

            
661
    // ---------------------------------------------------------------------
662
    // TextInputManager::new  (constructor invariants)
663
    // ---------------------------------------------------------------------
664

            
665
    #[test]
666
    fn new_starts_with_no_pending_state() {
667
        let m = TextInputManager::new();
668
        assert!(m.pending_changesets.is_empty());
669
        assert_eq!(m.pending_changesets.len(), 0);
670
        assert!(m.get_pending_changeset().is_none());
671
        assert!(m.get_pending_source().is_none());
672
        assert!(m.get_newest_changeset().is_none());
673
        assert!(m.get_pending_events(ts()).is_empty());
674
    }
675

            
676
    #[test]
677
    fn default_matches_new() {
678
        let d = TextInputManager::default();
679
        assert!(d.pending_changesets.is_empty());
680
        assert!(d.get_pending_source().is_none());
681
    }
682

            
683
    // ---------------------------------------------------------------------
684
    // TextInputManager::record_input / get_pending_changeset / clear_changeset
685
    // ---------------------------------------------------------------------
686

            
687
    #[test]
688
    fn record_input_returns_the_node_it_was_given_and_stores_it() {
689
        let mut m = TextInputManager::new();
690
        let node = dom_node(3, 42);
691
        let returned = m.record_input(
692
            node,
693
            "abc".to_string(),
694
            "xyz".to_string(),
695
            TextInputSource::Keyboard,
696
        );
697
        assert_eq!(returned, node);
698

            
699
        let pending = m
700
            .get_pending_changeset()
701
            .expect("changeset must be recorded");
702
        assert_eq!(pending.node, node);
703
        assert_eq!(pending.inserted_text.as_str(), "abc");
704
        assert_eq!(pending.old_text.as_str(), "xyz");
705
        assert_eq!(m.get_pending_source(), Some(TextInputSource::Keyboard));
706
    }
707

            
708
    #[test]
709
    fn record_input_survives_empty_unicode_and_huge_payloads() {
710
        let mut m = TextInputManager::new();
711
        for s in adversarial_strings() {
712
            let returned =
713
                m.record_input(dom_node(0, 0), s.clone(), s.clone(), TextInputSource::Ime);
714
            assert_eq!(returned, dom_node(0, 0));
715
            let pending = m.get_newest_changeset().expect("recorded");
716
            assert_eq!(pending.inserted_text.as_str(), s.as_str());
717
            assert_eq!(pending.old_text.as_str(), s.as_str());
718
        }
719
        assert_eq!(m.pending_changesets.len(), adversarial_strings().len());
720

            
721
        let huge = "z".repeat(1_000_000);
722
        m.record_input(
723
            dom_node(0, 0),
724
            huge.clone(),
725
            String::new(),
726
            TextInputSource::Programmatic,
727
        );
728
        assert_eq!(
729
            m.get_newest_changeset()
730
                .expect("recorded")
731
                .inserted_text
732
                .as_str()
733
                .len(),
734
            1_000_000
735
        );
736
    }
737

            
738
    #[test]
739
    fn record_input_accepts_extreme_node_ids() {
740
        let mut m = TextInputManager::new();
741

            
742
        // usize::MAX DomId + the sentinel "no node" hierarchy id (DomNodeId::ROOT's).
743
        let none_node = DomNodeId {
744
            dom: DomId { inner: usize::MAX },
745
            node: NodeHierarchyItemId::NONE,
746
        };
747
        assert_eq!(
748
            m.record_input(none_node, "a".into(), "b".into(), TextInputSource::Keyboard),
749
            none_node
750
        );
751
        assert_eq!(m.get_pending_changeset().expect("recorded").node, none_node);
752

            
753
        // The largest representable (1-based encoded) node index.
754
        let max_node = DomNodeId {
755
            dom: DomId::ROOT_ID,
756
            node: NodeHierarchyItemId::from_raw(usize::MAX),
757
        };
758
        assert_eq!(
759
            m.record_input(max_node, "a".into(), "b".into(), TextInputSource::Keyboard),
760
            max_node
761
        );
762
        assert_eq!(m.get_newest_changeset().expect("recorded").node, max_node);
763

            
764
        assert_eq!(DomNodeId::ROOT.node.into_crate_internal(), None);
765
    }
766

            
767
    // ---------------------------------------------------------------------
768
    // The QUEUE contract (replaces the deleted last-write-wins debt marker)
769
    // ---------------------------------------------------------------------
770

            
771
    #[test]
772
    fn record_input_queues_and_keeps_every_edit_in_order() {
773
        let mut m = TextInputManager::new();
774
        m.record_input(
775
            dom_node(0, 1),
776
            "first".into(),
777
            "old1".into(),
778
            TextInputSource::Keyboard,
779
        );
780
        m.record_input(
781
            dom_node(0, 1),
782
            "second".into(),
783
            "old2".into(),
784
            TextInputSource::Keyboard,
785
        );
786
        m.record_input(
787
            dom_node(0, 1),
788
            "third".into(),
789
            "old3".into(),
790
            TextInputSource::Keyboard,
791
        );
792

            
793
        assert_eq!(m.pending_changesets.len(), 3);
794
        let inserted: Vec<&str> = m
795
            .pending_changesets
796
            .iter()
797
            .map(|q| q.edit.inserted_text.as_str())
798
            .collect();
799
        assert_eq!(inserted, ["first", "second", "third"]);
800

            
801
        // The front is the OLDEST — applying front-first replays the typing order.
802
        assert_eq!(
803
            m.get_pending_changeset()
804
                .expect("front")
805
                .inserted_text
806
                .as_str(),
807
            "first"
808
        );
809
        assert_eq!(
810
            m.get_newest_changeset()
811
                .expect("back")
812
                .inserted_text
813
                .as_str(),
814
            "third"
815
        );
816
    }
817

            
818
    #[test]
819
    fn take_next_changeset_drains_oldest_first_without_dropping_the_rest() {
820
        let mut m = TextInputManager::new();
821
        for s in ["a", "b", "c"] {
822
            m.record_input(
823
                dom_node(0, 1),
824
                s.into(),
825
                String::new(),
826
                TextInputSource::Keyboard,
827
            );
828
        }
829

            
830
        let mut drained = Vec::new();
831
        while let Some(q) = m.take_next_changeset() {
832
            drained.push(q.edit.inserted_text.as_str().to_string());
833
        }
834
        assert_eq!(drained, ["a", "b", "c"]);
835
        assert!(m.pending_changesets.is_empty());
836
        assert!(m.get_pending_changeset().is_none());
837
    }
838

            
839
    #[test]
840
    fn get_pending_events_emits_one_event_per_queued_edit_in_order() {
841
        let mut m = TextInputManager::new();
842
        m.record_input(
843
            dom_node(0, 1),
844
            "a".into(),
845
            "old-a".into(),
846
            TextInputSource::Keyboard,
847
        );
848
        m.record_input(
849
            dom_node(0, 1),
850
            "b".into(),
851
            "old-b".into(),
852
            TextInputSource::Keyboard,
853
        );
854
        m.record_input(
855
            dom_node(0, 1),
856
            "c".into(),
857
            "old-c".into(),
858
            TextInputSource::Keyboard,
859
        );
860

            
861
        let events = m.get_pending_events(ts());
862
        assert_eq!(events.len(), 3, "one Input event per queued edit");
863
        let inserted: Vec<&str> = events
864
            .iter()
865
            .map(|e| text_input_data(e).inserted_text.as_str())
866
            .collect();
867
        assert_eq!(inserted, ["a", "b", "c"]);
868
        let old: Vec<&str> = events
869
            .iter()
870
            .map(|e| text_input_data(e).old_text.as_str())
871
            .collect();
872
        assert_eq!(old, ["old-a", "old-b", "old-c"]);
873
    }
874

            
875
    #[test]
876
    fn a_batch_can_hold_edits_for_several_different_nodes() {
877
        let mut m = TextInputManager::new();
878
        m.record_input(
879
            dom_node(0, 1),
880
            "x".into(),
881
            String::new(),
882
            TextInputSource::Keyboard,
883
        );
884
        m.record_input(
885
            dom_node(1, 2),
886
            "y".into(),
887
            String::new(),
888
            TextInputSource::Keyboard,
889
        );
890
        m.record_input(
891
            dom_node(0, 3),
892
            "z".into(),
893
            String::new(),
894
            TextInputSource::Keyboard,
895
        );
896

            
897
        let targets: Vec<DomNodeId> = m
898
            .get_pending_events(ts())
899
            .iter()
900
            .map(|e| e.target)
901
            .collect();
902
        assert_eq!(targets, [dom_node(0, 1), dom_node(1, 2), dom_node(0, 3)]);
903
    }
904

            
905
    #[test]
906
    fn each_queued_edit_carries_its_own_source() {
907
        // The whole reason the source is per entry: a keyboard edit and an
908
        // accessibility edit can be queued together, and a manager-wide
909
        // "current source" would relabel the older one.
910
        let mut m = TextInputManager::new();
911
        m.record_input(
912
            dom_node(0, 1),
913
            "k".into(),
914
            String::new(),
915
            TextInputSource::Keyboard,
916
        );
917
        m.record_input(
918
            dom_node(0, 2),
919
            "p".into(),
920
            String::new(),
921
            TextInputSource::Programmatic,
922
        );
923
        m.record_input(
924
            dom_node(0, 3),
925
            "a".into(),
926
            String::new(),
927
            TextInputSource::Accessibility,
928
        );
929

            
930
        let sources: Vec<TextInputSource> = m.pending_changesets.iter().map(|q| q.source).collect();
931
        assert_eq!(
932
            sources,
933
            [
934
                TextInputSource::Keyboard,
935
                TextInputSource::Programmatic,
936
                TextInputSource::Accessibility
937
            ]
938
        );
939

            
940
        let event_sources: Vec<CoreEventSource> = m
941
            .get_pending_events(ts())
942
            .iter()
943
            .map(|e| e.source)
944
            .collect();
945
        assert_eq!(
946
            event_sources,
947
            [
948
                CoreEventSource::User,
949
                CoreEventSource::Programmatic,
950
                CoreEventSource::User
951
            ],
952
            "the Programmatic edit must not drag the keyboard edit's label with it"
953
        );
954

            
955
        assert_eq!(m.get_pending_source(), Some(TextInputSource::Keyboard));
956
        assert_eq!(m.get_newest_source(), Some(TextInputSource::Accessibility));
957
    }
958

            
959
    #[test]
960
    fn set_changeset_rewrites_only_the_in_flight_edit() {
961
        let mut m = TextInputManager::new();
962
        m.record_input(
963
            dom_node(0, 1),
964
            "a".into(),
965
            "old-a".into(),
966
            TextInputSource::Keyboard,
967
        );
968
        m.record_input(
969
            dom_node(0, 2),
970
            "b".into(),
971
            "old-b".into(),
972
            TextInputSource::Ime,
973
        );
974

            
975
        m.set_changeset(PendingTextEdit {
976
            node: dom_node(0, 1),
977
            inserted_text: "A".to_string().into(),
978
            old_text: "old-a".to_string().into(),
979
        });
980

            
981
        assert_eq!(m.pending_changesets.len(), 2, "the queued sibling survives");
982
        assert_eq!(
983
            m.get_pending_changeset()
984
                .expect("front")
985
                .inserted_text
986
                .as_str(),
987
            "A"
988
        );
989
        assert_eq!(
990
            m.get_pending_source(),
991
            Some(TextInputSource::Keyboard),
992
            "overriding the text must not relabel where it came from"
993
        );
994
        assert_eq!(
995
            m.get_newest_changeset()
996
                .expect("back")
997
                .inserted_text
998
                .as_str(),
999
            "b"
        );
    }
    #[test]
    fn set_changeset_on_an_empty_queue_records_a_programmatic_edit() {
        let mut m = TextInputManager::new();
        m.set_changeset(PendingTextEdit {
            node: dom_node(0, 4),
            inserted_text: "p".to_string().into(),
            old_text: String::new().into(),
        });
        assert_eq!(m.pending_changesets.len(), 1);
        assert_eq!(m.get_pending_source(), Some(TextInputSource::Programmatic));
        assert_eq!(
            m.get_pending_events(ts())[0].source,
            CoreEventSource::Programmatic
        );
    }
    #[test]
    fn clear_changeset_is_idempotent_on_a_fresh_manager() {
        let mut m = TextInputManager::new();
        m.clear_changeset();
        m.clear_changeset();
        m.clear_changeset();
        assert!(m.get_pending_changeset().is_none());
        assert!(m.get_pending_source().is_none());
    }
    #[test]
    fn clear_changeset_empties_the_whole_queue() {
        let mut m = TextInputManager::new();
        m.record_input(
            dom_node(0, 5),
            "x".into(),
            "y".into(),
            TextInputSource::Programmatic,
        );
        m.record_input(
            dom_node(0, 6),
            "x2".into(),
            "y2".into(),
            TextInputSource::Keyboard,
        );
        m.record_input(
            dom_node(1, 7),
            "x3".into(),
            "y3".into(),
            TextInputSource::Ime,
        );
        assert_eq!(m.pending_changesets.len(), 3);
        // A preventDefault veto kills the whole batch: an entry left behind
        // would land a pass later, which is what the veto forbade.
        m.clear_changeset();
        assert!(m.pending_changesets.is_empty());
        assert_eq!(m.pending_changesets.len(), 0);
        assert!(m.get_pending_changeset().is_none());
        // A stale source would mislabel the NEXT event's EventSource.
        assert!(m.get_pending_source().is_none());
        assert!(m.get_newest_changeset().is_none());
        assert!(m.get_pending_events(ts()).is_empty());
        // Clearing twice must stay clean, not resurrect anything.
        m.clear_changeset();
        assert!(m.get_pending_changeset().is_none());
        // ...and the queue is still usable afterwards.
        m.record_input(
            dom_node(0, 8),
            "after".into(),
            String::new(),
            TextInputSource::Keyboard,
        );
        assert_eq!(m.pending_changesets.len(), 1);
        assert_eq!(
            m.get_pending_changeset().expect("front").node,
            dom_node(0, 8)
        );
    }
    // ---------------------------------------------------------------------
    // EventProvider::get_pending_events  (invariants)
    // ---------------------------------------------------------------------
    #[test]
    fn no_events_without_a_pending_changeset() {
        assert!(TextInputManager::new().get_pending_events(ts()).is_empty());
    }
    #[test]
    fn pending_event_carries_text_verbatim() {
        for s in adversarial_strings() {
            let mut m = TextInputManager::new();
            m.record_input(
                dom_node(2, 9),
                s.clone(),
                format!("old-{s}"),
                TextInputSource::Keyboard,
            );
            let events = m.get_pending_events(ts());
            assert_eq!(events.len(), 1, "exactly one Input event per changeset");
            assert_eq!(events[0].event_type, EventType::Input);
            assert_eq!(events[0].target, dom_node(2, 9));
            let data = text_input_data(&events[0]);
            assert_eq!(data.inserted_text, s);
            assert_eq!(data.old_text, format!("old-{s}"));
        }
    }
    #[test]
    fn event_source_mapping_is_stable_for_every_input_source() {
        let cases = [
            (TextInputSource::Keyboard, CoreEventSource::User),
            (TextInputSource::Ime, CoreEventSource::User),
            (TextInputSource::Accessibility, CoreEventSource::User),
            (TextInputSource::Programmatic, CoreEventSource::Programmatic),
        ];
        for (input_source, expected) in cases {
            let mut m = TextInputManager::new();
            m.record_input(dom_node(0, 0), "a".into(), String::new(), input_source);
            let events = m.get_pending_events(ts());
            assert_eq!(events.len(), 1);
            assert_eq!(
                events[0].source, expected,
                "{input_source:?} must map to {expected:?}"
            );
        }
    }
    #[test]
    fn a_queued_edit_always_has_a_source() {
        // A changeset without a source used to be representable (two public
        // fields that could disagree) and had to fall back to `User`. The
        // source now travels WITH the edit, so the torn state is gone: even
        // hand-building the queue entry demands one.
        let mut m = TextInputManager::new();
        m.pending_changesets.push(QueuedTextEdit {
            seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
            edit: edit("old", "ins"),
            source: TextInputSource::Keyboard,
        });
        let events = m.get_pending_events(ts());
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].source, CoreEventSource::User);
        assert_eq!(text_input_data(&events[0]).inserted_text, "ins");
        assert_eq!(m.get_pending_source(), Some(TextInputSource::Keyboard));
    }
    #[test]
    fn get_pending_events_does_not_consume_the_changeset() {
        let mut m = TextInputManager::new();
        m.record_input(
            dom_node(0, 4),
            "a".into(),
            "b".into(),
            TextInputSource::Keyboard,
        );
        m.record_input(
            dom_node(0, 4),
            "c".into(),
            "d".into(),
            TextInputSource::Keyboard,
        );
        assert_eq!(m.get_pending_events(ts()).len(), 2);
        // Reading events is a pure query — only clear_changeset()/
        // take_next_changeset() drain it.
        assert_eq!(m.get_pending_events(ts()).len(), 2);
        assert_eq!(m.pending_changesets.len(), 2);
    }
    // ---------------------------------------------------------------------
    // NodeIdRemap  (stale-NodeId invariants)
    // ---------------------------------------------------------------------
    #[test]
    fn remap_rewrites_a_surviving_node() {
        let mut m = TextInputManager::new();
        m.record_input(
            dom_node(0, 3),
            "a".into(),
            "b".into(),
            TextInputSource::Keyboard,
        );
        let map = NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(1))]);
        m.remap_node_ids(DomId::ROOT_ID, &map);
        let pending = m.get_pending_changeset().expect("mapped node must survive");
        assert_eq!(pending.node, dom_node(0, 1));
        assert_eq!(pending.inserted_text.as_str(), "a");
        assert_eq!(m.get_pending_source(), Some(TextInputSource::Keyboard));
    }
    #[test]
    fn remap_drops_changeset_and_source_when_the_node_is_unmounted() {
        let mut m = TextInputManager::new();
        m.record_input(dom_node(0, 3), "a".into(), "b".into(), TextInputSource::Ime);
        // Node 3 is absent from the map => it was unmounted. Applying the edit
        // would write into whichever node inherited index 3.
        let map = NodeIdMap::from_pairs([(NodeId::new(4), NodeId::new(3))]);
        m.remap_node_ids(DomId::ROOT_ID, &map);
        assert!(m.get_pending_changeset().is_none());
        assert!(
            m.get_pending_source().is_none(),
            "source must be dropped with the changeset"
        );
        assert!(m.get_pending_events(ts()).is_empty());
    }
    #[test]
    fn remap_drops_only_the_unmounted_entries_of_a_queue() {
        let mut m = TextInputManager::new();
        m.record_input(
            dom_node(0, 1),
            "keep1".into(),
            String::new(),
            TextInputSource::Keyboard,
        );
        m.record_input(
            dom_node(0, 2),
            "gone".into(),
            String::new(),
            TextInputSource::Ime,
        );
        m.record_input(
            dom_node(0, 3),
            "keep2".into(),
            String::new(),
            TextInputSource::Accessibility,
        );
        // Node 2 is unmounted; 1 and 3 shift down by one.
        let map = NodeIdMap::from_pairs([
            (NodeId::new(1), NodeId::new(1)),
            (NodeId::new(3), NodeId::new(2)),
        ]);
        m.remap_node_ids(DomId::ROOT_ID, &map);
        assert_eq!(m.pending_changesets.len(), 2);
        let survivors: Vec<(&str, DomNodeId, TextInputSource)> = m
            .pending_changesets
            .iter()
            .map(|q| (q.edit.inserted_text.as_str(), q.edit.node, q.source))
            .collect();
        assert_eq!(
            survivors,
            [
                ("keep1", dom_node(0, 1), TextInputSource::Keyboard),
                ("keep2", dom_node(0, 2), TextInputSource::Accessibility),
            ],
            "order, rewritten ids and per-entry sources all survive the drop"
        );
        // The head/tail split must be intact: the front is still the oldest.
        assert_eq!(
            m.get_pending_changeset()
                .expect("front")
                .inserted_text
                .as_str(),
            "keep1"
        );
        assert_eq!(
            m.get_newest_changeset()
                .expect("back")
                .inserted_text
                .as_str(),
            "keep2"
        );
    }
    #[test]
    fn remap_dropping_the_head_promotes_the_next_entry() {
        let mut m = TextInputManager::new();
        m.record_input(
            dom_node(0, 1),
            "gone".into(),
            String::new(),
            TextInputSource::Keyboard,
        );
        m.record_input(
            dom_node(0, 2),
            "survivor".into(),
            String::new(),
            TextInputSource::Ime,
        );
        let map = NodeIdMap::from_pairs([(NodeId::new(2), NodeId::new(0))]);
        m.remap_node_ids(DomId::ROOT_ID, &map);
        assert_eq!(m.pending_changesets.len(), 1);
        let front = m
            .get_pending_changeset()
            .expect("the survivor becomes the head");
        assert_eq!(front.inserted_text.as_str(), "survivor");
        assert_eq!(front.node, dom_node(0, 0));
        assert_eq!(m.get_pending_source(), Some(TextInputSource::Ime));
        assert_eq!(m.get_pending_events(ts()).len(), 1);
    }
    #[test]
    fn remap_with_an_empty_map_drops_everything() {
        let mut m = TextInputManager::new();
        m.record_input(
            dom_node(0, 0),
            "a".into(),
            "b".into(),
            TextInputSource::Keyboard,
        );
        m.record_input(
            dom_node(0, 1),
            "c".into(),
            "d".into(),
            TextInputSource::Keyboard,
        );
        let map = NodeIdMap::from_pairs(Vec::<(NodeId, NodeId)>::new());
        assert!(map.is_empty());
        m.remap_node_ids(DomId::ROOT_ID, &map);
        assert!(m.pending_changesets.is_empty());
        assert!(m.get_pending_changeset().is_none());
        assert!(m.get_pending_source().is_none());
    }
    #[test]
    fn remap_leaves_other_doms_untouched() {
        let mut m = TextInputManager::new();
        m.record_input(
            dom_node(1, 3),
            "a".into(),
            "b".into(),
            TextInputSource::Keyboard,
        );
        // Reconciliation of DOM 0 says nothing about DOM 1's node ids.
        let map = NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(9))]);
        m.remap_node_ids(DomId::ROOT_ID, &map);
        let pending = m
            .get_pending_changeset()
            .expect("other-DOM state must survive");
        assert_eq!(
            pending.node,
            dom_node(1, 3),
            "node id must NOT be rewritten"
        );
    }
    #[test]
    fn remap_drops_a_changeset_recorded_on_the_none_node_sentinel() {
        // DomNodeId::ROOT carries NodeHierarchyItemId::NONE, which decodes to
        // `None` — it is unresolvable, so the edit must be dropped rather than
        // silently retargeted.
        let mut m = TextInputManager::new();
        m.record_input(
            DomNodeId::ROOT,
            "a".into(),
            "b".into(),
            TextInputSource::Keyboard,
        );
        let map = NodeIdMap::from_pairs([(NodeId::new(0), NodeId::new(0))]);
        m.remap_node_ids(DomId::ROOT_ID, &map);
        assert!(m.get_pending_changeset().is_none());
        assert!(m.get_pending_source().is_none());
    }
    #[test]
    fn remap_handles_extreme_node_indices() {
        let mut m = TextInputManager::new();
        let huge = DomNodeId {
            dom: DomId::ROOT_ID,
            node: NodeHierarchyItemId::from_raw(usize::MAX),
        };
        m.record_input(huge, "a".into(), "b".into(), TextInputSource::Keyboard);
        // from_raw(usize::MAX) decodes to NodeId(usize::MAX - 1); remapping it
        // down to a small index must not over/underflow the 1-based encoding.
        let map = NodeIdMap::from_pairs([(NodeId::new(usize::MAX - 1), NodeId::new(2))]);
        m.remap_node_ids(DomId::ROOT_ID, &map);
        assert_eq!(
            m.get_pending_changeset().expect("mapped").node,
            dom_node(0, 2)
        );
    }
    #[test]
    fn remap_on_an_empty_manager_is_a_noop() {
        let mut m = TextInputManager::new();
        let map = NodeIdMap::from_pairs([(NodeId::new(0), NodeId::new(1))]);
        m.remap_node_ids(DomId::ROOT_ID, &map);
        assert!(m.get_pending_changeset().is_none());
        assert!(m.get_pending_source().is_none());
    }
    #[test]
    fn remap_is_idempotent_when_ids_are_stable() {
        let mut m = TextInputManager::new();
        m.record_input(
            dom_node(0, 5),
            "a".into(),
            "b".into(),
            TextInputSource::Keyboard,
        );
        let map = NodeIdMap::from_pairs([(NodeId::new(5), NodeId::new(5))]);
        m.remap_node_ids(DomId::ROOT_ID, &map);
        m.remap_node_ids(DomId::ROOT_ID, &map);
        assert_eq!(
            m.get_pending_changeset().expect("stable").node,
            dom_node(0, 5)
        );
    }
}