strata-dom 0.1.2

Core DOM, reactive signals, and synthetic event routing for Strata
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
//! High-performance reactive text input editing engine with full cursor navigation,
//! range selection, word jumping, clipboard integration, and undo/redo history.

use crate::reactive::Signal;

/// Input navigation key representation for text editing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputKey {
    Char(char),
    Left,
    Right,
    Home,
    End,
    Backspace,
    Delete,
    Enter,
    Escape,
    A,
    C,
    V,
    X,
    Z,
    Y,
    Other,
}

/// Modifier keys active during text input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct InputModifiers {
    pub shift: bool,
    pub ctrl: bool,
    pub alt: bool,
    pub meta: bool,
}

/// Result of an input key handling operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputKeyResult {
    /// No change occurred.
    Ignored,
    /// Text or cursor changed; UI repaint recommended.
    Handled,
    /// Selected text to be copied to system clipboard.
    CopyToClipboard(String),
    /// Enter was pressed (submit/commit).
    Submitted,
}

/// Reactive state model for a rich text input field.
#[derive(Clone)]
pub struct TextInputState {
    pub text: Signal<String>,
    pub cursor_index: Signal<usize>,
    pub selection_anchor: Signal<Option<usize>>,
    pub is_focused: Signal<bool>,
    pub scroll_x: std::cell::Cell<f32>,
    undo_stack: Vec<(String, usize)>,
    redo_stack: Vec<(String, usize)>,
}

impl TextInputState {
    /// Creates a new `TextInputState` initialized with default empty text.
    pub fn new() -> Self {
        Self::with_text("")
    }

    /// Creates a new `TextInputState` with initial text and cursor placed at end.
    pub fn with_text(initial: &str) -> Self {
        let text = Signal::new(initial.to_string());
        let cursor_index = Signal::new(initial.chars().count());
        let selection_anchor = Signal::new(None);
        let is_focused = Signal::new(false);

        Self {
            text,
            cursor_index,
            selection_anchor,
            is_focused,
            scroll_x: std::cell::Cell::new(0.0),
            undo_stack: Vec::new(),
            redo_stack: Vec::new(),
        }
    }

    /// Returns the active selection character range as `(start, end)` where `start <= end`.
    pub fn selection_range(&self) -> Option<(usize, usize)> {
        if let Some(anchor) = self.selection_anchor.get() {
            let cursor = self.cursor_index.get();
            if anchor != cursor {
                return Some((anchor.min(cursor), anchor.max(cursor)));
            }
        }
        None
    }

    /// Checks if there is an active non-empty text selection.
    pub fn has_selection(&self) -> bool {
        self.selection_range().is_some()
    }

    /// Returns the currently selected substring, if any.
    pub fn selected_text(&self) -> Option<String> {
        self.selection_range().map(|(start, end)| {
            let text = self.text.get();
            text.chars().skip(start).take(end - start).collect()
        })
    }

    /// Selects the entire text buffer.
    pub fn select_all(&self) {
        let total_chars = self.text.get().chars().count();
        self.selection_anchor.set(Some(0));
        self.cursor_index.set(total_chars);
    }

    /// Clears any active selection.
    pub fn clear_selection(&self) {
        self.selection_anchor.set(None);
    }

    /// Starts a mouse drag selection from a character index.
    pub fn start_selection(&self, index: usize) {
        let total = self.text.get().chars().count();
        let clamped = index.min(total);
        self.selection_anchor.set(Some(clamped));
        self.cursor_index.set(clamped);
    }

    /// Extends an active mouse drag selection to a new character index.
    pub fn update_selection_drag(&self, index: usize) {
        let total = self.text.get().chars().count();
        let clamped = index.min(total);
        if self.selection_anchor.get().is_none() {
            self.selection_anchor.set(Some(self.cursor_index.get()));
        }
        self.cursor_index.set(clamped);
    }

