//! Editor state and the input pipeline. //! //! Every change goes through the model: a command (intercepted input, keys) or the //! read-back of text the browser typed natively (plain typing, IME, Android). The //! model's block splices drive `View::flush`, which patches the DOM; then the //! selection goes back. use loro::LoroDoc; use note_model::flat::Kind as Leaf; use note_model::write::Inline; use wasm_bindgen::JsCast; use web_sys::{CompositionEvent, HtmlElement, InputEvent, KeyboardEvent, MutationObserver, MutationRecord, Node as DomNode}; use crate::core::commands::{self as c, Command, Cx}; use crate::core::doc::Kind; use crate::core::history::History; use crate::core::marks::{MarkType, Marks}; use crate::core::model::Model; use crate::core::pos::{self, Pos, SelAnchors, Selection}; use crate::view::{RunKind, View}; const ENTER: &[Command] = &[c::split_list_item, c::newline_in_code, c::create_paragraph_near, c::lift_empty_block, c::split_block]; const BACKSPACE: &[Command] = &[c::delete_selection, c::join_backward, c::select_node_backward]; const DELETE: &[Command] = &[c::delete_selection, c::join_forward, c::select_node_forward]; /// A structural input the browser would not let us cancel (Android): run it after /// the DOM change is undone. #[derive(Clone, Copy)] enum Intent { Enter, Backspace, Delete, LineBreak, } /// Text the browser is typing natively into a run with these marks. #[derive(Clone)] struct Native { block: usize, marks: Marks, /// The text node the browser types into, the caret offset in it, its length /// before typing, the model offset and the typed text: enough to check the edit /// without reading the whole block back. node: DomNode, at: u32, len: u32, off: Pos, data: String, } pub struct Editor { /// The model's doc (shared), for sync. pub doc: LoroDoc, pub m: Model, pub history: History, pub view: View, pub sel: Selection, pub stored: Option, pub observer: Option, pub editable: bool, native: Option, composition_marks: Option, composition_end: f64, intent: Option, is_mac: bool, /// The placeholder text and the element showing it. pub placeholder_text: String, placeholder_el: Option, /// The element marked as the selected node. selected_el: std::cell::RefCell>, /// Doc state right after an input rule, and the text it replaced. pub last_rule: Option<(loro::Frontiers, String)>, /// Whether the browser's spellchecker is off (a huge note). spell_off: bool, /// Called after every change of doc or selection (toolbar, presence, status). pub listeners: Vec>, } fn now() -> f64 { js_sys::Date::now() } impl Editor { pub fn new(doc: LoroDoc, root: HtmlElement) -> Self { let view = View::new(root); let is_mac = web_sys::window() .and_then(|w| w.navigator().platform().ok()) .is_some_and(|p| p.contains("Mac") || p.contains("iP")); let m = Model::new(doc.clone()); Editor { doc, m, history: History::default(), view, sel: Selection::caret(0), stored: None, observer: None, editable: false, native: None, composition_marks: None, composition_end: 0.0, intent: None, is_mac, last_rule: None, spell_off: false, placeholder_text: String::new(), placeholder_el: None, selected_el: Default::default(), listeners: Vec::new(), } } pub fn cx(&self) -> Cx<'_> { Cx { m: &self.m, sel: self.sel.clone(), stored: self.stored.clone() } } // ----------------------------------------------------------------------- // Change cycle // ----------------------------------------------------------------------- /// Runs a command against the current selection and records it for undo. pub fn run(&mut self, f: impl FnOnce(&mut Cx) -> bool) -> bool { if self.m.is_empty() { return false; } let before = self.sel.clone(); let mut cx = self.cx(); let ran = f(&mut cx); let (sel, stored) = (cx.sel, cx.stored); if ran { self.m.commit(); self.history.push(&self.m, &before, &sel, now()); self.sel = sel; self.stored = stored; self.render(true); } else { self.m.take_ops(); } ran } /// Sets (`Some`) or clears (`None`: detect it) the language of the code block at `off`. pub fn set_code_language(&mut self, off: Pos, lang: Option<&str>) -> bool { let b = self.m.at(off); if b.kind() != Leaf::Code || b.attrs.lang.as_deref() == lang { return false; } let start = b.start; self.run(|cx| c::set_code_language(cx.m, start, lang)) } /// Replaces the code of the block at `off` with `code`, editing only the part that /// differs, so carets (ours and remote ones) stay where they were. Does nothing /// unless the block still holds `expected`: the code may have changed while it was /// formatted. pub fn replace_code(&mut self, off: Pos, expected: &str, code: &str) -> bool { let b = self.m.at(off); if b.kind() != Leaf::Code || expected == code || self.m.plain(b.start, b.sep) != expected { return false; } let before = self.sel.clone(); let anchors = SelAnchors::new(&self.m, &self.sel); let (old, new): (Vec, Vec) = (expected.encode_utf16().collect(), code.encode_utf16().collect()); let mut p = old.iter().zip(&new).take_while(|(a, b)| a == b).count(); let max = old.len().min(new.len()) - p; let mut s = old.iter().rev().zip(new.iter().rev()).take(max).take_while(|(a, b)| a == b).count(); // Never split a surrogate pair. while p > 0 && is_low(old.get(p)) { p -= 1; } while s > 0 && is_low(old.get(old.len() - s)) { s -= 1; } let max = (old.len() - p).min(new.len() - p); s = s.min(max); let mid = String::from_utf16_lossy(&new[p..new.len() - s]); self.m.delete(b.start + p, b.start + old.len() - s); if !mid.is_empty() { self.m.insert(b.start + p, &mid, &Marks::none()); } self.sel = anchors.resolve(&self.m); self.history.push(&self.m, &before, &self.sel, now()); self.history.checkpoint(); let focused = self.focused(); self.render(focused); true } pub fn chain(&mut self, cmds: &[Command]) -> bool { self.run(|cx| c::chain(cx, cmds, true)) } /// Whether a command would apply now (toolbar state). pub fn can(&self, f: impl FnOnce(&mut Cx) -> bool) -> bool { if self.m.is_empty() { return false; } let mut cx = self.cx(); f(&mut cx) } /// Flushes model changes to the DOM, then the selection. pub fn render(&mut self, set_dom_sel: bool) { let changed = self.view.flush(&self.m); if changed { self.drain_own_mutations(); self.placeholder(); self.spellcheck(); } self.sel = pos::clamp(&self.m, &self.sel); if set_dom_sel { self.write_dom_selection(); } self.notify(changed); } fn notify(&mut self, changed: bool) { let mut ls = std::mem::take(&mut self.listeners); for l in ls.iter_mut() { l(self, changed); } ls.append(&mut self.listeners); self.listeners = ls; } pub(crate) fn drain_own_mutations(&self) { if let Some(o) = &self.observer { o.take_records(); } } /// Applies remote updates; keeps the local selection anchored. pub fn import(&mut self, bytes: &[u8]) -> loro::LoroResult<()> { if !self.editable { let r = self.m.import(bytes); self.sel = Selection::caret(pos::snap(&self.m, 0)); return r; } let anchors = SelAnchors::new(&self.m, &self.sel); self.m.import(bytes)?; self.m.close_body(); self.sel = anchors.resolve(&self.m); let focused = self.focused(); self.render(focused); Ok(()) } /// Turns the pre-rendered page into the live editor. pub fn make_editable(&mut self) { if self.editable { return; } self.m.close_body(); self.m.take_ops(); self.view.render_all(&self.m); self.drain_own_mutations(); self.placeholder(); // Before the root is editable, so the spellchecker never starts on a huge note. self.spellcheck(); let _ = self.view.root.set_attribute("contenteditable", "true"); self.editable = true; self.sel = Selection::caret(pos::snap(&self.m, 0)); self.notify(true); } /// The `is-placeholder` hint while the note is one empty paragraph. /// Turns the spellchecker off for a huge note: it rechecks moved text in idle /// tasks that held the main thread for 70 ms after Enter in a 55 MB paragraph, /// and checking megabytes of text helps nobody. fn spellcheck(&mut self) { const SPELL_MAX: usize = 1 << 20; let off = self.m.total() > SPELL_MAX; if off != self.spell_off { self.spell_off = off; self.view.root.set_spellcheck(!off); } } fn placeholder(&mut self) { let target = (self.m.len() == 1) .then(|| self.m.block(0)) .flatten() .filter(|b| b.kind() == Leaf::Para && b.is_empty() && b.depth() == 0) .and_then(|_| self.view.element(0).cloned()); if target == self.placeholder_el { return; } if let Some(old) = self.placeholder_el.take() { let _ = old.class_list().remove_1("is-placeholder"); let _ = old.remove_attribute("data-placeholder"); } if let Some(el) = &target { let _ = el.class_list().add_1("is-placeholder"); let _ = el.set_attribute("data-placeholder", &self.placeholder_text); } self.placeholder_el = target; } pub fn undo(&mut self) -> bool { self.history(true) } pub fn redo(&mut self) -> bool { self.history(false) } fn history(&mut self, undo: bool) -> bool { let sel = if undo { self.history.undo(&self.m) } else { self.history.redo(&self.m) }; let Some(sel) = sel else { return false }; self.sel = sel; self.stored = None; self.render(true); true } pub fn can_undo(&self) -> bool { self.history.can_undo() } pub fn can_redo(&self) -> bool { self.history.can_redo() } // ----------------------------------------------------------------------- // DOM selection // ----------------------------------------------------------------------- pub fn focused(&self) -> bool { let doc = self.view.root.owner_document().unwrap(); doc.active_element().is_some_and(|a| self.view.root.contains(Some(&a))) } /// Reads the DOM selection into the model. Returns false when it is outside. pub fn read_dom_selection(&mut self) -> bool { let Some(ds) = web_sys::window().and_then(|w| w.get_selection().ok().flatten()) else { return false }; let (Some(an), Some(fo)) = (ds.anchor_node(), ds.focus_node()) else { return false }; let root: &DomNode = self.view.root.as_ref(); if !root.contains(Some(&an)) || !root.contains(Some(&fo)) { return false; } if let Selection::Node(_) | Selection::All = self.sel { // Kept while the DOM selection is the one we set for it. if !ds.is_collapsed() { return true; } } let a = self.view.dom_to_pos(&self.m, &an, ds.anchor_offset()); let f = self.view.dom_to_pos(&self.m, &fo, ds.focus_offset()); if let (Some(anchor), Some(head)) = (a, f) { let sel = pos::clamp(&self.m, &Selection::Text { anchor, head }); if sel != self.sel { self.sel = sel; self.stored = None; } } true } /// Puts the model selection into the DOM if it differs. pub fn write_dom_selection(&mut self) { match self.sel { Selection::Text { anchor, head } => { self.view.show(&self.m, self.m.at(anchor).index); self.view.show(&self.m, self.m.at(head).index); self.view.ensure_live(&self.m, &[anchor, head]); } Selection::Node(p) => self.view.show(&self.m, self.m.at(p).index), _ => {} } self.drain_own_mutations(); let Some(ds) = web_sys::window().and_then(|w| w.get_selection().ok().flatten()) else { return }; if let Some(old) = self.selected_el.borrow_mut().take() { let _ = old.class_list().remove_1("ProseMirror-selectednode"); } match self.sel { Selection::Text { anchor, head } => { 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 }; let same = ds.anchor_node().as_ref() == Some(&an) && ds.anchor_offset() == ao && ds.focus_node().as_ref() == Some(&fo) && ds.focus_offset() == foo; if !same { let _ = ds.set_base_and_extent(&an, ao, &fo, foo); } } Selection::Node(p) => { if let Some(el) = self.node_element(p) { let _ = el.class_list().add_1("ProseMirror-selectednode"); *self.selected_el.borrow_mut() = Some(el.clone()); if let Some(parent) = el.parent_node() { let i = index_in(&parent, &el); let _ = ds.set_base_and_extent(&parent, i, &parent, i + 1); } } } Selection::All => { let root: &DomNode = self.view.root.as_ref(); let _ = ds.set_base_and_extent(root, 0, root, root.child_nodes().length()); } Selection::Gap(_) => {} } } /// The element of a selected node: a rule, or the image at `p`. pub fn node_element(&self, p: Pos) -> Option { let b = self.m.at(p); let v = self.view.bview(b.index)?; if b.kind() == Leaf::Rule { return Some(v.el.clone()); } let mut acc = b.start; for r in &v.runs { if acc == p && matches!(r.kind, RunKind::Image { .. }) { return r.dom.clone().dyn_into().ok(); } acc += r.len; } None } /// A click on a rule or image selects it as a node. pub fn on_mousedown(&mut self, ev: &web_sys::MouseEvent) { if !self.editable || ev.button() != 0 { return; } let Some(target) = ev.target().and_then(|t| t.dyn_into::().ok()) else { return }; let p = match target.tag_name().as_str() { "HR" => self.view.owner(&target).and_then(|(i, _)| self.m.block(i)).map(|b| b.start), "IMG" => target.parent_node().and_then(|parent| { let i = index_in(&parent, &target); self.view.dom_to_pos(&self.m, &parent, i) }), _ => return, }; let Some(p) = p else { return }; ev.prevent_default(); let _ = self.view.root.focus(); self.sel = Selection::Node(p); self.stored = None; self.write_dom_selection(); self.notify(false); } pub fn on_selection_change(&mut self) { if self.view.composing.is_some() || !self.editable { return; } if self.read_dom_selection() { self.notify(false); } } // ----------------------------------------------------------------------- // Input // ----------------------------------------------------------------------- pub fn on_beforeinput(&mut self, ev: &InputEvent) { if !self.editable { ev.prevent_default(); return; } let kind = ev.input_type(); if kind.contains("Composition") { return; } self.read_dom_selection(); let cancel = ev.cancelable(); match kind.as_str() { "insertText" => { let data = ev.data().unwrap_or_default(); if let Some(native) = self.native_insert(&data) { self.native = Some(native); return; } ev.prevent_default(); self.type_text(&data); } "insertReplacementText" => { ev.prevent_default(); let text = ev .data_transfer() .and_then(|d| d.get_data("text/plain").ok()) .or_else(|| ev.data()) .unwrap_or_default(); if let Some((from, to)) = self.target_range(ev) { self.sel = Selection::Text { anchor: from, head: to }; } self.run(|cx| c::insert_text(cx, &text)); } "insertParagraph" => self.structural(ev, cancel, Intent::Enter), "insertLineBreak" => self.structural(ev, cancel, Intent::LineBreak), k if k.starts_with("delete") => { let back = k.contains("Backward"); let intent = if back { Intent::Backspace } else { Intent::Delete }; if !cancel { self.intent = Some(intent); return; } ev.prevent_default(); if !self.sel.is_empty() { self.chain(BACKSPACE); return; } match self.target_range(ev) { Some((from, to)) if from != to && self.m.at(from).index == self.m.at(to).index => { self.run(|cx| { cx.sel = Selection::Text { anchor: from, head: to }; c::delete_selection(cx, true) }); } _ => self.delete_char(back), } } "historyUndo" => { ev.prevent_default(); self.undo(); } "historyRedo" => { ev.prevent_default(); self.redo(); } "formatBold" => { ev.prevent_default(); self.run(|cx| c::toggle_mark(cx, MarkType::Strong, true)); } "formatItalic" => { ev.prevent_default(); self.run(|cx| c::toggle_mark(cx, MarkType::Em, true)); } // Paste and drop are handled by their own events. _ => ev.prevent_default(), } } fn structural(&mut self, ev: &InputEvent, cancel: bool, intent: Intent) { if !cancel { self.intent = Some(intent); return; } ev.prevent_default(); self.run_intent(intent); } fn run_intent(&mut self, intent: Intent) { match intent { Intent::Enter => { self.chain(ENTER); } Intent::Backspace => self.delete_char(true), Intent::Delete => self.delete_char(false), Intent::LineBreak => { self.run(|cx| { let code = cx.sel.cursor().is_some_and(|p| cx.m.at(p).kind() == Leaf::Code); if code { c::insert_text(cx, "\n") } else { c::insert_inline(cx, &[Inline::HardBreak]) } }); } } } /// One character (surrogate pair aware) backward or forward, else the structural chain. fn delete_char(&mut self, back: bool) { if self.chain(if back { BACKSPACE } else { DELETE }) { return; } let Some(p) = self.sel.cursor() else { return }; let b = self.m.at(p); let u = self.m.to_u(p); let (from, to) = if back { if p <= b.start { return; } (self.m.to16(u - 1).max(b.start), p) } else { if p >= b.sep { return; } (p, self.m.to16(u + 1).min(b.sep)) }; if from == to { return; } self.run(|cx| { cx.sel = Selection::Text { anchor: from, head: to }; c::delete_selection(cx, true) }); } /// The first target range of an input event, in model offsets, in order. fn target_range(&self, ev: &InputEvent) -> Option<(Pos, Pos)> { let ranges = ev.get_target_ranges(); let r: web_sys::StaticRange = ranges.get(0).dyn_into().ok()?; let a = self.view.dom_to_pos(&self.m, &r.start_container(), r.start_offset())?; let b = self.view.dom_to_pos(&self.m, &r.end_container(), r.end_offset())?; Some((a.min(b), a.max(b))) } /// Typed text that is not left to the browser. pub fn type_text(&mut self, data: &str) { if crate::rules::apply(self, data) { return; } self.run(|cx| c::insert_text(cx, data)); } /// Ends undo merging, so the next change is its own undo step. pub fn checkpoint(&mut self) { self.history.checkpoint(); } /// Whether the browser may type `data` itself: a collapsed caret inside one of our /// text nodes whose marks are exactly the marks the text should get. fn native_insert(&self, data: &str) -> Option { if data.is_empty() || data.contains('\n') { return None; } let p = self.sel.cursor()?; let b = self.m.at(p); if !b.kind().is_text() { return None; } let ds = web_sys::window()?.get_selection().ok()??; let an = ds.anchor_node()?; if an.node_type() != DomNode::TEXT_NODE || !ds.is_collapsed() { return None; } let v = self.view.bview(b.index)?; let run = v.runs.iter().find(|r| r.text.as_ref().is_some_and(|t| ***t == an))?; let marks = c::pending_marks(&self.cx()); if Marks::from(&run.marks) != marks { return None; } if b.kind() != Leaf::Code && crate::rules::may_trigger(data) { return None; } let len = an.unchecked_ref::().length(); Some(Native { block: b.index, marks, at: ds.anchor_offset(), len, off: p, data: data.to_owned(), node: an }) } pub fn on_input(&mut self) { let records = self.observer.as_ref().map(|o| o.take_records()).unwrap_or_default(); self.on_mutations(&records.iter().filter_map(|r| r.dyn_into::().ok()).collect::>()); } /// Reconciles DOM changes the browser made with the model. pub fn on_mutations(&mut self, records: &[MutationRecord]) { if self.view.composing.is_some() || !self.editable { return; } let mut blocks: Vec = Vec::new(); let mut containers: Vec = Vec::new(); for r in records { let Some(target) = r.target() else { continue }; match self.view.owner(&target) { Some((i, _)) => { if !blocks.contains(&i) { blocks.push(i); } } None => containers.push(target), } } if let Some(n) = &self.native && !blocks.contains(&n.block) { blocks.push(n.block); } if let Some(intent) = self.intent.take() { for &i in &blocks { self.view.repair(&self.m, i); } for n in &containers { self.view.repair_page_of(&self.m, n); } self.drain_own_mutations(); self.write_dom_selection(); self.run_intent(intent); return; } if blocks.is_empty() && containers.is_empty() { return; } let before = self.sel.clone(); let mut changed = false; let native = self.native.take(); for &i in &blocks { let fast = native.as_ref().is_some_and(|n| n.block == i && self.typed_natively(n, records)); if !fast { self.native = native.clone(); } changed |= fast || self.read_back(i); } self.native = None; // The browser's caret is where the text went. self.read_dom_selection(); if changed { self.history.push(&self.m, &before, &self.sel, now()); } self.view.flush(&self.m); let mut repaired = false; for &i in &blocks { if !self.view.intact(i) { self.view.repair(&self.m, i); repaired = true; } } for n in &containers { if n.is_connected() || self.view.root.contains(Some(n)) { self.view.repair_page_of(&self.m, n); repaired = true; } } self.drain_own_mutations(); self.placeholder(); self.sel = pos::clamp(&self.m, &self.sel); if repaired { self.write_dom_selection(); } self.notify(changed); } /// The browser typed exactly `n.data` at the caret and nothing else: applies it to /// the model without reading the block back. False when the DOM shows anything else. fn typed_natively(&mut self, n: &Native, records: &[MutationRecord]) -> bool { let only_text = records.iter().all(|r| r.type_() == "characterData" && r.target().as_ref() == Some(&n.node)); let t: &web_sys::CharacterData = n.node.unchecked_ref(); let len16 = n.data.encode_utf16().count() as u32; if !only_text || t.length() != n.len + len16 || t.substring_data(n.at, len16).ok().as_deref() != Some(n.data.as_str()) { return false; } if !self.view.typed(n.block, &n.node, n.at as usize, &n.data) { return false; } self.m.insert(n.off, &n.data, &n.marks); true } /// Applies the difference between a block's DOM text and the model as one /// replacement. Returns whether the model changed. fn read_back(&mut self, i: usize) -> bool { let Some(b) = self.m.block(i) else { return false }; if !b.kind().is_text() { return false; } let Some(dom) = self.view.dom_text(i) else { return false }; let model: Vec = self.m.plain(b.start, b.sep).encode_utf16().collect(); if dom == model { return false; } // The browser changed the DOM: the run caches follow it before the model does. self.view.resync(i); let mut p = 0; while p < dom.len() && p < model.len() && dom[p] == model[p] { p += 1; } let mut s = 0; while s < dom.len() - p && s < model.len() - p && dom[dom.len() - 1 - s] == model[model.len() - 1 - s] { s += 1; } // Do not split a surrogate pair. if p > 0 && is_low(model.get(p)) { p -= 1; } let inserted = &dom[p..dom.len() - s]; if inserted.contains(&0xfffc) { // The browser made an element we did not ask for; the model wins. self.view.repair(&self.m, i); return false; } let marks = match (&self.native, &self.composition_marks) { (Some(n), _) if n.block == i => n.marks.clone(), (_, Some(mk)) => mk.clone(), _ if b.kind() == Leaf::Code => Marks::none(), _ => c::marks_at(&self.m, b.start + p), }; let text = String::from_utf16_lossy(inserted); self.m.delete(b.start + p, b.start + model.len() - s); if !text.is_empty() { self.m.insert(b.start + p, &text, &marks); } true } pub fn on_composition_start(&mut self, _ev: &CompositionEvent) { self.read_dom_selection(); if let Selection::Text { anchor, head } = self.sel && self.m.at(anchor).index != self.m.at(head).index { self.chain(&[c::delete_selection]); } self.composition_marks = Some(c::pending_marks(&self.cx())); self.view.composing = match self.sel { Selection::Text { head, .. } => Some(self.m.at(head).index), _ => None, }; } pub fn on_composition_end(&mut self, _ev: &CompositionEvent) { let block = self.view.composing.take(); let deferred = self.view.take_deferred(); let records = self.observer.as_ref().map(|o| o.take_records()).unwrap_or_default(); let mut recs: Vec = records.iter().filter_map(|r| r.dyn_into().ok()).collect(); recs.retain(|r| r.target().is_some()); let before = self.sel.clone(); let mut changed = false; if let Some(i) = block { changed = self.read_back(i); } self.composition_marks = None; self.read_dom_selection(); if changed { self.history.push(&self.m, &before, &self.sel, now()); } self.view.flush(&self.m); if let Some(i) = block && (deferred || !self.view.intact(i)) { self.view.repair(&self.m, i); self.write_dom_selection(); } self.drain_own_mutations(); self.placeholder(); self.composition_end = now(); self.notify(changed); // Mutations outside the composed block still need handling. if !recs.is_empty() { self.on_mutations(&recs); } } // ----------------------------------------------------------------------- // Keys // ----------------------------------------------------------------------- pub fn on_keydown(&mut self, ev: &KeyboardEvent) -> bool { if ev.is_composing() || ev.key_code() == 229 { return false; } let key = ev.key(); // Safari sends Enter right after compositionend for the commit key. if key == "Enter" && now() - self.composition_end < 500.0 { ev.prevent_default(); return true; } if !self.editable { return false; } self.read_dom_selection(); let m = if self.is_mac { ev.meta_key() } else { ev.ctrl_key() }; let (shift, alt) = (ev.shift_key(), ev.alt_key()); let lower = key.to_lowercase(); let handled = match (m, shift, alt, lower.as_str()) { (false, false, false, "enter") => self.chain(ENTER), (true, false, false, "enter") => self.run(|cx| c::exit_code(cx, true)), (false, false, false, "backspace") => crate::rules::undo_rule(self) || self.can(|cx| c::chain(cx, BACKSPACE, false)) && self.chain(BACKSPACE), (false, false, false, "delete") => self.can(|cx| c::chain(cx, DELETE, false)) && self.chain(DELETE), (true, false, false, "a") => self.run(|cx| c::select_all(cx, true)), (true, false, false, "k") if self.can(|cx| c::can_link(cx)) => { crate::ui::request_link(&self.view.root); true } (false, false, false, "tab") => { self.run(|cx| c::sink_list_item(cx, true)); // Tab never leaves the editor. true } (false, true, false, "tab") => { self.run(|cx| c::lift_list_item(cx, true)); true } (true, false, false, "z") => { self.undo(); true } (true, false, false, "y") | (true, true, false, "z") => { self.redo(); true } (true, false, false, "b") => self.run(|cx| c::toggle_mark(cx, MarkType::Strong, true)), (true, false, false, "i") => self.run(|cx| c::toggle_mark(cx, MarkType::Em, true)), (true, false, false, "`") | (true, false, false, "e") => self.run(|cx| c::toggle_mark(cx, MarkType::Code, true)), (true, false, true, "0") => self.run(|cx| c::set_block_type(cx, Kind::Paragraph, true)), (true, false, true, d @ ("1" | "2" | "3")) => { let level = d.parse::().unwrap(); self.run(|cx| c::toggle_block(cx, Kind::Heading(level), true)) } (true, true, false, "8" | "*") => self.run(|cx| c::toggle_list(cx, Kind::BulletList, true)), (true, true, false, "9" | "(") => self.run(|cx| c::toggle_list(cx, Kind::OrderedList, true)), _ => false, }; // Ctrl-Alt digits arrive as `key` = the shifted symbol on some layouts. let handled = handled || (m && alt && self.heading_by_code(&ev.code())); if handled { ev.prevent_default(); } handled } fn heading_by_code(&mut self, code: &str) -> bool { match code { "Digit0" => self.run(|cx| c::set_block_type(cx, Kind::Paragraph, true)), "Digit1" | "Digit2" | "Digit3" => { let level = code[5..].parse::().unwrap(); self.run(|cx| c::toggle_block(cx, Kind::Heading(level), true)) } _ => false, } } } fn is_low(u: Option<&u16>) -> bool { u.is_some_and(|u| (0xdc00..0xe000).contains(u)) } fn index_in(parent: &DomNode, child: &DomNode) -> u32 { let kids = parent.child_nodes(); (0..kids.length()).find(|&i| kids.get(i).as_ref() == Some(child)).unwrap_or(0) }