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(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 // The selection the native view last reported, and the same echo guard `native_text` is:
448 // a caret move the user made must not be written back to the view it came from.
449 //
450 // Writing it back is not merely redundant. A `selectionchange` fires on every mouse-move
451 // of a drag, and re-setting the selection mid-drag re-anchors it; on the web
452 // (`removeAllRanges` + `addRange`) that visibly collapses the selection the user is in
453 // the middle of making, so a drag cannot select anything at all.
454 let native_sel: Rc<RefCell<Option<std::ops::Range<usize>>>> = Rc::new(RefCell::new(None));
455 // A selection Day wrote and has not yet heard echoed. The bridges deliver a view's
456 // reports on their own schedule, so the caret move an insertion caused can be reported
457 // AFTER the `SetSelection` that followed it was applied; until the write's echo arrives,
458 // such a report is stale and is ignored. A keystroke clears the wait, so an arm that
459 // never echoes a programmatic selection costs nothing past one report.
460 let pending_sel: Rc<RefCell<Option<std::ops::Range<usize>>>> = Rc::new(RefCell::new(None));
461 if let Some(sel) = selection {
462 let native_sel = native_sel.clone();
463 let pending_sel = pending_sel.clone();
464 bind_seeded(
465 0..0,
466 move || sel.get(),
467 move |r: &std::ops::Range<usize>| {
468 if native_sel.borrow().as_ref() == Some(r) {
469 return; // the echo of the view's own report
470 }
471 *pending_sel.borrow_mut() = Some(r.clone());
472 with_tree(|t| {
473 t.patch(node, Box::new(EditorPatch::SetSelection(r.clone())), false);
474 });
475 },
476 );
477 }
478 // What the next typed character takes, as Day last knew it. `None` when the app bound no
479 // typing style, which is what leaves plain inheritance in charge.
480 let typing_now: Rc<RefCell<Option<RunStyle>>> = Rc::new(RefCell::new(None));
481 if let Some(style) = typing {
482 let typing_now = typing_now.clone();
483 bind_seeded(
484 RunStyle::plain(base),
485 move || style.get(),
486 move |s: &RunStyle| {
487 // Recorded as well as patched. A native `typingAttributes` styles the
488 // keystroke, but Day's own attribute patch lands a moment later and would
489 // repaint it from the model, so the model has to learn the style too.
490 *typing_now.borrow_mut() = Some(s.clone());
491 with_tree(|t| {
492 t.patch(
493 node,
494 Box::new(EditorPatch::SetTypingStyle(s.clone())),
495 false,
496 );
497 });
498 },
499 );
500 }
501 {
502 let editable = editable.clone();
503 bind_seeded(
504 editable.get_untracked(),
505 move || editable.get(),
506 move |v: &bool| {
507 with_tree(|t| t.patch(node, Box::new(EditorPatch::SetEditable(*v)), false));
508 },
509 );
510 }
511
512 // Native edits → the signal.
513 let synthesized_against = native_text.clone();
514 let caret_after_closer = native_sel.clone();
515 let pending_after_closer = pending_sel.clone();
516 let pending_on_edit = pending_sel.clone();
517 // The text the closer's insertion will report, so `edited` can tell it from a keystroke.
518 let closer_text: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
519 let closer_text_on_edit = closer_text.clone();
520 let closer_text_on_sel = closer_text.clone();
521 let edited = move |new_text: &str| {
522 let old = native_text.borrow().clone();
523 if old == new_text {
524 // The echo of a patch Day just sent. Nothing changed, so nothing to write, which
525 // is what keeps `SetDocument` from looping.
526 return;
527 }
528 // The text moved on, so whatever selection write was outstanding is history,
529 // unless this is the closer's own insertion reporting back: the write that put the
530 // caret between the pair is still the one to wait for.
531 if closer_text_on_edit.borrow_mut().take().as_deref() != Some(new_text) {
532 *pending_on_edit.borrow_mut() = None;
533 }
534 let (offset, removed, inserted) = diff_edit(&old, new_text);
535 // What the view holds is the raw text; the model may take a flattened one below, and
536 // the difference is what makes the bind above paint the view with it.
537 *native_text.borrow_mut() = new_text.to_string();
538 // A single line: a newline that got in (a paste, a drop) becomes a space. Same byte
539 // length, so the edit's offsets hold.
540 let flattened;
541 let new_text = if single_line && new_text.contains(['\n', '\r']) {
542 flattened = flatten(new_text);
543 flattened.as_str()
544 } else {
545 new_text
546 };
547 with_tree(|t| t.set_probe_value(node, 0.0, new_text.to_string()));
548 let pending = typing_now.borrow().clone();
549 doc.update(|d| {
550 d.text = new_text.to_string();
551 // Inserted text inherits the run it landed in, which is what an editor does when
552 // nothing is pending, and what typing at the end of a bold word should do. A
553 // pending typing style then overrides exactly the new characters.
554 d.reflow(offset, removed, inserted);
555 if inserted > 0
556 && let Some(style) = &pending
557 {
558 d.apply(offset..offset + inserted, base, |s| *s = style.clone());
559 }
560 });
561 // Code mode, after one typed character: Enter keeps the indentation, an opener gets
562 // its closer. Both go through the view's own insertion (`Insert`), so undo sees them
563 // as typing, and the view reports them back through this same path.
564 if code && inserted == 1 && removed == 0 {
565 let typed = &new_text[offset..=offset];
566 if typed == "\n" {
567 if let Some(ws) = auto_indent(new_text, offset, indent) {
568 with_tree(|t| {
569 t.patch(
570 node,
571 Box::new(EditorPatch::Insert {
572 at: offset + 1,
573 text: ws,
574 }),
575 true,
576 );
577 });
578 }
579 } else if let Some(closer) = closer_after(new_text, offset) {
580 with_tree(|t| {
581 t.patch(
582 node,
583 Box::new(EditorPatch::Insert {
584 at: offset + 1,
585 text: closer.to_string(),
586 }),
587 true,
588 );
589 // Back between the pair: the insertion left the caret after the closer.
590 t.patch(
591 node,
592 Box::new(EditorPatch::SetSelection(offset + 1..offset + 1)),
593 false,
594 );
595 });
596 // Recorded here as well, and marked as the write awaiting its echo, so a
597 // report of the caret the insertion left after the closer cannot stand in
598 // for it, whichever order the bridge delivers them in.
599 *caret_after_closer.borrow_mut() = Some(offset + 1..offset + 1);
600 *pending_after_closer.borrow_mut() = Some(offset + 1..offset + 1);
601 *closer_text.borrow_mut() = Some(format!(
602 "{}{}{}",
603 &new_text[..=offset],
604 closer,
605 &new_text[offset + 1..]
606 ));
607 }
608 }
609 };
610 // A key one of the modes claimed, as an arm reports it (an `Event::Key`, or `key <name>`
611 // on the custom channel for the arm that has only that) and as a dayscript `key` step
612 // delivers it: Enter in a single line submits; Tab in code indents, through the view's
613 // own insertion at the caret the arm last reported.
614 let key_submit = on_submit.clone();
615 let key_sel = native_sel.clone();
616 let handle_key = move |key: &str, modifiers: u8| {
617 if single_line && key == "Enter" {
618 if let Some(f) = &key_submit {
619 f();
620 }
621 } else if modifiers == 0 {
622 // What goes in at the caret: Tab's indentation in code; and, from a dayscript
623 // `key` step only (no arm reports a printable key or an unclaimed Enter here),
624 // the character itself, or a newline in code, so a script can type one
625 // character through the view's own insertion and the editing rules above run
626 // on the view's report of it, as they do for a keystroke.
627 let text = doc.with_untracked(|d| d.text.clone());
628 let caret = key_sel
629 .borrow()
630 .as_ref()
631 .map_or(text.len(), |r| r.start.min(text.len()));
632 let insert = if code && key == "Tab" {
633 tab_indent(&text, caret, indent)
634 } else if code && key == "Enter" {
635 "\n".to_string()
636 } else if key.chars().count() == 1 {
637 key.to_string()
638 } else {
639 return;
640 };
641 with_tree(|t| {
642 t.patch(
643 node,
644 Box::new(EditorPatch::Insert {
645 at: caret,
646 text: insert,
647 }),
648 true,
649 );
650 });
651 }
652 };
653 cx.on(node, move |ev| match ev {
654 Event::TextChanged(new_text) => edited(new_text),
655 Event::Custom { tag, text, .. } if *tag == day_core::SYNTHESIZED_TEXT => {
656 // A dayscript `input` step: text the view has NOT seen, unlike a `TextChanged`.
657 // Written as the app would write it, so the bind above paints the view with a
658 // document patch; the `TextChanged` that follows is then the echo it ignores.
659 let new_text = if single_line {
660 flatten(text)
661 } else {
662 text.clone()
663 };
664 let old = synthesized_against.borrow().clone();
665 let (offset, removed, inserted) = diff_edit(&old, &new_text);
666 doc.update(|d| {
667 d.text = new_text;
668 d.reflow(offset, removed, inserted);
669 });
670 }
671 Event::Custom { text, .. } => {
672 // A backend whose piece channel carries only `Event::Custom` reports its text
673 // and its claimed keys here instead (HarmonyOS's ArkTS bridge is the one that
674 // must).
675 if let Some(new_text) = text.strip_prefix(TEXT_PREFIX) {
676 edited(new_text);
677 return;
678 }
679 if let Some(name) = text.strip_prefix(KEY_PREFIX) {
680 handle_key(name, 0);
681 return;
682 }
683 let Some(range) = parse_selection(text) else {
684 return;
685 };
686 // The caret's own style becomes the pending one, so a toolbar bound to it reads
687 // the text the caret sits in and typing continues that text's style. An app write
688 // lands the same way and wins until the caret moves again.
689 //
690 // `set_if_changed`, because this runs on every mouse-move of a drag: an unchanged
691 // style would patch the native typing attributes hundreds of times for nothing.
692 if let Some(style) = typing {
693 style.set_if_changed(doc.with_untracked(|d| d.style_of(range.clone(), base)));
694 }
695 // A report while a write of Day's own is outstanding: its echo ends the wait,
696 // anything else is the view's state from before the write and is dropped.
697 // Until the closer's own insertion has reported, every selection report is
698 // from before it (the bridges queue them), including one that happens to equal
699 // the write, as the caret after the opener does: dropped.
700 if closer_text_on_sel.borrow().is_some() {
701 return;
702 }
703 let outstanding = pending_sel.borrow().clone();
704 if let Some(wanted) = outstanding {
705 if wanted != range {
706 return;
707 }
708 *pending_sel.borrow_mut() = None;
709 }
710 // Recorded before the write, so the bind above sees it as an echo and sends no
711 // patch back to the view the report came from; and recorded whether or not the
712 // app bound the selection, since a Tab needs the caret.
713 *native_sel.borrow_mut() = Some(range.clone());
714 if let Some(sel) = selection {
715 sel.set_if_changed(range);
716 }
717 }
718 // A `submit` step, or Enter as an arm with a direct channel reports it.
719 Event::Submitted => {
720 if let Some(f) = &on_submit {
721 f();
722 }
723 }
724 Event::Key(k) => handle_key(&k.key, k.modifiers),
725 _ => {}
726 });
727 node
728 }
729}
730
731/// Recover a single contiguous edit from the old and new text: `(offset, removed, inserted)` in
732/// bytes.
733///
734/// The whole reason a keystroke does not need the backend's cooperation. A common prefix and a
735/// common suffix bracket exactly what changed, which for one keystroke, one deletion, one paste or
736/// one autocorrect is the edit. An edit that touched two separate places (a multi-cursor change)
737/// comes back as one span covering both: coarser, never wrong, and it costs only the styling
738/// between them.
739///
740/// Both ends are pulled back to character boundaries, so a multi-byte character that changed
741/// mid-sequence never produces a range that would split one.
742#[must_use]
743pub fn diff_edit(old: &str, new: &str) -> (usize, usize, usize) {
744 let (ob, nb) = (old.as_bytes(), new.as_bytes());
745 let max_prefix = ob.len().min(nb.len());
746 let mut prefix = 0usize;
747 while prefix < max_prefix && ob[prefix] == nb[prefix] {
748 prefix += 1;
749 }
750 while prefix > 0 && (!old.is_char_boundary(prefix) || !new.is_char_boundary(prefix)) {
751 prefix -= 1;
752 }
753 let mut suffix = 0usize;
754 while suffix < max_prefix - prefix && ob[ob.len() - 1 - suffix] == nb[nb.len() - 1 - suffix] {
755 suffix += 1;
756 }
757 while suffix > 0
758 && (!old.is_char_boundary(ob.len() - suffix) || !new.is_char_boundary(nb.len() - suffix))
759 {
760 suffix -= 1;
761 }
762 (
763 prefix,
764 ob.len() - suffix - prefix,
765 nb.len() - suffix - prefix,
766 )
767}
768
769// ---------------------------------------------------------------------------
770// The editing rules of the two modes, as pure functions over the text, so the mock proves them
771// and every arm shares them.
772// ---------------------------------------------------------------------------
773
774/// A single-line editor's text: every line break a space, byte for byte, so the offsets of an
775/// edit computed against the raw text still hold.
776#[must_use]
777pub fn flatten(text: &str) -> String {
778 text.chars()
779 .map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
780 .collect()
781}
782
783/// The spaces a Tab inserts at `caret`: to the next tab stop of width `indent`, counted in
784/// characters from the start of the caret's line.
785#[must_use]
786pub fn tab_indent(text: &str, caret: usize, indent: u8) -> String {
787 let caret = caret.min(text.len());
788 let line_start = text[..caret].rfind('\n').map_or(0, |i| i + 1);
789 let column = text[line_start..caret].chars().count();
790 let width = usize::from(indent.max(1));
791 " ".repeat(width - column % width)
792}
793
794/// The indentation a new line takes after Enter typed at `newline_at`: the previous line's
795/// leading whitespace, one level deeper when that line ends in an opening bracket. `None` when
796/// there is nothing to insert.
797#[must_use]
798pub fn auto_indent(text: &str, newline_at: usize, indent: u8) -> Option<String> {
799 let before = &text[..newline_at.min(text.len())];
800 let line_start = before.rfind('\n').map_or(0, |i| i + 1);
801 let line = &before[line_start..];
802 let mut ws: String = line
803 .chars()
804 .take_while(|c| *c == ' ' || *c == '\t')
805 .collect();
806 if matches!(line.trim_end().chars().last(), Some('{' | '[' | '(')) {
807 ws.push_str(&" ".repeat(usize::from(indent.max(1))));
808 }
809 (!ws.is_empty()).then_some(ws)
810}
811
812/// The closer to type after an opener typed at `at`, when the caret sits at the end of its line
813/// or before whitespace or another closer: `{` `[` `(` and the two quotes. `None` where a
814/// closer would land inside a word.
815#[must_use]
816pub fn closer_after(text: &str, at: usize) -> Option<&'static str> {
817 let opener = text[at..].chars().next()?;
818 let closer = match opener {
819 '{' => "}",
820 '[' => "]",
821 '(' => ")",
822 '"' => "\"",
823 '\'' => "'",
824 _ => return None,
825 };
826 let next = text[at + opener.len_utf8()..].chars().next();
827 let free = match next {
828 None => true,
829 Some(c) => c.is_whitespace() || matches!(c, '}' | ']' | ')' | ',' | ';'),
830 };
831 if !free {
832 return None;
833 }
834 // A quote closes an open quote rather than opening a new pair: an odd count before it on
835 // the line means this one is the closer.
836 if opener == '"' || opener == '\'' {
837 let line_start = text[..at].rfind('\n').map_or(0, |i| i + 1);
838 let open = text[line_start..at]
839 .chars()
840 .filter(|c| *c == opener)
841 .count();
842 if open % 2 == 1 {
843 return None;
844 }
845 }
846 Some(closer)
847}
848
849/// Decode a `"sel <start> <end>"` payload into a byte range.
850fn parse_selection(payload: &str) -> Option<std::ops::Range<usize>> {
851 let rest = payload.strip_prefix(SEL_PREFIX)?;
852 let (a, b) = rest.split_once(' ')?;
853 let (a, b) = (a.parse::<usize>().ok()?, b.parse::<usize>().ok()?);
854 Some(a.min(b)..a.max(b))
855}
856
857// ---------------------------------------------------------------------------
858// Offset conversion. Every arm speaks its toolkit's index unit and converts here, so the
859// arithmetic is written and tested once rather than eight times; an off-by-N here styles the
860// wrong words, and only in text with an emoji or a CJK character.
861// ---------------------------------------------------------------------------
862
863/// A byte range as a UTF-16 range (Apple, Android, XAML).
864#[must_use]
865pub fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<(usize, usize)> {
866 let start = text.get(..r.start)?.encode_utf16().count();
867 let len = text.get(r.clone())?.encode_utf16().count();
868 Some((start, len))
869}
870
871/// A UTF-16 offset back to a byte offset, clamped into the string.
872#[must_use]
873pub fn byte_of_utf16(text: &str, units: usize) -> usize {
874 let mut seen = 0usize;
875 for (i, c) in text.char_indices() {
876 if seen >= units {
877 return i;
878 }
879 seen += c.len_utf16();
880 }
881 text.len()
882}
883
884/// A byte range as a character range (GTK's `TextIter`, ArkUI's spans).
885#[must_use]
886pub fn char_range(text: &str, r: &std::ops::Range<usize>) -> Option<(usize, usize)> {
887 let start = text.get(..r.start)?.chars().count();
888 let len = text.get(r.clone())?.chars().count();
889 Some((start, len))
890}
891
892/// A character offset back to a byte offset, clamped into the string.
893#[must_use]
894pub fn byte_of_char(text: &str, chars: usize) -> usize {
895 text.char_indices()
896 .nth(chars)
897 .map_or(text.len(), |(i, _)| i)
898}
899
900/// The selection payload every arm emits.
901#[must_use]
902pub fn selection_payload(start: usize, end: usize) -> String {
903 format!("{SEL_PREFIX}{start} {end}")
904}
905
906/// The text payload for an arm that has only the custom channel; see [`TEXT_PREFIX`].
907#[must_use]
908pub fn text_payload(text: &str) -> String {
909 format!("{TEXT_PREFIX}{text}")
910}
911
912// ---------------------------------------------------------------------------
913// Per-toolkit native renderers, one file per backend.
914// ---------------------------------------------------------------------------
915
916day_pieces::glue_modules!(appkit, gtk, qt, uikit, material, xaml, arkui, dom);
917
918// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
919
920/// The styled editor's conformance cases (docs/testing.md).
921#[cfg(feature = "conformance")]
922pub mod conformance {
923 use day_core::conformance::{Case, Drive, NativeExpect};
924 use day_pieces::*;
925 use day_reactive::Signal;
926 use day_spec::Font;
927 use day_spec::styled::StyledText;
928
929 use super::{KIND, text_editor};
930
931 /// Typing reaches the bound document, and a document the app writes reaches the view.
932 #[day_macros::test(day_core)]
933 fn texteditor_text_two_way() -> Case {
934 Case::new()
935 .proves(KIND)
936 .page(|| {
937 let doc = Signal::new(StyledText::plain("Start"));
938 column((
939 label(move || format!("doc {}", doc.get().text))
940 .id(day_core::id!(texteditor::doc)),
941 button("Replace")
942 .action(move || doc.set(StyledText::markdown("**Bold** end", Font::Body)))
943 .id(day_core::id!(texteditor::replace)),
944 text_editor(doc)
945 .min_lines(3)
946 .id(day_core::id!(texteditor::editor)),
947 ))
948 })
949 .drive(|d: Drive| async move {
950 d.input("texteditor::editor", "Hello world").await?;
951 d.assert_text("texteditor::doc", "doc Hello world").await?;
952 d.tap("texteditor::replace").await?;
953 d.assert_text("texteditor::doc", "doc Bold end").await?;
954 d.assert_native(
955 "texteditor::editor",
956 NativeExpect {
957 text: Some("Bold end".into()),
958 ..Default::default()
959 },
960 )
961 .await
962 })
963 }
964
965 /// A live highlighter restyles what was typed without replacing it: the runs are fresh
966 /// (one per token and gap) and the native view still holds the characters as typed.
967 #[day_macros::test(day_core)]
968 fn texteditor_highlight_restyles_in_place() -> Case {
969 use super::highlight::{Language, Palette, highlighter};
970 Case::new()
971 .proves(KIND)
972 .page(|| {
973 let doc = Signal::new(StyledText::default());
974 column((
975 label(move || format!("runs {}", doc.get().runs.len()))
976 .id(day_core::id!(texteditor::runs)),
977 text_editor(doc)
978 .highlight(highlighter(Language::Json, Palette::default(), false))
979 .min_lines(3)
980 .id(day_core::id!(texteditor::editor)),
981 ))
982 })
983 .drive(|d: Drive| async move {
984 d.input("texteditor::editor", "{\"a\": 1}").await?;
985 // `{`, the key, `: `, the number, `}`: five runs over every byte.
986 d.assert_text("texteditor::runs", "runs 5").await?;
987 d.assert_native(
988 "texteditor::editor",
989 NativeExpect {
990 text: Some("{\"a\": 1}".into()),
991 ..Default::default()
992 },
993 )
994 .await
995 })
996 }
997
998 /// A single line: Enter submits and inserts nothing, and a newline that gets in becomes
999 /// a space in the model and in the view.
1000 #[day_macros::test(day_core)]
1001 fn texteditor_single_line_submits() -> Case {
1002 Case::new()
1003 .proves(KIND)
1004 .page(|| {
1005 let text = Signal::new(String::new());
1006 let submits = Signal::new(0u32);
1007 column((
1008 label(move || format!("submits {}", submits.get()))
1009 .id(day_core::id!(texteditor::submits)),
1010 super::text_editor_text(text)
1011 .single_line()
1012 .on_submit(move || submits.update(|n| *n += 1))
1013 .id(day_core::id!(texteditor::editor)),
1014 ))
1015 })
1016 .drive(|d: Drive| async move {
1017 d.key(Some("texteditor::editor"), "Enter").await?;
1018 d.assert_text("texteditor::submits", "submits 1").await?;
1019 d.input("texteditor::editor", "a\nb").await?;
1020 d.assert_text("texteditor::editor", "a b").await?;
1021 d.assert_native(
1022 "texteditor::editor",
1023 NativeExpect {
1024 text: Some("a b".into()),
1025 ..Default::default()
1026 },
1027 )
1028 .await
1029 })
1030 }
1031
1032 /// Code: Tab indents through the view's own insertion rather than leaving the editor.
1033 #[day_macros::test(day_core)]
1034 fn texteditor_code_tab_indents() -> Case {
1035 Case::new()
1036 .proves(KIND)
1037 .page(|| {
1038 let text = Signal::new(String::new());
1039 column((super::text_editor_text(text)
1040 .code()
1041 .indent(4)
1042 .id(day_core::id!(texteditor::editor)),))
1043 })
1044 .drive(|d: Drive| async move {
1045 d.key(Some("texteditor::editor"), "Tab").await?;
1046 d.assert_text("texteditor::editor", " ").await?;
1047 d.assert_native(
1048 "texteditor::editor",
1049 NativeExpect {
1050 text: Some(" ".into()),
1051 ..Default::default()
1052 },
1053 )
1054 .await
1055 })
1056 }
1057
1058 /// Code: an opening bracket gets its closer after the caret, and Enter between the pair
1059 /// keeps the line's indentation one level deeper. Each character goes in through the
1060 /// view, so the rules run on the view's own report, as they do for a keystroke.
1061 #[day_macros::test(day_core)]
1062 fn texteditor_code_closes_and_indents() -> Case {
1063 Case::new()
1064 .proves(KIND)
1065 .page(|| {
1066 let text = Signal::new(String::new());
1067 column((super::text_editor_text(text)
1068 .code()
1069 .id(day_core::id!(texteditor::editor)),))
1070 })
1071 .drive(|d: Drive| async move {
1072 // Each key is two round trips through the view (the character, then what the
1073 // rule inserts), and on Android the view's report crosses JNI a turn later:
1074 // settle before reading.
1075 d.key(Some("texteditor::editor"), "{").await?;
1076 d.wait_idle().await?;
1077 d.assert_text("texteditor::editor", "{}").await?;
1078 d.key(Some("texteditor::editor"), "Enter").await?;
1079 d.wait_idle().await?;
1080 d.assert_text("texteditor::editor", "{\n }").await?;
1081 d.assert_native(
1082 "texteditor::editor",
1083 NativeExpect {
1084 text: Some("{\n }".into()),
1085 ..Default::default()
1086 },
1087 )
1088 .await
1089 })
1090 }
1091}
1092
1093#[cfg(test)]
1094mod tests {
1095 use super::*;
1096
1097 #[test]
1098 fn a_single_line_gives_way_like_a_field_and_a_wrapping_editor_keeps_room() {
1099 // The band is what says "single line": `.single_line()` pins it to exactly one.
1100 assert_eq!(width_floor(1), 48.0);
1101 // Unbounded (0), the default band, and a capped multi-line editor all wrap.
1102 for max_lines in [0, 3, 12] {
1103 assert_eq!(width_floor(max_lines), 120.0, "max_lines {max_lines}");
1104 }
1105 }
1106
1107 #[test]
1108 fn diff_recovers_a_keystroke() {
1109 assert_eq!(diff_edit("hello", "hellXo"), (4, 0, 1));
1110 assert_eq!(diff_edit("hello", "hello!"), (5, 0, 1));
1111 assert_eq!(diff_edit("hello", "Xhello"), (0, 0, 1));
1112 }
1113
1114 #[test]
1115 fn diff_recovers_a_deletion_and_a_replacement() {
1116 assert_eq!(diff_edit("hello", "helo"), (3, 1, 0));
1117 assert_eq!(diff_edit("hello", "heLLo"), (2, 2, 2));
1118 assert_eq!(diff_edit("hello", ""), (0, 5, 0));
1119 assert_eq!(diff_edit("", "hi"), (0, 0, 2));
1120 }
1121
1122 #[test]
1123 fn diff_never_splits_a_character() {
1124 // "é" is two bytes; replacing it must not produce a range inside it.
1125 let (o, r, i) = diff_edit("café", "cafe");
1126 assert!("café".is_char_boundary(o) && "café".is_char_boundary(o + r));
1127 assert!("cafe".is_char_boundary(o + i));
1128 // An emoji swapped for another, both four bytes.
1129 let (o, r, i) = diff_edit("a😀b", "a😃b");
1130 assert!("a😀b".is_char_boundary(o) && "a😀b".is_char_boundary(o + r));
1131 assert!("a😃b".is_char_boundary(o + i));
1132 }
1133
1134 #[test]
1135 fn an_unchanged_string_is_an_empty_edit() {
1136 assert_eq!(diff_edit("hello", "hello"), (5, 0, 0));
1137 }
1138
1139 #[test]
1140 fn a_tab_reaches_the_next_stop() {
1141 assert_eq!(tab_indent("", 0, 2), " ");
1142 assert_eq!(tab_indent("a", 1, 2), " ");
1143 assert_eq!(tab_indent("ab\ncd", 5, 4), " ");
1144 assert_eq!(
1145 tab_indent("é", 2, 4),
1146 " ",
1147 "columns are characters, not bytes"
1148 );
1149 }
1150
1151 #[test]
1152 fn enter_keeps_the_indentation_and_deepens_after_an_opener() {
1153 assert_eq!(auto_indent(" a\n", 3, 2), Some(" ".into()));
1154 assert_eq!(auto_indent("{\n", 1, 2), Some(" ".into()));
1155 assert_eq!(auto_indent(" [ \n", 4, 4), Some(" ".into()));
1156 assert_eq!(auto_indent("a\n", 1, 2), None);
1157 assert_eq!(
1158 auto_indent("x\n y\n", 5, 2),
1159 Some(" ".into()),
1160 "the caret's own line"
1161 );
1162 }
1163
1164 #[test]
1165 fn an_opener_gets_a_closer_only_where_one_fits() {
1166 assert_eq!(closer_after("{", 0), Some("}"));
1167 assert_eq!(closer_after("a[ b", 1), Some("]"));
1168 assert_eq!(closer_after("f(x", 1), None, "inside a word");
1169 assert_eq!(closer_after("\"", 0), Some("\""));
1170 assert_eq!(closer_after("\"a\"", 2), None, "the second quote closes");
1171 assert_eq!(closer_after("x", 0), None);
1172 }
1173
1174 #[test]
1175 fn flattening_keeps_the_byte_length() {
1176 assert_eq!(flatten("a\r\nb\nc"), "a b c");
1177 assert_eq!(flatten("é\n").len(), "é\n".len());
1178 }
1179
1180 #[test]
1181 fn selection_payload_round_trips() {
1182 assert_eq!(parse_selection(&selection_payload(3, 9)), Some(3..9));
1183 // Backwards drags arrive with end < start; the range comes back ordered.
1184 assert_eq!(parse_selection(&selection_payload(9, 3)), Some(3..9));
1185 assert_eq!(parse_selection("something else"), None);
1186 assert_eq!(parse_selection("sel 3"), None);
1187 }
1188
1189 #[test]
1190 fn offset_conversions_agree_on_astral_text() {
1191 let s = "a😀é b";
1192 let r = 1..(1 + '😀'.len_utf8());
1193 let (u16_start, u16_len) = utf16_range(s, &r).unwrap();
1194 assert_eq!(
1195 (u16_start, u16_len),
1196 (1, 2),
1197 "a surrogate pair is two units"
1198 );
1199 assert_eq!(byte_of_utf16(s, u16_start), 1);
1200 assert_eq!(byte_of_utf16(s, u16_start + u16_len), r.end);
1201 let (c_start, c_len) = char_range(s, &r).unwrap();
1202 assert_eq!((c_start, c_len), (1, 1), "and one character");
1203 assert_eq!(byte_of_char(s, c_start + c_len), r.end);
1204 }
1205}