    /// Selects the entire word or token surrounding the given character index (double-click contract).
    pub fn select_word_at_index(&self, index: usize) {
        let cur_text = self.text.get();
        let chars: Vec<char> = cur_text.chars().collect();
        let len = chars.len();
        if len == 0 {
            return;
        }
        let clamped = index.min(len.saturating_sub(1));
        let is_word = is_word_char(chars[clamped]);

        let mut start = clamped;
        while start > 0 {
            let prev = chars[start - 1];
            if prev.is_whitespace() || (is_word != is_word_char(prev)) {
                break;
            }
            start -= 1;
        }

        let mut end = clamped;
        while end < len {
            let ch = chars[end];
            if ch.is_whitespace() || (is_word != is_word_char(ch)) {
                break;
            }
            end += 1;
        }

        self.selection_anchor.set(Some(start));
        self.cursor_index.set(end);
    }

    /// Selects the entire line surrounding the given character index (triple-click contract).
    /// The newline terminator itself is excluded from the selected range.
    pub fn select_line_at_index(&self, index: usize) {
        let cur_text = self.text.get();
        let chars: Vec<char> = cur_text.chars().collect();
        let len = chars.len();
        let clamped = index.min(len);

        let mut start = clamped;
        while start > 0 && chars[start - 1] != '\n' {
            start -= 1;
        }

        let mut end = clamped;
        while end < len && chars[end] != '\n' {
            end += 1;
        }

        self.selection_anchor.set(Some(start));
        self.cursor_index.set(end);
    }

    /// Calculates character index from an x offset in pixels.
    pub fn calculate_char_index_at_offset(text: &str, x_offset: f32, font_size: f32) -> usize {
        if x_offset <= 0.0 || text.is_empty() {
            return 0;
        }

        let char_w = font_size * 0.55;
        let approx_idx = (x_offset / char_w).round() as usize;
        approx_idx.min(text.chars().count())
    }

    /// Replaces the entire text buffer, pushing an undo snapshot so Ctrl+Z can restore it.
    pub fn replace_all_text(&mut self, new_text: &str) {
        self.push_undo_snapshot();
        self.text.set(new_text.to_string());
        self.cursor_index.set(new_text.chars().count());
        self.selection_anchor.set(None);
    }

    /// Synchronizes text from an external source without destroying undo/redo history.
    pub fn sync_external_text(&mut self, new_text: &str) {
        if self.text.get() != new_text {
            self.push_undo_snapshot();
            self.text.set(new_text.to_string());
            let count = new_text.chars().count();
            if self.cursor_index.get() > count {
                self.cursor_index.set(count);
            }
            self.selection_anchor.set(None);
        }
    }

    /// Sets the text value, resetting the cursor to the end and clearing undo stacks.
    pub fn set_text(&mut self, new_text: &str) {
        self.undo_stack.clear();
        self.redo_stack.clear();
        self.text.set(new_text.to_string());
        self.cursor_index.set(new_text.chars().count());
        self.selection_anchor.set(None);
    }

    /// Inserts text at the current cursor position, replacing any active selection.
    pub fn insert_text(&mut self, inserted: &str) {
        self.push_undo_snapshot();
        let cur_text = self.text.get();
        let chars: Vec<char> = cur_text.chars().collect();

        if let Some((start, end)) = self.selection_range() {
            let mut new_chars = Vec::with_capacity(chars.len() + inserted.len());
            new_chars.extend_from_slice(&chars[..start]);
            new_chars.extend(inserted.chars());
            new_chars.extend_from_slice(&chars[end..]);

            let new_cursor = start + inserted.chars().count();
            self.text.set(new_chars.into_iter().collect());
            self.cursor_index.set(new_cursor);
            self.selection_anchor.set(None);
        } else {
            let cursor = self.cursor_index.get().min(chars.len());
            let mut new_chars = Vec::with_capacity(chars.len() + inserted.len());
            new_chars.extend_from_slice(&chars[..cursor]);
            new_chars.extend(inserted.chars());
            new_chars.extend_from_slice(&chars[cursor..]);

            let new_cursor = cursor + inserted.chars().count();
            self.text.set(new_chars.into_iter().collect());
            self.cursor_index.set(new_cursor);
            self.selection_anchor.set(None);
        }
    }

