incular-text 0.1.2

Text layout and typography foundations for Incular
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
//! Renderer-independent editing and selection state.

use crate::{TextGeometry, TextStyle};
use icu_segmenter::GraphemeClusterSegmenter;
use incular_core::time::Instant;
use incular_core::{RestorationKey, RestorationScope};
use std::{cell::RefCell, fmt, ops::Range, rc::Rc};

/// Whether a caret is associated with the leading or trailing edge of a
/// bidirectional run.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextAffinity {
    #[default]
    Downstream,
    Upstream,
}

/// A half-open UTF-8 byte range. Text engines use byte offsets so ranges can
/// be passed directly to shaping and grapheme segmentation without lossy
/// conversions. Call [`Self::clamp_to`] before slicing arbitrary user input.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct TextRange {
    pub start: usize,
    pub end: usize,
}

impl TextRange {
    pub const EMPTY: Self = Self { start: 0, end: 0 };

    #[must_use]
    pub const fn new(start: usize, end: usize) -> Self {
        Self { start, end }
    }

    #[must_use]
    pub const fn collapsed(offset: usize) -> Self {
        Self::new(offset, offset)
    }

    #[must_use]
    pub const fn is_collapsed(self) -> bool {
        self.start == self.end
    }

    #[must_use]
    pub const fn is_valid(self) -> bool {
        self.start <= self.end
    }

    #[must_use]
    pub const fn len(self) -> usize {
        self.end.saturating_sub(self.start)
    }

    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.start == self.end
    }

    #[must_use]
    pub const fn as_range(self) -> Range<usize> {
        self.start..self.end
    }

    /// Clamps the range to a string and moves each endpoint to a valid UTF-8
    /// boundary. This keeps editing operations panic-free for IME byte offsets.
    #[must_use]
    pub fn clamp_to(self, text: &str) -> Self {
        let start = nearest_char_boundary(text, self.start.min(text.len()));
        let end = nearest_char_boundary(text, self.end.min(text.len())).max(start);
        Self::new(start, end)
    }

    #[must_use]
    pub fn normalized(self) -> Self {
        if self.start <= self.end {
            self
        } else {
            Self::new(self.end, self.start)
        }
    }
}

/// A selection preserves directional base/extent while exposing a normalized
/// range for text replacement.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct TextSelection {
    pub base: usize,
    pub extent: usize,
}

impl TextSelection {
    #[must_use]
    pub const fn new(base: usize, extent: usize) -> Self {
        Self { base, extent }
    }

    #[must_use]
    pub const fn collapsed(offset: usize) -> Self {
        Self::new(offset, offset)
    }

    #[must_use]
    pub const fn start(self) -> usize {
        if self.base < self.extent {
            self.base
        } else {
            self.extent
        }
    }

    #[must_use]
    pub const fn end(self) -> usize {
        if self.base > self.extent {
            self.base
        } else {
            self.extent
        }
    }

    #[must_use]
    pub const fn is_collapsed(self) -> bool {
        self.base == self.extent
    }

    #[must_use]
    pub const fn is_forward(self) -> bool {
        self.base <= self.extent
    }

    #[must_use]
    pub const fn range(self) -> TextRange {
        TextRange::new(self.start(), self.end())
    }

    /// Clamps both edges into the text at UTF-8 char boundaries,
    /// snapping down. Char boundaries are deliberately not grapheme
    /// boundaries: a mid-grapheme edge survives clamping and the caret
    /// mapping below resolves it to the shaping-cluster edge instead.
    #[must_use]
    pub fn clamp_to(self, text: &str) -> Self {
        let base = nearest_char_boundary(text, self.base.min(text.len()));
        let extent = nearest_char_boundary(text, self.extent.min(text.len()));
        Self::new(base, extent)
    }
}

/// A composing/marked range supplied by an IME.
pub type ComposingRange = TextRange;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextEditingValue {
    pub text: String,
    pub selection: TextSelection,
    pub composing: Option<ComposingRange>,
}

impl TextEditingValue {
    #[must_use]
    pub fn new(text: impl Into<String>) -> Self {
        let text = text.into();
        let caret = text.len();
        Self {
            text,
            selection: TextSelection::collapsed(caret),
            composing: None,
        }
    }

    #[must_use]
    pub const fn empty() -> Self {
        Self {
            text: String::new(),
            selection: TextSelection::collapsed(0),
            composing: None,
        }
    }

