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