    /// Deletes the character before the cursor, or the current selection.
    pub fn delete_backward(&mut self) {
        if self.has_selection() {
            self.delete_selection();
            return;
        }

        let cursor = self.cursor_index.get();
        if cursor == 0 {
            return;
        }

        self.push_undo_snapshot();
        let cur_text = self.text.get();
        let mut chars: Vec<char> = cur_text.chars().collect();
        if cursor <= chars.len() {
            chars.remove(cursor - 1);
            self.cursor_index.set(cursor - 1);
            self.text.set(chars.into_iter().collect());
        }
    }

    /// Deletes the character after the cursor, or the current selection.
    pub fn delete_forward(&mut self) {
        if self.has_selection() {
            self.delete_selection();
            return;
        }

        let cursor = self.cursor_index.get();
        let cur_text = self.text.get();
        let mut chars: Vec<char> = cur_text.chars().collect();
        if cursor < chars.len() {
            self.push_undo_snapshot();
            chars.remove(cursor);
            self.text.set(chars.into_iter().collect());
        }
    }

    /// Deletes the word preceding the cursor.
    pub fn delete_word_backward(&mut self) {
        if self.has_selection() {
            self.delete_selection();
            return;
        }

        let cursor = self.cursor_index.get();
        if cursor == 0 {
            return;
        }

        let cur_text = self.text.get();
        let chars: Vec<char> = cur_text.chars().collect();
        let prev_boundary = find_prev_word_boundary(&chars, cursor);

        self.push_undo_snapshot();
        let mut new_chars = Vec::with_capacity(chars.len());
        new_chars.extend_from_slice(&chars[..prev_boundary]);
        new_chars.extend_from_slice(&chars[cursor..]);

        self.cursor_index.set(prev_boundary);
        self.text.set(new_chars.into_iter().collect());
    }

    /// Deletes the word following the cursor.
    pub fn delete_word_forward(&mut self) {
        if self.has_selection() {
            self.delete_selection();
            return;
        }

        let cursor = self.cursor_index.get();
        let cur_text = self.text.get();
        let chars: Vec<char> = cur_text.chars().collect();
        if cursor >= chars.len() {
            return;
        }

        let next_boundary = find_next_word_boundary(&chars, cursor);

        self.push_undo_snapshot();
        let mut new_chars = Vec::with_capacity(chars.len());
        new_chars.extend_from_slice(&chars[..cursor]);
        new_chars.extend_from_slice(&chars[next_boundary..]);

        self.text.set(new_chars.into_iter().collect());
    }

    /// Deletes the active selection range.
    pub fn delete_selection(&mut self) {
        if let Some((start, end)) = self.selection_range() {
            self.push_undo_snapshot();
            let cur_text = self.text.get();
            let chars: Vec<char> = cur_text.chars().collect();

            let mut new_chars = Vec::with_capacity(chars.len());
            new_chars.extend_from_slice(&chars[..start]);
            new_chars.extend_from_slice(&chars[end..]);

            self.text.set(new_chars.into_iter().collect());
            self.cursor_index.set(start);
            self.selection_anchor.set(None);
        }
    }

    /// Moves the cursor left, optionally extending selection or jumping by word.
    pub fn move_left(&self, extend_selection: bool, by_word: bool) {
        let cur_text = self.text.get();
        let chars: Vec<char> = cur_text.chars().collect();
        let cursor = self.cursor_index.get();

        if !extend_selection && self.has_selection() {
            if let Some((start, _)) = self.selection_range() {
                self.selection_anchor.set(None);
                self.cursor_index.set(start);
                return;
            }
        }

        let new_cursor = if by_word {
            find_prev_word_boundary(&chars, cursor)
        } else {
            cursor.saturating_sub(1)
        };

        if extend_selection {
            if self.selection_anchor.get().is_none() {
                self.selection_anchor.set(Some(cursor));
            }
        } else {
            self.selection_anchor.set(None);
        }

        self.cursor_index.set(new_cursor);
    }