    #[must_use]
    pub fn with_selection(mut self, selection: TextSelection) -> Self {
        self.selection = selection.clamp_to(&self.text);
        self
    }

    #[must_use]
    pub fn with_composing(mut self, composing: Option<ComposingRange>) -> Self {
        self.composing = composing.map(|range| range.clamp_to(&self.text));
        self
    }

    #[must_use]
    pub fn replace(mut self, range: TextRange, replacement: &str) -> Self {
        let range = range.normalized().clamp_to(&self.text);
        self.text.replace_range(range.as_range(), replacement);
        let caret = range.start + replacement.len();
        self.selection = TextSelection::collapsed(caret);
        self.composing = None;
        self
    }
}

impl Default for TextEditingValue {
    fn default() -> Self {
        Self::empty()
    }
}

/// An atomic editing operation, useful for integrating native IMEs and undo
/// stacks without coupling those systems to a widget.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextEditingDelta {
    pub range: TextRange,
    pub replacement: String,
    pub selection: Option<TextSelection>,
    pub composing: Option<ComposingRange>,
}

impl TextEditingDelta {
    #[must_use]
    pub fn replace(range: TextRange, replacement: impl Into<String>) -> Self {
        Self {
            range,
            replacement: replacement.into(),
            selection: None,
            composing: None,
        }
    }

    #[must_use]
    pub fn apply(&self, value: &TextEditingValue) -> TextEditingValue {
        let mut next = value.clone().replace(self.range, &self.replacement);
        if let Some(selection) = self.selection {
            next.selection = selection.clamp_to(&next.text);
        }
        next.composing = self.composing.map(|range| range.clamp_to(&next.text));
        next
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SelectionChangedCause {
    #[default]
    Unknown,
    Keyboard,
    Tap,
    DoubleTap,
    LongPress,
    Drag,
    Accessibility,
    Programmatic,
}

type Listener = Rc<dyn Fn(&TextEditingValue)>;
type EditTransform = Rc<dyn Fn(&TextEditingValue, &TextEditingValue) -> TextEditingValue>;

#[derive(Default)]
struct ControllerState {
    value: TextEditingValue,
    listeners: Vec<(usize, Listener)>,
    next_listener: usize,
    content_revision: u64,
    visual_revision: u64,
    caret_reset: Option<Instant>,
    preferred_caret_x: Option<f32>,
    caret_affinity: TextAffinity,
    preedit: Option<String>,
    preedit_selection: Option<TextRange>,
    restoration: Option<TextRestoration>,
    restoration_generation: u64,
}

#[derive(Clone)]
struct TextRestoration {
    scope: RestorationScope,
    key: RestorationKey,
}

/// Cloneable editing controller. It owns no platform resources; platform and
/// widget layers can subscribe to value changes and decide when to repaint.
#[derive(Clone, Default)]
pub struct TextEditingController {
    changes: incular_core::reactivity::DependencySource,
    transforms: incular_core::reactivity::DependencySource,
    inner: Rc<RefCell<ControllerState>>,
}

/// Owns a text-controller listener until dropped.
#[must_use = "keep the subscription alive to observe changes"]
pub struct TextEditingSubscription {
    _subscription: incular_core::reactivity::Subscription,
}

impl PartialEq for TextEditingController {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.inner, &other.inner)
    }
}

impl fmt::Debug for TextEditingController {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TextEditingController")
            .field("value", &self.value())
            .finish()
    }
}

impl TextEditingController {
    #[must_use]
    pub fn new() -> Self {
        Self::from_value(TextEditingValue::default())
    }

    /// Creates a controller initialized with committed text.
    #[must_use]
    pub fn with_text(text: impl Into<String>) -> Self {
        Self::from_value(TextEditingValue::new(text))
    }

    /// Creates an empty editor and restores its committed state, if present.
    #[must_use]
    pub fn restored(scope: RestorationScope, key: RestorationKey) -> Self {
        let controller = Self::new();
        controller.bind_restoration(scope, key);
        controller
    }

