//! The DOM side of the editor: the body's blocks in pages, an incremental flush //! driven by the model's block splices, DOM <-> offset mapping and the read-back of //! text the browser typed natively. //! //! Blocks are flat in the model; the DOM nests them (`ul > li > p`, `blockquote`) per //! page. A container cut by a page boundary is split: the part on the later page has //! `pm-cont` (and the earlier part `pm-more`), which the stylesheet joins seamlessly. use std::collections::HashMap; use std::rc::Rc; use note_model::flat::{Attrs, Kind, OBJ, Wrap}; use note_model::marks::Marks; use note_model::render::{self, TRAILING_BREAK}; use note_model::write::Inline; use wasm_bindgen::{JsCast, JsValue}; use web_sys::{Document, Element, HtmlElement, Node as DomNode, Text}; use crate::core::commands::keep; use crate::core::model::{Blk, Model}; use crate::core::pos::Pos; use crate::strings::Strings; /// Expando on page elements: the page's uid. const PAGE_KEY: &str = "__pmPage"; /// Expando on block elements. const BLOCK_KEY: &str = "__pmBlock"; /// Property on a chunk element: its last known index in its block's runs. const RUN_KEY: &str = "__pmRun"; /// Blocks per page. const PAGE: usize = 64; /// Assumed height of a block never measured (px). const EST_BLOCK_PX: f64 = 32.0; pub struct BView { /// Stable while the block's element lives (UI state is keyed by it). pub key: u32, pub el: Element, /// Where the runs go (`code` inside `pre`, else `el`). pub content: Element, pub attrs: Attrs, pub runs: Vec, trailing: Option, /// Content changed: `Some(range)` for one plain edit (Unicode, from the block /// start), `None` for anything else (attributes may have changed too). dirty: Option>, /// The DOM already matches the model (typed natively): the next dirty mark is moot. synced: bool, /// Hidden chunks' spacers are drawn this much shorter (see `MAX_PX`). scale: f64, /// For a chunked code block: lines per chunk (see [`code_chunk_lines`]). lines: usize, } #[derive(Clone, PartialEq, Debug)] pub enum RunKind { Text, Break, Image { src: String, alt: String, title: Option }, } pub struct Run { pub kind: RunKind, /// UTF-16 length. pub len: usize, /// Outermost DOM node of the run (a mark wrapper, the text, or the element). pub dom: DomNode, pub text: Option, /// The text of `text`, kept equal to the DOM node: patches compare against it /// instead of reading the DOM, and edits typed natively update it. pub s: String, /// Unicode scalars of the run (Loro's text positions). pub chars: usize, pub marks: Marks, /// A piece of a long block, wrapped in its own element (`dom`). pub chunk: bool, /// For a chunk: its content is attached. Chunks far from the viewport and the caret /// are empty placeholders sized by their line count (`inner` stays detached, still /// holding the text): the browser's per-keystroke cost grows with all editable text. pub live: bool, /// For a chunk: the node inside `dom` (the text, or its mark wrapper). pub inner: Option, /// For a chunk: last seen near the viewport. pub near: bool, /// `dom` is in the block's content element (see `place_runs`). shown: bool, /// For a chunk: its height while hidden (px, unscaled). px: f64, /// For a hidden chunk shown as a spacer: the height written on it. styled: Option, } /// A run of consecutive blocks under one element. Only pages near the viewport (or /// holding the selection) are built; the rest keep their last measured height, and /// each run of them is one empty spacer in the DOM (see `View::layout`). The browser's per-keystroke cost grows with the editable content /// in the DOM, so this keeps typing flat in documents of any length. struct Page { el: Element, uid: u32, n: usize, live: bool, height: f64, /// `el` is in the root: a live page, or the spacer standing for a run of dead ones. attached: bool, /// The height written on `el` as a spacer. styled: Option, /// When live, one entry per block; `None` until built. blocks: Vec>, /// What the grouping was built from (see `View::shape`). shape: Shape, } #[derive(PartialEq, Default)] struct Shape { prev: Option, next: Option, blocks: Vec<(Vec, Option, Option)>, numbers: Vec, } pub struct View { pub root: HtmlElement, document: Document, pages: Vec, /// The first block of each page, and the block count last; empty when stale. /// Changes to the pages or their block counts clear it (`pages_changed`). starts: std::cell::RefCell>, next_uid: u32, page_key: JsValue, block_key: JsValue, /// The block being composed into; the flush leaves it alone. pub composing: Option, /// The composed block changed meanwhile: rebuilt when the composition ends. deferred: bool, /// Content width when text chunks were last built (see `TEXT_CHAR_AREA`). text_width: f64, /// Spacers are drawn this much shorter than the pages they stand for (see `MAX_PX`). scale: f64, /// The state of each take on the server, `live` or `lost`; a take not listed is absent. /// Sync keeps it up to date, and a take's embed reads it when the embed is built. pub takes: Rc>>, } impl View { pub fn new(root: HtmlElement) -> Self { let document = root.owner_document().unwrap(); View { root, document, pages: Vec::new(), starts: Default::default(), next_uid: 0, page_key: JsValue::from_str(PAGE_KEY), block_key: JsValue::from_str(BLOCK_KEY), composing: None, deferred: false, text_width: 800.0, scale: 1.0, takes: Rc::default(), } } /// Renders the whole body, replacing what is in the root (the server pre-render). pub fn render_all(&mut self, m: &Model) { m.take_splices(); self.pages.clear(); self.pages_changed(); self.root.set_text_content(None); let n = m.len(); let mut i = 0; while i < n { let k = PAGE.min(n - i); let page = self.new_page(k, k as f64 * EST_BLOCK_PX); self.pages.push(page); i += k; } self.pages_changed(); self.layout(); // The top shows at once; `sync_viewport` brings in the rest as it scrolls near. for p in 0..self.pages.len().min(2) { self.set_page_live(m, p, true); } } fn new_page(&mut self, n: usize, height: f64) -> Page { let el = self.document.create_element("div").unwrap(); el.set_class_name("pm-page"); let uid = self.next_uid; self.next_uid += 1; let _ = js_sys::Reflect::set(&el, &self.page_key, &JsValue::from(uid)); Page { el, uid, n, live: false, height, attached: false, styled: None, blocks: Vec::new(), shape: Shape::default() } } fn starts(&self) -> std::cell::Ref<'_, Vec> { if self.starts.borrow().is_empty() { let mut s = self.starts.borrow_mut(); s.reserve(self.pages.len() + 1); let mut acc = 0; s.push(0); for p in &self.pages { acc += p.n; s.push(acc); } } self.starts.borrow() } fn pages_changed(&mut self) { self.starts.get_mut().clear(); } /// The first block of page `pi`. fn page_start(&self, pi: usize) -> usize { self.starts()[pi] } /// Page and position in it of block `i`. fn locate(&self, i: usize) -> Option<(usize, usize)> { let s = self.starts(); if i >= *s.last()? { return None; } let pi = s.partition_point(|&x| x <= i) - 1; Some((pi, i - s[pi])) } fn set_page_live(&mut self, m: &Model, pi: usize, live: bool) { if self.pages[pi].live == live { return; } if live { let n = self.pages[pi].n; self.pages[pi].blocks = (0..n).map(|_| None).collect(); self.pages[pi].live = true; self.pages[pi].shape = Shape::default(); self.build_missing(m, pi); self.group(m, pi); } else { let p = &mut self.pages[pi]; p.blocks.clear(); p.el.set_text_content(None); p.live = false; } self.layout(); } /// Puts the live pages in the root, and for each run of dead pages one spacer (the /// run's first page) as tall as the run: the root holds a few elements however long /// the note is. Firefox's spellchecker handles every node added to or removed from /// an editable root right away, 2 s for 15k placeholder pages. fn layout(&mut self) { let total: f64 = self.pages.iter().map(|p| p.height).sum(); self.scale = rescale(self.scale, total); let mut prev: Option = None; let mut i = 0; while i < self.pages.len() { if self.pages[i].live { self.attach(i, &mut prev, None); i += 1; continue; } let mut j = i; let mut h = 0.0; while j < self.pages.len() && !self.pages[j].live { h += self.pages[j].height; j += 1; } self.attach(i, &mut prev, Some((h * self.scale).round() as i64)); for p in &mut self.pages[i + 1..j] { if p.attached { p.el.remove(); p.attached = false; } } i = j; } } fn attach(&mut self, i: usize, prev: &mut Option, height: Option) { let p = &mut self.pages[i]; if !p.attached { let _ = match prev { Some(e) => e.after_with_node_1(&p.el), None => self.root.prepend_with_node_1(&p.el), }; p.attached = true; } if p.styled != height { let _ = match height { Some(h) => p.el.set_attribute("style", &format!("height:{h}px")), None => p.el.remove_attribute("style"), }; p.styled = height; } *prev = Some(p.el.clone()); } /// Viewport top and bottom of page `i`; a dead page's lie within its run's spacer. fn page_box(&self, i: usize) -> (f64, f64) { let mut h = 0.0; let mut head = i; if !self.pages[i].live { while head > 0 && !self.pages[head - 1].live { head -= 1; h += self.pages[head].height; } } let r = self.pages[head].el.get_bounding_client_rect(); if self.pages[i].live { (r.top(), r.bottom()) } else { let k = self.scale; (r.top() + h * k, r.top() + (h + self.pages[i].height) * k) } } /// Builds the page holding block `i`, so it can take the selection. pub fn show(&mut self, m: &Model, i: usize) { if let Some((pi, _)) = self.locate(i) { self.set_page_live(m, pi, true); } } /// Builds the pages and attaches the chunks within `NEAR_PX` of the viewport, and /// empties the others, except where the selection or a composition is. Pages and /// chunks are stacked top to bottom, so binary searches on their boxes find the /// range: a few layout reads per frame however long the note is. Returns whether /// anything changed, which moves what follows and needs another pass. pub fn sync_viewport(&mut self, m: &Model) -> bool { let Some(win) = web_sys::window() else { return false }; let height = win.inner_height().ok().and_then(|h| h.as_f64()).unwrap_or(800.0); let (top, bottom) = (-NEAR_PX, height + NEAR_PX); let ds = win.get_selection().ok().flatten(); let holds_selection = |n: &DomNode| { ds.as_ref().is_some_and(|ds| { [ds.anchor_node(), ds.focus_node()].into_iter().flatten().any(|s| n.contains(Some(&s))) }) }; let mut changed = false; let composing_page = self.composing.and_then(|c| self.locate(c)).map(|l| l.0); let (first, last) = near_range(self.pages.len(), |i| self.page_box(i), top, bottom); for i in 0..self.pages.len() { let near = (first..last).contains(&i); if near == self.pages[i].live { continue; } if !near { let el: DomNode = self.pages[i].el.clone().into(); if holds_selection(&el) || composing_page == Some(i) { continue; } let h = self.pages[i].el.get_bounding_client_rect().height(); if h > 0.0 { self.pages[i].height = h; } } self.set_page_live(m, i, near); changed = true; } let composing = self.composing; let mut g = 0; for pi in 0..self.pages.len() { let n = self.pages[pi].n; if !self.pages[pi].live { g += n; continue; } for k in 0..n { if composing == Some(g + k) { continue; } let Some(v) = self.pages[pi].blocks[k].as_mut() else { continue }; if !v.runs.first().is_some_and(|r| r.chunk) { continue; } // Shown chunks' heights, read while layout is fresh: a chunk hidden later // keeps it (wrapped text has no line count to size it by). for r in v.runs.iter_mut().filter(|r| r.live && r.shown) { let h = r.dom.unchecked_ref::().get_bounding_client_rect().height(); if h > 0.0 { r.px = h; } } let (first, last) = near_range(v.runs.len(), |i| chunk_box(v, i), top, bottom); for i in 0..v.runs.len() { let near = (first..last).contains(&i); let r = &mut v.runs[i]; if r.near == near { continue; } r.near = near; if near || !holds_selection(&r.dom) { let was = r.live; set_live(r, near); changed |= was != near; } } place_runs(v); } g += n; } changed } // ----------------------------------------------------------------------- // Building // ----------------------------------------------------------------------- fn el(&self, spec: &render::Spec) -> Element { let el = self.document.create_element(spec.tag).unwrap(); for (k, v) in &spec.attrs { let _ = el.set_attribute(k, v); } el } fn build_block(&mut self, m: &Model, b: &Blk) -> BView { let mut v = self.block_shell(b); if b.kind() == Kind::Rule { let _ = v.el.set_attribute("contenteditable", "false"); } else { self.patch_runs(m, b, &mut v, true); } v } /// The element of block `b`, without its content. fn block_shell(&mut self, b: &Blk) -> BView { let spec = render::block_spec(&b.attrs); let el = self.el(&spec); let content = match spec.inner { Some(tag) => { let c = self.document.create_element(tag).unwrap(); el.append_child(&c).unwrap(); c } None => el.clone(), }; let _ = js_sys::Reflect::set(&el, &self.block_key, &JsValue::TRUE); self.next_uid += 1; BView { key: self.next_uid, el, content, attrs: b.attrs.clone(), runs: Vec::new(), trailing: None, dirty: None, synced: false, scale: 1.0, lines: CHUNK_LINES } } /// Builds the unbuilt blocks of live page `pi` and patches its dirty ones. fn build_missing(&mut self, m: &Model, pi: usize) { let n = self.pages[pi].n; let g0 = self.page_start(pi); let blks = m.blocks(g0, g0 + n); for (k, b) in blks.iter().enumerate() { match self.pages[pi].blocks[k].take() { None => { let v = self.build_block(m, b); self.pages[pi].blocks[k] = Some(v); } Some(mut v) => { if let Some(range) = v.dirty.take() { if self.composing == Some(b.index) { self.deferred = true; } else if v.synced && range.is_some() { // Typed natively: the DOM already shows it. } else if v.attrs.kind != b.attrs.kind { let nv = self.build_block(m, b); let _ = v.el.replace_with_with_node_1(&nv.el); v = nv; } else { if v.attrs.lang != b.attrs.lang { match b.attrs.lang.as_deref().filter(|l| !l.is_empty()) { Some(l) => drop(v.el.set_attribute("data-language", l)), None => drop(v.el.remove_attribute("data-language")), } } v.attrs = b.attrs.clone(); if b.kind() != Kind::Rule { let edit = range.and_then(|r| self.chunk_patch(m, b, &v, r)); self.apply_runs(m, b, &mut v, edit, false); } } } v.synced = false; self.pages[pi].blocks[k] = Some(v); } } } } /// The numbers of ordered lists continued from before the page: for each level of /// the first block's wrap, the number of its item there (0 when not an ordered /// list continued). fn numbers(m: &Model, g0: usize, prev: Option<&Attrs>, first: &Attrs) -> Vec { let k = keep(prev, first); let common = prev.map_or(0, |p| common(&p.wrap, &first.wrap)); let new_item = k < common && first.wrap[k].is_list(); let cont = if new_item { k + 1 } else { k }; (0..cont).map(|l| if first.wrap[l] == Wrap::Ordered { item_number(m, g0, l) } else { 0 }).collect() } /// Rebuilds the list and quote elements of live page `pi` around its blocks if /// anything they depend on changed. fn group(&mut self, m: &Model, pi: usize) { let n = self.pages[pi].n; if n == 0 || self.pages[pi].blocks.iter().any(Option::is_none) { return; } let g0 = self.page_start(pi); let prev = g0.checked_sub(1).and_then(|i| m.block(i)).map(|b| b.attrs); let next = m.block(g0 + n).map(|b| b.attrs); let page = &self.pages[pi]; let first = &page.blocks[0].as_ref().unwrap().attrs; let numbers = if first.wrap.contains(&Wrap::Ordered) { Self::numbers(m, g0, prev.as_ref(), first) } else { Vec::new() }; let shape = Shape { blocks: page.blocks.iter().map(|b| { let a = &b.as_ref().unwrap().attrs; (a.wrap.clone(), a.join, a.start) }).collect(), prev, next, numbers, }; if shape == page.shape { return; } if shape.blocks.iter().all(|b| b.0.is_empty()) && page.el.query_selector("ul,ol,blockquote").ok().flatten().is_none() { // No containers: the blocks are the page's children; move only what is out // of place (an Enter is one insertion, not a rebuilt page). let page_el = page.el.clone(); let mut cursor = page_el.first_child(); for v in page.blocks.iter().flatten() { let el: &DomNode = v.el.as_ref(); if cursor.as_ref() == Some(el) { cursor = el.next_sibling(); } else { page_el.insert_before(el, cursor.as_ref()).unwrap(); } } while let Some(c) = cursor { cursor = c.next_sibling(); page_el.remove_child(&c).unwrap(); } self.pages[pi].shape = shape; return; } struct Lvl { el: Element, item: Option, } let page_el = page.el.clone(); page_el.set_text_content(None); let mut stack: Vec = Vec::new(); let doc = self.document.clone(); let mk = |w: Wrap, start: i64, cont: bool| -> Element { let s = render::wrap_spec(w, start); let el = doc.create_element(s.tag).unwrap(); for (k, v) in &s.attrs { let _ = el.set_attribute(k, v); } if cont { el.set_class_name("pm-cont"); } el }; let li = |cont: bool| -> Element { let el = doc.create_element("li").unwrap(); if cont { el.set_class_name("pm-cont"); } el }; let parent = |stack: &[Lvl]| -> Element { match stack.last() { Some(l) => l.item.clone().unwrap_or_else(|| l.el.clone()), None => page_el.clone(), } }; let mut prev_attrs = shape.prev.clone(); for (idx, b) in self.pages[pi].blocks.iter().enumerate() { let b = b.as_ref().unwrap(); let wrap = &b.attrs.wrap; let k = keep(prev_attrs.as_ref(), &b.attrs); let common = prev_attrs.as_ref().map_or(0, |p| common(&p.wrap, wrap)); let new_item = k < common && wrap[k].is_list(); if idx == 0 { // Levels continued from the page before. let cont = if new_item { k + 1 } else { k }; for (l, &w) in wrap.iter().enumerate().take(cont) { let start = shape.numbers.get(l).copied().filter(|&x| x > 0).unwrap_or(1); let el = mk(w, start, true); parent(&stack).append_child(&el).unwrap(); let item = w.is_list().then(|| li(l < k)); if let Some(i) = &item { el.append_child(i).unwrap(); } stack.push(Lvl { el, item }); } } else { let stay = if new_item { k + 1 } else { k }; stack.truncate(stay); if new_item { let i = li(false); stack[k].el.append_child(&i).unwrap(); stack[k].item = Some(i); } } let deepest = (stack.len()..wrap.len()).rev().find(|&i| wrap[i] == Wrap::Ordered); for (l, &w) in wrap.iter().enumerate().skip(stack.len()) { let start = if Some(l) == deepest { b.attrs.start.unwrap_or(1) } else { 1 }; let el = mk(w, start, false); parent(&stack).append_child(&el).unwrap(); let item = w.is_list().then(|| li(false)); if let Some(i) = &item { el.append_child(i).unwrap(); } stack.push(Lvl { el, item }); } parent(&stack).append_child(&b.el).unwrap(); prev_attrs = Some(b.attrs.clone()); } // Levels the page after continues. if let (Some(last), Some(next)) = (&prev_attrs, &shape.next) { let k = keep(Some(last), next); let common = common(&last.wrap, &next.wrap); let new_item = k < common && next.wrap[k].is_list(); for (l, lvl) in stack.iter().enumerate() { if l < k || l == k && new_item { let _ = lvl.el.class_list().add_1("pm-more"); if let Some(i) = lvl.item.as_ref().filter(|_| l < k) { let _ = i.class_list().add_1("pm-more"); } } } } self.pages[pi].shape = shape; } /// Brings a block's runs up to date from the model. With `force` the content is /// rebuilt from scratch (used when the DOM went foreign). fn patch_runs(&mut self, m: &Model, b: &Blk, v: &mut BView, force: bool) { self.apply_runs(m, b, v, None, force); } fn apply_runs(&mut self, m: &Model, b: &Blk, v: &mut BView, edit: Option>, force: bool) { let code = b.kind() == Kind::Code; let new = match edit { Some(new) if !force => new, _ => { let mut lines = v.lines; let runs = chunk_text(model_runs(m, b), if force { &[] } else { &v.runs }, code, &mut lines); v.lines = lines; runs } }; if !code && new.iter().any(|n| matches!(n, MRun::Text(_, _, true))) { // Hidden text chunks are sized from their length at this width until shown. self.text_width = self.root.client_width().max(200) as f64; } if force { v.content.set_text_content(None); v.runs.clear(); v.trailing = None; } let old = std::mem::take(&mut v.runs); let content = v.content.clone(); let same = |i: usize, o: &Run, n: &MRun| -> bool { match n { MRun::Keep(k) => *k == i, // `o.s` always holds what the DOM text node holds (see `Run::s`). MRun::Text(s, mk, c) => o.kind == RunKind::Text && &o.marks == mk && o.chunk == *c && o.s == *s, MRun::Other(k) => o.kind == *k, } }; let mut pre = 0; while pre < old.len() && pre < new.len() && same(pre, &old[pre], &new[pre]) { pre += 1; } let mut suf = 0; while suf < old.len() - pre && suf < new.len() - pre && same(old.len() - 1 - suf, &old[old.len() - 1 - suf], &new[new.len() - 1 - suf]) { suf += 1; } let old_mid = &old[pre..old.len() - suf]; let new_mid = &new[pre..new.len() - suf]; let mut mid: Vec = Vec::with_capacity(new_mid.len()); // One text run changed in place: keep its node so spellcheck and IME state survive. let in_place = match (old_mid, new_mid) { ([o], [MRun::Text(s, mk, c)]) if o.kind == RunKind::Text && &o.marks == mk && o.chunk == *c => Some((o, s)), _ => None, }; if let Some((o, s)) = in_place { let t = o.text.clone().unwrap(); replace_minimal(&t, &o.s, s); let mut px = o.px; if o.chunk && code { px = line_count(s) as f64 * CODE_LINE_PX; if o.styled.is_none() { set_lines(&o.dom, s); } } mid.push(Run { kind: RunKind::Text, len: utf16_len(s), dom: o.dom.clone(), text: Some(t), s: s.clone(), chars: s.chars().count(), marks: o.marks.clone(), chunk: o.chunk, live: o.live, inner: o.inner.clone(), near: o.near, shown: o.shown, px, styled: o.styled }); } else { // New chunks replacing a shown one are shown too (the caret is likely there). let live = old_mid.iter().any(|o| o.live); for o in old_mid { if o.dom.parent_node().is_some_and(|p| p == *content) { content.remove_child(&o.dom).unwrap(); } } for n in new_mid { mid.push(self.build_run(n, live, code)); } } let mut old = old; let tail: Vec = old.drain(old.len() - suf..).collect(); let mut runs: Vec = Vec::with_capacity(new.len()); runs.extend(old.drain(..pre)); runs.extend(mid); runs.extend(tail); v.runs = runs; self.fix_trailing(v); } /// Adds or drops the trailing `
` an empty block or one ending in a line break needs. fn fix_trailing(&self, v: &mut BView) { place_runs(v); let content = v.content.clone(); let need_trailing = match v.runs.last() { None => true, Some(r) => r.kind == RunKind::Break || r.kind == RunKind::Text && r.s.ends_with('\n'), }; match (&v.trailing, need_trailing) { (None, true) => { let br = self.document.create_element("br").unwrap(); br.set_class_name(TRAILING_BREAK); content.append_child(&br).unwrap(); v.trailing = Some(br); } (Some(br), false) => { br.remove(); v.trailing = None; } (Some(br), true) if br.next_sibling().is_some() => { content.append_child(br).unwrap(); } _ => {} } } /// The new runs of a chunked block after one plain edit, reading only the changed /// chunks' text from the model (a huge block is never copied whole per keystroke). fn chunk_patch(&self, m: &Model, b: &Blk, v: &BView, (lo, hi): (usize, usize)) -> Option> { let runs = &v.runs; let plain = Marks::default(); if runs.is_empty() || runs.iter().any(|r| !r.chunk || r.marks != plain || r.kind != RunKind::Text) { return None; } let code = b.kind() == Kind::Code; let len = b.sepu - b.startu; let tail = len.checked_sub(hi)?; let (mut i, mut a) = (0, 0); while i < runs.len() && a + runs[i].chars <= lo { a += runs[i].chars; i += 1; } let (mut j, mut kept) = (runs.len(), 0); while j > i && kept + runs[j - 1].chars <= tail { kept += runs[j - 1].chars; j -= 1; } let e = len.checked_sub(kept).filter(|&e| e >= a)?; let mid = m.text.slice(b.startu + a, b.startu + e).ok()?; if !code && mid.contains(['\n', OBJ]) { return None; } let mut out: Vec = (0..i).map(MRun::Keep).collect(); // One edited chunk stays one node until it doubles: Enter then edits it in place // instead of rebuilding it as two. let small = if code { mid.bytes().filter(|&c| c == b'\n').count() < 2 * v.lines } else { mid.len() < 2 * CHUNK_BYTES }; if i + 1 == j && small && !mid.is_empty() { out.push(MRun::Text(mid, plain, true)); } else { out.extend(split_chunks(&mid, &plain, code, v.lines)); } out.extend((j..runs.len()).map(MRun::Keep)); Some(out) } fn build_run(&self, n: &MRun, live: bool, code: bool) -> Run { match n { MRun::Text(s, mk, chunk) => { let t = self.document.create_text_node(s); let mut dom: DomNode = t.clone().into(); for spec in render::mark_specs(mk).iter().rev() { let w = self.el(spec); w.append_child(&dom).unwrap(); dom = w.into(); } let mut inner = None; let mut px = 0.0; if *chunk { let w = self.document.create_element("div").unwrap(); if code { w.set_class_name("code-chunk"); set_lines(&w, s); px = line_count(s) as f64 * CODE_LINE_PX; } else { w.set_class_name("text-chunk"); px = utf16_len(s) as f64 * TEXT_CHAR_AREA / self.text_width; } if live { w.append_child(&dom).unwrap(); } inner = Some(dom); dom = w.into(); } Run { kind: RunKind::Text, len: utf16_len(s), dom, text: Some(t), s: s.clone(), chars: s.chars().count(), marks: mk.clone(), chunk: *chunk, live, inner, near: false, shown: false, px, styled: None } } MRun::Keep(_) => unreachable!("kept chunks are never rebuilt"), MRun::Other(kind) => { let el = match kind { RunKind::Image { src, alt, title } => { let el = self.el(&render::image_spec(src, alt, title.as_deref())); let _ = el.set_attribute("contenteditable", "false"); match src.strip_prefix("/media/rec/") { Some(id) => self.take_span(id, el), None => el, } } _ => self.document.create_element("br").unwrap(), }; Run { kind: kind.clone(), len: 1, dom: el.into(), text: None, s: String::new(), chars: 1, marks: Marks::default(), chunk: false, live: false, inner: None, near: false, shown: false, px: 0.0, styled: None } } } } /// The embed of a recording take: its audio, and a button to continue the take. Its state /// comes from `takes`. Only attributes change after this, never the children or the text, /// so the editor's observer does not see the state change. fn take_span(&self, id: &str, audio: Element) -> Element { let strings = Strings::load(&self.document); let state = self.takes.borrow().get(id).cloned().unwrap_or_else(|| "absent".to_owned()); let span = self.document.create_element("span").unwrap(); span.set_class_name("note-take"); let _ = span.set_attribute("contenteditable", "false"); let _ = span.set_attribute("data-take", id); let _ = span.set_attribute("data-take-state", &state); let _ = span.set_attribute("data-recording-label", &strings.get("recordingNow")); let _ = span.set_attribute("data-lost-label", &strings.get("recordingLost")); let _ = span.append_child(&audio); let button = self.document.create_element("button").unwrap(); let _ = button.set_attribute("type", "button"); button.set_class_name("note-take-continue"); button.set_text_content(Some(&strings.get("continueRecording"))); let _ = span.append_child(&button); span } // ----------------------------------------------------------------------- // Flush // ----------------------------------------------------------------------- /// Applies the model's block splices to the DOM. pub fn flush(&mut self, m: &Model) -> bool { let splices = m.take_splices(); if splices.is_empty() { return false; } let mut structural = false; for s in &splices { if let Some(c) = self.composing { if c >= s.at + s.removed { self.composing = Some(c + s.inserted - s.removed); } else if c >= s.at && !(s.removed == 1 && s.inserted == 1) { self.composing = None; } } if s.removed == 1 && s.inserted == 1 { if let Some((pi, k)) = self.locate(s.at) && let Some(Some(v)) = self.pages[pi].blocks.get_mut(k) { v.dirty = Some(match (v.dirty, s.edit) { (None, e) => e, _ => None, }); } structural |= s.edit.is_none(); continue; } structural = true; let quick = splices.len() == 1 && self.composing.is_none() && match (s.removed, s.inserted) { (1, 2) => self.split_chunked(m, s.at) || self.keep_first(s.at, 1, 2), (2, 1) => self.join_chunked(m, s.at) || self.keep_first(s.at, 2, 1), _ => false, }; if !quick { self.remove_blocks(s.at, s.removed); self.insert_blocks(s.at, s.inserted); } } if self.pages.is_empty() && m.len() > 0 { self.insert_blocks(0, m.len()); } if structural { self.layout(); } for pi in 0..self.pages.len() { if self.pages[pi].live { self.build_missing(m, pi); } } if structural { for pi in 0..self.pages.len() { if self.pages[pi].live { self.group(m, pi); } } } true } /// Enter inside a huge chunked block: the first part keeps the element and its /// chunks, the second one's chunks move to a new element after it, and only the /// chunk holding the split is rebuilt; both halves (tens of MB) are never read back /// and rendered again. Moving a first part with shown chunks instead would take away /// the browser's scroll anchor (shown text above the caret), and the view would /// jump megapixels. fn split_chunked(&mut self, m: &Model, at: usize) -> bool { let (Some(a), Some(b)) = (m.block(at), m.block(at + 1)) else { return false }; let Some((pi, k)) = self.locate(at) else { return false }; let Some(Some(v)) = self.pages[pi].blocks.get(k) else { return false }; let (la, lb) = (a.sepu - a.startu, b.sepu - b.startu); let text = |x: &Blk| x.kind().is_text() && x.kind() != Kind::Code; if !chunked(v) || v.dirty.is_some() || !text(&a) || !text(&b) || (v.attrs.kind != a.attrs.kind && v.attrs.kind != b.attrs.kind) { return false; } if v.runs.iter().map(|r| r.chars).sum::() != la + lb { return false; } let mut v = self.pages[pi].blocks[k].take().unwrap(); let mut i = 0; let mut acc = 0; while i < v.runs.len() && acc + v.runs[i].chars <= la { acc += v.runs[i].chars; i += 1; } let mut right = v.runs.split_off(i); let mut left = std::mem::take(&mut v.runs); if acc < la { // The split falls inside this chunk: its two parts are new runs. let r = right.remove(0); r.dom.unchecked_ref::().remove(); let cut = r.s.char_indices().nth(la - acc).map_or(r.s.len(), |(o, _)| o); left.push(self.build_run(&MRun::Text(r.s[..cut].to_owned(), Marks::default(), true), r.live, false)); if cut < r.s.len() { right.insert(0, self.build_run(&MRun::Text(r.s[cut..].to_owned(), Marks::default(), true), r.live, false)); } } // An empty first part (Enter at the block's start) moves for free. let keep_left = v.attrs.kind == a.attrs.kind && (left.iter().any(|r| r.shown) || v.attrs.kind != b.attrs.kind); let mut w = self.block_shell(if keep_left { &b } else { &a }); // Both halves keep the spacer scale, so nothing moves. w.scale = v.scale; let (stay, mut moved) = if keep_left { (left, right) } else { (right, left) }; unplace(&mut moved); v.runs = stay; w.runs = moved; v.attrs = if keep_left { a.attrs.clone() } else { b.attrs.clone() }; self.fix_trailing(&mut v); self.fix_trailing(&mut w); let (first, second) = if keep_left { (v, w) } else { (w, v) }; self.pages[pi].blocks[k] = Some(first); self.insert_blocks(at + 1, 1); // On a dead page (the next one) the second block is not shown yet. if let Some((pj, kj)) = self.locate(at + 1) && let Some(slot) = self.pages[pj].blocks.get_mut(kj) { *slot = Some(second); } else { second.el.remove(); } true } /// Enter or Backspace on a built block: it keeps its element, re-rendered from the /// model, and only the blocks after it are added or removed. Firefox's editor /// handles every element removed under the root, so replacing it would cost more. fn keep_first(&mut self, at: usize, removed: usize, inserted: usize) -> bool { let Some((pi, k)) = self.locate(at) else { return false }; match self.pages[pi].blocks.get_mut(k) { Some(Some(v)) => v.dirty = Some(None), _ => return false, } self.remove_blocks(at + 1, removed - 1); if inserted > 1 { // On the block's own page, which is live, even when it is the page's last. self.insert_in_page(pi, k + 1, inserted - 1); } true } /// Backspace or Delete joining a huge chunked block with its neighbour: the one with /// more chunks keeps its element, the other's content moves into it. fn join_chunked(&mut self, m: &Model, at: usize) -> bool { let Some(a) = m.block(at) else { return false }; let (Some((pi, k)), Some((pj, kj))) = (self.locate(at), self.locate(at + 1)) else { return false }; let (Some(Some(v)), Some(Some(w))) = (self.pages[pi].blocks.get(k), self.pages[pj].blocks.get(kj)) else { return false }; let plain = |x: &BView| x.runs.iter().all(|r| r.kind == RunKind::Text && r.marks == Marks::default()); if !(chunked(v) || chunked(w)) || !plain(v) || !plain(w) || v.dirty.is_some() || w.dirty.is_some() || a.kind() == Kind::Code { return false; } let chars = |x: &BView| x.runs.iter().map(|r| r.chars).sum::(); if chars(v) + chars(w) != a.sepu - a.startu { return false; } let host_first = match (v.attrs.kind == a.attrs.kind, w.attrs.kind == a.attrs.kind) { (true, true) => v.runs.len() >= w.runs.len(), (true, false) => true, (false, true) => false, (false, false) => return false, }; let v = self.pages[pi].blocks[k].take().unwrap(); let w = self.pages[pj].blocks[kj].take().unwrap(); // A short plain block joining a chunked one becomes a chunk too. let rechunk = |runs: Vec, this: &Self| -> Vec { if runs.iter().all(|r| r.chunk) { return runs; } let text: String = runs.iter().map(|r| r.s.as_str()).collect(); for r in &runs { r.dom.unchecked_ref::().remove(); } if text.is_empty() { return Vec::new(); } vec![this.build_run(&MRun::Text(text, Marks::default(), true), true, false)] }; let (mut host, other) = if host_first { (v, w) } else { (w, v) }; let (host_runs, mut other_runs) = (rechunk(std::mem::take(&mut host.runs), self), rechunk(other.runs, self)); unplace(&mut other_runs); let runs: Vec = if host_first { host_runs.into_iter().chain(other_runs).collect() } else { other_runs.into_iter().chain(host_runs).collect() }; other.el.remove(); host.runs = runs; host.attrs = a.attrs.clone(); self.fix_trailing(&mut host); self.pages[pi].blocks[k] = Some(host); self.remove_blocks(at + 1, 1); true } fn remove_blocks(&mut self, at: usize, mut n: usize) { let Some((mut pi, mut k)) = self.locate(at) else { return }; self.pages_changed(); let mut emptied = false; while n > 0 && pi < self.pages.len() { let p = &mut self.pages[pi]; let take = n.min(p.n - k); if take == p.n { // The whole page goes, its blocks with it. if p.attached { p.el.remove(); } emptied = true; } else if p.live { for v in p.blocks.drain(k..k + take).flatten() { v.el.remove(); } } else { p.height *= (p.n - take) as f64 / p.n as f64; } p.n -= take; p.shape = Shape::default(); n -= take; pi += 1; k = 0; } if emptied { self.pages.retain(|p| p.n > 0); } } fn insert_blocks(&mut self, at: usize, n: usize) { if n == 0 { return; } let (pi, k) = match self.locate(at) { Some(l) => l, None if self.pages.is_empty() => (0, 0), None => { let last = self.pages.len() - 1; (last, self.pages[last].n) } }; self.pages_changed(); if n <= PAGE && !self.pages.is_empty() { self.insert_in_page(pi, k, n); return; } // Many blocks (paste, undo of a large delete, a remote import): new placeholder // pages between the two halves of the page at the insertion point. let mut at_page = pi; if self.pages.is_empty() { } else if k > 0 && k < self.pages[pi].n { self.split_page(pi, k); at_page = pi + 1; } else if k > 0 { at_page = pi + 1; } let mut new = Vec::with_capacity(n.div_ceil(PAGE)); let mut left = n; while left > 0 { let c = PAGE.min(left); new.push(self.new_page(c, c as f64 * EST_BLOCK_PX)); left -= c; } self.pages.splice(at_page..at_page, new); } /// `n` new blocks at position `k` of page `pi`. fn insert_in_page(&mut self, pi: usize, k: usize, n: usize) { self.pages_changed(); let p = &mut self.pages[pi]; if p.live { p.blocks.splice(k..k, (0..n).map(|_| None)); } else { p.height += n as f64 * EST_BLOCK_PX; } p.n += n; p.shape = Shape::default(); if p.n > 2 * PAGE { let half = p.n / 2; self.split_page(pi, half); } } /// Splits page `pi` before its block `at`; the new page follows it, same state. fn split_page(&mut self, pi: usize, at: usize) { self.pages_changed(); let total = self.pages[pi].n; let mut page = self.new_page(total - at, 0.0); if self.pages[pi].live { page.blocks = self.pages[pi].blocks.split_off(at); page.live = true; } else { page.height = self.pages[pi].height * (total - at) as f64 / total as f64; self.pages[pi].height -= page.height; } self.pages[pi].n = at; self.pages[pi].shape = Shape::default(); self.pages.insert(pi + 1, page); } /// Re-renders a block from the model, discarding whatever the browser did to it. pub fn repair(&mut self, m: &Model, i: usize) { let Some(b) = m.block(i) else { return }; let Some((pi, k)) = self.locate(i) else { return }; let Some(mut v) = self.pages[pi].blocks.get_mut(k).and_then(Option::take) else { return }; if b.kind() != Kind::Rule { self.patch_runs(m, &b, &mut v, true); } self.pages[pi].blocks[k] = Some(v); } /// Rebuilds the page holding DOM node `n` (the browser changed its containers). pub fn repair_page_of(&mut self, m: &Model, n: &DomNode) { let Some(pi) = self.page_of(n) else { return }; if self.pages[pi].live { self.set_page_live(m, pi, false); self.set_page_live(m, pi, true); } } /// Whether the composed block changed while composing (it needs a rebuild). pub fn take_deferred(&mut self) -> bool { std::mem::take(&mut self.deferred) } /// Whether a block's DOM is exactly what the view built (no foreign nodes). pub fn intact(&self, i: usize) -> bool { let Some(v) = self.bview(i) else { return false }; let kids = v.content.child_nodes(); let expect = v.runs.iter().filter(|r| r.shown).count() + v.trailing.is_some() as usize; if kids.length() as usize != expect { return false; } for (i, r) in v.runs.iter().filter(|r| r.shown).enumerate() { if kids.get(i as u32).as_ref() != Some(&r.dom) { return false; } if r.chunk && !r.live { if r.dom.has_child_nodes() { return false; } continue; } if let Some(t) = &r.text { if r.dom != ***t && !r.dom.contains(Some(t)) { return false; } if t.length() == 0 { return false; } } } true } // ----------------------------------------------------------------------- // Lookup // ----------------------------------------------------------------------- pub fn bview(&self, i: usize) -> Option<&BView> { let (pi, k) = self.locate(i)?; self.pages[pi].blocks.get(k)?.as_ref() } fn bview_mut(&mut self, i: usize) -> Option<&mut BView> { let (pi, k) = self.locate(i)?; self.pages[pi].blocks.get_mut(k)?.as_mut() } pub fn element(&self, i: usize) -> Option<&Element> { self.bview(i).map(|v| &v.el) } /// The built blocks, with their indexes. pub fn live_blocks(&self) -> impl Iterator { let mut g = 0; self.pages.iter().flat_map(move |p| { let g0 = g; g += p.n; p.blocks.iter().enumerate().filter_map(move |(k, v)| v.as_ref().map(|v| (g0 + k, v))) }) } /// The index of the built block with `key`. pub fn find_key(&self, key: u32) -> Option { self.live_blocks().find(|(_, v)| v.key == key).map(|(i, _)| i) } fn page_index(&self, uid: u32) -> Option { self.pages.iter().position(|p| p.uid == uid) } /// The page holding DOM node `n`. fn page_of(&self, n: &DomNode) -> Option { let mut cur = Some(n.clone()); while let Some(c) = cur { if c == **self.root { return None; } if let Some(uid) = js_sys::Reflect::get(&c, &self.page_key).ok().and_then(|v| v.as_f64()) { return self.page_index(uid as u32); } cur = c.parent_node(); } None } /// The block whose element holds DOM node `n` (or is it), and that element. pub fn owner(&self, n: &DomNode) -> Option<(usize, Element)> { let mut cur = Some(n.clone()); while let Some(c) = cur { if c == **self.root { return None; } if js_sys::Reflect::get(&c, &self.block_key).ok().is_some_and(|v| v.is_truthy()) { let el: Element = c.unchecked_into(); let pi = self.page_of(&el)?; let k = self.pages[pi].blocks.iter().position(|v| v.as_ref().is_some_and(|v| v.el == el))?; return Some((self.page_start(pi) + k, el)); } cur = c.parent_node(); } None } // ----------------------------------------------------------------------- // Positions // ----------------------------------------------------------------------- /// The DOM point for a model offset (its page must be live). pub fn pos_to_dom(&self, m: &Model, p: Pos) -> Option<(DomNode, u32)> { let b = m.at(p); let v = self.bview(b.index)?; if b.kind() == Kind::Rule { let parent = v.el.parent_node()?; let i = index_in(&parent, v.el.as_ref()); return Some((parent, i + u32::from(p > b.start))); } let off = p.saturating_sub(b.start); let mut acc = 0; for (i, r) in v.runs.iter().enumerate() { if let Some(t) = &r.text { // At a boundary the caret sits at the end of the text before it, except // after a chunk's closing newline: that is the next chunk's first line. let next_line = r.chunk && off == acc + r.len && i + 1 < v.runs.len(); if off <= acc + r.len && !next_line { return Some((t.clone().into(), (off - acc) as u32)); } } else if off == acc { return Some((v.content.clone().into(), i as u32)); } acc += r.len; } Some((v.content.clone().into(), v.runs.len() as u32)) } /// The model offset for a DOM point, by walking the DOM (robust to foreign nodes). pub fn dom_to_pos(&self, m: &Model, node: &DomNode, offset: u32) -> Option { if let Some((i, el)) = self.owner(node) { let b = m.block(i)?; let v = self.bview(i)?; if b.kind() == Kind::Rule { return Some(b.start); } let content: &DomNode = v.content.as_ref(); if node == AsRef::::as_ref(&el) && el != v.content { // On `pre` itself: before or after its `code`. return Some(if offset == 0 { b.start } else { b.sep }); } let off = if v.runs.iter().any(|r| r.chunk) { chunk_offset(v, node, offset) } else { None }; let off = match off { Some(o) => o, None => dom_offset(content, node, offset)?, }; return Some(b.start + off.min(b.len())); } let root: &DomNode = self.root.as_ref(); if node == root { // The root's children are live pages and spacers. let Some(child) = root.child_nodes().get(offset) else { return Some(m.last().sep) }; let pi = self.page_of(&child)?; return m.block(self.page_start(pi)).map(|b| b.start); } // Between blocks, inside a page's containers. let pi = self.page_of(node)?; let g0 = self.page_start(pi); let page = &self.pages[pi]; if !page.live { return m.block(g0).map(|b| b.start); } let after = node.child_nodes().get(offset); for (k, v) in page.blocks.iter().enumerate() { let Some(v) = v else { continue }; let el: &DomNode = v.el.as_ref(); let following = match &after { Some(a) => a == el || a.contains(Some(el)) || a.compare_document_position(el) & DomNode::DOCUMENT_POSITION_FOLLOWING != 0, None => node.compare_document_position(el) & DomNode::DOCUMENT_POSITION_FOLLOWING != 0 && !node.contains(Some(el)), }; if following { return m.block(g0 + k).map(|b| b.start); } } m.block(g0 + page.n - 1).map(|b| b.sep) } /// After the browser typed `data` into text node `t` at UTF-16 offset `at`: the run /// cache follows, and the block's next dirty mark is skipped (DOM and model agree). /// Returns false when `t` is not one of the block's runs. pub fn typed(&mut self, i: usize, t: &DomNode, at: usize, data: &str) -> bool { let Some(v) = self.bview_mut(i) else { return false }; let Some(r) = v.runs.iter_mut().find(|r| r.text.as_ref().is_some_and(|x| AsRef::::as_ref(x) == t)) else { return false; }; let at = byte_at_utf16(&r.s, at); r.s.insert_str(at, data); r.len += utf16_len(data); r.chars += data.chars().count(); v.synced = true; true } /// Re-reads the run caches of a block from the DOM, after the browser changed it in /// ways only a full read-back understood. pub fn resync(&mut self, i: usize) { if let Some(v) = self.bview_mut(i) { for r in v.runs.iter_mut().filter(|r| !r.chunk || r.live) { if let Some(t) = &r.text { r.s = t.data(); r.len = utf16_len(&r.s); r.chars = r.s.chars().count(); } } } } /// The text the DOM shows for a block, UTF-16: our breaks as `\n`, images as /// U+FFFC, and any element the browser made as U+FFFC too (the model wins then). pub fn dom_text(&self, i: usize) -> Option> { let v = self.bview(i)?; let mut out = Vec::new(); walk(v.content.as_ref(), &mut |n| { if let Some(ri) = v.runs.iter().position(|r| r.dom == *n) { let r = &v.runs[ri]; match r.kind { RunKind::Break => { out.push(b'\n' as u16); return true; } RunKind::Image { .. } => { out.push(OBJ as u16); return true; } RunKind::Text if r.chunk && !r.live => { for r in v.runs[ri..].iter().take_while(|x| x.chunk && !x.live && (x.dom == *n || !x.shown)) { out.extend(r.s.encode_utf16()); } return true; } RunKind::Text => {} } } match n.node_type() { DomNode::TEXT_NODE => out.extend(n.node_value().unwrap_or_default().encode_utf16()), DomNode::ELEMENT_NODE => { let e: &Element = n.unchecked_ref(); match e.tag_name().as_str() { "BR" if e.class_name() != TRAILING_BREAK => out.push(OBJ as u16), "IMG" => out.push(OBJ as u16), _ => {} } } _ => {} } false }); Some(out) } /// Shows the chunks holding (and next to) the selection ends, so the DOM selection /// can be placed and arrow keys find text around it. pub fn ensure_live(&mut self, m: &Model, positions: &[Pos]) { for &p in positions { let b = m.at(p); let ends: Vec = positions.iter().filter(|&&q| b.holds(q)).map(|q| q - b.start).collect(); let Some(v) = self.bview_mut(b.index) else { continue }; if !v.runs.first().is_some_and(|r| r.chunk) { continue; } let off = p - b.start; let mut acc = 0; let mut at = v.runs.len() - 1; for (i, r) in v.runs.iter().enumerate() { if off < acc + r.len || off == acc + r.len && i + 1 == v.runs.len() { at = i; break; } acc += r.len; } // Shown: what the observer reports near, plus the chunks holding a selection // end and their neighbours. Everything else goes back to a placeholder. let mut start = 0; for (i, r) in v.runs.iter_mut().enumerate() { let holds = ends.iter().any(|&o| o >= start && o <= start + r.len); start += r.len; let want = r.near || holds || i + 1 >= at && i <= at + 1; set_live(r, want); } place_runs(v); } } } fn common(a: &[Wrap], b: &[Wrap]) -> usize { a.iter().zip(b).take_while(|(x, y)| x == y).count() } /// The number of the level-`l` ordered list item holding block `g` (counting a new /// item `g` starts), walking back to where the list starts. fn item_number(m: &Model, g: usize, l: usize) -> i64 { let Some(first) = m.block(g) else { return 1 }; let mut count = 0; let mut cur = first.attrs; let mut result = None; m.scan(g, true, |_, prev| { let k = keep(Some(prev), &cur); if k > l { // Same item. } else if k == l && common(&prev.wrap, &cur.wrap) > l && cur.wrap[l].is_list() { count += 1; } else { result = Some(list_start(prev, &cur, l) + count); return false; } cur = prev.clone(); true }); // Reached the first block: the list starts there. result.unwrap_or_else(|| list_start_first(&cur, l) + count) } /// The first number of the level-`l` list `cur` opens after `prev`. fn list_start(prev: &Attrs, cur: &Attrs, l: usize) -> i64 { let k = keep(Some(prev), cur); let common = common(&prev.wrap, &cur.wrap); let stay = if k < common && cur.wrap[k].is_list() { k + 1 } else { k }; let deepest = (stay..cur.wrap.len()).rev().find(|&i| cur.wrap[i] == Wrap::Ordered); if deepest == Some(l) { cur.start.unwrap_or(1) } else { 1 } } fn list_start_first(cur: &Attrs, l: usize) -> i64 { let deepest = (0..cur.wrap.len()).rev().find(|&i| cur.wrap[i] == Wrap::Ordered); if deepest == Some(l) { cur.start.unwrap_or(1) } else { 1 } } 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) } /// Attaches or detaches a chunk's content (see `Run::live`). fn set_live(r: &mut Run, live: bool) { if !r.chunk || r.live == live { return; } let Some(inner) = &r.inner else { return }; if live { let _ = r.dom.append_child(inner); } else if inner.parent_node().is_some_and(|p| p == r.dom) { // It keeps the height `sync_viewport` last saw (measuring here would force a // layout in the middle of an edit). let _ = r.dom.remove_child(inner); } r.live = live; } /// Depth-first walk; `f` returns true to skip a node's children. fn walk(n: &DomNode, f: &mut dyn FnMut(&DomNode) -> bool) { let mut c = n.first_child(); while let Some(k) = c { if !f(&k) { walk(&k, f); } c = k.next_sibling(); } } /// Turns text node `t` (holding `old`) into `new` with one `replaceData` over the /// part that differs, so the caret and spellcheck state around it survive. fn replace_minimal(t: &Text, old: &str, new: &str) { if old == new { return; } let (a, b) = (old.as_bytes(), new.as_bytes()); let mut p = a.iter().zip(b).take_while(|(x, y)| x == y).count(); while !old.is_char_boundary(p) || !new.is_char_boundary(p) { p -= 1; } let max_s = (a.len() - p).min(b.len() - p); let mut q = a.iter().rev().zip(b.iter().rev()).take(max_s).take_while(|(x, y)| x == y).count(); while !old.is_char_boundary(a.len() - q) || !new.is_char_boundary(b.len() - q) { q -= 1; } let at = utf16_len(&old[..p]) as u32; let count = utf16_len(&old[p..a.len() - q]) as u32; let _ = t.replace_data(at, count, &new[p..b.len() - q]); } /// Byte index of UTF-16 offset `off` in `s` (clamped to the end). pub fn byte_at_utf16(s: &str, off: usize) -> usize { if s.is_ascii() { return off.min(s.len()); } let mut n = 0; for (i, c) in s.char_indices() { if n >= off { return i; } n += c.len_utf16(); } s.len() } fn node_len(n: &DomNode) -> usize { match n.node_type() { DomNode::TEXT_NODE => n.unchecked_ref::().length() as usize, DomNode::ELEMENT_NODE => { let e: &Element = n.unchecked_ref(); match e.tag_name().as_str() { "BR" if e.class_name() != TRAILING_BREAK => 1, "IMG" => 1, _ => { let mut s = 0; let mut c = n.first_child(); while let Some(k) = c { s += node_len(&k); c = k.next_sibling(); } s } } } _ => 0, } } /// UTF-16 offset of DOM point (node, offset) inside `content`. fn dom_offset(content: &DomNode, node: &DomNode, offset: u32) -> Option { enum Stop { /// Inside a text node, at this offset. Text(DomNode, usize), /// Just before this node. Before(DomNode), /// Just after this node's content. After(DomNode), } let stop = if node.node_type() == DomNode::TEXT_NODE { Stop::Text(node.clone(), offset as usize) } else { match node.child_nodes().get(offset) { Some(c) => Stop::Before(c), None => Stop::After(node.clone()), } }; if let Stop::After(n) = &stop && n == content { return Some(node_len(content)); } fn go(n: &DomNode, stop: &Stop, acc: &mut usize) -> bool { let mut c = n.first_child(); while let Some(k) = c { match stop { Stop::Text(t, o) if *t == k => { *acc += (*o).min(node_len(&k)); return true; } Stop::Before(b) if *b == k => return true, Stop::After(a) if *a == k => { *acc += node_len(&k); return true; } _ => {} } let target = match stop { Stop::Text(t, _) => t, Stop::Before(t) => t, Stop::After(t) => t, }; if k.contains(Some(target)) { return go(&k, stop, acc); } *acc += node_len(&k); c = k.next_sibling(); } false } let mut acc = 0; go(content, &stop, &mut acc).then_some(acc) } pub fn utf16_len(s: &str) -> usize { note_model::flat::str_lens(s).1 } enum MRun { /// Text, its marks, and whether it is a chunk. Text(String, Marks, bool), /// A break or an image. Other(RunKind), /// Old run `i`, unchanged (chunks reuse their runs without copying text). Keep(usize), } /// Line height of code (px), which sizes hidden code chunks. const CODE_LINE_PX: f64 = 22.0; fn line_count(s: &str) -> usize { (s.bytes().filter(|&b| b == b'\n').count() + usize::from(!s.ends_with('\n'))).max(1) } /// Puts a block's runs in its content element: every run but hidden chunks, and for /// each run of hidden chunks one spacer (the first one) as tall as all of them. Only /// what changed touches the DOM: Firefox's editor handles every node added or removed /// right away, and lays out every child of the block on each keystroke. fn place_runs(v: &mut BView) { let hidden = |r: &Run| r.chunk && !r.live; if v.runs.iter().all(|r| r.shown && !hidden(r)) { return; } let total: f64 = v.runs.iter().filter(|r| hidden(r)).map(|r| r.px).sum(); v.scale = rescale(v.scale, total); let mut prev: Option = None; let mut i = 0; while i < v.runs.len() { let mut j = i + 1; let mut height = None; if hidden(&v.runs[i]) { let mut h = v.runs[i].px; while j < v.runs.len() && hidden(&v.runs[j]) { h += v.runs[j].px; j += 1; } height = Some((h * v.scale).round() as i64); } if !v.runs[i].shown { let next = match prev { Some(p) => v.runs[p].dom.next_sibling(), None => v.content.first_child(), }; let _ = v.content.insert_before(&v.runs[i].dom, next.as_ref()); } let r = &mut v.runs[i]; r.shown = true; if r.chunk && r.styled != height { let el: &Element = r.dom.unchecked_ref(); match height { Some(h) => set_height(el, h as f64), None if el.class_name() == "code-chunk" => set_lines(&r.dom, &r.s), None => { let _ = el.remove_attribute("style"); } } r.styled = height; } prev = Some(i); for r in &mut v.runs[i + 1..j] { if r.shown { r.dom.unchecked_ref::().remove(); r.shown = false; } } i = j; } } /// Takes runs out of the DOM before they move to another block. fn unplace(runs: &mut [Run]) { for r in runs.iter_mut().filter(|r| r.shown) { r.dom.unchecked_ref::().remove(); r.shown = false; } } /// Viewport top and bottom of run `i`; a hidden chunk's lie within its spacer. fn chunk_box(v: &BView, i: usize) -> (f64, f64) { let mut head = i; let mut h = 0.0; while !v.runs[head].shown && head > 0 { head -= 1; h += v.runs[head].px; } let r = v.runs[head].dom.unchecked_ref::().get_bounding_client_rect(); if head == i && !(v.runs[i].chunk && !v.runs[i].live) { return (r.top(), r.bottom()); } let top = r.top() + h * v.scale; (top, top + v.runs[i].px * v.scale) } /// A block shown as plain text chunks. fn chunked(v: &BView) -> bool { !v.runs.is_empty() && v.runs.iter().all(|r| r.chunk && r.kind == RunKind::Text && r.marks == Marks::default()) } fn model_runs(m: &Model, b: &Blk) -> Vec { let fb = m.read_block(b); let mut out = Vec::with_capacity(fb.inl.len()); for i in fb.inl { match i { Inline::Text(s, mk) if !s.is_empty() => out.push(MRun::Text(s, mk, false)), Inline::Text(..) => {} Inline::HardBreak => out.push(MRun::Other(RunKind::Break)), Inline::Image { src, alt, title } => out.push(MRun::Other(RunKind::Image { src, alt, title })), } } out } /// Most the spacers add up to (px): browsers cap layout lengths (Firefox near 17.9M px), /// past which a long note could not scroll to its end. const MAX_PX: f64 = 12_000_000.0; /// Spacers may add up to this before the scale shrinks again. const HARD_PX: f64 = 16_000_000.0; /// The scale for spacers adding up to `total` px, kept while it still fits and is /// not far below what is needed: a new scale changes every spacer's height, which /// moves everything and costs a layout of all that is shown (Enter splitting a huge /// block halves it; each block added to a long note grows the total). fn rescale(scale: f64, total: f64) -> f64 { let want = if total > MAX_PX { MAX_PX / total } else { 1.0 }; if total * scale <= HARD_PX && scale * 2.5 > want { scale } else { want } } /// Pages and chunks within this distance of the viewport (px) have their content. const NEAR_PX: f64 = 1500.0; /// The items `first..last` of `n` boxes stacked top to bottom that overlap `top..=bottom` /// (viewport coordinates). `rect(i)` is item `i`'s top and bottom. fn near_range(n: usize, rect: impl Fn(usize) -> (f64, f64), top: f64, bottom: f64) -> (usize, usize) { let (mut lo, mut hi) = (0, n); while lo < hi { let mid = (lo + hi) / 2; if rect(mid).1 < top { lo = mid + 1; } else { hi = mid; } } let mut last = lo; while last < n && rect(last).0 <= bottom { last += 1; } (lo, last) } /// Area (px²) one character of body text takes, for sizing hidden text chunks /// never shown yet: about 8px wide on a 26px line. const TEXT_CHAR_AREA: f64 = 8.0 * 26.0; fn set_height(el: &Element, px: f64) { let _ = el.set_attribute("style", &format!("height:{}px", px.round())); } /// Sizes a chunk's placeholder: its number of lines. fn set_lines(el: &DomNode, s: &str) { let _ = el.unchecked_ref::().set_attribute("style", &format!("--lines:{}", line_count(s))); } /// UTF-16 offset of DOM point (node, offset) in a chunked block, counting hidden chunks /// by their cached length. `None` when the point is outside every run. fn chunk_offset(v: &BView, node: &DomNode, offset: u32) -> Option { let content: &DomNode = v.content.as_ref(); if node != content { if let Some(off) = chunk_offset_hinted(v, node, offset) { return Some(off); } } if node == content { // A shown node stands for itself and the hidden runs after it. let kids = content.child_nodes(); let mut acc = 0; for k in 0..offset.min(kids.length()) { let c = kids.get(k)?; match v.runs.iter().position(|r| r.dom == c) { Some(ri) => { let j = ri + 1 + v.runs[ri + 1..].iter().take_while(|r| !r.shown).count(); acc = v.runs[..j].iter().map(|r| r.len).sum(); } None => acc += node_len(&c), } } return Some(acc); } let mut acc = 0; for r in &v.runs { if r.dom == *node { return Some(acc + if offset == 0 { 0 } else { r.len }); } if r.dom.contains(Some(node)) { return Some(acc + dom_offset(&r.dom, node, offset)?.min(r.len)); } acc += r.len; } None } /// [`chunk_offset`] inside a run, found from the node's ancestor under the content. The /// run's index is cached on that element and checked before use: comparing every /// chunk, thousands of JS calls, took milliseconds a keystroke. fn chunk_offset_hinted(v: &BView, node: &DomNode, offset: u32) -> Option { let key = &JsValue::from_str(RUN_KEY); let content: &DomNode = v.content.as_ref(); let mut child = node.clone(); loop { let parent = child.parent_node()?; if parent == *content { break; } child = parent; } let hint = js_sys::Reflect::get(&child, key).ok().and_then(|h| h.as_f64()).map(|h| h as usize); let ri = match hint.filter(|&h| v.runs.get(h).is_some_and(|r| r.dom == child)) { Some(h) => h, None => { let ri = v.runs.iter().position(|r| r.dom == child)?; let _ = js_sys::Reflect::set(&child, key, &JsValue::from_f64(ri as f64)); ri } }; let r = &v.runs[ri]; let acc: usize = v.runs[..ri].iter().map(|r| r.len).sum(); if r.dom == *node { return Some(acc + if offset == 0 { 0 } else { r.len }); } Some(acc + dom_offset(&r.dom, node, offset)?.min(r.len)) } /// Code blocks longer than this many lines render as chunks of at least this size: /// a line added or removed relays out the chunk it is in, so the smaller the better. const CHUNK_LINES: usize = 250; /// Chunks of one code block at most: every keystroke walks them. const MAX_CHUNKS: usize = 8000; /// Lines per chunk of a code block of `total` lines. fn code_chunk_lines(total: usize) -> usize { total.div_ceil(MAX_CHUNKS).max(CHUNK_LINES) } /// Other blocks longer than twice this many bytes render as chunks of about this /// size, cut after a space. const CHUNK_BYTES: usize = 8 * 1024; /// Splits a huge block of one text run into chunks (code at line ends, other text /// after spaces), reusing the boundaries of the `old` runs wherever their text is /// unchanged, so an edit rebuilds only its chunk. /// `lines` is the code block's lines per chunk, set from its length. fn chunk_text(new: Vec, old: &[Run], code: bool, lines: &mut usize) -> Vec { let [MRun::Text(text, marks, _)] = new.as_slice() else { return new }; let was_chunked = old.first().is_some_and(|r| r.chunk); // Hysteresis: a chunked block goes back to one text node only well below the limit. let big = if code { let limit = if was_chunked { CHUNK_LINES / 2 } else { CHUNK_LINES }; text.bytes().filter(|&b| b == b'\n').nth(limit).is_some() } else { text.len() > if was_chunked { CHUNK_BYTES } else { 2 * CHUNK_BYTES } }; if !big { return new; } if code { *lines = code_chunk_lines(text.bytes().filter(|&b| b == b'\n').count()); } let sep = if code { b'\n' } else { b' ' }; let reusable = |r: &Run| r.chunk && r.kind == RunKind::Text && &r.marks == marks; // Unchanged leading and trailing chunks, at boundaries. let (mut a, mut i) = (0, 0); while i < old.len() && reusable(&old[i]) && text[a..].starts_with(&old[i].s) && old[i].s.as_bytes().last() == Some(&sep) { a += old[i].s.len(); i += 1; } let (mut b, mut j) = (text.len(), old.len()); while j > i && reusable(&old[j - 1]) && b - a >= old[j - 1].s.len() && text[..b].ends_with(&old[j - 1].s) { let start = b - old[j - 1].s.len(); if start > 0 && text.as_bytes()[start - 1] != sep { break; } b = start; j -= 1; } let mut out: Vec = (0..i).map(MRun::Keep).collect(); out.extend(split_chunks(&text[a..b], marks, code, *lines)); out.extend((j..old.len()).map(MRun::Keep)); out } /// Cuts text into chunks every `per` lines (code) or after CHUNK_BYTES bytes at a space. fn split_chunks(text: &str, marks: &Marks, code: bool, per: usize) -> Vec { let sep = if code { b'\n' } else { b' ' }; let mut out = Vec::new(); let (mut start, mut lines) = (0, 0); for (k, c) in text.bytes().enumerate() { if c == sep { lines += 1; if if code { lines == per } else { k + 1 - start >= CHUNK_BYTES } { out.push(MRun::Text(text[start..=k].to_owned(), marks.clone(), true)); start = k + 1; lines = 0; } } } if start < text.len() { out.push(MRun::Text(text[start..].to_owned(), marks.clone(), true)); } out }