    /// Moves the cursor right, optionally extending selection or jumping by word.
    pub fn move_right(&self, extend_selection: bool, by_word: bool) {
        let cur_text = self.text.get();
        let chars: Vec<char> = cur_text.chars().collect();
        let cursor = self.cursor_index.get();

        if !extend_selection && self.has_selection() {
            if let Some((_, end)) = self.selection_range() {
                self.selection_anchor.set(None);
                self.cursor_index.set(end);
                return;
            }
        }

        let new_cursor = if by_word {
            find_next_word_boundary(&chars, cursor)
        } else {
            (cursor + 1).min(chars.len())
        };

        if extend_selection {
            if self.selection_anchor.get().is_none() {
                self.selection_anchor.set(Some(cursor));
            }
        } else {
            self.selection_anchor.set(None);
        }

        self.cursor_index.set(new_cursor);
    }

    /// Moves the cursor to the beginning of the line.
    pub fn move_home(&self, extend_selection: bool) {
        let cursor = self.cursor_index.get();
        if extend_selection {
            if self.selection_anchor.get().is_none() {
                self.selection_anchor.set(Some(cursor));
            }
        } else {
            self.selection_anchor.set(None);
        }
        self.cursor_index.set(0);
    }

    /// Moves the cursor to the end of the line.
    pub fn move_end(&self, extend_selection: bool) {
        let total = self.text.get().chars().count();
        let cursor = self.cursor_index.get();
        if extend_selection {
            if self.selection_anchor.get().is_none() {
                self.selection_anchor.set(Some(cursor));
            }
        } else {
            self.selection_anchor.set(None);
        }
        self.cursor_index.set(total);
    }

    /// Pushes current text and cursor position to the undo stack.
    fn push_undo_snapshot(&mut self) {
        self.undo_stack
            .push((self.text.get(), self.cursor_index.get()));
        if self.undo_stack.len() > 100 {
            self.undo_stack.remove(0);
        }
        self.redo_stack.clear();
    }

    /// Reverts to the previous state on the undo stack.
    pub fn undo(&mut self) -> bool {
        if let Some((prev_text, prev_cursor)) = self.undo_stack.pop() {
            self.redo_stack
                .push((self.text.get(), self.cursor_index.get()));
            self.text.set(prev_text);
            self.cursor_index.set(prev_cursor);
            self.selection_anchor.set(None);
            true
        } else {
            false
        }
    }

    /// Re-applies the next state on the redo stack.
    pub fn redo(&mut self) -> bool {
        if let Some((next_text, next_cursor)) = self.redo_stack.pop() {
            self.undo_stack
                .push((self.text.get(), self.cursor_index.get()));
            self.text.set(next_text);
            self.cursor_index.set(next_cursor);
            self.selection_anchor.set(None);
            true
        } else {
            false
        }
    }