    /// Binds committed text and selection to a stable restoration value.
    pub fn bind_restoration(&self, scope: RestorationScope, key: RestorationKey) {
        let restored = scope.get_json(&key).and_then(value_from_json);
        let changed = restored
            .as_ref()
            .is_some_and(|value| *value != self.inner.borrow().value);
        let mut state = self.inner.borrow_mut();
        state.restoration = Some(TextRestoration { scope, key });
        // Restoration is a baseline, not an edit: bump the generation so
        // history observers rebaseline instead of recording an undo step.
        state.restoration_generation = state
            .restoration_generation
            .checked_add(1)
            .expect("text restoration generation exhausted");
        if let Some(value) = restored {
            state.value = value;
            state.content_revision = state
                .content_revision
                .checked_add(1)
                .expect("content revision exhausted");
            state.visual_revision = state
                .visual_revision
                .checked_add(1)
                .expect("visual revision exhausted");
            state.preedit = None;
            state.preedit_selection = None;
            state.caret_reset = None;
            state.preferred_caret_x = None;
            state.caret_affinity = TextAffinity::Downstream;
        }
        drop(state);
        if changed {
            self.notify_listeners();
        }
    }

    /// Stops persisting subsequent editor mutations without deleting the saved value.
    pub fn unbind_restoration(&self) {
        self.inner.borrow_mut().restoration = None;
    }

    #[must_use]
    pub fn from_value(value: TextEditingValue) -> Self {
        Self {
            changes: incular_core::reactivity::DependencySource::default(),
            transforms: incular_core::reactivity::DependencySource::default(),
            inner: Rc::new(RefCell::new(ControllerState {
                value,
                ..ControllerState::default()
            })),
        }
    }

    #[must_use]
    pub fn value(&self) -> TextEditingValue {
        self.changes.track();
        self.inner.borrow().value.clone()
    }

    /// Runs `f` against the current value without cloning it. Dependency
    /// tracking matches [`Self::value`]. The controller must not be mutated
    /// from inside `f`.
    pub fn with_value<R>(&self, f: impl FnOnce(&TextEditingValue) -> R) -> R {
        self.changes.track();
        f(&self.inner.borrow().value)
    }

    #[must_use]
    pub fn text(&self) -> String {
        self.changes.track();
        self.inner.borrow().value.text.clone()
    }

    #[must_use]
    pub fn selection(&self) -> TextSelection {
        self.changes.track();
        self.inner.borrow().value.selection
    }

    #[must_use]
    pub fn composing(&self) -> Option<ComposingRange> {
        self.changes.track();
        self.inner.borrow().value.composing
    }

    pub fn set_value(&self, value: TextEditingValue) {
        self.update(value, true);
        self.inner.borrow_mut().caret_affinity = TextAffinity::Downstream;
    }

    pub fn set_text(&self, text: impl Into<String>) {
        self.update(TextEditingValue::new(text), true);
        self.inner.borrow_mut().caret_affinity = TextAffinity::Downstream;
    }

    pub fn clear(&self) {
        self.set_text("");
    }

    pub fn set_selection(&self, selection: TextSelection) {
        let mut value = self.value();
        value.selection = selection.clamp_to(&value.text);
        self.update(value, false);
        self.inner.borrow_mut().caret_affinity = TextAffinity::Downstream;
    }

    /// Sets a selection while preserving which visual edge of a bidi run owns
    /// a collapsed caret. Native hit testing should use this overload.
    pub fn set_selection_with_affinity(&self, selection: TextSelection, affinity: TextAffinity) {
        let mut value = self.value();
        value.selection = selection.clamp_to(&value.text);
        self.update(value, false);
        self.inner.borrow_mut().caret_affinity = affinity;
    }

    pub fn set_composing(&self, composing: Option<ComposingRange>) {
        let mut value = self.value();
        value.composing = composing.map(|range| range.clamp_to(&value.text));
        self.update(value, false);
    }

    /// Observes committed editing changes with automatic cleanup on drop.
    pub fn observe(
        &self,
        listener: impl Fn(&TextEditingValue) + 'static,
    ) -> TextEditingSubscription {
        let state = Rc::downgrade(&self.inner);
        TextEditingSubscription {
            _subscription: self.changes.subscribe((), move || {
                if let Some(state) = state.upgrade() {
                    let value = state.borrow().value.clone();
                    listener(&value);
                }
            }),
        }
    }

    #[doc(hidden)]
    pub fn register_edit_transform(
        &self,
        transform: impl Fn(&TextEditingValue, &TextEditingValue) -> TextEditingValue + 'static,
    ) -> incular_core::reactivity::Subscription {
        let transform: EditTransform = Rc::new(transform);
        self.transforms.subscribe(transform, || {})
    }

