forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

editor.rs917 lines, 33.7 KiBHistoryRawDownload
1//! Editor state and the input pipeline.
2//!
3//! Every change goes through the model: a command (intercepted input, keys) or the
4//! read-back of text the browser typed natively (plain typing, IME, Android). The
5//! model's block splices drive `View::flush`, which patches the DOM; then the
6//! selection goes back.
7
8use loro::LoroDoc;
9use note_model::flat::Kind as Leaf;
10use note_model::write::Inline;
11use wasm_bindgen::JsCast;
12use web_sys::{CompositionEvent, HtmlElement, InputEvent, KeyboardEvent, MutationObserver, MutationRecord, Node as DomNode};
13
14use crate::core::commands::{self as c, Command, Cx};
15use crate::core::doc::Kind;
16use crate::core::history::History;
17use crate::core::marks::{MarkType, Marks};
18use crate::core::model::Model;
19use crate::core::pos::{self, Pos, SelAnchors, Selection};
20use crate::view::{RunKind, View};
21
22const ENTER: &[Command] = &[c::split_list_item, c::newline_in_code, c::create_paragraph_near, c::lift_empty_block, c::split_block];
23const BACKSPACE: &[Command] = &[c::delete_selection, c::join_backward, c::select_node_backward];
24const DELETE: &[Command] = &[c::delete_selection, c::join_forward, c::select_node_forward];
25
26/// A structural input the browser would not let us cancel (Android): run it after
27/// the DOM change is undone.
28#[derive(Clone, Copy)]
29enum Intent {
30 Enter,
31 Backspace,
32 Delete,
33 LineBreak,
34}
35
36/// Text the browser is typing natively into a run with these marks.
37#[derive(Clone)]
38struct Native {
39 block: usize,
40 marks: Marks,
41 /// The text node the browser types into, the caret offset in it, its length
42 /// before typing, the model offset and the typed text: enough to check the edit
43 /// without reading the whole block back.
44 node: DomNode,
45 at: u32,
46 len: u32,
47 off: Pos,
48 data: String,
49}
50
51pub struct Editor {
52 /// The model's doc (shared), for sync.
53 pub doc: LoroDoc,
54 pub m: Model,
55 pub history: History,
56 pub view: View,
57 pub sel: Selection,
58 pub stored: Option<Marks>,
59 pub observer: Option<MutationObserver>,
60 pub editable: bool,
61 native: Option<Native>,
62 composition_marks: Option<Marks>,
63 composition_end: f64,
64 intent: Option<Intent>,
65 is_mac: bool,
66 /// The placeholder text and the element showing it.
67 pub placeholder_text: String,
68 placeholder_el: Option<web_sys::Element>,
69 /// The element marked as the selected node.
70 selected_el: std::cell::RefCell<Option<web_sys::Element>>,
71 /// Doc state right after an input rule, and the text it replaced.
72 pub last_rule: Option<(loro::Frontiers, String)>,
73 /// Whether the browser's spellchecker is off (a huge note).
74 spell_off: bool,
75 /// Called after every change of doc or selection (toolbar, presence, status).
76 pub listeners: Vec<Box<dyn FnMut(&Editor, bool)>>,
77}
78
79fn now() -> f64 {
80 js_sys::Date::now()
81}
82
83impl Editor {
84 pub fn new(doc: LoroDoc, root: HtmlElement) -> Self {
85 let view = View::new(root);
86 let is_mac = web_sys::window()
87 .and_then(|w| w.navigator().platform().ok())
88 .is_some_and(|p| p.contains("Mac") || p.contains("iP"));
89 let m = Model::new(doc.clone());
90 Editor {
91 doc,
92 m,
93 history: History::default(),
94 view,
95 sel: Selection::caret(0),
96 stored: None,
97 observer: None,
98 editable: false,
99 native: None,
100 composition_marks: None,
101 composition_end: 0.0,
102 intent: None,
103 is_mac,
104 last_rule: None,
105 spell_off: false,
106 placeholder_text: String::new(),
107 placeholder_el: None,
108 selected_el: Default::default(),
109 listeners: Vec::new(),
110 }
111 }
112
113 pub fn cx(&self) -> Cx<'_> {
114 Cx { m: &self.m, sel: self.sel.clone(), stored: self.stored.clone() }
115 }
116
117 // -----------------------------------------------------------------------
118 // Change cycle
119 // -----------------------------------------------------------------------
120
121 /// Runs a command against the current selection and records it for undo.
122 pub fn run(&mut self, f: impl FnOnce(&mut Cx) -> bool) -> bool {
123 if self.m.is_empty() {
124 return false;
125 }
126 let before = self.sel.clone();
127 let mut cx = self.cx();
128 let ran = f(&mut cx);
129 let (sel, stored) = (cx.sel, cx.stored);
130 if ran {
131 self.m.commit();
132 self.history.push(&self.m, &before, &sel, now());
133 self.sel = sel;
134 self.stored = stored;
135 self.render(true);
136 } else {
137 self.m.take_ops();
138 }
139 ran
140 }
141
142 /// Sets (`Some`) or clears (`None`: detect it) the language of the code block at `off`.
143 pub fn set_code_language(&mut self, off: Pos, lang: Option<&str>) -> bool {
144 let b = self.m.at(off);
145 if b.kind() != Leaf::Code || b.attrs.lang.as_deref() == lang {
146 return false;
147 }
148 let start = b.start;
149 self.run(|cx| c::set_code_language(cx.m, start, lang))
150 }
151
152 /// Replaces the code of the block at `off` with `code`, editing only the part that
153 /// differs, so carets (ours and remote ones) stay where they were. Does nothing
154 /// unless the block still holds `expected`: the code may have changed while it was
155 /// formatted.
156 pub fn replace_code(&mut self, off: Pos, expected: &str, code: &str) -> bool {
157 let b = self.m.at(off);
158 if b.kind() != Leaf::Code || expected == code || self.m.plain(b.start, b.sep) != expected {
159 return false;
160 }
161 let before = self.sel.clone();
162 let anchors = SelAnchors::new(&self.m, &self.sel);
163 let (old, new): (Vec<u16>, Vec<u16>) = (expected.encode_utf16().collect(), code.encode_utf16().collect());
164 let mut p = old.iter().zip(&new).take_while(|(a, b)| a == b).count();
165 let max = old.len().min(new.len()) - p;
166 let mut s = old.iter().rev().zip(new.iter().rev()).take(max).take_while(|(a, b)| a == b).count();
167 // Never split a surrogate pair.
168 while p > 0 && is_low(old.get(p)) {
169 p -= 1;
170 }
171 while s > 0 && is_low(old.get(old.len() - s)) {
172 s -= 1;
173 }
174 let max = (old.len() - p).min(new.len() - p);
175 s = s.min(max);
176 let mid = String::from_utf16_lossy(&new[p..new.len() - s]);
177 self.m.delete(b.start + p, b.start + old.len() - s);
178 if !mid.is_empty() {
179 self.m.insert(b.start + p, &mid, &Marks::none());
180 }
181 self.sel = anchors.resolve(&self.m);
182 self.history.push(&self.m, &before, &self.sel, now());
183 self.history.checkpoint();
184 let focused = self.focused();
185 self.render(focused);
186 true
187 }
188
189 pub fn chain(&mut self, cmds: &[Command]) -> bool {
190 self.run(|cx| c::chain(cx, cmds, true))
191 }
192
193 /// Whether a command would apply now (toolbar state).
194 pub fn can(&self, f: impl FnOnce(&mut Cx) -> bool) -> bool {
195 if self.m.is_empty() {
196 return false;
197 }
198 let mut cx = self.cx();
199 f(&mut cx)
200 }
201
202 /// Flushes model changes to the DOM, then the selection.
203 pub fn render(&mut self, set_dom_sel: bool) {
204 let changed = self.view.flush(&self.m);
205 if changed {
206 self.drain_own_mutations();
207 self.placeholder();
208 self.spellcheck();
209 }
210 self.sel = pos::clamp(&self.m, &self.sel);
211 if set_dom_sel {
212 self.write_dom_selection();
213 }
214 self.notify(changed);
215 }
216
217 fn notify(&mut self, changed: bool) {
218 let mut ls = std::mem::take(&mut self.listeners);
219 for l in ls.iter_mut() {
220 l(self, changed);
221 }
222 ls.append(&mut self.listeners);
223 self.listeners = ls;
224 }
225
226 pub(crate) fn drain_own_mutations(&self) {
227 if let Some(o) = &self.observer {
228 o.take_records();
229 }
230 }
231
232 /// Applies remote updates; keeps the local selection anchored.
233 pub fn import(&mut self, bytes: &[u8]) -> loro::LoroResult<()> {
234 if !self.editable {
235 let r = self.m.import(bytes);
236 self.sel = Selection::caret(pos::snap(&self.m, 0));
237 return r;
238 }
239 let anchors = SelAnchors::new(&self.m, &self.sel);
240 self.m.import(bytes)?;
241 self.m.close_body();
242 self.sel = anchors.resolve(&self.m);
243 let focused = self.focused();
244 self.render(focused);
245 Ok(())
246 }
247
248 /// Turns the pre-rendered page into the live editor.
249 pub fn make_editable(&mut self) {
250 if self.editable {
251 return;
252 }
253 self.m.close_body();
254 self.m.take_ops();
255 self.view.render_all(&self.m);
256 self.drain_own_mutations();
257 self.placeholder();
258 // Before the root is editable, so the spellchecker never starts on a huge note.
259 self.spellcheck();
260 let _ = self.view.root.set_attribute("contenteditable", "true");
261 self.editable = true;
262 self.sel = Selection::caret(pos::snap(&self.m, 0));
263 self.notify(true);
264 }
265
266 /// The `is-placeholder` hint while the note is one empty paragraph.
267 /// Turns the spellchecker off for a huge note: it rechecks moved text in idle
268 /// tasks that held the main thread for 70 ms after Enter in a 55 MB paragraph,
269 /// and checking megabytes of text helps nobody.
270 fn spellcheck(&mut self) {
271 const SPELL_MAX: usize = 1 << 20;
272 let off = self.m.total() > SPELL_MAX;
273 if off != self.spell_off {
274 self.spell_off = off;
275 self.view.root.set_spellcheck(!off);
276 }
277 }
278
279 fn placeholder(&mut self) {
280 let target = (self.m.len() == 1)
281 .then(|| self.m.block(0))
282 .flatten()
283 .filter(|b| b.kind() == Leaf::Para && b.is_empty() && b.depth() == 0)
284 .and_then(|_| self.view.element(0).cloned());
285 if target == self.placeholder_el {
286 return;
287 }
288 if let Some(old) = self.placeholder_el.take() {
289 let _ = old.class_list().remove_1("is-placeholder");
290 let _ = old.remove_attribute("data-placeholder");
291 }
292 if let Some(el) = &target {
293 let _ = el.class_list().add_1("is-placeholder");
294 let _ = el.set_attribute("data-placeholder", &self.placeholder_text);
295 }
296 self.placeholder_el = target;
297 }
298
299 pub fn undo(&mut self) -> bool {
300 self.history(true)
301 }
302
303 pub fn redo(&mut self) -> bool {
304 self.history(false)
305 }
306
307 fn history(&mut self, undo: bool) -> bool {
308 let sel = if undo { self.history.undo(&self.m) } else { self.history.redo(&self.m) };
309 let Some(sel) = sel else { return false };
310 self.sel = sel;
311 self.stored = None;
312 self.render(true);
313 true
314 }
315
316 pub fn can_undo(&self) -> bool {
317 self.history.can_undo()
318 }
319
320 pub fn can_redo(&self) -> bool {
321 self.history.can_redo()
322 }
323
324 // -----------------------------------------------------------------------
325 // DOM selection
326 // -----------------------------------------------------------------------
327
328 pub fn focused(&self) -> bool {
329 let doc = self.view.root.owner_document().unwrap();
330 doc.active_element().is_some_and(|a| self.view.root.contains(Some(&a)))
331 }
332
333 /// Reads the DOM selection into the model. Returns false when it is outside.
334 pub fn read_dom_selection(&mut self) -> bool {
335 let Some(ds) = web_sys::window().and_then(|w| w.get_selection().ok().flatten()) else { return false };
336 let (Some(an), Some(fo)) = (ds.anchor_node(), ds.focus_node()) else { return false };
337 let root: &DomNode = self.view.root.as_ref();
338 if !root.contains(Some(&an)) || !root.contains(Some(&fo)) {
339 return false;
340 }
341 if let Selection::Node(_) | Selection::All = self.sel {
342 // Kept while the DOM selection is the one we set for it.
343 if !ds.is_collapsed() {
344 return true;
345 }
346 }
347 let a = self.view.dom_to_pos(&self.m, &an, ds.anchor_offset());
348 let f = self.view.dom_to_pos(&self.m, &fo, ds.focus_offset());
349 if let (Some(anchor), Some(head)) = (a, f) {
350 let sel = pos::clamp(&self.m, &Selection::Text { anchor, head });
351 if sel != self.sel {
352 self.sel = sel;
353 self.stored = None;
354 }
355 }
356 true
357 }
358
359 /// Puts the model selection into the DOM if it differs.
360 pub fn write_dom_selection(&mut self) {
361 match self.sel {
362 Selection::Text { anchor, head } => {
363 self.view.show(&self.m, self.m.at(anchor).index);
364 self.view.show(&self.m, self.m.at(head).index);
365 self.view.ensure_live(&self.m, &[anchor, head]);
366 }
367 Selection::Node(p) => self.view.show(&self.m, self.m.at(p).index),
368 _ => {}
369 }
370 self.drain_own_mutations();
371 let Some(ds) = web_sys::window().and_then(|w| w.get_selection().ok().flatten()) else { return };
372 if let Some(old) = self.selected_el.borrow_mut().take() {
373 let _ = old.class_list().remove_1("ProseMirror-selectednode");
374 }
375 match self.sel {
376 Selection::Text { anchor, head } => {
377 let (Some((an, ao)), Some((fo, foo))) = (self.view.pos_to_dom(&self.m, anchor), self.view.pos_to_dom(&self.m, head)) else { return };
378 let same = ds.anchor_node().as_ref() == Some(&an)
379 && ds.anchor_offset() == ao
380 && ds.focus_node().as_ref() == Some(&fo)
381 && ds.focus_offset() == foo;
382 if !same {
383 let _ = ds.set_base_and_extent(&an, ao, &fo, foo);
384 }
385 }
386 Selection::Node(p) => {
387 if let Some(el) = self.node_element(p) {
388 let _ = el.class_list().add_1("ProseMirror-selectednode");
389 *self.selected_el.borrow_mut() = Some(el.clone());
390 if let Some(parent) = el.parent_node() {
391 let i = index_in(&parent, &el);
392 let _ = ds.set_base_and_extent(&parent, i, &parent, i + 1);
393 }
394 }
395 }
396 Selection::All => {
397 let root: &DomNode = self.view.root.as_ref();
398 let _ = ds.set_base_and_extent(root, 0, root, root.child_nodes().length());
399 }
400 Selection::Gap(_) => {}
401 }
402 }
403
404 /// The element of a selected node: a rule, or the image at `p`.
405 pub fn node_element(&self, p: Pos) -> Option<web_sys::Element> {
406 let b = self.m.at(p);
407 let v = self.view.bview(b.index)?;
408 if b.kind() == Leaf::Rule {
409 return Some(v.el.clone());
410 }
411 let mut acc = b.start;
412 for r in &v.runs {
413 if acc == p && matches!(r.kind, RunKind::Image { .. }) {
414 return r.dom.clone().dyn_into().ok();
415 }
416 acc += r.len;
417 }
418 None
419 }
420
421 /// A click on a rule or image selects it as a node.
422 pub fn on_mousedown(&mut self, ev: &web_sys::MouseEvent) {
423 if !self.editable || ev.button() != 0 {
424 return;
425 }
426 let Some(target) = ev.target().and_then(|t| t.dyn_into::<web_sys::Element>().ok()) else { return };
427 let p = match target.tag_name().as_str() {
428 "HR" => self.view.owner(&target).and_then(|(i, _)| self.m.block(i)).map(|b| b.start),
429 "IMG" => target.parent_node().and_then(|parent| {
430 let i = index_in(&parent, &target);
431 self.view.dom_to_pos(&self.m, &parent, i)
432 }),
433 _ => return,
434 };
435 let Some(p) = p else { return };
436 ev.prevent_default();
437 let _ = self.view.root.focus();
438 self.sel = Selection::Node(p);
439 self.stored = None;
440 self.write_dom_selection();
441 self.notify(false);
442 }
443
444 pub fn on_selection_change(&mut self) {
445 if self.view.composing.is_some() || !self.editable {
446 return;
447 }
448 if self.read_dom_selection() {
449 self.notify(false);
450 }
451 }
452
453 // -----------------------------------------------------------------------
454 // Input
455 // -----------------------------------------------------------------------
456
457 pub fn on_beforeinput(&mut self, ev: &InputEvent) {
458 if !self.editable {
459 ev.prevent_default();
460 return;
461 }
462 let kind = ev.input_type();
463 if kind.contains("Composition") {
464 return;
465 }
466 self.read_dom_selection();
467 let cancel = ev.cancelable();
468 match kind.as_str() {
469 "insertText" => {
470 let data = ev.data().unwrap_or_default();
471 if let Some(native) = self.native_insert(&data) {
472 self.native = Some(native);
473 return;
474 }
475 ev.prevent_default();
476 self.type_text(&data);
477 }
478 "insertReplacementText" => {
479 ev.prevent_default();
480 let text = ev
481 .data_transfer()
482 .and_then(|d| d.get_data("text/plain").ok())
483 .or_else(|| ev.data())
484 .unwrap_or_default();
485 if let Some((from, to)) = self.target_range(ev) {
486 self.sel = Selection::Text { anchor: from, head: to };
487 }
488 self.run(|cx| c::insert_text(cx, &text));
489 }
490 "insertParagraph" => self.structural(ev, cancel, Intent::Enter),
491 "insertLineBreak" => self.structural(ev, cancel, Intent::LineBreak),
492 k if k.starts_with("delete") => {
493 let back = k.contains("Backward");
494 let intent = if back { Intent::Backspace } else { Intent::Delete };
495 if !cancel {
496 self.intent = Some(intent);
497 return;
498 }
499 ev.prevent_default();
500 if !self.sel.is_empty() {
501 self.chain(BACKSPACE);
502 return;
503 }
504 match self.target_range(ev) {
505 Some((from, to)) if from != to && self.m.at(from).index == self.m.at(to).index => {
506 self.run(|cx| {
507 cx.sel = Selection::Text { anchor: from, head: to };
508 c::delete_selection(cx, true)
509 });
510 }
511 _ => self.delete_char(back),
512 }
513 }
514 "historyUndo" => {
515 ev.prevent_default();
516 self.undo();
517 }
518 "historyRedo" => {
519 ev.prevent_default();
520 self.redo();
521 }
522 "formatBold" => {
523 ev.prevent_default();
524 self.run(|cx| c::toggle_mark(cx, MarkType::Strong, true));
525 }
526 "formatItalic" => {
527 ev.prevent_default();
528 self.run(|cx| c::toggle_mark(cx, MarkType::Em, true));
529 }
530 // Paste and drop are handled by their own events.
531 _ => ev.prevent_default(),
532 }
533 }
534
535 fn structural(&mut self, ev: &InputEvent, cancel: bool, intent: Intent) {
536 if !cancel {
537 self.intent = Some(intent);
538 return;
539 }
540 ev.prevent_default();
541 self.run_intent(intent);
542 }
543
544 fn run_intent(&mut self, intent: Intent) {
545 match intent {
546 Intent::Enter => {
547 self.chain(ENTER);
548 }
549 Intent::Backspace => self.delete_char(true),
550 Intent::Delete => self.delete_char(false),
551 Intent::LineBreak => {
552 self.run(|cx| {
553 let code = cx.sel.cursor().is_some_and(|p| cx.m.at(p).kind() == Leaf::Code);
554 if code { c::insert_text(cx, "\n") } else { c::insert_inline(cx, &[Inline::HardBreak]) }
555 });
556 }
557 }
558 }
559
560 /// One character (surrogate pair aware) backward or forward, else the structural chain.
561 fn delete_char(&mut self, back: bool) {
562 if self.chain(if back { BACKSPACE } else { DELETE }) {
563 return;
564 }
565 let Some(p) = self.sel.cursor() else { return };
566 let b = self.m.at(p);
567 let u = self.m.to_u(p);
568 let (from, to) = if back {
569 if p <= b.start {
570 return;
571 }
572 (self.m.to16(u - 1).max(b.start), p)
573 } else {
574 if p >= b.sep {
575 return;
576 }
577 (p, self.m.to16(u + 1).min(b.sep))
578 };
579 if from == to {
580 return;
581 }
582 self.run(|cx| {
583 cx.sel = Selection::Text { anchor: from, head: to };
584 c::delete_selection(cx, true)
585 });
586 }
587
588 /// The first target range of an input event, in model offsets, in order.
589 fn target_range(&self, ev: &InputEvent) -> Option<(Pos, Pos)> {
590 let ranges = ev.get_target_ranges();
591 let r: web_sys::StaticRange = ranges.get(0).dyn_into().ok()?;
592 let a = self.view.dom_to_pos(&self.m, &r.start_container(), r.start_offset())?;
593 let b = self.view.dom_to_pos(&self.m, &r.end_container(), r.end_offset())?;
594 Some((a.min(b), a.max(b)))
595 }
596
597 /// Typed text that is not left to the browser.
598 pub fn type_text(&mut self, data: &str) {
599 if crate::rules::apply(self, data) {
600 return;
601 }
602 self.run(|cx| c::insert_text(cx, data));
603 }
604
605 /// Ends undo merging, so the next change is its own undo step.
606 pub fn checkpoint(&mut self) {
607 self.history.checkpoint();
608 }
609
610 /// Whether the browser may type `data` itself: a collapsed caret inside one of our
611 /// text nodes whose marks are exactly the marks the text should get.
612 fn native_insert(&self, data: &str) -> Option<Native> {
613 if data.is_empty() || data.contains('\n') {
614 return None;
615 }
616 let p = self.sel.cursor()?;
617 let b = self.m.at(p);
618 if !b.kind().is_text() {
619 return None;
620 }
621 let ds = web_sys::window()?.get_selection().ok()??;
622 let an = ds.anchor_node()?;
623 if an.node_type() != DomNode::TEXT_NODE || !ds.is_collapsed() {
624 return None;
625 }
626 let v = self.view.bview(b.index)?;
627 let run = v.runs.iter().find(|r| r.text.as_ref().is_some_and(|t| ***t == an))?;
628 let marks = c::pending_marks(&self.cx());
629 if Marks::from(&run.marks) != marks {
630 return None;
631 }
632 if b.kind() != Leaf::Code && crate::rules::may_trigger(data) {
633 return None;
634 }
635 let len = an.unchecked_ref::<web_sys::CharacterData>().length();
636 Some(Native { block: b.index, marks, at: ds.anchor_offset(), len, off: p, data: data.to_owned(), node: an })
637 }
638
639 pub fn on_input(&mut self) {
640 let records = self.observer.as_ref().map(|o| o.take_records()).unwrap_or_default();
641 self.on_mutations(&records.iter().filter_map(|r| r.dyn_into::<MutationRecord>().ok()).collect::<Vec<_>>());
642 }
643
644 /// Reconciles DOM changes the browser made with the model.
645 pub fn on_mutations(&mut self, records: &[MutationRecord]) {
646 if self.view.composing.is_some() || !self.editable {
647 return;
648 }
649 let mut blocks: Vec<usize> = Vec::new();
650 let mut containers: Vec<DomNode> = Vec::new();
651 for r in records {
652 let Some(target) = r.target() else { continue };
653 match self.view.owner(&target) {
654 Some((i, _)) => {
655 if !blocks.contains(&i) {
656 blocks.push(i);
657 }
658 }
659 None => containers.push(target),
660 }
661 }
662 if let Some(n) = &self.native
663 && !blocks.contains(&n.block)
664 {
665 blocks.push(n.block);
666 }
667 if let Some(intent) = self.intent.take() {
668 for &i in &blocks {
669 self.view.repair(&self.m, i);
670 }
671 for n in &containers {
672 self.view.repair_page_of(&self.m, n);
673 }
674 self.drain_own_mutations();
675 self.write_dom_selection();
676 self.run_intent(intent);
677 return;
678 }
679 if blocks.is_empty() && containers.is_empty() {
680 return;
681 }
682 let before = self.sel.clone();
683 let mut changed = false;
684 let native = self.native.take();
685 for &i in &blocks {
686 let fast = native.as_ref().is_some_and(|n| n.block == i && self.typed_natively(n, records));
687 if !fast {
688 self.native = native.clone();
689 }
690 changed |= fast || self.read_back(i);
691 }
692 self.native = None;
693 // The browser's caret is where the text went.
694 self.read_dom_selection();
695 if changed {
696 self.history.push(&self.m, &before, &self.sel, now());
697 }
698 self.view.flush(&self.m);
699 let mut repaired = false;
700 for &i in &blocks {
701 if !self.view.intact(i) {
702 self.view.repair(&self.m, i);
703 repaired = true;
704 }
705 }
706 for n in &containers {
707 if n.is_connected() || self.view.root.contains(Some(n)) {
708 self.view.repair_page_of(&self.m, n);
709 repaired = true;
710 }
711 }
712 self.drain_own_mutations();
713 self.placeholder();
714 self.sel = pos::clamp(&self.m, &self.sel);
715 if repaired {
716 self.write_dom_selection();
717 }
718 self.notify(changed);
719 }
720
721 /// The browser typed exactly `n.data` at the caret and nothing else: applies it to
722 /// the model without reading the block back. False when the DOM shows anything else.
723 fn typed_natively(&mut self, n: &Native, records: &[MutationRecord]) -> bool {
724 let only_text = records.iter().all(|r| r.type_() == "characterData" && r.target().as_ref() == Some(&n.node));
725 let t: &web_sys::CharacterData = n.node.unchecked_ref();
726 let len16 = n.data.encode_utf16().count() as u32;
727 if !only_text || t.length() != n.len + len16 || t.substring_data(n.at, len16).ok().as_deref() != Some(n.data.as_str()) {
728 return false;
729 }
730 if !self.view.typed(n.block, &n.node, n.at as usize, &n.data) {
731 return false;
732 }
733 self.m.insert(n.off, &n.data, &n.marks);
734 true
735 }
736
737 /// Applies the difference between a block's DOM text and the model as one
738 /// replacement. Returns whether the model changed.
739 fn read_back(&mut self, i: usize) -> bool {
740 let Some(b) = self.m.block(i) else { return false };
741 if !b.kind().is_text() {
742 return false;
743 }
744 let Some(dom) = self.view.dom_text(i) else { return false };
745 let model: Vec<u16> = self.m.plain(b.start, b.sep).encode_utf16().collect();
746 if dom == model {
747 return false;
748 }
749 // The browser changed the DOM: the run caches follow it before the model does.
750 self.view.resync(i);
751 let mut p = 0;
752 while p < dom.len() && p < model.len() && dom[p] == model[p] {
753 p += 1;
754 }
755 let mut s = 0;
756 while s < dom.len() - p && s < model.len() - p && dom[dom.len() - 1 - s] == model[model.len() - 1 - s] {
757 s += 1;
758 }
759 // Do not split a surrogate pair.
760 if p > 0 && is_low(model.get(p)) {
761 p -= 1;
762 }
763 let inserted = &dom[p..dom.len() - s];
764 if inserted.contains(&0xfffc) {
765 // The browser made an element we did not ask for; the model wins.
766 self.view.repair(&self.m, i);
767 return false;
768 }
769 let marks = match (&self.native, &self.composition_marks) {
770 (Some(n), _) if n.block == i => n.marks.clone(),
771 (_, Some(mk)) => mk.clone(),
772 _ if b.kind() == Leaf::Code => Marks::none(),
773 _ => c::marks_at(&self.m, b.start + p),
774 };
775 let text = String::from_utf16_lossy(inserted);
776 self.m.delete(b.start + p, b.start + model.len() - s);
777 if !text.is_empty() {
778 self.m.insert(b.start + p, &text, &marks);
779 }
780 true
781 }
782
783 pub fn on_composition_start(&mut self, _ev: &CompositionEvent) {
784 self.read_dom_selection();
785 if let Selection::Text { anchor, head } = self.sel
786 && self.m.at(anchor).index != self.m.at(head).index
787 {
788 self.chain(&[c::delete_selection]);
789 }
790 self.composition_marks = Some(c::pending_marks(&self.cx()));
791 self.view.composing = match self.sel {
792 Selection::Text { head, .. } => Some(self.m.at(head).index),
793 _ => None,
794 };
795 }
796
797 pub fn on_composition_end(&mut self, _ev: &CompositionEvent) {
798 let block = self.view.composing.take();
799 let deferred = self.view.take_deferred();
800 let records = self.observer.as_ref().map(|o| o.take_records()).unwrap_or_default();
801 let mut recs: Vec<MutationRecord> = records.iter().filter_map(|r| r.dyn_into().ok()).collect();
802 recs.retain(|r| r.target().is_some());
803 let before = self.sel.clone();
804 let mut changed = false;
805 if let Some(i) = block {
806 changed = self.read_back(i);
807 }
808 self.composition_marks = None;
809 self.read_dom_selection();
810 if changed {
811 self.history.push(&self.m, &before, &self.sel, now());
812 }
813 self.view.flush(&self.m);
814 if let Some(i) = block
815 && (deferred || !self.view.intact(i))
816 {
817 self.view.repair(&self.m, i);
818 self.write_dom_selection();
819 }
820 self.drain_own_mutations();
821 self.placeholder();
822 self.composition_end = now();
823 self.notify(changed);
824 // Mutations outside the composed block still need handling.
825 if !recs.is_empty() {
826 self.on_mutations(&recs);
827 }
828 }
829
830 // -----------------------------------------------------------------------
831 // Keys
832 // -----------------------------------------------------------------------
833
834 pub fn on_keydown(&mut self, ev: &KeyboardEvent) -> bool {
835 if ev.is_composing() || ev.key_code() == 229 {
836 return false;
837 }
838 let key = ev.key();
839 // Safari sends Enter right after compositionend for the commit key.
840 if key == "Enter" && now() - self.composition_end < 500.0 {
841 ev.prevent_default();
842 return true;
843 }
844 if !self.editable {
845 return false;
846 }
847 self.read_dom_selection();
848 let m = if self.is_mac { ev.meta_key() } else { ev.ctrl_key() };
849 let (shift, alt) = (ev.shift_key(), ev.alt_key());
850 let lower = key.to_lowercase();
851 let handled = match (m, shift, alt, lower.as_str()) {
852 (false, false, false, "enter") => self.chain(ENTER),
853 (true, false, false, "enter") => self.run(|cx| c::exit_code(cx, true)),
854 (false, false, false, "backspace") => crate::rules::undo_rule(self) || self.can(|cx| c::chain(cx, BACKSPACE, false)) && self.chain(BACKSPACE),
855 (false, false, false, "delete") => self.can(|cx| c::chain(cx, DELETE, false)) && self.chain(DELETE),
856 (true, false, false, "a") => self.run(|cx| c::select_all(cx, true)),
857 (true, false, false, "k") if self.can(|cx| c::can_link(cx)) => {
858 crate::ui::request_link(&self.view.root);
859 true
860 }
861 (false, false, false, "tab") => {
862 self.run(|cx| c::sink_list_item(cx, true));
863 // Tab never leaves the editor.
864 true
865 }
866 (false, true, false, "tab") => {
867 self.run(|cx| c::lift_list_item(cx, true));
868 true
869 }
870 (true, false, false, "z") => {
871 self.undo();
872 true
873 }
874 (true, false, false, "y") | (true, true, false, "z") => {
875 self.redo();
876 true
877 }
878 (true, false, false, "b") => self.run(|cx| c::toggle_mark(cx, MarkType::Strong, true)),
879 (true, false, false, "i") => self.run(|cx| c::toggle_mark(cx, MarkType::Em, true)),
880 (true, false, false, "`") | (true, false, false, "e") => self.run(|cx| c::toggle_mark(cx, MarkType::Code, true)),
881 (true, false, true, "0") => self.run(|cx| c::set_block_type(cx, Kind::Paragraph, true)),
882 (true, false, true, d @ ("1" | "2" | "3")) => {
883 let level = d.parse::<u8>().unwrap();
884 self.run(|cx| c::toggle_block(cx, Kind::Heading(level), true))
885 }
886 (true, true, false, "8" | "*") => self.run(|cx| c::toggle_list(cx, Kind::BulletList, true)),
887 (true, true, false, "9" | "(") => self.run(|cx| c::toggle_list(cx, Kind::OrderedList, true)),
888 _ => false,
889 };
890 // Ctrl-Alt digits arrive as `key` = the shifted symbol on some layouts.
891 let handled = handled || (m && alt && self.heading_by_code(&ev.code()));
892 if handled {
893 ev.prevent_default();
894 }
895 handled
896 }
897
898 fn heading_by_code(&mut self, code: &str) -> bool {
899 match code {
900 "Digit0" => self.run(|cx| c::set_block_type(cx, Kind::Paragraph, true)),
901 "Digit1" | "Digit2" | "Digit3" => {
902 let level = code[5..].parse::<u8>().unwrap();
903 self.run(|cx| c::toggle_block(cx, Kind::Heading(level), true))
904 }
905 _ => false,
906 }
907 }
908}
909
910fn is_low(u: Option<&u16>) -> bool {
911 u.is_some_and(|u| (0xdc00..0xe000).contains(u))
912}
913
914fn index_in(parent: &DomNode, child: &DomNode) -> u32 {
915 let kids = parent.child_nodes();
916 (0..kids.length()).find(|&i| kids.get(i).as_ref() == Some(child)).unwrap_or(0)
917}