    /// Processes an input keyboard event according to standard Chromium/OS input contracts.
    pub fn handle_key(
        &mut self,
        key: InputKey,
        modifiers: InputModifiers,
        clipboard_content: Option<&str>,
    ) -> InputKeyResult {
        // Handle Ctrl shortcuts
        if modifiers.ctrl {
            match key {
                InputKey::A => {
                    self.select_all();
                    return InputKeyResult::Handled;
                }
                InputKey::C => {
                    if let Some(sel) = self.selected_text() {
                        return InputKeyResult::CopyToClipboard(sel);
                    }
                    return InputKeyResult::Ignored;
                }
                InputKey::X => {
                    if let Some(sel) = self.selected_text() {
                        self.delete_selection();
                        return InputKeyResult::CopyToClipboard(sel);
                    }
                    return InputKeyResult::Ignored;
                }
                InputKey::V => {
                    if let Some(clip) = clipboard_content {
                        self.insert_text(clip);
                        return InputKeyResult::Handled;
                    }
                    return InputKeyResult::Ignored;
                }
                InputKey::Z => {
                    if modifiers.shift {
                        if self.redo() {
                            return InputKeyResult::Handled;
                        }
                    } else if self.undo() {
                        return InputKeyResult::Handled;
                    }
                    return InputKeyResult::Ignored;
                }
                InputKey::Y => {
                    if self.redo() {
                        return InputKeyResult::Handled;
                    }
                    return InputKeyResult::Ignored;
                }
                InputKey::Left => {
                    self.move_left(modifiers.shift, true);
                    return InputKeyResult::Handled;
                }
                InputKey::Right => {
                    self.move_right(modifiers.shift, true);
                    return InputKeyResult::Handled;
                }
                InputKey::Backspace => {
                    self.delete_word_backward();
                    return InputKeyResult::Handled;
                }
                InputKey::Delete => {
                    self.delete_word_forward();
                    return InputKeyResult::Handled;
                }
                _ => {}
            }
        }

        // Standard navigation and editing
        match key {
            InputKey::Left => {
                self.move_left(modifiers.shift, false);
                InputKeyResult::Handled
            }
            InputKey::Right => {
                self.move_right(modifiers.shift, false);
                InputKeyResult::Handled
            }
            InputKey::Home => {
                self.move_home(modifiers.shift);
                InputKeyResult::Handled
            }
            InputKey::End => {
                self.move_end(modifiers.shift);
                InputKeyResult::Handled
            }
            InputKey::Backspace => {
                self.delete_backward();
                InputKeyResult::Handled
            }
            InputKey::Delete => {
                self.delete_forward();
                InputKeyResult::Handled
            }
            InputKey::Enter => InputKeyResult::Submitted,
            InputKey::Escape => {
                self.clear_selection();
                InputKeyResult::Handled
            }
            InputKey::Char(c) => {
                let mut buf = [0u8; 4];
                self.insert_text(c.encode_utf8(&mut buf));
                InputKeyResult::Handled
            }
            _ => InputKeyResult::Ignored,
        }
    }
}

impl Default for TextInputState {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for TextInputState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TextInputState")
            .field("text", &self.text.get())
            .field("cursor_index", &self.cursor_index.get())
            .field("selection_anchor", &self.selection_anchor.get())
            .field("undo_count", &self.undo_stack.len())
            .field("redo_count", &self.redo_stack.len())
            .finish()
    }
}

#[inline]
fn is_word_char(c: char) -> bool {
    c.is_alphanumeric() || c == '_'
}

/// Helper locating the previous word boundary index before `cursor`.
fn find_prev_word_boundary(chars: &[char], cursor: usize) -> usize {
    if cursor == 0 {
        return 0;
    }
    let mut idx = cursor;

    // Skip trailing whitespace
    while idx > 0 && chars[idx - 1].is_whitespace() {
        idx -= 1;
    }
    if idx == 0 {
        return 0;
    }

    if is_word_char(chars[idx - 1]) {
        while idx > 0 && is_word_char(chars[idx - 1]) {
            idx -= 1;
        }
    } else {
        while idx > 0 && !is_word_char(chars[idx - 1]) && !chars[idx - 1].is_whitespace() {
            idx -= 1;
        }
    }
    idx
}

/// Helper locating the next word boundary index after `cursor`.
fn find_next_word_boundary(chars: &[char], cursor: usize) -> usize {
    let len = chars.len();
    if cursor >= len {
        return len;
    }
    let mut idx = cursor;

    // Skip whitespace
    while idx < len && chars[idx].is_whitespace() {
        idx += 1;
    }
    if idx >= len {
        return len;
    }

    if is_word_char(chars[idx]) {
        while idx < len && is_word_char(chars[idx]) {
            idx += 1;
        }
    } else {
        while idx < len && !is_word_char(chars[idx]) && !chars[idx].is_whitespace() {
            idx += 1;
        }
    }
    idx
}