    /// Low-level manual registration for backend integrations. Prefer `observe`.
    /// Returns an opaque token accepted by
    /// [`Self::remove_listener`].
    pub fn add_listener(&self, listener: impl Fn(&TextEditingValue) + 'static) -> usize {
        let mut state = self.inner.borrow_mut();
        let token = state.next_listener;
        state.next_listener = state
            .next_listener
            .checked_add(1)
            .expect("text editing listener identity space exhausted");
        state.listeners.push((token, Rc::new(listener)));
        token
    }

    pub fn remove_listener(&self, token: usize) -> bool {
        let mut state = self.inner.borrow_mut();
        let before = state.listeners.len();
        state.listeners.retain(|(id, _)| *id != token);
        before != state.listeners.len()
    }

    pub fn apply_delta(&self, delta: &TextEditingDelta) {
        let next = delta.apply(&self.value());
        self.update(next, true);
    }

    pub fn replace_selection(&self, replacement: &str) {
        let value = self.value();
        let range = value.selection.range();
        self.update(value.replace(range, replacement), true);
    }

    pub fn insert_text(&self, text: &str) {
        self.replace_selection(text);
    }

    pub fn delete_backward(&self) {
        self.backspace();
    }

    pub fn delete_forward(&self) {
        let value = self.value();
        let range = if value.selection.is_collapsed() {
            next_grapheme_boundary(&value.text, value.selection.extent)
                .map_or(TextRange::collapsed(value.selection.extent), |end| {
                    TextRange::new(value.selection.extent, end)
                })
        } else {
            value.selection.range()
        };
        self.update(value.replace(range, ""), true);
    }

    /// Alias used by the Widgets editor API.
    pub fn insert(&self, text: &str) {
        self.insert_text(text);
    }

    /// Deletes one grapheme cluster behind the caret, or the active selection.
    pub fn backspace(&self) {
        let value = self.value();
        let range = if value.selection.is_collapsed() {
            previous_grapheme_boundary(&value.text, value.selection.extent)
                .map_or(TextRange::collapsed(value.selection.extent), |start| {
                    TextRange::new(start, value.selection.extent)
                })
        } else {
            value.selection.range()
        };
        self.update(value.replace(range, ""), true);
    }

    /// Deletes one grapheme cluster ahead of the caret, or the active selection.
    pub fn delete(&self) {
        self.delete_forward();
    }

    pub fn move_left(&self, extend: bool) {
        self.move_cursor(
            previous_grapheme_boundary(&self.value().text, self.value().selection.extent)
                .unwrap_or(0),
            extend,
        );
    }

    pub fn move_right(&self, extend: bool) {
        let value = self.value();
        self.move_cursor(
            next_grapheme_boundary(&value.text, value.selection.extent).unwrap_or(value.text.len()),
            extend,
        );
    }

    /// Moves one grapheme in screen/visual order using the bidi caret stops
    /// of a [`TextGeometry`]. The logical byte offset may move backwards
    /// while the caret moves right, which is required for right-to-left text.
    pub fn move_left_visual(&self, layout: &(impl TextGeometry + ?Sized), extend: bool) {
        self.move_visual(layout, false, extend);
    }

    /// Moves one grapheme in screen/visual order using the bidi caret stops
    /// of a [`TextGeometry`].
    pub fn move_right_visual(&self, layout: &(impl TextGeometry + ?Sized), extend: bool) {
        self.move_visual(layout, true, extend);
    }

    pub fn move_home(&self, extend: bool) {
        self.move_cursor(0, extend);
    }

    pub fn move_end(&self, extend: bool) {
        self.move_cursor(self.text().len(), extend);
    }

    pub fn select_all(&self) {
        self.set_selection(TextSelection::new(0, self.text().len()));
    }

    #[must_use]
    pub fn selected_text(&self) -> String {
        let value = self.value();
        let range = value.selection.range();
        value.text[range.as_range()].to_owned()
    }

    /// Sets transient IME preedit text without changing committed content.
    pub fn set_preedit(&self, text: impl Into<String>, selection: Option<TextRange>) {
        incular_core::reactivity::assert_mutation_allowed();
        let text = text.into();
        let mut state = self.inner.borrow_mut();
        state.preedit_selection = selection.map(|range| range.clamp_to(&text));
        state.preedit = (!text.is_empty()).then_some(text);
        state.visual_revision = state
            .visual_revision
            .checked_add(1)
            .expect("visual revision exhausted");
        drop(state);
        self.notify_listeners();
    }

