Skip to main content

day_piece_text_editor/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-piece-text-editor: a styled-text editor bound two-way to a `Signal<StyledText>`
5//! (docs/texteditor.md).
6//!
7//! ```ignore
8//! let doc = Signal::new(StyledText::markdown("**Hello**, _world_.", Font::Body));
9//! let sel = Signal::new(0..0);
10//!
11//! column((
12//!     // The toolbar is ordinary Day pieces; the piece ships no chrome of its own.
13//!     button("B").action(move || doc.update(|d| {
14//!         let on = !d.style_of(sel.get_untracked(), Font::Body).bold();
15//!         d.apply(sel.get_untracked(), Font::Body, move |s| s.set_bold(on));
16//!     })),
17//!     text_editor(doc).selection(sel).min_lines(8),
18//! ))
19//! ```
20//!
21//! It edits the same [`StyledText`] a label renders and the Markdown / HTML / RTF codecs read and
22//! write, in each platform's own rich-text view: `NSTextView`, `UITextView`, `GtkTextView`,
23//! `QTextEdit`, an `EditText` over a `SpannableStringBuilder`, `RichEditBox`, the ArkTS
24//! `RichEditor`, and a `contenteditable` element. There is **no composed tier** and there must not
25//! be one: a hand-rolled editor loses IME composition, bidirectional cursor movement, the
26//! platform's undo stack, dictation, and the accessibility tree, and loses them invisibly.
27//!
28//! ## Who owns the attributes
29//!
30//! Day does. The native view owns the *characters* (typing, deletion, IME, undo, autocorrect)
31//! and reports them as [`Event::TextChanged`]; the piece diffs that against the text it last knew,
32//! reflows its runs over the edit ([`StyledText::reflow`]), and writes the signal. Attributes only
33//! ever travel Day → native.
34//!
35//! That is why every arm turns the platform's own formatting UI off (iOS's
36//! `allowsEditingTextAttributes`, the macOS font panel) rather than reading it back: an editor
37//! whose attributes can change from two directions has to reconcile them, and reconciling an
38//! attributed string across eight toolkits is a much larger promise than this piece makes.
39//! Everything a toolbar does goes through the bound signal instead, in Rust, where it behaves
40//! identically on all nine targets and is testable on the headless one. docs/texteditor.md records
41//! the per-toolkit hook a future read-back would use.
42
43use day_core::{BuildCx, Flex, Piece, RNode, with_tree};
44use day_pieces::{Binding, Decorated, IntoText, TextSource};
45use day_reactive::{AnyBinding, Effect, Signal, bind_seeded, watch};
46use day_spec::{Event, Font, RunStyle, StyledText, Support};
47// Re-exported for the per-toolkit arms below, which build native attributes out of them.
48#[allow(unused_imports)]
49use day_spec::{ParagraphRun, TextRun};
50use std::cell::RefCell;
51use std::rc::Rc;
52
53pub mod highlight;
54
55pub const KIND: &str = "day.piece.texteditor";
56
57/// What [`TextEditor::highlight`] takes: text in, runs over every byte of it out.
58pub type Highlighter = Rc<dyn Fn(&str) -> Vec<TextRun>>;
59
60/// The prefix a selection report carries in its payload. The tag cannot cross a JNI / C-ABI / JS
61/// boundary (§8.2), so the payload has to be self-describing: `"sel <start> <end>"`, in BYTE
62/// offsets, which every arm converts into from its own indexing.
63pub const SEL_PREFIX: &str = "sel ";
64
65/// The prefix a text report carries on the same channel, for a backend whose piece bridge can
66/// only send `Event::Custom` (HarmonyOS's ArkTS side is the one that has to): `"txt <the text>"`,
67/// the whole document, exactly as [`Event::TextChanged`] carries it.
68pub const TEXT_PREFIX: &str = "txt ";
69
70/// The prefix a claimed key rides on that same channel: `"key Enter"`, `"key Tab"`, the day key
71/// name an [`Event::Key`] would carry on a backend that can send one.
72pub const KEY_PREFIX: &str = "key ";
73
74/// Full props (realize). Only `doc`, `selection` and `editable` change after build.
75#[derive(Clone, Debug, PartialEq)]
76pub struct EditorProps {
77    pub doc: StyledText,
78    /// The style unstyled text is drawn in, and the size relative runs scale against.
79    pub base: Font,
80    pub editable: bool,
81    pub placeholder: String,
82    pub min_lines: u32,
83    pub max_lines: u32,
84    /// Show the platform's spell-check squiggles. Prose wants them; a code editor does not.
85    pub spellcheck: bool,
86    /// One line that scrolls sideways instead of wrapping: Enter reports [`Event::Key`] `"Enter"`
87    /// (the piece turns it into a submit) and inserts nothing, and a pasted newline is flattened
88    /// by the piece. `min_lines`/`max_lines` are both 1.
89    pub single_line: bool,
90    /// Code editing: Tab reports [`Event::Key`] `"Tab"` instead of moving focus (the piece
91    /// inserts the indentation through [`EditorPatch::Insert`]), and an arm whose view
92    /// auto-substitutes (smart quotes, capitalization) turns that off.
93    pub code: bool,
94}
95
96impl Default for EditorProps {
97    fn default() -> Self {
98        EditorProps {
99            doc: StyledText::default(),
100            base: Font::Body,
101            editable: true,
102            placeholder: String::new(),
103            min_lines: 3,
104            max_lines: 0,
105            spellcheck: true,
106            single_line: false,
107            code: false,
108        }
109    }
110}
111
112#[derive(Clone, Debug, PartialEq)]
113pub enum EditorPatch {
114    /// Replace both the text and its attributes. Moves the caret, so it is sent only when the text
115    /// itself changed under the app's hand.
116    SetDocument(StyledText),
117    /// Restyle text the native view already holds, preserving the selection and the undo stack.
118    ///
119    /// The patch a live syntax highlighter sends on every keystroke: re-tokenizing produces fresh
120    /// runs for the same characters, and pushing them as a document would move the caret back to
121    /// wherever the app last set it.
122    ///
123    /// It carries the whole document even though only the attributes are new. The text is what an
124    /// arm converts byte ranges against, and the four whose toolkit cannot hand back its own
125    /// string cheaply (Qt, Android, HarmonyOS, XAML) would otherwise each need a cache that a
126    /// keystroke could leave one edit stale.
127    SetAttributes(StyledText),
128    SetSelection(std::ops::Range<usize>),
129    /// What the next typed character takes. Native where the toolkit has the concept, emulated on
130    /// GTK and the web, which do not.
131    SetTypingStyle(Box<RunStyle>),
132    SetEditable(bool),
133    /// Insert `text` at byte offset `at` through the view's own insertion, so the platform's
134    /// undo stack records it like typing and the caret lands after it. The view reports the
135    /// result as a `TextChanged`, which is how the model learns of it; nothing is written to the
136    /// document here. What the piece's code mode sends for a Tab, an auto-indent and a closing
137    /// bracket.
138    Insert {
139        at: usize,
140        text: String,
141    },
142}
143
144/// Whether the compiled backend edits styled text natively.
145///
146/// [`Support::Native`] on all eight toolkits; every one ships a rich-text view
147/// (docs/texteditor.md). [`Support::Emulated`] only on the headless mock and on an external
148/// toolkit with no arm, where the piece degrades to plain text: the characters round-trip and the
149/// styling does not.
150#[must_use]
151pub fn support() -> Support {
152    if cfg!(any(
153        all(feature = "appkit", target_os = "macos"),
154        all(feature = "uikit", target_os = "ios"),
155        all(feature = "material", target_os = "android"),
156        all(feature = "xaml", windows),
157        all(feature = "arkui", target_env = "ohos"),
158        all(feature = "dom", target_arch = "wasm32"),
159        feature = "gtk",
160        feature = "qt",
161    )) {
162        Support::Native
163    } else {
164        Support::Emulated
165    }
166}
167
168/// A styled-text editor bound two-way to a [`StyledText`] signal. Build with [`text_editor`].
169#[must_use]
170pub struct TextEditor {
171    doc: Signal<StyledText>,
172    selection: Option<AnyBinding<std::ops::Range<usize>>>,
173    typing: Option<AnyBinding<RunStyle>>,
174    base: Font,
175    editable: day_pieces::Reactive<bool>,
176    placeholder: Option<TextSource>,
177    min_lines: u32,
178    max_lines: u32,
179    spellcheck: bool,
180    highlight: Option<Highlighter>,
181    highlight_limit: usize,
182    single_line: bool,
183    on_submit: Option<Rc<dyn Fn()>>,
184    code: bool,
185    indent: u8,
186}
187
188/// The size past which a live highlighter leaves the text plain (512 KiB); see
189/// [`TextEditor::highlight_limit`].
190pub const HIGHLIGHT_LIMIT: usize = 512 * 1024;
191
192/// The narrowest an editor answers a width proposal with, given its `max_lines` (every arm's
193/// `measure` goes through this, so the toolkits agree). An editor that wraps keeps 120 points
194/// to wrap in. A [`TextEditor::single_line`] one (a band of exactly one line) is a styled
195/// text field, usually one of several controls on a row, and gives way the way a text field
196/// does, down to the width of a few characters.
197// Each arm is compiled for its own toolkit only, so a build with none (the mock) never calls it.
198#[allow(dead_code)]
199pub(crate) fn width_floor(max_lines: u32) -> f64 {
200    if max_lines == 1 { 48.0 } else { 120.0 }
201}
202
203/// `text_editor(doc)`: the platform's rich-text view over a [`StyledText`] signal.
204pub fn text_editor(doc: Signal<StyledText>) -> TextEditor {
205    // web-dom's registry is populated at runtime (no `linkme` on wasm), and a constructor always
206    // runs before the node it returns is realized.
207    #[cfg(all(feature = "dom", target_arch = "wasm32"))]
208    dom_impl::register();
209    TextEditor {
210        doc,
211        selection: None,
212        typing: None,
213        base: Font::Body,
214        editable: day_pieces::IntoReactive::into_reactive(true),
215        placeholder: None,
216        min_lines: 3,
217        max_lines: 0,
218        spellcheck: true,
219        highlight: None,
220        highlight_limit: HIGHLIGHT_LIMIT,
221        single_line: false,
222        on_submit: None,
223        code: false,
224        indent: 2,
225    }
226}
227
228/// `text_editor_text(text)`: the same editor over a plain `String` signal, for an app whose model
229/// holds text rather than a document (a request body, a file). The piece keeps a [`StyledText`]
230/// of its own: edits write the string, a string the app writes replaces the document's text,
231/// and a [`TextEditor::highlight`] supplies whatever styling there is.
232pub fn text_editor_text(text: impl day_reactive::Binding<String>) -> TextEditor {
233    let doc = Signal::new(StyledText::plain(text.peek()));
234    // Editor → string: the text only, since the runs are the highlighter's and not the model's.
235    {
236        let text = text.clone();
237        watch(
238            move || doc.with(|d| d.text.clone()),
239            move |t: &String, _| {
240                if text.peek() != *t {
241                    text.write(t.clone());
242                }
243            },
244        );
245    }
246    // String → editor: a new text takes a fresh plain document (the highlighter restyles it on
247    // the next pass); the same text, which is the echo of the write above, changes nothing.
248    watch(
249        move || text.read(),
250        move |t: &String, _| {
251            if doc.with_untracked(|d| d.text != *t) {
252                doc.set(StyledText::plain(t.clone()));
253            }
254        },
255    );
256    text_editor(doc)
257}
258
259#[day_pieces::builder(TextEditorBuilder)]
260impl TextEditor {
261    /// Live syntax highlighting: `f` turns the text into runs, and runs again after every edit
262    /// (and whenever a signal it reads changes). The runs reach the native view as an attributes
263    /// patch, so the caret and the platform's undo stack stay put. [`highlight::highlighter`]
264    /// builds `f` for the languages the crate knows.
265    pub fn highlight(mut self, f: impl Fn(&str) -> Vec<TextRun> + 'static) -> Self {
266        self.highlight = Some(Rc::new(f));
267        self
268    }
269    /// The size, in bytes, past which [`TextEditor::highlight`] leaves the text plain (default
270    /// [`HIGHLIGHT_LIMIT`], 512 KiB). The tokenizers are linear, but every keystroke restyles
271    /// the whole document in the native view, and a body of hundreds of thousands of runs is
272    /// where that stops feeling like typing. A read-only body is styled once and can afford
273    /// more: raise it there.
274    pub fn highlight_limit(mut self, bytes: usize) -> Self {
275        self.highlight_limit = bytes;
276        self
277    }
278    /// One line, scrolling sideways instead of wrapping: a styled `text_field`. Enter submits
279    /// ([`TextEditor::on_submit`]) and inserts nothing; a pasted newline becomes a space. For a
280    /// URL bar or a header value that wants template tags or other runs drawn inline.
281    pub fn single_line(mut self) -> Self {
282        self.single_line = true;
283        self.min_lines = 1;
284        self.max_lines = 1;
285        self
286    }
287    /// What Enter does in a [`TextEditor::single_line`] editor (and what a dayscript `submit`
288    /// step delivers).
289    pub fn on_submit(mut self, f: impl Fn() + 'static) -> Self {
290        self.on_submit = Some(Rc::new(f));
291        self
292    }
293    /// Code editing: Tab indents instead of moving focus, Enter keeps the previous line's
294    /// indentation (one level deeper after an opening bracket), and an opening bracket or quote
295    /// gets its closer typed after the caret. Spell-check is off.
296    pub fn code(mut self) -> Self {
297        self.code = true;
298        self.spellcheck = false;
299        self
300    }
301    /// The width of one indentation level in spaces (default 2), for [`TextEditor::code`].
302    pub fn indent(mut self, spaces: u8) -> Self {
303        self.indent = spaces.max(1);
304        self
305    }
306    /// Bind the selection, in BYTE offsets into `doc.text`, two-way: the user moving the caret
307    /// writes it, and writing it moves the caret. Collapsed when `start == end`.
308    pub fn selection(mut self, sel: impl Binding<std::ops::Range<usize>>) -> Self {
309        self.selection = Some(AnyBinding::new(sel));
310        self
311    }
312    /// Bind what the next typed character will be styled with.
313    ///
314    /// The one piece of editor state an app cannot derive from the document and the selection:
315    /// with a collapsed caret there is no text to read a style off, and "what happens if I type
316    /// now" is the platform's own pending state. Writing it is how a toolbar makes the next word
317    /// bold rather than the last one.
318    pub fn typing_style(mut self, style: impl Binding<RunStyle>) -> Self {
319        self.typing = Some(AnyBinding::new(style));
320        self
321    }
322    /// The style unstyled text draws in, and what relative runs scale against (default `Body`).
323    pub fn base(mut self, base: Font) -> Self {
324        self.base = base;
325        self
326    }
327    pub fn editable<M>(mut self, v: impl day_pieces::IntoReactive<bool, M>) -> Self {
328        self.editable = v.into_reactive();
329        self
330    }
331    /// Hide the platform's spell-check squiggles (they are on by default); what prose that is
332    /// not in the system language, or an identifier field, wants. [`code`](Self::code) does
333    /// this too.
334    pub fn no_spellcheck(mut self) -> Self {
335        self.spellcheck = false;
336        self
337    }
338    pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
339        self.placeholder = Some(t.into_text());
340        self
341    }
342    /// The height band, in lines: never shorter than `min_lines`, grows to `max_lines` and then
343    /// scrolls (`0` = unbounded).
344    pub fn min_lines(mut self, n: u32) -> Self {
345        self.min_lines = n;
346        self
347    }
348    pub fn max_lines(mut self, n: u32) -> Self {
349        self.max_lines = n;
350        self
351    }
352}
353
354impl Piece for TextEditor {
355    fn build(self, cx: &mut BuildCx) -> RNode {
356        let TextEditor {
357            doc,
358            selection,
359            typing,
360            base,
361            editable,
362            placeholder,
363            min_lines,
364            max_lines,
365            spellcheck,
366            highlight,
367            highlight_limit,
368            single_line,
369            on_submit,
370            code,
371            indent,
372        } = self;
373        // The highlighter runs before the first realize, so the view is seeded styled rather than
374        // restyled a frame later. Writing the runs back re-runs this reaction; the second pass
375        // produces the same runs and writes nothing, which is what ends it. Past the size limit
376        // the text stays plain: the tokenizers are linear, but every keystroke then rebuilds the
377        // view's attributes over the whole document, and a body of hundreds of thousands of runs
378        // is where that stops being a keystroke.
379        if let Some(f) = highlight {
380            Effect::new(move || {
381                let runs = doc.with(|d| {
382                    if d.text.len() > highlight_limit {
383                        Vec::new()
384                    } else {
385                        f(&d.text)
386                    }
387                });
388                if doc.with_untracked(|d| d.runs != runs) {
389                    doc.update(|d| d.runs = runs);
390                }
391            });
392        }
393        let initial = doc.get_untracked();
394        let node = cx.leaf(
395            KIND,
396            &EditorProps {
397                doc: initial.clone(),
398                base,
399                editable: editable.get_untracked(),
400                placeholder: placeholder.map_or_default(|p| p.initial()),
401                min_lines,
402                max_lines,
403                spellcheck,
404                single_line,
405                code,
406            },
407            Flex {
408                grow_w: true,
409                ..Default::default()
410            },
411        );
412
413        // The text the native view is known to hold. Two jobs: it is what an incoming
414        // `TextChanged` is diffed against to recover the edit, and it is what an outgoing patch
415        // is compared against to decide whether the text changed at all (which decides between
416        // replacing the document and repainting its attributes).
417        let native_text = Rc::new(RefCell::new(initial.text.clone()));
418        // The dayscript probe starts with the text the editor is built with: the bind below
419        // reports changes only, and a read-only editor (a response body) never has one.
420        with_tree(|t| t.set_probe_value(node, 0.0, initial.text.clone()));
421
422        // App writes → the native view.
423        {
424            let native_text = native_text.clone();
425            bind_seeded(
426                initial.clone(),
427                move || doc.get(),
428                move |d: &StyledText| {
429                    let text_changed = *native_text.borrow() != d.text;
430                    let patch = if text_changed {
431                        (*native_text.borrow_mut()).clone_from(&d.text);
432                        // The dayscript probe (`assert_text`) reads the tree, not the view, and
433                        // the tree knows this piece's patches only through this line.
434                        with_tree(|t| t.set_probe_value(node, 0.0, d.text.clone()));
435                        EditorPatch::SetDocument(d.clone())
436                    } else {
437                        // Same characters, different attributes: the syntax-highlighting path.
438                        // Keeps the caret and the platform's undo stack, which replacing the
439                        // document would not.
440                        EditorPatch::SetAttributes(d.clone())
441                    };
442                    with_tree(|t| t.patch(node, Box::new(patch), text_changed));
443                },
444            );
445        }
446
447        // An appearance change: the arms that hand their view concrete colors (a GTK tag, Qt's
448        // and WinUI's character formats, the web's markup, the ArkTS and Android spans) resolved
449        // each run's inks when they applied them, so the same attributes go again, resolved
450        // against the new palette. AppKit and
451        // UIKit draw dynamic colors, which follow by themselves, and the repeat changes nothing
452        // they show. A document whose inks are all fixed has nothing to recolor.
453        {
454            let native_text = native_text.clone();
455            watch(day_core::palette, move |now, before| {
456                if before == Some(now) {
457                    return;
458                }
459                let d = doc.get_untracked();
460                if !follows_appearance(&d) || *native_text.borrow() != d.text {
461                    return;
462                }
463                with_tree(|t| t.patch(node, Box::new(EditorPatch::SetAttributes(d)), false));
464            });
465        }
466
467        // The selection the native view last reported, and the same echo guard `native_text` is:
468        // a caret move the user made must not be written back to the view it came from.
469        //
470        // Writing it back is not merely redundant. A `selectionchange` fires on every mouse-move
471        // of a drag, and re-setting the selection mid-drag re-anchors it; on the web
472        // (`removeAllRanges` + `addRange`) that visibly collapses the selection the user is in
473        // the middle of making, so a drag cannot select anything at all.
474        let native_sel: Rc<RefCell<Option<std::ops::Range<usize>>>> = Rc::new(RefCell::new(None));
475        // A selection Day wrote and has not yet heard echoed. The bridges deliver a view's
476        // reports on their own schedule, so the caret move an insertion caused can be reported
477        // AFTER the `SetSelection` that followed it was applied; until the write's echo arrives,
478        // such a report is stale and is ignored. A keystroke clears the wait, so an arm that
479        // never echoes a programmatic selection costs nothing past one report.
480        let pending_sel: Rc<RefCell<Option<std::ops::Range<usize>>>> = Rc::new(RefCell::new(None));
481        if let Some(sel) = selection {
482            let native_sel = native_sel.clone();
483            let pending_sel = pending_sel.clone();
484            bind_seeded(
485                0..0,
486                move || sel.get(),
487                move |r: &std::ops::Range<usize>| {
488                    if native_sel.borrow().as_ref() == Some(r) {
489                        return; // the echo of the view's own report
490                    }
491                    *pending_sel.borrow_mut() = Some(r.clone());
492                    with_tree(|t| {
493                        t.patch(node, Box::new(EditorPatch::SetSelection(r.clone())), false);
494                    });
495                },
496            );
497        }
498        // What the next typed character takes, as Day last knew it. `None` when the app bound no
499        // typing style, which is what leaves plain inheritance in charge.
500        let typing_now: Rc<RefCell<Option<RunStyle>>> = Rc::new(RefCell::new(None));
501        if let Some(style) = typing {
502            let typing_now = typing_now.clone();
503            bind_seeded(
504                RunStyle::plain(base),
505                move || style.get(),
506                move |s: &RunStyle| {
507                    // Recorded as well as patched. A native `typingAttributes` styles the
508                    // keystroke, but Day's own attribute patch lands a moment later and would
509                    // repaint it from the model, so the model has to learn the style too.
510                    *typing_now.borrow_mut() = Some(s.clone());
511                    with_tree(|t| {
512                        t.patch(
513                            node,
514                            Box::new(EditorPatch::SetTypingStyle(Box::new(s.clone()))),
515                            false,
516                        );
517                    });
518                },
519            );
520        }
521        {
522            let editable = editable.clone();
523            bind_seeded(
524                editable.get_untracked(),
525                move || editable.get(),
526                move |v: &bool| {
527                    with_tree(|t| t.patch(node, Box::new(EditorPatch::SetEditable(*v)), false));
528                },
529            );
530        }
531
532        // Native edits → the signal.
533        let synthesized_against = native_text.clone();
534        let caret_after_closer = native_sel.clone();
535        let pending_after_closer = pending_sel.clone();
536        let pending_on_edit = pending_sel.clone();
537        // The text the closer's insertion will report, so `edited` can tell it from a keystroke.
538        let closer_text: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
539        let closer_text_on_edit = closer_text.clone();
540        let closer_text_on_sel = closer_text.clone();
541        let edited = move |new_text: &str| {
542            let old = native_text.borrow().clone();
543            if old == new_text {
544                // The echo of a patch Day just sent. Nothing changed, so nothing to write, which
545                // is what keeps `SetDocument` from looping.
546                return;
547            }
548            // The text moved on, so whatever selection write was outstanding is history,
549            // unless this is the closer's own insertion reporting back: the write that put the
550            // caret between the pair is still the one to wait for.
551            if closer_text_on_edit.borrow_mut().take().as_deref() != Some(new_text) {
552                *pending_on_edit.borrow_mut() = None;
553            }
554            let (offset, removed, inserted) = diff_edit(&old, new_text);
555            // What the view holds is the raw text; the model may take a flattened one below, and
556            // the difference is what makes the bind above paint the view with it.
557            *native_text.borrow_mut() = new_text.to_string();
558            // A single line: a newline that got in (a paste, a drop) becomes a space. Same byte
559            // length, so the edit's offsets hold.
560            let flattened;
561            let new_text = if single_line && new_text.contains(['\n', '\r']) {
562                flattened = flatten(new_text);
563                flattened.as_str()
564            } else {
565                new_text
566            };
567            with_tree(|t| t.set_probe_value(node, 0.0, new_text.to_string()));
568            let pending = typing_now.borrow().clone();
569            doc.update(|d| {
570                d.text = new_text.to_string();
571                // Inserted text inherits the run it landed in, which is what an editor does when
572                // nothing is pending, and what typing at the end of a bold word should do. A
573                // pending typing style then overrides exactly the new characters.
574                d.reflow(offset, removed, inserted);
575                if inserted > 0
576                    && let Some(style) = &pending
577                {
578                    d.apply(offset..offset + inserted, base, |s| *s = style.clone());
579                }
580            });
581            // Code mode, after one typed character: Enter keeps the indentation, an opener gets
582            // its closer. Both go through the view's own insertion (`Insert`), so undo sees them
583            // as typing, and the view reports them back through this same path.
584            if code && inserted == 1 && removed == 0 {
585                let typed = &new_text[offset..=offset];
586                if typed == "\n" {
587                    if let Some(ws) = auto_indent(new_text, offset, indent) {
588                        with_tree(|t| {
589                            t.patch(
590                                node,
591                                Box::new(EditorPatch::Insert {
592                                    at: offset + 1,
593                                    text: ws,
594                                }),
595                                true,
596                            );
597                        });
598                    }
599                } else if let Some(closer) = closer_after(new_text, offset) {
600                    with_tree(|t| {
601                        t.patch(
602                            node,
603                            Box::new(EditorPatch::Insert {
604                                at: offset + 1,
605                                text: closer.to_string(),
606                            }),
607                            true,
608                        );
609                        // Back between the pair: the insertion left the caret after the closer.
610                        t.patch(
611                            node,
612                            Box::new(EditorPatch::SetSelection(offset + 1..offset + 1)),
613                            false,
614                        );
615                    });
616                    // Recorded here as well, and marked as the write awaiting its echo, so a
617                    // report of the caret the insertion left after the closer cannot stand in
618                    // for it, whichever order the bridge delivers them in.
619                    *caret_after_closer.borrow_mut() = Some(offset + 1..offset + 1);
620                    *pending_after_closer.borrow_mut() = Some(offset + 1..offset + 1);
621                    *closer_text.borrow_mut() = Some(format!(
622                        "{}{}{}",
623                        &new_text[..=offset],
624                        closer,
625                        &new_text[offset + 1..]
626                    ));
627                }
628            }
629        };
630        // A key one of the modes claimed, as an arm reports it (an `Event::Key`, or `key <name>`
631        // on the custom channel for the arm that has only that) and as a dayscript `key` step
632        // delivers it: Enter in a single line submits; Tab in code indents, through the view's
633        // own insertion at the caret the arm last reported.
634        let key_submit = on_submit.clone();
635        let key_sel = native_sel.clone();
636        let handle_key = move |key: day_spec::Key, modifiers: day_spec::Modifiers| {
637            use day_spec::Key;
638            if single_line && key == Key::Enter {
639                if let Some(f) = &key_submit {
640                    f();
641                }
642            } else if modifiers.is_empty() {
643                // What goes in at the caret: Tab's indentation in code; and, from a dayscript
644                // `key` step only (no arm reports a printable key or an unclaimed Enter here),
645                // the character itself, or a newline in code, so a script can type one
646                // character through the view's own insertion and the editing rules above run
647                // on the view's report of it, as they do for a keystroke.
648                let text = doc.with_untracked(|d| d.text.clone());
649                let caret = key_sel
650                    .borrow()
651                    .as_ref()
652                    .map_or(text.len(), |r| r.start.min(text.len()));
653                let insert = match key {
654                    Key::Tab if code => tab_indent(&text, caret, indent),
655                    Key::Enter if code => "\n".to_string(),
656                    Key::Character(c) => c.to_string(),
657                    _ => return,
658                };
659                with_tree(|t| {
660                    t.patch(
661                        node,
662                        Box::new(EditorPatch::Insert {
663                            at: caret,
664                            text: insert,
665                        }),
666                        true,
667                    );
668                });
669            }
670        };
671        cx.on(node, move |ev| match ev {
672            Event::TextChanged(new_text) => edited(new_text),
673            Event::Custom { tag, text, .. } if *tag == day_core::SYNTHESIZED_TEXT => {
674                // A dayscript `input` step: text the view has NOT seen, unlike a `TextChanged`.
675                // Written as the app would write it, so the bind above paints the view with a
676                // document patch; the `TextChanged` that follows is then the echo it ignores.
677                let new_text = if single_line {
678                    flatten(text)
679                } else {
680                    text.clone()
681                };
682                let old = synthesized_against.borrow().clone();
683                let (offset, removed, inserted) = diff_edit(&old, &new_text);
684                doc.update(|d| {
685                    d.text = new_text;
686                    d.reflow(offset, removed, inserted);
687                });
688            }
689            Event::Custom { text, .. } => {
690                // A backend whose piece channel carries only `Event::Custom` reports its text
691                // and its claimed keys here instead (HarmonyOS's ArkTS bridge is the one that
692                // must).
693                if let Some(new_text) = text.strip_prefix(TEXT_PREFIX) {
694                    edited(new_text);
695                    return;
696                }
697                if let Some(name) = text.strip_prefix(KEY_PREFIX) {
698                    handle_key(day_spec::Key::from_name(name), day_spec::Modifiers::NONE);
699                    return;
700                }
701                let Some(range) = parse_selection(text) else {
702                    return;
703                };
704                // The caret's own style becomes the pending one, so a toolbar bound to it reads
705                // the text the caret sits in and typing continues that text's style. An app write
706                // lands the same way and wins until the caret moves again.
707                //
708                // `set_if_changed`, because this runs on every mouse-move of a drag: an unchanged
709                // style would patch the native typing attributes hundreds of times for nothing.
710                if let Some(style) = typing {
711                    style.set_if_changed(doc.with_untracked(|d| d.style_of(range.clone(), base)));
712                }
713                // A report while a write of Day's own is outstanding: its echo ends the wait,
714                // anything else is the view's state from before the write and is dropped.
715                // Until the closer's own insertion has reported, every selection report is
716                // from before it (the bridges queue them), including one that happens to equal
717                // the write, as the caret after the opener does: dropped.
718                if closer_text_on_sel.borrow().is_some() {
719                    return;
720                }
721                let outstanding = pending_sel.borrow().clone();
722                if let Some(wanted) = outstanding {
723                    if wanted != range {
724                        return;
725                    }
726                    *pending_sel.borrow_mut() = None;
727                }
728                // Recorded before the write, so the bind above sees it as an echo and sends no
729                // patch back to the view the report came from; and recorded whether or not the
730                // app bound the selection, since a Tab needs the caret.
731                *native_sel.borrow_mut() = Some(range.clone());
732                if let Some(sel) = selection {
733                    sel.set_if_changed(range);
734                }
735            }
736            // A `submit` step, or Enter as an arm with a direct channel reports it.
737            Event::Submitted => {
738                if let Some(f) = &on_submit {
739                    f();
740                }
741            }
742            Event::Key(k) if k.is_press() => handle_key(k.key, k.modifiers),
743            _ => {}
744        });
745        node
746    }
747}
748
749/// Recover a single contiguous edit from the old and new text: `(offset, removed, inserted)` in
750/// bytes.
751///
752/// The whole reason a keystroke does not need the backend's cooperation. A common prefix and a
753/// common suffix bracket exactly what changed, which for one keystroke, one deletion, one paste or
754/// one autocorrect is the edit. An edit that touched two separate places (a multi-cursor change)
755/// comes back as one span covering both: coarser, never wrong, and it costs only the styling
756/// between them.
757///
758/// Both ends are pulled back to character boundaries, so a multi-byte character that changed
759/// mid-sequence never produces a range that would split one.
760#[must_use]
761pub fn diff_edit(old: &str, new: &str) -> (usize, usize, usize) {
762    let (ob, nb) = (old.as_bytes(), new.as_bytes());
763    let max_prefix = ob.len().min(nb.len());
764    let mut prefix = 0usize;
765    while prefix < max_prefix && ob[prefix] == nb[prefix] {
766        prefix += 1;
767    }
768    while prefix > 0 && (!old.is_char_boundary(prefix) || !new.is_char_boundary(prefix)) {
769        prefix -= 1;
770    }
771    let mut suffix = 0usize;
772    while suffix < max_prefix - prefix && ob[ob.len() - 1 - suffix] == nb[nb.len() - 1 - suffix] {
773        suffix += 1;
774    }
775    while suffix > 0
776        && (!old.is_char_boundary(ob.len() - suffix) || !new.is_char_boundary(nb.len() - suffix))
777    {
778        suffix -= 1;
779    }
780    (
781        prefix,
782        ob.len() - suffix - prefix,
783        nb.len() - suffix - prefix,
784    )
785}
786
787// ---------------------------------------------------------------------------
788// The editing rules of the two modes, as pure functions over the text, so the mock proves them
789// and every arm shares them.
790// ---------------------------------------------------------------------------
791
792/// Whether any run of `doc` carries an ink that depends on the appearance (a light/dark pair or
793/// a role), in its color, its background or a decoration's line: what an appearance change
794/// has to re-send to the arms that apply concrete colors.
795#[must_use]
796pub fn follows_appearance(doc: &StyledText) -> bool {
797    let adaptive = |ink: Option<day_spec::Ink>| ink.is_some_and(|i| i.fixed().is_none());
798    doc.runs.iter().any(|r| {
799        adaptive(r.color)
800            || adaptive(r.background)
801            || adaptive(r.underline.and_then(|d| d.color))
802            || adaptive(r.strikethrough.and_then(|d| d.color))
803    })
804}
805
806/// A single-line editor's text: every line break a space, byte for byte, so the offsets of an
807/// edit computed against the raw text still hold.
808#[must_use]
809pub fn flatten(text: &str) -> String {
810    text.chars()
811        .map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
812        .collect()
813}
814
815/// The spaces a Tab inserts at `caret`: to the next tab stop of width `indent`, counted in
816/// characters from the start of the caret's line.
817#[must_use]
818pub fn tab_indent(text: &str, caret: usize, indent: u8) -> String {
819    let caret = caret.min(text.len());
820    let line_start = text[..caret].rfind('\n').map_or(0, |i| i + 1);
821    let column = text[line_start..caret].chars().count();
822    let width = usize::from(indent.max(1));
823    " ".repeat(width - column % width)
824}
825
826/// The indentation a new line takes after Enter typed at `newline_at`: the previous line's
827/// leading whitespace, one level deeper when that line ends in an opening bracket. `None` when
828/// there is nothing to insert.
829#[must_use]
830pub fn auto_indent(text: &str, newline_at: usize, indent: u8) -> Option<String> {
831    let before = &text[..newline_at.min(text.len())];
832    let line_start = before.rfind('\n').map_or(0, |i| i + 1);
833    let line = &before[line_start..];
834    let mut ws: String = line
835        .chars()
836        .take_while(|c| *c == ' ' || *c == '\t')
837        .collect();
838    if matches!(line.trim_end().chars().last(), Some('{' | '[' | '(')) {
839        ws.push_str(&" ".repeat(usize::from(indent.max(1))));
840    }
841    (!ws.is_empty()).then_some(ws)
842}
843
844/// The closer to type after an opener typed at `at`, when the caret sits at the end of its line
845/// or before whitespace or another closer: `{` `[` `(` and the two quotes. `None` where a
846/// closer would land inside a word.
847#[must_use]
848pub fn closer_after(text: &str, at: usize) -> Option<&'static str> {
849    let opener = text[at..].chars().next()?;
850    let closer = match opener {
851        '{' => "}",
852        '[' => "]",
853        '(' => ")",
854        '"' => "\"",
855        '\'' => "'",
856        _ => return None,
857    };
858    let next = text[at + opener.len_utf8()..].chars().next();
859    let free = match next {
860        None => true,
861        Some(c) => c.is_whitespace() || matches!(c, '}' | ']' | ')' | ',' | ';'),
862    };
863    if !free {
864        return None;
865    }
866    // A quote closes an open quote rather than opening a new pair: an odd count before it on
867    // the line means this one is the closer.
868    if opener == '"' || opener == '\'' {
869        let line_start = text[..at].rfind('\n').map_or(0, |i| i + 1);
870        let open = text[line_start..at]
871            .chars()
872            .filter(|c| *c == opener)
873            .count();
874        if open % 2 == 1 {
875            return None;
876        }
877    }
878    Some(closer)
879}
880
881/// Decode a `"sel <start> <end>"` payload into a byte range.
882fn parse_selection(payload: &str) -> Option<std::ops::Range<usize>> {
883    let rest = payload.strip_prefix(SEL_PREFIX)?;
884    let (a, b) = rest.split_once(' ')?;
885    let (a, b) = (a.parse::<usize>().ok()?, b.parse::<usize>().ok()?);
886    Some(a.min(b)..a.max(b))
887}
888
889// ---------------------------------------------------------------------------
890// Offset conversion. Every arm speaks its toolkit's index unit and converts here, so the
891// arithmetic is written and tested once rather than eight times; an off-by-N here styles the
892// wrong words, and only in text with an emoji or a CJK character.
893// ---------------------------------------------------------------------------
894
895/// A byte range as a UTF-16 range (Apple, Android, XAML).
896#[must_use]
897pub fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<(usize, usize)> {
898    let start = text.get(..r.start)?.encode_utf16().count();
899    let len = text.get(r.clone())?.encode_utf16().count();
900    Some((start, len))
901}
902
903/// A UTF-16 offset back to a byte offset, clamped into the string.
904#[must_use]
905pub fn byte_of_utf16(text: &str, units: usize) -> usize {
906    let mut seen = 0usize;
907    for (i, c) in text.char_indices() {
908        if seen >= units {
909            return i;
910        }
911        seen += c.len_utf16();
912    }
913    text.len()
914}
915
916/// A byte range as a character range (GTK's `TextIter`, ArkUI's spans).
917#[must_use]
918pub fn char_range(text: &str, r: &std::ops::Range<usize>) -> Option<(usize, usize)> {
919    let start = text.get(..r.start)?.chars().count();
920    let len = text.get(r.clone())?.chars().count();
921    Some((start, len))
922}
923
924/// A character offset back to a byte offset, clamped into the string.
925#[must_use]
926pub fn byte_of_char(text: &str, chars: usize) -> usize {
927    text.char_indices()
928        .nth(chars)
929        .map_or(text.len(), |(i, _)| i)
930}
931
932/// The selection payload every arm emits.
933#[must_use]
934pub fn selection_payload(start: usize, end: usize) -> String {
935    format!("{SEL_PREFIX}{start} {end}")
936}
937
938/// The text payload for an arm that has only the custom channel; see [`TEXT_PREFIX`].
939#[must_use]
940pub fn text_payload(text: &str) -> String {
941    format!("{TEXT_PREFIX}{text}")
942}
943
944// ---------------------------------------------------------------------------
945// Per-toolkit native renderers, one file per backend.
946// ---------------------------------------------------------------------------
947
948day_pieces::glue_modules!(appkit, gtk, qt, uikit, material, xaml, arkui, dom);
949
950// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
951
952/// The styled editor's conformance cases (docs/testing.md).
953#[cfg(feature = "conformance")]
954pub mod conformance {
955    use day_core::conformance::{Case, Drive, NativeExpect};
956    use day_pieces::*;
957    use day_reactive::Signal;
958    use day_spec::Font;
959    use day_spec::styled::StyledText;
960
961    use super::{KIND, text_editor};
962
963    /// Typing reaches the bound document, and a document the app writes reaches the view.
964    #[day_macros::test(day_core)]
965    fn texteditor_text_two_way() -> Case {
966        Case::new()
967            .proves(KIND)
968            .page(|| {
969                let doc = Signal::new(StyledText::plain("Start"));
970                column((
971                    label(move || format!("doc {}", doc.get().text))
972                        .id(day_core::id!(texteditor::doc)),
973                    button("Replace")
974                        .action(move || doc.set(StyledText::markdown("**Bold** end", Font::Body)))
975                        .id(day_core::id!(texteditor::replace)),
976                    text_editor(doc)
977                        .min_lines(3)
978                        .id(day_core::id!(texteditor::editor)),
979                ))
980            })
981            .drive(|d: Drive| async move {
982                d.input("texteditor::editor", "Hello world").await?;
983                d.assert_text("texteditor::doc", "doc Hello world").await?;
984                d.tap("texteditor::replace").await?;
985                d.assert_text("texteditor::doc", "doc Bold end").await?;
986                d.assert_native(
987                    "texteditor::editor",
988                    NativeExpect {
989                        text: Some("Bold end".into()),
990                        ..Default::default()
991                    },
992                )
993                .await
994            })
995    }
996
997    /// A run whose inks are a light/dark pair recolors when the appearance switches while the
998    /// editor is shown (docs/texteditor.md "Document and selection").
999    #[day_macros::test(day_core)]
1000    fn texteditor_runs_follow_the_appearance() -> Case {
1001        const PAIR: day_spec::Ink = day_spec::Ink::adaptive(
1002            day_spec::Color::rgb(1.0, 0.0, 0.0),
1003            day_spec::Color::rgb(0.0, 0.0, 1.0),
1004        );
1005        Case::new()
1006            .proves(KIND)
1007            .requires(day_spec::Cap::Appearance)
1008            .requires(day_spec::Cap::Snapshot)
1009            .page(|| {
1010                // Full blocks in the pair over a background in the pair: the line is solid.
1011                let text = "\u{2588}".repeat(24);
1012                let doc = Signal::new(StyledText {
1013                    runs: vec![day_spec::TextRun {
1014                        range: 0..text.len(),
1015                        color: Some(PAIR),
1016                        background: Some(PAIR),
1017                        ..Default::default()
1018                    }],
1019                    text,
1020                    ..Default::default()
1021                });
1022                column((
1023                    text_editor(doc)
1024                        .frame(200.0, 40.0)
1025                        .id(day_core::id!(texteditor::inked)),
1026                    button("Light")
1027                        .action(|| day_core::set_appearance(Some(false)))
1028                        .id(day_core::id!(texteditor::light)),
1029                    button("Dark")
1030                        .action(|| day_core::set_appearance(Some(true)))
1031                        .id(day_core::id!(texteditor::dark)),
1032                    button("System")
1033                        .action(|| day_core::set_appearance(None))
1034                        .id(day_core::id!(texteditor::system)),
1035                ))
1036            })
1037            .drive(|d: Drive| async move {
1038                d.tap("texteditor::light").await?;
1039                d.sample_pixel("texteditor::inked", 0.25, 0.3, "#ff0000")
1040                    .await?;
1041                d.tap("texteditor::dark").await?;
1042                d.sample_pixel("texteditor::inked", 0.25, 0.3, "#0000ff")
1043                    .await?;
1044                d.tap("texteditor::system").await
1045            })
1046    }
1047
1048    /// A live highlighter restyles what was typed without replacing it: the runs are fresh
1049    /// (one per token and gap) and the native view still holds the characters as typed.
1050    #[day_macros::test(day_core)]
1051    fn texteditor_highlight_restyles_in_place() -> Case {
1052        use super::highlight::{Language, Palette, highlighter};
1053        Case::new()
1054            .proves(KIND)
1055            .page(|| {
1056                let doc = Signal::new(StyledText::default());
1057                column((
1058                    label(move || format!("runs {}", doc.get().runs.len()))
1059                        .id(day_core::id!(texteditor::runs)),
1060                    text_editor(doc)
1061                        .highlight(highlighter(Language::Json, Palette::default(), false))
1062                        .min_lines(3)
1063                        .id(day_core::id!(texteditor::editor)),
1064                ))
1065            })
1066            .drive(|d: Drive| async move {
1067                d.input("texteditor::editor", "{\"a\": 1}").await?;
1068                // `{`, the key, `: `, the number, `}`: five runs over every byte.
1069                d.assert_text("texteditor::runs", "runs 5").await?;
1070                d.assert_native(
1071                    "texteditor::editor",
1072                    NativeExpect {
1073                        text: Some("{\"a\": 1}".into()),
1074                        ..Default::default()
1075                    },
1076                )
1077                .await
1078            })
1079    }
1080
1081    /// A single line: Enter submits and inserts nothing, and a newline that gets in becomes
1082    /// a space in the model and in the view.
1083    #[day_macros::test(day_core)]
1084    fn texteditor_single_line_submits() -> Case {
1085        Case::new()
1086            .proves(KIND)
1087            .page(|| {
1088                let text = Signal::new(String::new());
1089                let submits = Signal::new(0u32);
1090                column((
1091                    label(move || format!("submits {}", submits.get()))
1092                        .id(day_core::id!(texteditor::submits)),
1093                    super::text_editor_text(text)
1094                        .single_line()
1095                        .on_submit(move || submits.update(|n| *n += 1))
1096                        .id(day_core::id!(texteditor::editor)),
1097                ))
1098            })
1099            .drive(|d: Drive| async move {
1100                d.key(Some("texteditor::editor"), "Enter").await?;
1101                d.assert_text("texteditor::submits", "submits 1").await?;
1102                d.input("texteditor::editor", "a\nb").await?;
1103                d.assert_text("texteditor::editor", "a b").await?;
1104                d.assert_native(
1105                    "texteditor::editor",
1106                    NativeExpect {
1107                        text: Some("a b".into()),
1108                        ..Default::default()
1109                    },
1110                )
1111                .await
1112            })
1113    }
1114
1115    /// Code: Tab indents through the view's own insertion rather than leaving the editor.
1116    #[day_macros::test(day_core)]
1117    fn texteditor_code_tab_indents() -> Case {
1118        Case::new()
1119            .proves(KIND)
1120            .page(|| {
1121                let text = Signal::new(String::new());
1122                column((super::text_editor_text(text)
1123                    .code()
1124                    .indent(4)
1125                    .id(day_core::id!(texteditor::editor)),))
1126            })
1127            .drive(|d: Drive| async move {
1128                d.key(Some("texteditor::editor"), "Tab").await?;
1129                d.assert_text("texteditor::editor", "    ").await?;
1130                d.assert_native(
1131                    "texteditor::editor",
1132                    NativeExpect {
1133                        text: Some("    ".into()),
1134                        ..Default::default()
1135                    },
1136                )
1137                .await
1138            })
1139    }
1140
1141    /// Code: an opening bracket gets its closer after the caret, and Enter between the pair
1142    /// keeps the line's indentation one level deeper. Each character goes in through the
1143    /// view, so the rules run on the view's own report, as they do for a keystroke.
1144    #[day_macros::test(day_core)]
1145    fn texteditor_code_closes_and_indents() -> Case {
1146        Case::new()
1147            .proves(KIND)
1148            .page(|| {
1149                let text = Signal::new(String::new());
1150                column((super::text_editor_text(text)
1151                    .code()
1152                    .id(day_core::id!(texteditor::editor)),))
1153            })
1154            .drive(|d: Drive| async move {
1155                // Each key is two round trips through the view (the character, then what the
1156                // rule inserts), and on Android the view's report crosses JNI a turn later:
1157                // settle before reading.
1158                d.key(Some("texteditor::editor"), "{").await?;
1159                d.wait_idle().await?;
1160                d.assert_text("texteditor::editor", "{}").await?;
1161                d.key(Some("texteditor::editor"), "Enter").await?;
1162                d.wait_idle().await?;
1163                d.assert_text("texteditor::editor", "{\n  }").await?;
1164                d.assert_native(
1165                    "texteditor::editor",
1166                    NativeExpect {
1167                        text: Some("{\n  }".into()),
1168                        ..Default::default()
1169                    },
1170                )
1171                .await
1172            })
1173    }
1174}
1175
1176#[cfg(test)]
1177mod tests {
1178    use super::*;
1179
1180    #[test]
1181    fn a_single_line_gives_way_like_a_field_and_a_wrapping_editor_keeps_room() {
1182        // The band is what says "single line": `.single_line()` pins it to exactly one.
1183        assert_eq!(width_floor(1), 48.0);
1184        // Unbounded (0), the default band, and a capped multi-line editor all wrap.
1185        for max_lines in [0, 3, 12] {
1186            assert_eq!(width_floor(max_lines), 120.0, "max_lines {max_lines}");
1187        }
1188    }
1189
1190    #[test]
1191    fn diff_recovers_a_keystroke() {
1192        assert_eq!(diff_edit("hello", "hellXo"), (4, 0, 1));
1193        assert_eq!(diff_edit("hello", "hello!"), (5, 0, 1));
1194        assert_eq!(diff_edit("hello", "Xhello"), (0, 0, 1));
1195    }
1196
1197    #[test]
1198    fn diff_recovers_a_deletion_and_a_replacement() {
1199        assert_eq!(diff_edit("hello", "helo"), (3, 1, 0));
1200        assert_eq!(diff_edit("hello", "heLLo"), (2, 2, 2));
1201        assert_eq!(diff_edit("hello", ""), (0, 5, 0));
1202        assert_eq!(diff_edit("", "hi"), (0, 0, 2));
1203    }
1204
1205    #[test]
1206    fn diff_never_splits_a_character() {
1207        // "é" is two bytes; replacing it must not produce a range inside it.
1208        let (o, r, i) = diff_edit("café", "cafe");
1209        assert!("café".is_char_boundary(o) && "café".is_char_boundary(o + r));
1210        assert!("cafe".is_char_boundary(o + i));
1211        // An emoji swapped for another, both four bytes.
1212        let (o, r, i) = diff_edit("a😀b", "a😃b");
1213        assert!("a😀b".is_char_boundary(o) && "a😀b".is_char_boundary(o + r));
1214        assert!("a😃b".is_char_boundary(o + i));
1215    }
1216
1217    #[test]
1218    fn an_unchanged_string_is_an_empty_edit() {
1219        assert_eq!(diff_edit("hello", "hello"), (5, 0, 0));
1220    }
1221
1222    #[test]
1223    fn a_tab_reaches_the_next_stop() {
1224        assert_eq!(tab_indent("", 0, 2), "  ");
1225        assert_eq!(tab_indent("a", 1, 2), " ");
1226        assert_eq!(tab_indent("ab\ncd", 5, 4), "  ");
1227        assert_eq!(
1228            tab_indent("é", 2, 4),
1229            "   ",
1230            "columns are characters, not bytes"
1231        );
1232    }
1233
1234    #[test]
1235    fn enter_keeps_the_indentation_and_deepens_after_an_opener() {
1236        assert_eq!(auto_indent("  a\n", 3, 2), Some("  ".into()));
1237        assert_eq!(auto_indent("{\n", 1, 2), Some("  ".into()));
1238        assert_eq!(auto_indent("  [ \n", 4, 4), Some("      ".into()));
1239        assert_eq!(auto_indent("a\n", 1, 2), None);
1240        assert_eq!(
1241            auto_indent("x\n  y\n", 5, 2),
1242            Some("  ".into()),
1243            "the caret's own line"
1244        );
1245    }
1246
1247    #[test]
1248    fn an_opener_gets_a_closer_only_where_one_fits() {
1249        assert_eq!(closer_after("{", 0), Some("}"));
1250        assert_eq!(closer_after("a[ b", 1), Some("]"));
1251        assert_eq!(closer_after("f(x", 1), None, "inside a word");
1252        assert_eq!(closer_after("\"", 0), Some("\""));
1253        assert_eq!(closer_after("\"a\"", 2), None, "the second quote closes");
1254        assert_eq!(closer_after("x", 0), None);
1255    }
1256
1257    #[test]
1258    fn flattening_keeps_the_byte_length() {
1259        assert_eq!(flatten("a\r\nb\nc"), "a  b c");
1260        assert_eq!(flatten("é\n").len(), "é\n".len());
1261    }
1262
1263    #[test]
1264    fn selection_payload_round_trips() {
1265        assert_eq!(parse_selection(&selection_payload(3, 9)), Some(3..9));
1266        // Backwards drags arrive with end < start; the range comes back ordered.
1267        assert_eq!(parse_selection(&selection_payload(9, 3)), Some(3..9));
1268        assert_eq!(parse_selection("something else"), None);
1269        assert_eq!(parse_selection("sel 3"), None);
1270    }
1271
1272    #[test]
1273    fn offset_conversions_agree_on_astral_text() {
1274        let s = "a😀é b";
1275        let r = 1..(1 + '😀'.len_utf8());
1276        let (u16_start, u16_len) = utf16_range(s, &r).unwrap();
1277        assert_eq!(
1278            (u16_start, u16_len),
1279            (1, 2),
1280            "a surrogate pair is two units"
1281        );
1282        assert_eq!(byte_of_utf16(s, u16_start), 1);
1283        assert_eq!(byte_of_utf16(s, u16_start + u16_len), r.end);
1284        let (c_start, c_len) = char_range(s, &r).unwrap();
1285        assert_eq!((c_start, c_len), (1, 1), "and one character");
1286        assert_eq!(byte_of_char(s, c_start + c_len), r.end);
1287    }
1288}