    pub fn commit_preedit(&self, text: &str) {
        let value = self.value();
        let range = value.selection.range();
        self.update_committed(value.replace(range, text), true, true);
    }

    pub fn clear_preedit(&self) {
        incular_core::reactivity::assert_mutation_allowed();
        let mut state = self.inner.borrow_mut();
        if state.preedit.take().is_some() {
            state.preedit_selection = None;
            state.visual_revision = state
                .visual_revision
                .checked_add(1)
                .expect("visual revision exhausted");
            drop(state);
            self.notify_listeners();
        }
    }

    #[must_use]
    pub fn preedit(&self) -> Option<String> {
        self.inner.borrow().preedit.clone()
    }

    #[must_use]
    pub fn preedit_selection(&self) -> Option<TextRange> {
        self.inner.borrow().preedit_selection
    }

    /// Returns committed and visual revisions used by retained repaint scheduling.
    #[doc(hidden)]
    #[must_use]
    pub fn revisions(&self) -> (u64, u64) {
        let state = self.inner.borrow();
        (state.content_revision, state.visual_revision)
    }

    /// Restoration baseline generation; history rebaselines when observed.
    #[doc(hidden)]
    #[must_use]
    pub fn restoration_generation(&self) -> u64 {
        self.inner.borrow().restoration_generation
    }

    /// Restarts the caret blink after an editing interaction.
    #[doc(hidden)]
    pub fn reset_caret(&self, now: Instant) {
        let mut state = self.inner.borrow_mut();
        state.caret_reset = Some(now);
        state.visual_revision = state
            .visual_revision
            .checked_add(1)
            .expect("visual revision exhausted");
    }

    /// Returns whether the caret should be painted at `now`.
    #[doc(hidden)]
    #[must_use]
    pub fn caret_visible(&self, now: Instant) -> bool {
        self.caret_opacity(now, false) > 0.0
    }

    /// The caret's opacity at `now` since the blink last restarted. Without
    /// `animates` the caret is on, then off, for `_kCursorBlinkHalfPeriod`
    /// (500 ms) each; with it, it follows Flutter's
    /// `_KeyFrame.iOSBlinkingCaretKeyFrames` (iOS 15.4 UIKit) once a second
    /// (`EditableText.cursorOpacityAnimates`).
    #[must_use]
    pub fn caret_opacity(&self, now: Instant, animates: bool) -> f32 {
        // (time in seconds, opacity) key frames, held until the next one.
        const IOS_BLINKING_CARET: [(f32, f32); 11] = [
            (0.0, 1.0),
            (0.5, 1.0),
            (0.5375, 0.75),
            (0.575, 0.5),
            (0.6125, 0.25),
            (0.65, 0.0),
            (0.85, 0.0),
            (0.8875, 0.25),
            (0.925, 0.5),
            (0.9625, 0.75),
            (1.0, 1.0),
        ];
        let Some(start) = self.inner.borrow().caret_reset else {
            return 0.0;
        };
        let elapsed = now.checked_duration_since(start).unwrap_or_default();
        if !animates {
            return if (elapsed.as_millis() / 500).is_multiple_of(2) {
                1.0
            } else {
                0.0
            };
        }
        // The simulation restarts when it completes, every second.
        let time = (elapsed.as_micros() % 1_000_000) as f32 / 1_000_000.0;
        IOS_BLINKING_CARET
            .iter()
            .rev()
            .find(|(at, _)| *at <= time)
            .map_or(1.0, |(_, opacity)| *opacity)
    }

    #[doc(hidden)]
    #[must_use]
    pub fn preferred_caret_x(&self) -> Option<f32> {
        self.inner.borrow().preferred_caret_x
    }

    /// Retains the horizontal column used by vertical movement without
    /// changing the editing value.
    #[doc(hidden)]
    pub fn set_preferred_caret_x(&self, x: f32) {
        self.inner.borrow_mut().preferred_caret_x = x.is_finite().then_some(x);
    }

    /// Returns the visual affinity of the collapsed caret.
    #[must_use]
    pub fn caret_affinity(&self) -> TextAffinity {
        self.inner.borrow().caret_affinity
    }

    #[doc(hidden)]
    pub fn move_cursor(&self, target: usize, extend: bool) {
        self.move_cursor_impl(target, extend, None, TextAffinity::Downstream);
    }

    #[doc(hidden)]
    pub fn move_cursor_with_affinity(&self, target: usize, affinity: TextAffinity, extend: bool) {
        self.move_cursor_impl(target, extend, None, affinity);
    }

    fn move_cursor_impl(
        &self,
        target: usize,
        extend: bool,
        preferred_x: Option<f32>,
        affinity: TextAffinity,
    ) {
        let mut value = self.value();
        let target = nearest_char_boundary(&value.text, target.min(value.text.len()));
        value.selection = if extend {
            TextSelection::new(value.selection.base, target)
        } else {
            TextSelection::collapsed(target)
        };
        self.update(value, false);
        let mut state = self.inner.borrow_mut();
        state.preferred_caret_x = preferred_x;
        state.caret_affinity = affinity;
    }

    fn move_visual(&self, layout: &(impl TextGeometry + ?Sized), right: bool, extend: bool) {
        let value = self.value();
        let extent = value.selection.extent;
        // An unextended arrow first collapses an active selection, matching
        // native editors and avoiding a surprising extra visual step.
        if !extend && !value.selection.is_collapsed() {
            let target = if right {
                value.selection.end()
            } else {
                value.selection.start()
            };
            self.move_cursor_with_affinity(target, TextAffinity::Downstream, false);
            return;
        }
        let line = layout
            .lines()
            .position(|line| extent >= line.start() && extent <= line.end())
            .unwrap_or_else(|| layout.line_count().saturating_sub(1));
        let stops = layout.line_caret_positions(line);
        if stops.is_empty() {
            return;
        }
        let affinity = self.caret_affinity();
        let current = stops
            .iter()
            .position(|stop| stop.offset == extent && stop.affinity == affinity)
            .or_else(|| stops.iter().position(|stop| stop.offset == extent))
            .unwrap_or_else(|| {
                if right {
                    0
                } else {
                    stops.len().saturating_sub(1)
                }
            });
        let target = if right {
            stops.get(current + 1).copied().or_else(|| {
                (line + 1..layout.line_count())
                    .find_map(|next_line| layout.line_caret_positions(next_line).first().copied())
            })
        } else {
            current
                .checked_sub(1)
                .and_then(|index| stops.get(index).copied())
                .or_else(|| {
                    (0..line).rev().find_map(|previous_line| {
                        layout.line_caret_positions(previous_line).last().copied()
                    })
                })
        };
        let Some(target) = target else {
            return;
        };
        self.move_cursor_with_affinity(target.offset, target.affinity, extend);
    }

    fn update(&self, value: TextEditingValue, content_changed: bool) {
        self.update_committed(value, content_changed, false);
    }

    fn update_committed(&self, value: TextEditingValue, content_changed: bool, end_preedit: bool) {
        incular_core::reactivity::assert_mutation_allowed();
        let (old, revision) = {
            let state = self.inner.borrow();
            (state.value.clone(), state.visual_revision)
        };
        let value = {
            let transforms = self.transforms.subscribers::<EditTransform>();
            let mut next = value;
            for transform in transforms {
                let _guard = incular_core::reactivity::ReadOnlyGuard::enter();
                next = transform(&old, &next);
                if self.inner.borrow().visual_revision != revision {
                    return;
                }
            }
            next.selection = next.selection.clamp_to(&next.text);
            next.composing = next.composing.map(|range| range.clamp_to(&next.text));
            next
        };
        let listeners = {
            let mut state = self.inner.borrow_mut();
            if state.value == value && !(end_preedit && state.preedit.is_some()) {
                return;
            }
            state.value = value;
            if content_changed {
                state.content_revision = state
                    .content_revision
                    .checked_add(1)
                    .expect("content revision exhausted");
            }
            state.visual_revision = state
                .visual_revision
                .checked_add(1)
                .expect("visual revision exhausted");
            state.preedit = None;
            state.preedit_selection = None;
            state.preferred_caret_x = None;
            state
                .listeners
                .iter()
                .map(|(_, listener)| listener.clone())
                .collect::<Vec<_>>()
        };
        let value = self.inner.borrow().value.clone();
        for listener in listeners {
            listener(&value);
        }
        self.persist_restoration();
        self.changes.notify();
    }

    fn notify_listeners(&self) {
        let (value, listeners) = {
            let state = self.inner.borrow();
            (
                state.value.clone(),
                state
                    .listeners
                    .iter()
                    .map(|(_, listener)| listener.clone())
                    .collect::<Vec<_>>(),
            )
        };
        for listener in listeners {
            listener(&value);
        }
        self.changes.notify();
    }

    fn persist_restoration(&self) {
        let (restoration, value) = {
            let state = self.inner.borrow();
            let Some(restoration) = state.restoration.clone() else {
                return;
            };
            (restoration, value_to_json(&state.value))
        };
        restoration.scope.set_json(&restoration.key, value);
    }
}

fn value_to_json(value: &TextEditingValue) -> serde_json::Value {
    serde_json::json!({
        "text": value.text,
        "selection": {
            "base": value.selection.base,
            "extent": value.selection.extent,
        },
    })
}

fn value_from_json(value: serde_json::Value) -> Option<TextEditingValue> {
    let object = value.as_object()?;
    let text = object.get("text")?.as_str()?.to_owned();
    let selection = object
        .get("selection")
        .and_then(serde_json::Value::as_object)
        .and_then(|selection| {
            let base = usize::try_from(selection.get("base")?.as_u64()?).ok()?;
            let extent = usize::try_from(selection.get("extent")?.as_u64()?).ok()?;
            Some(TextSelection::new(base, extent))
        })
        .unwrap_or_else(|| TextSelection::collapsed(text.len()));
    Some(TextEditingValue::new(text.clone()).with_selection(selection.clamp_to(&text)))
}

/// A renderer-neutral editable text description.
#[derive(Clone, Debug)]
pub struct EditableText {
    pub controller: TextEditingController,
    pub style: TextStyle,
    pub read_only: bool,
    pub obscure_text: bool,
    pub max_lines: Option<usize>,
}

impl EditableText {
    #[must_use]
    pub fn new(controller: TextEditingController) -> Self {
        Self {
            controller,
            style: TextStyle::default(),
            read_only: false,
            obscure_text: false,
            max_lines: Some(1),
        }
    }

    #[must_use]
    pub fn style(mut self, style: TextStyle) -> Self {
        self.style = style;
        self
    }

    #[must_use]
    pub fn read_only(mut self, read_only: bool) -> Self {
        self.read_only = read_only;
        self
    }

    #[must_use]
    pub fn obscure_text(mut self, obscure_text: bool) -> Self {
        self.obscure_text = obscure_text;
        self
    }

    #[must_use]
    pub fn max_lines(mut self, max_lines: Option<usize>) -> Self {
        self.max_lines = max_lines;
        self
    }
}

/// Convenience text-field configuration built on [`EditableText`].
#[derive(Clone, Debug)]
pub struct TextField {
    pub editable: EditableText,
    pub placeholder: String,
}

impl TextField {
    #[must_use]
    pub fn new(controller: TextEditingController) -> Self {
        Self {
            editable: EditableText::new(controller),
            placeholder: String::new(),
        }
    }

    #[must_use]
    pub fn style(mut self, style: TextStyle) -> Self {
        self.editable = self.editable.style(style);
        self
    }

    #[must_use]
    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    #[must_use]
    pub fn read_only(mut self, read_only: bool) -> Self {
        self.editable = self.editable.read_only(read_only);
        self
    }
}

fn nearest_char_boundary(text: &str, offset: usize) -> usize {
    if text.is_char_boundary(offset) {
        return offset;
    }
    let mut boundary = offset;
    while boundary > 0 && !text.is_char_boundary(boundary) {
        boundary -= 1;
    }
    boundary
}

fn previous_grapheme_boundary(text: &str, offset: usize) -> Option<usize> {
    let offset = nearest_char_boundary(text, offset.min(text.len()));
    (offset > 0).then(|| {
        GraphemeClusterSegmenter::new()
            .segment_str(text)
            .take_while(|index| *index < offset)
            .last()
            .unwrap_or(0)
    })
}

fn next_grapheme_boundary(text: &str, offset: usize) -> Option<usize> {
    let offset = nearest_char_boundary(text, offset.min(text.len()));
    (offset < text.len()).then(|| {
        GraphemeClusterSegmenter::new()
            .segment_str(text)
            .find(|index| *index > offset)
            .unwrap_or(text.len())
    })
}