forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

view.rs1966 lines, 76.5 KiBHistoryRawDownload
1//! The DOM side of the editor: the body's blocks in pages, an incremental flush
2//! driven by the model's block splices, DOM <-> offset mapping and the read-back of
3//! text the browser typed natively.
4//!
5//! Blocks are flat in the model; the DOM nests them (`ul > li > p`, `blockquote`) per
6//! page. A container cut by a page boundary is split: the part on the later page has
7//! `pm-cont` (and the earlier part `pm-more`), which the stylesheet joins seamlessly.
8
9use std::collections::HashMap;
10use std::rc::Rc;
11
12use note_model::flat::{Attrs, Kind, OBJ, Wrap};
13use note_model::marks::Marks;
14use note_model::render::{self, TRAILING_BREAK};
15use note_model::write::Inline;
16use wasm_bindgen::{JsCast, JsValue};
17use web_sys::{Document, Element, HtmlElement, Node as DomNode, Text};
18
19use crate::core::commands::keep;
20use crate::core::model::{Blk, Model};
21use crate::core::pos::Pos;
22use crate::strings::Strings;
23
24/// Expando on page elements: the page's uid.
25const PAGE_KEY: &str = "__pmPage";
26/// Expando on block elements.
27const BLOCK_KEY: &str = "__pmBlock";
28/// Property on a chunk element: its last known index in its block's runs.
29const RUN_KEY: &str = "__pmRun";
30
31/// Blocks per page.
32const PAGE: usize = 64;
33/// Assumed height of a block never measured (px).
34const EST_BLOCK_PX: f64 = 32.0;
35
36pub struct BView {
37 /// Stable while the block's element lives (UI state is keyed by it).
38 pub key: u32,
39 pub el: Element,
40 /// Where the runs go (`code` inside `pre`, else `el`).
41 pub content: Element,
42 pub attrs: Attrs,
43 pub runs: Vec<Run>,
44 trailing: Option<Element>,
45 /// Content changed: `Some(range)` for one plain edit (Unicode, from the block
46 /// start), `None` for anything else (attributes may have changed too).
47 dirty: Option<Option<(usize, usize)>>,
48 /// The DOM already matches the model (typed natively): the next dirty mark is moot.
49 synced: bool,
50 /// Hidden chunks' spacers are drawn this much shorter (see `MAX_PX`).
51 scale: f64,
52 /// For a chunked code block: lines per chunk (see [`code_chunk_lines`]).
53 lines: usize,
54}
55
56#[derive(Clone, PartialEq, Debug)]
57pub enum RunKind {
58 Text,
59 Break,
60 Image { src: String, alt: String, title: Option<String> },
61}
62
63pub struct Run {
64 pub kind: RunKind,
65 /// UTF-16 length.
66 pub len: usize,
67 /// Outermost DOM node of the run (a mark wrapper, the text, or the element).
68 pub dom: DomNode,
69 pub text: Option<Text>,
70 /// The text of `text`, kept equal to the DOM node: patches compare against it
71 /// instead of reading the DOM, and edits typed natively update it.
72 pub s: String,
73 /// Unicode scalars of the run (Loro's text positions).
74 pub chars: usize,
75 pub marks: Marks,
76 /// A piece of a long block, wrapped in its own element (`dom`).
77 pub chunk: bool,
78 /// For a chunk: its content is attached. Chunks far from the viewport and the caret
79 /// are empty placeholders sized by their line count (`inner` stays detached, still
80 /// holding the text): the browser's per-keystroke cost grows with all editable text.
81 pub live: bool,
82 /// For a chunk: the node inside `dom` (the text, or its mark wrapper).
83 pub inner: Option<DomNode>,
84 /// For a chunk: last seen near the viewport.
85 pub near: bool,
86 /// `dom` is in the block's content element (see `place_runs`).
87 shown: bool,
88 /// For a chunk: its height while hidden (px, unscaled).
89 px: f64,
90 /// For a hidden chunk shown as a spacer: the height written on it.
91 styled: Option<i64>,
92}
93
94/// A run of consecutive blocks under one element. Only pages near the viewport (or
95/// holding the selection) are built; the rest keep their last measured height, and
96/// 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
97/// in the DOM, so this keeps typing flat in documents of any length.
98struct Page {
99 el: Element,
100 uid: u32,
101 n: usize,
102 live: bool,
103 height: f64,
104 /// `el` is in the root: a live page, or the spacer standing for a run of dead ones.
105 attached: bool,
106 /// The height written on `el` as a spacer.
107 styled: Option<i64>,
108 /// When live, one entry per block; `None` until built.
109 blocks: Vec<Option<BView>>,
110 /// What the grouping was built from (see `View::shape`).
111 shape: Shape,
112}
113
114#[derive(PartialEq, Default)]
115struct Shape {
116 prev: Option<Attrs>,
117 next: Option<Attrs>,
118 blocks: Vec<(Vec<Wrap>, Option<usize>, Option<i64>)>,
119 numbers: Vec<i64>,
120}
121
122pub struct View {
123 pub root: HtmlElement,
124 document: Document,
125 pages: Vec<Page>,
126 /// The first block of each page, and the block count last; empty when stale.
127 /// Changes to the pages or their block counts clear it (`pages_changed`).
128 starts: std::cell::RefCell<Vec<usize>>,
129 next_uid: u32,
130 page_key: JsValue,
131 block_key: JsValue,
132 /// The block being composed into; the flush leaves it alone.
133 pub composing: Option<usize>,
134 /// The composed block changed meanwhile: rebuilt when the composition ends.
135 deferred: bool,
136 /// Content width when text chunks were last built (see `TEXT_CHAR_AREA`).
137 text_width: f64,
138 /// Spacers are drawn this much shorter than the pages they stand for (see `MAX_PX`).
139 scale: f64,
140 /// The state of each take on the server, `live` or `lost`; a take not listed is absent.
141 /// Sync keeps it up to date, and a take's embed reads it when the embed is built.
142 pub takes: Rc<std::cell::RefCell<HashMap<String, String>>>,
143}
144
145impl View {
146 pub fn new(root: HtmlElement) -> Self {
147 let document = root.owner_document().unwrap();
148 View {
149 root,
150 document,
151 pages: Vec::new(),
152 starts: Default::default(),
153 next_uid: 0,
154 page_key: JsValue::from_str(PAGE_KEY),
155 block_key: JsValue::from_str(BLOCK_KEY),
156 composing: None,
157 deferred: false,
158 text_width: 800.0,
159 scale: 1.0,
160 takes: Rc::default(),
161 }
162 }
163
164 /// Renders the whole body, replacing what is in the root (the server pre-render).
165 pub fn render_all(&mut self, m: &Model) {
166 m.take_splices();
167 self.pages.clear();
168 self.pages_changed();
169 self.root.set_text_content(None);
170 let n = m.len();
171 let mut i = 0;
172 while i < n {
173 let k = PAGE.min(n - i);
174 let page = self.new_page(k, k as f64 * EST_BLOCK_PX);
175 self.pages.push(page);
176 i += k;
177 }
178 self.pages_changed();
179 self.layout();
180 // The top shows at once; `sync_viewport` brings in the rest as it scrolls near.
181 for p in 0..self.pages.len().min(2) {
182 self.set_page_live(m, p, true);
183 }
184 }
185
186 fn new_page(&mut self, n: usize, height: f64) -> Page {
187 let el = self.document.create_element("div").unwrap();
188 el.set_class_name("pm-page");
189 let uid = self.next_uid;
190 self.next_uid += 1;
191 let _ = js_sys::Reflect::set(&el, &self.page_key, &JsValue::from(uid));
192 Page { el, uid, n, live: false, height, attached: false, styled: None, blocks: Vec::new(), shape: Shape::default() }
193 }
194
195 fn starts(&self) -> std::cell::Ref<'_, Vec<usize>> {
196 if self.starts.borrow().is_empty() {
197 let mut s = self.starts.borrow_mut();
198 s.reserve(self.pages.len() + 1);
199 let mut acc = 0;
200 s.push(0);
201 for p in &self.pages {
202 acc += p.n;
203 s.push(acc);
204 }
205 }
206 self.starts.borrow()
207 }
208
209 fn pages_changed(&mut self) {
210 self.starts.get_mut().clear();
211 }
212
213 /// The first block of page `pi`.
214 fn page_start(&self, pi: usize) -> usize {
215 self.starts()[pi]
216 }
217
218 /// Page and position in it of block `i`.
219 fn locate(&self, i: usize) -> Option<(usize, usize)> {
220 let s = self.starts();
221 if i >= *s.last()? {
222 return None;
223 }
224 let pi = s.partition_point(|&x| x <= i) - 1;
225 Some((pi, i - s[pi]))
226 }
227
228 fn set_page_live(&mut self, m: &Model, pi: usize, live: bool) {
229 if self.pages[pi].live == live {
230 return;
231 }
232 if live {
233 let n = self.pages[pi].n;
234 self.pages[pi].blocks = (0..n).map(|_| None).collect();
235 self.pages[pi].live = true;
236 self.pages[pi].shape = Shape::default();
237 self.build_missing(m, pi);
238 self.group(m, pi);
239 } else {
240 let p = &mut self.pages[pi];
241 p.blocks.clear();
242 p.el.set_text_content(None);
243 p.live = false;
244 }
245 self.layout();
246 }
247
248 /// Puts the live pages in the root, and for each run of dead pages one spacer (the
249 /// run's first page) as tall as the run: the root holds a few elements however long
250 /// the note is. Firefox's spellchecker handles every node added to or removed from
251 /// an editable root right away, 2 s for 15k placeholder pages.
252 fn layout(&mut self) {
253 let total: f64 = self.pages.iter().map(|p| p.height).sum();
254 self.scale = rescale(self.scale, total);
255 let mut prev: Option<Element> = None;
256 let mut i = 0;
257 while i < self.pages.len() {
258 if self.pages[i].live {
259 self.attach(i, &mut prev, None);
260 i += 1;
261 continue;
262 }
263 let mut j = i;
264 let mut h = 0.0;
265 while j < self.pages.len() && !self.pages[j].live {
266 h += self.pages[j].height;
267 j += 1;
268 }
269 self.attach(i, &mut prev, Some((h * self.scale).round() as i64));
270 for p in &mut self.pages[i + 1..j] {
271 if p.attached {
272 p.el.remove();
273 p.attached = false;
274 }
275 }
276 i = j;
277 }
278 }
279
280 fn attach(&mut self, i: usize, prev: &mut Option<Element>, height: Option<i64>) {
281 let p = &mut self.pages[i];
282 if !p.attached {
283 let _ = match prev {
284 Some(e) => e.after_with_node_1(&p.el),
285 None => self.root.prepend_with_node_1(&p.el),
286 };
287 p.attached = true;
288 }
289 if p.styled != height {
290 let _ = match height {
291 Some(h) => p.el.set_attribute("style", &format!("height:{h}px")),
292 None => p.el.remove_attribute("style"),
293 };
294 p.styled = height;
295 }
296 *prev = Some(p.el.clone());
297 }
298
299 /// Viewport top and bottom of page `i`; a dead page's lie within its run's spacer.
300 fn page_box(&self, i: usize) -> (f64, f64) {
301 let mut h = 0.0;
302 let mut head = i;
303 if !self.pages[i].live {
304 while head > 0 && !self.pages[head - 1].live {
305 head -= 1;
306 h += self.pages[head].height;
307 }
308 }
309 let r = self.pages[head].el.get_bounding_client_rect();
310 if self.pages[i].live {
311 (r.top(), r.bottom())
312 } else {
313 let k = self.scale;
314 (r.top() + h * k, r.top() + (h + self.pages[i].height) * k)
315 }
316 }
317
318 /// Builds the page holding block `i`, so it can take the selection.
319 pub fn show(&mut self, m: &Model, i: usize) {
320 if let Some((pi, _)) = self.locate(i) {
321 self.set_page_live(m, pi, true);
322 }
323 }
324
325 /// Builds the pages and attaches the chunks within `NEAR_PX` of the viewport, and
326 /// empties the others, except where the selection or a composition is. Pages and
327 /// chunks are stacked top to bottom, so binary searches on their boxes find the
328 /// range: a few layout reads per frame however long the note is. Returns whether
329 /// anything changed, which moves what follows and needs another pass.
330 pub fn sync_viewport(&mut self, m: &Model) -> bool {
331 let Some(win) = web_sys::window() else { return false };
332 let height = win.inner_height().ok().and_then(|h| h.as_f64()).unwrap_or(800.0);
333 let (top, bottom) = (-NEAR_PX, height + NEAR_PX);
334 let ds = win.get_selection().ok().flatten();
335 let holds_selection = |n: &DomNode| {
336 ds.as_ref().is_some_and(|ds| {
337 [ds.anchor_node(), ds.focus_node()].into_iter().flatten().any(|s| n.contains(Some(&s)))
338 })
339 };
340 let mut changed = false;
341
342 let composing_page = self.composing.and_then(|c| self.locate(c)).map(|l| l.0);
343 let (first, last) = near_range(self.pages.len(), |i| self.page_box(i), top, bottom);
344 for i in 0..self.pages.len() {
345 let near = (first..last).contains(&i);
346 if near == self.pages[i].live {
347 continue;
348 }
349 if !near {
350 let el: DomNode = self.pages[i].el.clone().into();
351 if holds_selection(&el) || composing_page == Some(i) {
352 continue;
353 }
354 let h = self.pages[i].el.get_bounding_client_rect().height();
355 if h > 0.0 {
356 self.pages[i].height = h;
357 }
358 }
359 self.set_page_live(m, i, near);
360 changed = true;
361 }
362
363 let composing = self.composing;
364 let mut g = 0;
365 for pi in 0..self.pages.len() {
366 let n = self.pages[pi].n;
367 if !self.pages[pi].live {
368 g += n;
369 continue;
370 }
371 for k in 0..n {
372 if composing == Some(g + k) {
373 continue;
374 }
375 let Some(v) = self.pages[pi].blocks[k].as_mut() else { continue };
376 if !v.runs.first().is_some_and(|r| r.chunk) {
377 continue;
378 }
379 // Shown chunks' heights, read while layout is fresh: a chunk hidden later
380 // keeps it (wrapped text has no line count to size it by).
381 for r in v.runs.iter_mut().filter(|r| r.live && r.shown) {
382 let h = r.dom.unchecked_ref::<Element>().get_bounding_client_rect().height();
383 if h > 0.0 {
384 r.px = h;
385 }
386 }
387 let (first, last) = near_range(v.runs.len(), |i| chunk_box(v, i), top, bottom);
388 for i in 0..v.runs.len() {
389 let near = (first..last).contains(&i);
390 let r = &mut v.runs[i];
391 if r.near == near {
392 continue;
393 }
394 r.near = near;
395 if near || !holds_selection(&r.dom) {
396 let was = r.live;
397 set_live(r, near);
398 changed |= was != near;
399 }
400 }
401 place_runs(v);
402 }
403 g += n;
404 }
405 changed
406 }
407
408 // -----------------------------------------------------------------------
409 // Building
410 // -----------------------------------------------------------------------
411
412 fn el(&self, spec: &render::Spec) -> Element {
413 let el = self.document.create_element(spec.tag).unwrap();
414 for (k, v) in &spec.attrs {
415 let _ = el.set_attribute(k, v);
416 }
417 el
418 }
419
420 fn build_block(&mut self, m: &Model, b: &Blk) -> BView {
421 let mut v = self.block_shell(b);
422 if b.kind() == Kind::Rule {
423 let _ = v.el.set_attribute("contenteditable", "false");
424 } else {
425 self.patch_runs(m, b, &mut v, true);
426 }
427 v
428 }
429
430 /// The element of block `b`, without its content.
431 fn block_shell(&mut self, b: &Blk) -> BView {
432 let spec = render::block_spec(&b.attrs);
433 let el = self.el(&spec);
434 let content = match spec.inner {
435 Some(tag) => {
436 let c = self.document.create_element(tag).unwrap();
437 el.append_child(&c).unwrap();
438 c
439 }
440 None => el.clone(),
441 };
442 let _ = js_sys::Reflect::set(&el, &self.block_key, &JsValue::TRUE);
443 self.next_uid += 1;
444 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 }
445 }
446
447 /// Builds the unbuilt blocks of live page `pi` and patches its dirty ones.
448 fn build_missing(&mut self, m: &Model, pi: usize) {
449 let n = self.pages[pi].n;
450 let g0 = self.page_start(pi);
451 let blks = m.blocks(g0, g0 + n);
452 for (k, b) in blks.iter().enumerate() {
453 match self.pages[pi].blocks[k].take() {
454 None => {
455 let v = self.build_block(m, b);
456 self.pages[pi].blocks[k] = Some(v);
457 }
458 Some(mut v) => {
459 if let Some(range) = v.dirty.take() {
460 if self.composing == Some(b.index) {
461 self.deferred = true;
462 } else if v.synced && range.is_some() {
463 // Typed natively: the DOM already shows it.
464 } else if v.attrs.kind != b.attrs.kind {
465 let nv = self.build_block(m, b);
466 let _ = v.el.replace_with_with_node_1(&nv.el);
467 v = nv;
468 } else {
469 if v.attrs.lang != b.attrs.lang {
470 match b.attrs.lang.as_deref().filter(|l| !l.is_empty()) {
471 Some(l) => drop(v.el.set_attribute("data-language", l)),
472 None => drop(v.el.remove_attribute("data-language")),
473 }
474 }
475 v.attrs = b.attrs.clone();
476 if b.kind() != Kind::Rule {
477 let edit = range.and_then(|r| self.chunk_patch(m, b, &v, r));
478 self.apply_runs(m, b, &mut v, edit, false);
479 }
480 }
481 }
482 v.synced = false;
483 self.pages[pi].blocks[k] = Some(v);
484 }
485 }
486 }
487 }
488
489 /// The numbers of ordered lists continued from before the page: for each level of
490 /// the first block's wrap, the number of its item there (0 when not an ordered
491 /// list continued).
492 fn numbers(m: &Model, g0: usize, prev: Option<&Attrs>, first: &Attrs) -> Vec<i64> {
493 let k = keep(prev, first);
494 let common = prev.map_or(0, |p| common(&p.wrap, &first.wrap));
495 let new_item = k < common && first.wrap[k].is_list();
496 let cont = if new_item { k + 1 } else { k };
497 (0..cont).map(|l| if first.wrap[l] == Wrap::Ordered { item_number(m, g0, l) } else { 0 }).collect()
498 }
499
500 /// Rebuilds the list and quote elements of live page `pi` around its blocks if
501 /// anything they depend on changed.
502 fn group(&mut self, m: &Model, pi: usize) {
503 let n = self.pages[pi].n;
504 if n == 0 || self.pages[pi].blocks.iter().any(Option::is_none) {
505 return;
506 }
507 let g0 = self.page_start(pi);
508 let prev = g0.checked_sub(1).and_then(|i| m.block(i)).map(|b| b.attrs);
509 let next = m.block(g0 + n).map(|b| b.attrs);
510 let page = &self.pages[pi];
511 let first = &page.blocks[0].as_ref().unwrap().attrs;
512 let numbers = if first.wrap.contains(&Wrap::Ordered) { Self::numbers(m, g0, prev.as_ref(), first) } else { Vec::new() };
513 let shape = Shape {
514 blocks: page.blocks.iter().map(|b| {
515 let a = &b.as_ref().unwrap().attrs;
516 (a.wrap.clone(), a.join, a.start)
517 }).collect(),
518 prev,
519 next,
520 numbers,
521 };
522 if shape == page.shape {
523 return;
524 }
525 if shape.blocks.iter().all(|b| b.0.is_empty()) && page.el.query_selector("ul,ol,blockquote").ok().flatten().is_none() {
526 // No containers: the blocks are the page's children; move only what is out
527 // of place (an Enter is one insertion, not a rebuilt page).
528 let page_el = page.el.clone();
529 let mut cursor = page_el.first_child();
530 for v in page.blocks.iter().flatten() {
531 let el: &DomNode = v.el.as_ref();
532 if cursor.as_ref() == Some(el) {
533 cursor = el.next_sibling();
534 } else {
535 page_el.insert_before(el, cursor.as_ref()).unwrap();
536 }
537 }
538 while let Some(c) = cursor {
539 cursor = c.next_sibling();
540 page_el.remove_child(&c).unwrap();
541 }
542 self.pages[pi].shape = shape;
543 return;
544 }
545 struct Lvl {
546 el: Element,
547 item: Option<Element>,
548 }
549 let page_el = page.el.clone();
550 page_el.set_text_content(None);
551 let mut stack: Vec<Lvl> = Vec::new();
552 let doc = self.document.clone();
553 let mk = |w: Wrap, start: i64, cont: bool| -> Element {
554 let s = render::wrap_spec(w, start);
555 let el = doc.create_element(s.tag).unwrap();
556 for (k, v) in &s.attrs {
557 let _ = el.set_attribute(k, v);
558 }
559 if cont {
560 el.set_class_name("pm-cont");
561 }
562 el
563 };
564 let li = |cont: bool| -> Element {
565 let el = doc.create_element("li").unwrap();
566 if cont {
567 el.set_class_name("pm-cont");
568 }
569 el
570 };
571 let parent = |stack: &[Lvl]| -> Element {
572 match stack.last() {
573 Some(l) => l.item.clone().unwrap_or_else(|| l.el.clone()),
574 None => page_el.clone(),
575 }
576 };
577 let mut prev_attrs = shape.prev.clone();
578 for (idx, b) in self.pages[pi].blocks.iter().enumerate() {
579 let b = b.as_ref().unwrap();
580 let wrap = &b.attrs.wrap;
581 let k = keep(prev_attrs.as_ref(), &b.attrs);
582 let common = prev_attrs.as_ref().map_or(0, |p| common(&p.wrap, wrap));
583 let new_item = k < common && wrap[k].is_list();
584 if idx == 0 {
585 // Levels continued from the page before.
586 let cont = if new_item { k + 1 } else { k };
587 for (l, &w) in wrap.iter().enumerate().take(cont) {
588 let start = shape.numbers.get(l).copied().filter(|&x| x > 0).unwrap_or(1);
589 let el = mk(w, start, true);
590 parent(&stack).append_child(&el).unwrap();
591 let item = w.is_list().then(|| li(l < k));
592 if let Some(i) = &item {
593 el.append_child(i).unwrap();
594 }
595 stack.push(Lvl { el, item });
596 }
597 } else {
598 let stay = if new_item { k + 1 } else { k };
599 stack.truncate(stay);
600 if new_item {
601 let i = li(false);
602 stack[k].el.append_child(&i).unwrap();
603 stack[k].item = Some(i);
604 }
605 }
606 let deepest = (stack.len()..wrap.len()).rev().find(|&i| wrap[i] == Wrap::Ordered);
607 for (l, &w) in wrap.iter().enumerate().skip(stack.len()) {
608 let start = if Some(l) == deepest { b.attrs.start.unwrap_or(1) } else { 1 };
609 let el = mk(w, start, false);
610 parent(&stack).append_child(&el).unwrap();
611 let item = w.is_list().then(|| li(false));
612 if let Some(i) = &item {
613 el.append_child(i).unwrap();
614 }
615 stack.push(Lvl { el, item });
616 }
617 parent(&stack).append_child(&b.el).unwrap();
618 prev_attrs = Some(b.attrs.clone());
619 }
620 // Levels the page after continues.
621 if let (Some(last), Some(next)) = (&prev_attrs, &shape.next) {
622 let k = keep(Some(last), next);
623 let common = common(&last.wrap, &next.wrap);
624 let new_item = k < common && next.wrap[k].is_list();
625 for (l, lvl) in stack.iter().enumerate() {
626 if l < k || l == k && new_item {
627 let _ = lvl.el.class_list().add_1("pm-more");
628 if let Some(i) = lvl.item.as_ref().filter(|_| l < k) {
629 let _ = i.class_list().add_1("pm-more");
630 }
631 }
632 }
633 }
634 self.pages[pi].shape = shape;
635 }
636
637 /// Brings a block's runs up to date from the model. With `force` the content is
638 /// rebuilt from scratch (used when the DOM went foreign).
639 fn patch_runs(&mut self, m: &Model, b: &Blk, v: &mut BView, force: bool) {
640 self.apply_runs(m, b, v, None, force);
641 }
642
643 fn apply_runs(&mut self, m: &Model, b: &Blk, v: &mut BView, edit: Option<Vec<MRun>>, force: bool) {
644 let code = b.kind() == Kind::Code;
645 let new = match edit {
646 Some(new) if !force => new,
647 _ => {
648 let mut lines = v.lines;
649 let runs = chunk_text(model_runs(m, b), if force { &[] } else { &v.runs }, code, &mut lines);
650 v.lines = lines;
651 runs
652 }
653 };
654 if !code && new.iter().any(|n| matches!(n, MRun::Text(_, _, true))) {
655 // Hidden text chunks are sized from their length at this width until shown.
656 self.text_width = self.root.client_width().max(200) as f64;
657 }
658 if force {
659 v.content.set_text_content(None);
660 v.runs.clear();
661 v.trailing = None;
662 }
663 let old = std::mem::take(&mut v.runs);
664 let content = v.content.clone();
665 let same = |i: usize, o: &Run, n: &MRun| -> bool {
666 match n {
667 MRun::Keep(k) => *k == i,
668 // `o.s` always holds what the DOM text node holds (see `Run::s`).
669 MRun::Text(s, mk, c) => o.kind == RunKind::Text && &o.marks == mk && o.chunk == *c && o.s == *s,
670 MRun::Other(k) => o.kind == *k,
671 }
672 };
673 let mut pre = 0;
674 while pre < old.len() && pre < new.len() && same(pre, &old[pre], &new[pre]) {
675 pre += 1;
676 }
677 let mut suf = 0;
678 while suf < old.len() - pre && suf < new.len() - pre && same(old.len() - 1 - suf, &old[old.len() - 1 - suf], &new[new.len() - 1 - suf]) {
679 suf += 1;
680 }
681 let old_mid = &old[pre..old.len() - suf];
682 let new_mid = &new[pre..new.len() - suf];
683 let mut mid: Vec<Run> = Vec::with_capacity(new_mid.len());
684 // One text run changed in place: keep its node so spellcheck and IME state survive.
685 let in_place = match (old_mid, new_mid) {
686 ([o], [MRun::Text(s, mk, c)]) if o.kind == RunKind::Text && &o.marks == mk && o.chunk == *c => Some((o, s)),
687 _ => None,
688 };
689 if let Some((o, s)) = in_place {
690 let t = o.text.clone().unwrap();
691 replace_minimal(&t, &o.s, s);
692 let mut px = o.px;
693 if o.chunk && code {
694 px = line_count(s) as f64 * CODE_LINE_PX;
695 if o.styled.is_none() {
696 set_lines(&o.dom, s);
697 }
698 }
699 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 });
700 } else {
701 // New chunks replacing a shown one are shown too (the caret is likely there).
702 let live = old_mid.iter().any(|o| o.live);
703 for o in old_mid {
704 if o.dom.parent_node().is_some_and(|p| p == *content) {
705 content.remove_child(&o.dom).unwrap();
706 }
707 }
708 for n in new_mid {
709 mid.push(self.build_run(n, live, code));
710 }
711 }
712 let mut old = old;
713 let tail: Vec<Run> = old.drain(old.len() - suf..).collect();
714 let mut runs: Vec<Run> = Vec::with_capacity(new.len());
715 runs.extend(old.drain(..pre));
716 runs.extend(mid);
717 runs.extend(tail);
718 v.runs = runs;
719 self.fix_trailing(v);
720 }
721
722 /// Adds or drops the trailing `<br>` an empty block or one ending in a line break needs.
723 fn fix_trailing(&self, v: &mut BView) {
724 place_runs(v);
725 let content = v.content.clone();
726 let need_trailing = match v.runs.last() {
727 None => true,
728 Some(r) => r.kind == RunKind::Break || r.kind == RunKind::Text && r.s.ends_with('\n'),
729 };
730 match (&v.trailing, need_trailing) {
731 (None, true) => {
732 let br = self.document.create_element("br").unwrap();
733 br.set_class_name(TRAILING_BREAK);
734 content.append_child(&br).unwrap();
735 v.trailing = Some(br);
736 }
737 (Some(br), false) => {
738 br.remove();
739 v.trailing = None;
740 }
741 (Some(br), true) if br.next_sibling().is_some() => {
742 content.append_child(br).unwrap();
743 }
744 _ => {}
745 }
746 }
747
748 /// The new runs of a chunked block after one plain edit, reading only the changed
749 /// chunks' text from the model (a huge block is never copied whole per keystroke).
750 fn chunk_patch(&self, m: &Model, b: &Blk, v: &BView, (lo, hi): (usize, usize)) -> Option<Vec<MRun>> {
751 let runs = &v.runs;
752 let plain = Marks::default();
753 if runs.is_empty() || runs.iter().any(|r| !r.chunk || r.marks != plain || r.kind != RunKind::Text) {
754 return None;
755 }
756 let code = b.kind() == Kind::Code;
757 let len = b.sepu - b.startu;
758 let tail = len.checked_sub(hi)?;
759 let (mut i, mut a) = (0, 0);
760 while i < runs.len() && a + runs[i].chars <= lo {
761 a += runs[i].chars;
762 i += 1;
763 }
764 let (mut j, mut kept) = (runs.len(), 0);
765 while j > i && kept + runs[j - 1].chars <= tail {
766 kept += runs[j - 1].chars;
767 j -= 1;
768 }
769 let e = len.checked_sub(kept).filter(|&e| e >= a)?;
770 let mid = m.text.slice(b.startu + a, b.startu + e).ok()?;
771 if !code && mid.contains(['\n', OBJ]) {
772 return None;
773 }
774 let mut out: Vec<MRun> = (0..i).map(MRun::Keep).collect();
775 // One edited chunk stays one node until it doubles: Enter then edits it in place
776 // instead of rebuilding it as two.
777 let small = if code { mid.bytes().filter(|&c| c == b'\n').count() < 2 * v.lines } else { mid.len() < 2 * CHUNK_BYTES };
778 if i + 1 == j && small && !mid.is_empty() {
779 out.push(MRun::Text(mid, plain, true));
780 } else {
781 out.extend(split_chunks(&mid, &plain, code, v.lines));
782 }
783 out.extend((j..runs.len()).map(MRun::Keep));
784 Some(out)
785 }
786
787 fn build_run(&self, n: &MRun, live: bool, code: bool) -> Run {
788 match n {
789 MRun::Text(s, mk, chunk) => {
790 let t = self.document.create_text_node(s);
791 let mut dom: DomNode = t.clone().into();
792 for spec in render::mark_specs(mk).iter().rev() {
793 let w = self.el(spec);
794 w.append_child(&dom).unwrap();
795 dom = w.into();
796 }
797 let mut inner = None;
798 let mut px = 0.0;
799 if *chunk {
800 let w = self.document.create_element("div").unwrap();
801 if code {
802 w.set_class_name("code-chunk");
803 set_lines(&w, s);
804 px = line_count(s) as f64 * CODE_LINE_PX;
805 } else {
806 w.set_class_name("text-chunk");
807 px = utf16_len(s) as f64 * TEXT_CHAR_AREA / self.text_width;
808 }
809 if live {
810 w.append_child(&dom).unwrap();
811 }
812 inner = Some(dom);
813 dom = w.into();
814 }
815 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 }
816 }
817 MRun::Keep(_) => unreachable!("kept chunks are never rebuilt"),
818 MRun::Other(kind) => {
819 let el = match kind {
820 RunKind::Image { src, alt, title } => {
821 let el = self.el(&render::image_spec(src, alt, title.as_deref()));
822 let _ = el.set_attribute("contenteditable", "false");
823 match src.strip_prefix("/media/rec/") {
824 Some(id) => self.take_span(id, el),
825 None => el,
826 }
827 }
828 _ => self.document.create_element("br").unwrap(),
829 };
830 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 }
831 }
832 }
833 }
834
835 /// The embed of a recording take: its audio, and a button to continue the take. Its state
836 /// comes from `takes`. Only attributes change after this, never the children or the text,
837 /// so the editor's observer does not see the state change.
838 fn take_span(&self, id: &str, audio: Element) -> Element {
839 let strings = Strings::load(&self.document);
840 let state = self.takes.borrow().get(id).cloned().unwrap_or_else(|| "absent".to_owned());
841 let span = self.document.create_element("span").unwrap();
842 span.set_class_name("note-take");
843 let _ = span.set_attribute("contenteditable", "false");
844 let _ = span.set_attribute("data-take", id);
845 let _ = span.set_attribute("data-take-state", &state);
846 let _ = span.set_attribute("data-recording-label", &strings.get("recordingNow"));
847 let _ = span.set_attribute("data-lost-label", &strings.get("recordingLost"));
848 let _ = span.append_child(&audio);
849 let button = self.document.create_element("button").unwrap();
850 let _ = button.set_attribute("type", "button");
851 button.set_class_name("note-take-continue");
852 button.set_text_content(Some(&strings.get("continueRecording")));
853 let _ = span.append_child(&button);
854 span
855 }
856
857 // -----------------------------------------------------------------------
858 // Flush
859 // -----------------------------------------------------------------------
860
861 /// Applies the model's block splices to the DOM.
862 pub fn flush(&mut self, m: &Model) -> bool {
863 let splices = m.take_splices();
864 if splices.is_empty() {
865 return false;
866 }
867 let mut structural = false;
868 for s in &splices {
869 if let Some(c) = self.composing {
870 if c >= s.at + s.removed {
871 self.composing = Some(c + s.inserted - s.removed);
872 } else if c >= s.at && !(s.removed == 1 && s.inserted == 1) {
873 self.composing = None;
874 }
875 }
876 if s.removed == 1 && s.inserted == 1 {
877 if let Some((pi, k)) = self.locate(s.at)
878 && let Some(Some(v)) = self.pages[pi].blocks.get_mut(k)
879 {
880 v.dirty = Some(match (v.dirty, s.edit) {
881 (None, e) => e,
882 _ => None,
883 });
884 }
885 structural |= s.edit.is_none();
886 continue;
887 }
888 structural = true;
889 let quick = splices.len() == 1
890 && self.composing.is_none()
891 && match (s.removed, s.inserted) {
892 (1, 2) => self.split_chunked(m, s.at) || self.keep_first(s.at, 1, 2),
893 (2, 1) => self.join_chunked(m, s.at) || self.keep_first(s.at, 2, 1),
894 _ => false,
895 };
896 if !quick {
897 self.remove_blocks(s.at, s.removed);
898 self.insert_blocks(s.at, s.inserted);
899 }
900 }
901 if self.pages.is_empty() && m.len() > 0 {
902 self.insert_blocks(0, m.len());
903 }
904 if structural {
905 self.layout();
906 }
907 for pi in 0..self.pages.len() {
908 if self.pages[pi].live {
909 self.build_missing(m, pi);
910 }
911 }
912 if structural {
913 for pi in 0..self.pages.len() {
914 if self.pages[pi].live {
915 self.group(m, pi);
916 }
917 }
918 }
919 true
920 }
921
922 /// Enter inside a huge chunked block: the first part keeps the element and its
923 /// chunks, the second one's chunks move to a new element after it, and only the
924 /// chunk holding the split is rebuilt; both halves (tens of MB) are never read back
925 /// and rendered again. Moving a first part with shown chunks instead would take away
926 /// the browser's scroll anchor (shown text above the caret), and the view would
927 /// jump megapixels.
928 fn split_chunked(&mut self, m: &Model, at: usize) -> bool {
929 let (Some(a), Some(b)) = (m.block(at), m.block(at + 1)) else { return false };
930 let Some((pi, k)) = self.locate(at) else { return false };
931 let Some(Some(v)) = self.pages[pi].blocks.get(k) else { return false };
932 let (la, lb) = (a.sepu - a.startu, b.sepu - b.startu);
933 let text = |x: &Blk| x.kind().is_text() && x.kind() != Kind::Code;
934 if !chunked(v) || v.dirty.is_some() || !text(&a) || !text(&b) || (v.attrs.kind != a.attrs.kind && v.attrs.kind != b.attrs.kind) {
935 return false;
936 }
937 if v.runs.iter().map(|r| r.chars).sum::<usize>() != la + lb {
938 return false;
939 }
940 let mut v = self.pages[pi].blocks[k].take().unwrap();
941 let mut i = 0;
942 let mut acc = 0;
943 while i < v.runs.len() && acc + v.runs[i].chars <= la {
944 acc += v.runs[i].chars;
945 i += 1;
946 }
947 let mut right = v.runs.split_off(i);
948 let mut left = std::mem::take(&mut v.runs);
949 if acc < la {
950 // The split falls inside this chunk: its two parts are new runs.
951 let r = right.remove(0);
952 r.dom.unchecked_ref::<Element>().remove();
953 let cut = r.s.char_indices().nth(la - acc).map_or(r.s.len(), |(o, _)| o);
954 left.push(self.build_run(&MRun::Text(r.s[..cut].to_owned(), Marks::default(), true), r.live, false));
955 if cut < r.s.len() {
956 right.insert(0, self.build_run(&MRun::Text(r.s[cut..].to_owned(), Marks::default(), true), r.live, false));
957 }
958 }
959 // An empty first part (Enter at the block's start) moves for free.
960 let keep_left = v.attrs.kind == a.attrs.kind && (left.iter().any(|r| r.shown) || v.attrs.kind != b.attrs.kind);
961 let mut w = self.block_shell(if keep_left { &b } else { &a });
962 // Both halves keep the spacer scale, so nothing moves.
963 w.scale = v.scale;
964 let (stay, mut moved) = if keep_left { (left, right) } else { (right, left) };
965 unplace(&mut moved);
966 v.runs = stay;
967 w.runs = moved;
968 v.attrs = if keep_left { a.attrs.clone() } else { b.attrs.clone() };
969 self.fix_trailing(&mut v);
970 self.fix_trailing(&mut w);
971 let (first, second) = if keep_left { (v, w) } else { (w, v) };
972 self.pages[pi].blocks[k] = Some(first);
973 self.insert_blocks(at + 1, 1);
974 // On a dead page (the next one) the second block is not shown yet.
975 if let Some((pj, kj)) = self.locate(at + 1)
976 && let Some(slot) = self.pages[pj].blocks.get_mut(kj)
977 {
978 *slot = Some(second);
979 } else {
980 second.el.remove();
981 }
982 true
983 }
984
985 /// Enter or Backspace on a built block: it keeps its element, re-rendered from the
986 /// model, and only the blocks after it are added or removed. Firefox's editor
987 /// handles every element removed under the root, so replacing it would cost more.
988 fn keep_first(&mut self, at: usize, removed: usize, inserted: usize) -> bool {
989 let Some((pi, k)) = self.locate(at) else { return false };
990 match self.pages[pi].blocks.get_mut(k) {
991 Some(Some(v)) => v.dirty = Some(None),
992 _ => return false,
993 }
994 self.remove_blocks(at + 1, removed - 1);
995 if inserted > 1 {
996 // On the block's own page, which is live, even when it is the page's last.
997 self.insert_in_page(pi, k + 1, inserted - 1);
998 }
999 true
1000 }
1001
1002 /// Backspace or Delete joining a huge chunked block with its neighbour: the one with
1003 /// more chunks keeps its element, the other's content moves into it.
1004 fn join_chunked(&mut self, m: &Model, at: usize) -> bool {
1005 let Some(a) = m.block(at) else { return false };
1006 let (Some((pi, k)), Some((pj, kj))) = (self.locate(at), self.locate(at + 1)) else { return false };
1007 let (Some(Some(v)), Some(Some(w))) = (self.pages[pi].blocks.get(k), self.pages[pj].blocks.get(kj)) else { return false };
1008 let plain = |x: &BView| x.runs.iter().all(|r| r.kind == RunKind::Text && r.marks == Marks::default());
1009 if !(chunked(v) || chunked(w)) || !plain(v) || !plain(w) || v.dirty.is_some() || w.dirty.is_some() || a.kind() == Kind::Code {
1010 return false;
1011 }
1012 let chars = |x: &BView| x.runs.iter().map(|r| r.chars).sum::<usize>();
1013 if chars(v) + chars(w) != a.sepu - a.startu {
1014 return false;
1015 }
1016 let host_first = match (v.attrs.kind == a.attrs.kind, w.attrs.kind == a.attrs.kind) {
1017 (true, true) => v.runs.len() >= w.runs.len(),
1018 (true, false) => true,
1019 (false, true) => false,
1020 (false, false) => return false,
1021 };
1022 let v = self.pages[pi].blocks[k].take().unwrap();
1023 let w = self.pages[pj].blocks[kj].take().unwrap();
1024 // A short plain block joining a chunked one becomes a chunk too.
1025 let rechunk = |runs: Vec<Run>, this: &Self| -> Vec<Run> {
1026 if runs.iter().all(|r| r.chunk) {
1027 return runs;
1028 }
1029 let text: String = runs.iter().map(|r| r.s.as_str()).collect();
1030 for r in &runs {
1031 r.dom.unchecked_ref::<Element>().remove();
1032 }
1033 if text.is_empty() {
1034 return Vec::new();
1035 }
1036 vec![this.build_run(&MRun::Text(text, Marks::default(), true), true, false)]
1037 };
1038 let (mut host, other) = if host_first { (v, w) } else { (w, v) };
1039 let (host_runs, mut other_runs) = (rechunk(std::mem::take(&mut host.runs), self), rechunk(other.runs, self));
1040 unplace(&mut other_runs);
1041 let runs: Vec<Run> = if host_first { host_runs.into_iter().chain(other_runs).collect() } else { other_runs.into_iter().chain(host_runs).collect() };
1042 other.el.remove();
1043 host.runs = runs;
1044 host.attrs = a.attrs.clone();
1045 self.fix_trailing(&mut host);
1046 self.pages[pi].blocks[k] = Some(host);
1047 self.remove_blocks(at + 1, 1);
1048 true
1049 }
1050
1051 fn remove_blocks(&mut self, at: usize, mut n: usize) {
1052 let Some((mut pi, mut k)) = self.locate(at) else { return };
1053 self.pages_changed();
1054 let mut emptied = false;
1055 while n > 0 && pi < self.pages.len() {
1056 let p = &mut self.pages[pi];
1057 let take = n.min(p.n - k);
1058 if take == p.n {
1059 // The whole page goes, its blocks with it.
1060 if p.attached {
1061 p.el.remove();
1062 }
1063 emptied = true;
1064 } else if p.live {
1065 for v in p.blocks.drain(k..k + take).flatten() {
1066 v.el.remove();
1067 }
1068 } else {
1069 p.height *= (p.n - take) as f64 / p.n as f64;
1070 }
1071 p.n -= take;
1072 p.shape = Shape::default();
1073 n -= take;
1074 pi += 1;
1075 k = 0;
1076 }
1077 if emptied {
1078 self.pages.retain(|p| p.n > 0);
1079 }
1080 }
1081
1082 fn insert_blocks(&mut self, at: usize, n: usize) {
1083 if n == 0 {
1084 return;
1085 }
1086 let (pi, k) = match self.locate(at) {
1087 Some(l) => l,
1088 None if self.pages.is_empty() => (0, 0),
1089 None => {
1090 let last = self.pages.len() - 1;
1091 (last, self.pages[last].n)
1092 }
1093 };
1094 self.pages_changed();
1095 if n <= PAGE && !self.pages.is_empty() {
1096 self.insert_in_page(pi, k, n);
1097 return;
1098 }
1099 // Many blocks (paste, undo of a large delete, a remote import): new placeholder
1100 // pages between the two halves of the page at the insertion point.
1101 let mut at_page = pi;
1102 if self.pages.is_empty() {
1103 } else if k > 0 && k < self.pages[pi].n {
1104 self.split_page(pi, k);
1105 at_page = pi + 1;
1106 } else if k > 0 {
1107 at_page = pi + 1;
1108 }
1109 let mut new = Vec::with_capacity(n.div_ceil(PAGE));
1110 let mut left = n;
1111 while left > 0 {
1112 let c = PAGE.min(left);
1113 new.push(self.new_page(c, c as f64 * EST_BLOCK_PX));
1114 left -= c;
1115 }
1116 self.pages.splice(at_page..at_page, new);
1117 }
1118
1119 /// `n` new blocks at position `k` of page `pi`.
1120 fn insert_in_page(&mut self, pi: usize, k: usize, n: usize) {
1121 self.pages_changed();
1122 let p = &mut self.pages[pi];
1123 if p.live {
1124 p.blocks.splice(k..k, (0..n).map(|_| None));
1125 } else {
1126 p.height += n as f64 * EST_BLOCK_PX;
1127 }
1128 p.n += n;
1129 p.shape = Shape::default();
1130 if p.n > 2 * PAGE {
1131 let half = p.n / 2;
1132 self.split_page(pi, half);
1133 }
1134 }
1135
1136 /// Splits page `pi` before its block `at`; the new page follows it, same state.
1137 fn split_page(&mut self, pi: usize, at: usize) {
1138 self.pages_changed();
1139 let total = self.pages[pi].n;
1140 let mut page = self.new_page(total - at, 0.0);
1141 if self.pages[pi].live {
1142 page.blocks = self.pages[pi].blocks.split_off(at);
1143 page.live = true;
1144 } else {
1145 page.height = self.pages[pi].height * (total - at) as f64 / total as f64;
1146 self.pages[pi].height -= page.height;
1147 }
1148 self.pages[pi].n = at;
1149 self.pages[pi].shape = Shape::default();
1150 self.pages.insert(pi + 1, page);
1151 }
1152
1153 /// Re-renders a block from the model, discarding whatever the browser did to it.
1154 pub fn repair(&mut self, m: &Model, i: usize) {
1155 let Some(b) = m.block(i) else { return };
1156 let Some((pi, k)) = self.locate(i) else { return };
1157 let Some(mut v) = self.pages[pi].blocks.get_mut(k).and_then(Option::take) else { return };
1158 if b.kind() != Kind::Rule {
1159 self.patch_runs(m, &b, &mut v, true);
1160 }
1161 self.pages[pi].blocks[k] = Some(v);
1162 }
1163
1164 /// Rebuilds the page holding DOM node `n` (the browser changed its containers).
1165 pub fn repair_page_of(&mut self, m: &Model, n: &DomNode) {
1166 let Some(pi) = self.page_of(n) else { return };
1167 if self.pages[pi].live {
1168 self.set_page_live(m, pi, false);
1169 self.set_page_live(m, pi, true);
1170 }
1171 }
1172
1173 /// Whether the composed block changed while composing (it needs a rebuild).
1174 pub fn take_deferred(&mut self) -> bool {
1175 std::mem::take(&mut self.deferred)
1176 }
1177
1178 /// Whether a block's DOM is exactly what the view built (no foreign nodes).
1179 pub fn intact(&self, i: usize) -> bool {
1180 let Some(v) = self.bview(i) else { return false };
1181 let kids = v.content.child_nodes();
1182 let expect = v.runs.iter().filter(|r| r.shown).count() + v.trailing.is_some() as usize;
1183 if kids.length() as usize != expect {
1184 return false;
1185 }
1186 for (i, r) in v.runs.iter().filter(|r| r.shown).enumerate() {
1187 if kids.get(i as u32).as_ref() != Some(&r.dom) {
1188 return false;
1189 }
1190 if r.chunk && !r.live {
1191 if r.dom.has_child_nodes() {
1192 return false;
1193 }
1194 continue;
1195 }
1196 if let Some(t) = &r.text {
1197 if r.dom != ***t && !r.dom.contains(Some(t)) {
1198 return false;
1199 }
1200 if t.length() == 0 {
1201 return false;
1202 }
1203 }
1204 }
1205 true
1206 }
1207
1208 // -----------------------------------------------------------------------
1209 // Lookup
1210 // -----------------------------------------------------------------------
1211
1212 pub fn bview(&self, i: usize) -> Option<&BView> {
1213 let (pi, k) = self.locate(i)?;
1214 self.pages[pi].blocks.get(k)?.as_ref()
1215 }
1216
1217 fn bview_mut(&mut self, i: usize) -> Option<&mut BView> {
1218 let (pi, k) = self.locate(i)?;
1219 self.pages[pi].blocks.get_mut(k)?.as_mut()
1220 }
1221
1222 pub fn element(&self, i: usize) -> Option<&Element> {
1223 self.bview(i).map(|v| &v.el)
1224 }
1225
1226 /// The built blocks, with their indexes.
1227 pub fn live_blocks(&self) -> impl Iterator<Item = (usize, &BView)> {
1228 let mut g = 0;
1229 self.pages.iter().flat_map(move |p| {
1230 let g0 = g;
1231 g += p.n;
1232 p.blocks.iter().enumerate().filter_map(move |(k, v)| v.as_ref().map(|v| (g0 + k, v)))
1233 })
1234 }
1235
1236 /// The index of the built block with `key`.
1237 pub fn find_key(&self, key: u32) -> Option<usize> {
1238 self.live_blocks().find(|(_, v)| v.key == key).map(|(i, _)| i)
1239 }
1240
1241 fn page_index(&self, uid: u32) -> Option<usize> {
1242 self.pages.iter().position(|p| p.uid == uid)
1243 }
1244
1245 /// The page holding DOM node `n`.
1246 fn page_of(&self, n: &DomNode) -> Option<usize> {
1247 let mut cur = Some(n.clone());
1248 while let Some(c) = cur {
1249 if c == **self.root {
1250 return None;
1251 }
1252 if let Some(uid) = js_sys::Reflect::get(&c, &self.page_key).ok().and_then(|v| v.as_f64()) {
1253 return self.page_index(uid as u32);
1254 }
1255 cur = c.parent_node();
1256 }
1257 None
1258 }
1259
1260 /// The block whose element holds DOM node `n` (or is it), and that element.
1261 pub fn owner(&self, n: &DomNode) -> Option<(usize, Element)> {
1262 let mut cur = Some(n.clone());
1263 while let Some(c) = cur {
1264 if c == **self.root {
1265 return None;
1266 }
1267 if js_sys::Reflect::get(&c, &self.block_key).ok().is_some_and(|v| v.is_truthy()) {
1268 let el: Element = c.unchecked_into();
1269 let pi = self.page_of(&el)?;
1270 let k = self.pages[pi].blocks.iter().position(|v| v.as_ref().is_some_and(|v| v.el == el))?;
1271 return Some((self.page_start(pi) + k, el));
1272 }
1273 cur = c.parent_node();
1274 }
1275 None
1276 }
1277
1278 // -----------------------------------------------------------------------
1279 // Positions
1280 // -----------------------------------------------------------------------
1281
1282 /// The DOM point for a model offset (its page must be live).
1283 pub fn pos_to_dom(&self, m: &Model, p: Pos) -> Option<(DomNode, u32)> {
1284 let b = m.at(p);
1285 let v = self.bview(b.index)?;
1286 if b.kind() == Kind::Rule {
1287 let parent = v.el.parent_node()?;
1288 let i = index_in(&parent, v.el.as_ref());
1289 return Some((parent, i + u32::from(p > b.start)));
1290 }
1291 let off = p.saturating_sub(b.start);
1292 let mut acc = 0;
1293 for (i, r) in v.runs.iter().enumerate() {
1294 if let Some(t) = &r.text {
1295 // At a boundary the caret sits at the end of the text before it, except
1296 // after a chunk's closing newline: that is the next chunk's first line.
1297 let next_line = r.chunk && off == acc + r.len && i + 1 < v.runs.len();
1298 if off <= acc + r.len && !next_line {
1299 return Some((t.clone().into(), (off - acc) as u32));
1300 }
1301 } else if off == acc {
1302 return Some((v.content.clone().into(), i as u32));
1303 }
1304 acc += r.len;
1305 }
1306 Some((v.content.clone().into(), v.runs.len() as u32))
1307 }
1308
1309 /// The model offset for a DOM point, by walking the DOM (robust to foreign nodes).
1310 pub fn dom_to_pos(&self, m: &Model, node: &DomNode, offset: u32) -> Option<Pos> {
1311 if let Some((i, el)) = self.owner(node) {
1312 let b = m.block(i)?;
1313 let v = self.bview(i)?;
1314 if b.kind() == Kind::Rule {
1315 return Some(b.start);
1316 }
1317 let content: &DomNode = v.content.as_ref();
1318 if node == AsRef::<DomNode>::as_ref(&el) && el != v.content {
1319 // On `pre` itself: before or after its `code`.
1320 return Some(if offset == 0 { b.start } else { b.sep });
1321 }
1322 let off = if v.runs.iter().any(|r| r.chunk) { chunk_offset(v, node, offset) } else { None };
1323 let off = match off {
1324 Some(o) => o,
1325 None => dom_offset(content, node, offset)?,
1326 };
1327 return Some(b.start + off.min(b.len()));
1328 }
1329 let root: &DomNode = self.root.as_ref();
1330 if node == root {
1331 // The root's children are live pages and spacers.
1332 let Some(child) = root.child_nodes().get(offset) else { return Some(m.last().sep) };
1333 let pi = self.page_of(&child)?;
1334 return m.block(self.page_start(pi)).map(|b| b.start);
1335 }
1336 // Between blocks, inside a page's containers.
1337 let pi = self.page_of(node)?;
1338 let g0 = self.page_start(pi);
1339 let page = &self.pages[pi];
1340 if !page.live {
1341 return m.block(g0).map(|b| b.start);
1342 }
1343 let after = node.child_nodes().get(offset);
1344 for (k, v) in page.blocks.iter().enumerate() {
1345 let Some(v) = v else { continue };
1346 let el: &DomNode = v.el.as_ref();
1347 let following = match &after {
1348 Some(a) => a == el || a.contains(Some(el)) || a.compare_document_position(el) & DomNode::DOCUMENT_POSITION_FOLLOWING != 0,
1349 None => node.compare_document_position(el) & DomNode::DOCUMENT_POSITION_FOLLOWING != 0 && !node.contains(Some(el)),
1350 };
1351 if following {
1352 return m.block(g0 + k).map(|b| b.start);
1353 }
1354 }
1355 m.block(g0 + page.n - 1).map(|b| b.sep)
1356 }
1357
1358 /// After the browser typed `data` into text node `t` at UTF-16 offset `at`: the run
1359 /// cache follows, and the block's next dirty mark is skipped (DOM and model agree).
1360 /// Returns false when `t` is not one of the block's runs.
1361 pub fn typed(&mut self, i: usize, t: &DomNode, at: usize, data: &str) -> bool {
1362 let Some(v) = self.bview_mut(i) else { return false };
1363 let Some(r) = v.runs.iter_mut().find(|r| r.text.as_ref().is_some_and(|x| AsRef::<DomNode>::as_ref(x) == t)) else {
1364 return false;
1365 };
1366 let at = byte_at_utf16(&r.s, at);
1367 r.s.insert_str(at, data);
1368 r.len += utf16_len(data);
1369 r.chars += data.chars().count();
1370 v.synced = true;
1371 true
1372 }
1373
1374 /// Re-reads the run caches of a block from the DOM, after the browser changed it in
1375 /// ways only a full read-back understood.
1376 pub fn resync(&mut self, i: usize) {
1377 if let Some(v) = self.bview_mut(i) {
1378 for r in v.runs.iter_mut().filter(|r| !r.chunk || r.live) {
1379 if let Some(t) = &r.text {
1380 r.s = t.data();
1381 r.len = utf16_len(&r.s);
1382 r.chars = r.s.chars().count();
1383 }
1384 }
1385 }
1386 }
1387
1388 /// The text the DOM shows for a block, UTF-16: our breaks as `\n`, images as
1389 /// U+FFFC, and any element the browser made as U+FFFC too (the model wins then).
1390 pub fn dom_text(&self, i: usize) -> Option<Vec<u16>> {
1391 let v = self.bview(i)?;
1392 let mut out = Vec::new();
1393 walk(v.content.as_ref(), &mut |n| {
1394 if let Some(ri) = v.runs.iter().position(|r| r.dom == *n) {
1395 let r = &v.runs[ri];
1396 match r.kind {
1397 RunKind::Break => {
1398 out.push(b'\n' as u16);
1399 return true;
1400 }
1401 RunKind::Image { .. } => {
1402 out.push(OBJ as u16);
1403 return true;
1404 }
1405 RunKind::Text if r.chunk && !r.live => {
1406 for r in v.runs[ri..].iter().take_while(|x| x.chunk && !x.live && (x.dom == *n || !x.shown)) {
1407 out.extend(r.s.encode_utf16());
1408 }
1409 return true;
1410 }
1411 RunKind::Text => {}
1412 }
1413 }
1414 match n.node_type() {
1415 DomNode::TEXT_NODE => out.extend(n.node_value().unwrap_or_default().encode_utf16()),
1416 DomNode::ELEMENT_NODE => {
1417 let e: &Element = n.unchecked_ref();
1418 match e.tag_name().as_str() {
1419 "BR" if e.class_name() != TRAILING_BREAK => out.push(OBJ as u16),
1420 "IMG" => out.push(OBJ as u16),
1421 _ => {}
1422 }
1423 }
1424 _ => {}
1425 }
1426 false
1427 });
1428 Some(out)
1429 }
1430
1431 /// Shows the chunks holding (and next to) the selection ends, so the DOM selection
1432 /// can be placed and arrow keys find text around it.
1433 pub fn ensure_live(&mut self, m: &Model, positions: &[Pos]) {
1434 for &p in positions {
1435 let b = m.at(p);
1436 let ends: Vec<usize> = positions.iter().filter(|&&q| b.holds(q)).map(|q| q - b.start).collect();
1437 let Some(v) = self.bview_mut(b.index) else { continue };
1438 if !v.runs.first().is_some_and(|r| r.chunk) {
1439 continue;
1440 }
1441 let off = p - b.start;
1442 let mut acc = 0;
1443 let mut at = v.runs.len() - 1;
1444 for (i, r) in v.runs.iter().enumerate() {
1445 if off < acc + r.len || off == acc + r.len && i + 1 == v.runs.len() {
1446 at = i;
1447 break;
1448 }
1449 acc += r.len;
1450 }
1451 // Shown: what the observer reports near, plus the chunks holding a selection
1452 // end and their neighbours. Everything else goes back to a placeholder.
1453 let mut start = 0;
1454 for (i, r) in v.runs.iter_mut().enumerate() {
1455 let holds = ends.iter().any(|&o| o >= start && o <= start + r.len);
1456 start += r.len;
1457 let want = r.near || holds || i + 1 >= at && i <= at + 1;
1458 set_live(r, want);
1459 }
1460 place_runs(v);
1461 }
1462 }
1463}
1464
1465fn common(a: &[Wrap], b: &[Wrap]) -> usize {
1466 a.iter().zip(b).take_while(|(x, y)| x == y).count()
1467}
1468
1469/// The number of the level-`l` ordered list item holding block `g` (counting a new
1470/// item `g` starts), walking back to where the list starts.
1471fn item_number(m: &Model, g: usize, l: usize) -> i64 {
1472 let Some(first) = m.block(g) else { return 1 };
1473 let mut count = 0;
1474 let mut cur = first.attrs;
1475 let mut result = None;
1476 m.scan(g, true, |_, prev| {
1477 let k = keep(Some(prev), &cur);
1478 if k > l {
1479 // Same item.
1480 } else if k == l && common(&prev.wrap, &cur.wrap) > l && cur.wrap[l].is_list() {
1481 count += 1;
1482 } else {
1483 result = Some(list_start(prev, &cur, l) + count);
1484 return false;
1485 }
1486 cur = prev.clone();
1487 true
1488 });
1489 // Reached the first block: the list starts there.
1490 result.unwrap_or_else(|| list_start_first(&cur, l) + count)
1491}
1492
1493/// The first number of the level-`l` list `cur` opens after `prev`.
1494fn list_start(prev: &Attrs, cur: &Attrs, l: usize) -> i64 {
1495 let k = keep(Some(prev), cur);
1496 let common = common(&prev.wrap, &cur.wrap);
1497 let stay = if k < common && cur.wrap[k].is_list() { k + 1 } else { k };
1498 let deepest = (stay..cur.wrap.len()).rev().find(|&i| cur.wrap[i] == Wrap::Ordered);
1499 if deepest == Some(l) { cur.start.unwrap_or(1) } else { 1 }
1500}
1501
1502fn list_start_first(cur: &Attrs, l: usize) -> i64 {
1503 let deepest = (0..cur.wrap.len()).rev().find(|&i| cur.wrap[i] == Wrap::Ordered);
1504 if deepest == Some(l) { cur.start.unwrap_or(1) } else { 1 }
1505}
1506
1507fn index_in(parent: &DomNode, child: &DomNode) -> u32 {
1508 let kids = parent.child_nodes();
1509 (0..kids.length()).find(|&i| kids.get(i).as_ref() == Some(child)).unwrap_or(0)
1510}
1511
1512/// Attaches or detaches a chunk's content (see `Run::live`).
1513fn set_live(r: &mut Run, live: bool) {
1514 if !r.chunk || r.live == live {
1515 return;
1516 }
1517 let Some(inner) = &r.inner else { return };
1518 if live {
1519 let _ = r.dom.append_child(inner);
1520 } else if inner.parent_node().is_some_and(|p| p == r.dom) {
1521 // It keeps the height `sync_viewport` last saw (measuring here would force a
1522 // layout in the middle of an edit).
1523 let _ = r.dom.remove_child(inner);
1524 }
1525 r.live = live;
1526}
1527
1528/// Depth-first walk; `f` returns true to skip a node's children.
1529fn walk(n: &DomNode, f: &mut dyn FnMut(&DomNode) -> bool) {
1530 let mut c = n.first_child();
1531 while let Some(k) = c {
1532 if !f(&k) {
1533 walk(&k, f);
1534 }
1535 c = k.next_sibling();
1536 }
1537}
1538
1539/// Turns text node `t` (holding `old`) into `new` with one `replaceData` over the
1540/// part that differs, so the caret and spellcheck state around it survive.
1541fn replace_minimal(t: &Text, old: &str, new: &str) {
1542 if old == new {
1543 return;
1544 }
1545 let (a, b) = (old.as_bytes(), new.as_bytes());
1546 let mut p = a.iter().zip(b).take_while(|(x, y)| x == y).count();
1547 while !old.is_char_boundary(p) || !new.is_char_boundary(p) {
1548 p -= 1;
1549 }
1550 let max_s = (a.len() - p).min(b.len() - p);
1551 let mut q = a.iter().rev().zip(b.iter().rev()).take(max_s).take_while(|(x, y)| x == y).count();
1552 while !old.is_char_boundary(a.len() - q) || !new.is_char_boundary(b.len() - q) {
1553 q -= 1;
1554 }
1555 let at = utf16_len(&old[..p]) as u32;
1556 let count = utf16_len(&old[p..a.len() - q]) as u32;
1557 let _ = t.replace_data(at, count, &new[p..b.len() - q]);
1558}
1559
1560/// Byte index of UTF-16 offset `off` in `s` (clamped to the end).
1561pub fn byte_at_utf16(s: &str, off: usize) -> usize {
1562 if s.is_ascii() {
1563 return off.min(s.len());
1564 }
1565 let mut n = 0;
1566 for (i, c) in s.char_indices() {
1567 if n >= off {
1568 return i;
1569 }
1570 n += c.len_utf16();
1571 }
1572 s.len()
1573}
1574
1575fn node_len(n: &DomNode) -> usize {
1576 match n.node_type() {
1577 DomNode::TEXT_NODE => n.unchecked_ref::<web_sys::CharacterData>().length() as usize,
1578 DomNode::ELEMENT_NODE => {
1579 let e: &Element = n.unchecked_ref();
1580 match e.tag_name().as_str() {
1581 "BR" if e.class_name() != TRAILING_BREAK => 1,
1582 "IMG" => 1,
1583 _ => {
1584 let mut s = 0;
1585 let mut c = n.first_child();
1586 while let Some(k) = c {
1587 s += node_len(&k);
1588 c = k.next_sibling();
1589 }
1590 s
1591 }
1592 }
1593 }
1594 _ => 0,
1595 }
1596}
1597
1598/// UTF-16 offset of DOM point (node, offset) inside `content`.
1599fn dom_offset(content: &DomNode, node: &DomNode, offset: u32) -> Option<usize> {
1600 enum Stop {
1601 /// Inside a text node, at this offset.
1602 Text(DomNode, usize),
1603 /// Just before this node.
1604 Before(DomNode),
1605 /// Just after this node's content.
1606 After(DomNode),
1607 }
1608 let stop = if node.node_type() == DomNode::TEXT_NODE {
1609 Stop::Text(node.clone(), offset as usize)
1610 } else {
1611 match node.child_nodes().get(offset) {
1612 Some(c) => Stop::Before(c),
1613 None => Stop::After(node.clone()),
1614 }
1615 };
1616 if let Stop::After(n) = &stop
1617 && n == content
1618 {
1619 return Some(node_len(content));
1620 }
1621 fn go(n: &DomNode, stop: &Stop, acc: &mut usize) -> bool {
1622 let mut c = n.first_child();
1623 while let Some(k) = c {
1624 match stop {
1625 Stop::Text(t, o) if *t == k => {
1626 *acc += (*o).min(node_len(&k));
1627 return true;
1628 }
1629 Stop::Before(b) if *b == k => return true,
1630 Stop::After(a) if *a == k => {
1631 *acc += node_len(&k);
1632 return true;
1633 }
1634 _ => {}
1635 }
1636 let target = match stop {
1637 Stop::Text(t, _) => t,
1638 Stop::Before(t) => t,
1639 Stop::After(t) => t,
1640 };
1641 if k.contains(Some(target)) {
1642 return go(&k, stop, acc);
1643 }
1644 *acc += node_len(&k);
1645 c = k.next_sibling();
1646 }
1647 false
1648 }
1649 let mut acc = 0;
1650 go(content, &stop, &mut acc).then_some(acc)
1651}
1652
1653pub fn utf16_len(s: &str) -> usize {
1654 note_model::flat::str_lens(s).1
1655}
1656
1657enum MRun {
1658 /// Text, its marks, and whether it is a chunk.
1659 Text(String, Marks, bool),
1660 /// A break or an image.
1661 Other(RunKind),
1662 /// Old run `i`, unchanged (chunks reuse their runs without copying text).
1663 Keep(usize),
1664}
1665
1666/// Line height of code (px), which sizes hidden code chunks.
1667const CODE_LINE_PX: f64 = 22.0;
1668
1669fn line_count(s: &str) -> usize {
1670 (s.bytes().filter(|&b| b == b'\n').count() + usize::from(!s.ends_with('\n'))).max(1)
1671}
1672
1673/// Puts a block's runs in its content element: every run but hidden chunks, and for
1674/// each run of hidden chunks one spacer (the first one) as tall as all of them. Only
1675/// what changed touches the DOM: Firefox's editor handles every node added or removed
1676/// right away, and lays out every child of the block on each keystroke.
1677fn place_runs(v: &mut BView) {
1678 let hidden = |r: &Run| r.chunk && !r.live;
1679 if v.runs.iter().all(|r| r.shown && !hidden(r)) {
1680 return;
1681 }
1682 let total: f64 = v.runs.iter().filter(|r| hidden(r)).map(|r| r.px).sum();
1683 v.scale = rescale(v.scale, total);
1684 let mut prev: Option<usize> = None;
1685 let mut i = 0;
1686 while i < v.runs.len() {
1687 let mut j = i + 1;
1688 let mut height = None;
1689 if hidden(&v.runs[i]) {
1690 let mut h = v.runs[i].px;
1691 while j < v.runs.len() && hidden(&v.runs[j]) {
1692 h += v.runs[j].px;
1693 j += 1;
1694 }
1695 height = Some((h * v.scale).round() as i64);
1696 }
1697 if !v.runs[i].shown {
1698 let next = match prev {
1699 Some(p) => v.runs[p].dom.next_sibling(),
1700 None => v.content.first_child(),
1701 };
1702 let _ = v.content.insert_before(&v.runs[i].dom, next.as_ref());
1703 }
1704 let r = &mut v.runs[i];
1705 r.shown = true;
1706 if r.chunk && r.styled != height {
1707 let el: &Element = r.dom.unchecked_ref();
1708 match height {
1709 Some(h) => set_height(el, h as f64),
1710 None if el.class_name() == "code-chunk" => set_lines(&r.dom, &r.s),
1711 None => {
1712 let _ = el.remove_attribute("style");
1713 }
1714 }
1715 r.styled = height;
1716 }
1717 prev = Some(i);
1718 for r in &mut v.runs[i + 1..j] {
1719 if r.shown {
1720 r.dom.unchecked_ref::<Element>().remove();
1721 r.shown = false;
1722 }
1723 }
1724 i = j;
1725 }
1726}
1727
1728/// Takes runs out of the DOM before they move to another block.
1729fn unplace(runs: &mut [Run]) {
1730 for r in runs.iter_mut().filter(|r| r.shown) {
1731 r.dom.unchecked_ref::<Element>().remove();
1732 r.shown = false;
1733 }
1734}
1735
1736/// Viewport top and bottom of run `i`; a hidden chunk's lie within its spacer.
1737fn chunk_box(v: &BView, i: usize) -> (f64, f64) {
1738 let mut head = i;
1739 let mut h = 0.0;
1740 while !v.runs[head].shown && head > 0 {
1741 head -= 1;
1742 h += v.runs[head].px;
1743 }
1744 let r = v.runs[head].dom.unchecked_ref::<Element>().get_bounding_client_rect();
1745 if head == i && !(v.runs[i].chunk && !v.runs[i].live) {
1746 return (r.top(), r.bottom());
1747 }
1748 let top = r.top() + h * v.scale;
1749 (top, top + v.runs[i].px * v.scale)
1750}
1751
1752/// A block shown as plain text chunks.
1753fn chunked(v: &BView) -> bool {
1754 !v.runs.is_empty() && v.runs.iter().all(|r| r.chunk && r.kind == RunKind::Text && r.marks == Marks::default())
1755}
1756
1757fn model_runs(m: &Model, b: &Blk) -> Vec<MRun> {
1758 let fb = m.read_block(b);
1759 let mut out = Vec::with_capacity(fb.inl.len());
1760 for i in fb.inl {
1761 match i {
1762 Inline::Text(s, mk) if !s.is_empty() => out.push(MRun::Text(s, mk, false)),
1763 Inline::Text(..) => {}
1764 Inline::HardBreak => out.push(MRun::Other(RunKind::Break)),
1765 Inline::Image { src, alt, title } => out.push(MRun::Other(RunKind::Image { src, alt, title })),
1766 }
1767 }
1768 out
1769}
1770
1771/// Most the spacers add up to (px): browsers cap layout lengths (Firefox near 17.9M px),
1772/// past which a long note could not scroll to its end.
1773const MAX_PX: f64 = 12_000_000.0;
1774/// Spacers may add up to this before the scale shrinks again.
1775const HARD_PX: f64 = 16_000_000.0;
1776
1777/// The scale for spacers adding up to `total` px, kept while it still fits and is
1778/// not far below what is needed: a new scale changes every spacer's height, which
1779/// moves everything and costs a layout of all that is shown (Enter splitting a huge
1780/// block halves it; each block added to a long note grows the total).
1781fn rescale(scale: f64, total: f64) -> f64 {
1782 let want = if total > MAX_PX { MAX_PX / total } else { 1.0 };
1783 if total * scale <= HARD_PX && scale * 2.5 > want { scale } else { want }
1784}
1785
1786/// Pages and chunks within this distance of the viewport (px) have their content.
1787const NEAR_PX: f64 = 1500.0;
1788
1789/// The items `first..last` of `n` boxes stacked top to bottom that overlap `top..=bottom`
1790/// (viewport coordinates). `rect(i)` is item `i`'s top and bottom.
1791fn near_range(n: usize, rect: impl Fn(usize) -> (f64, f64), top: f64, bottom: f64) -> (usize, usize) {
1792 let (mut lo, mut hi) = (0, n);
1793 while lo < hi {
1794 let mid = (lo + hi) / 2;
1795 if rect(mid).1 < top {
1796 lo = mid + 1;
1797 } else {
1798 hi = mid;
1799 }
1800 }
1801 let mut last = lo;
1802 while last < n && rect(last).0 <= bottom {
1803 last += 1;
1804 }
1805 (lo, last)
1806}
1807
1808/// Area (px²) one character of body text takes, for sizing hidden text chunks
1809/// never shown yet: about 8px wide on a 26px line.
1810const TEXT_CHAR_AREA: f64 = 8.0 * 26.0;
1811
1812fn set_height(el: &Element, px: f64) {
1813 let _ = el.set_attribute("style", &format!("height:{}px", px.round()));
1814}
1815
1816/// Sizes a chunk's placeholder: its number of lines.
1817fn set_lines(el: &DomNode, s: &str) {
1818 let _ = el.unchecked_ref::<Element>().set_attribute("style", &format!("--lines:{}", line_count(s)));
1819}
1820
1821/// UTF-16 offset of DOM point (node, offset) in a chunked block, counting hidden chunks
1822/// by their cached length. `None` when the point is outside every run.
1823fn chunk_offset(v: &BView, node: &DomNode, offset: u32) -> Option<usize> {
1824 let content: &DomNode = v.content.as_ref();
1825 if node != content {
1826 if let Some(off) = chunk_offset_hinted(v, node, offset) {
1827 return Some(off);
1828 }
1829 }
1830 if node == content {
1831 // A shown node stands for itself and the hidden runs after it.
1832 let kids = content.child_nodes();
1833 let mut acc = 0;
1834 for k in 0..offset.min(kids.length()) {
1835 let c = kids.get(k)?;
1836 match v.runs.iter().position(|r| r.dom == c) {
1837 Some(ri) => {
1838 let j = ri + 1 + v.runs[ri + 1..].iter().take_while(|r| !r.shown).count();
1839 acc = v.runs[..j].iter().map(|r| r.len).sum();
1840 }
1841 None => acc += node_len(&c),
1842 }
1843 }
1844 return Some(acc);
1845 }
1846 let mut acc = 0;
1847 for r in &v.runs {
1848 if r.dom == *node {
1849 return Some(acc + if offset == 0 { 0 } else { r.len });
1850 }
1851 if r.dom.contains(Some(node)) {
1852 return Some(acc + dom_offset(&r.dom, node, offset)?.min(r.len));
1853 }
1854 acc += r.len;
1855 }
1856 None
1857}
1858
1859/// [`chunk_offset`] inside a run, found from the node's ancestor under the content. The
1860/// run's index is cached on that element and checked before use: comparing every
1861/// chunk, thousands of JS calls, took milliseconds a keystroke.
1862fn chunk_offset_hinted(v: &BView, node: &DomNode, offset: u32) -> Option<usize> {
1863 let key = &JsValue::from_str(RUN_KEY);
1864 let content: &DomNode = v.content.as_ref();
1865 let mut child = node.clone();
1866 loop {
1867 let parent = child.parent_node()?;
1868 if parent == *content {
1869 break;
1870 }
1871 child = parent;
1872 }
1873 let hint = js_sys::Reflect::get(&child, key).ok().and_then(|h| h.as_f64()).map(|h| h as usize);
1874 let ri = match hint.filter(|&h| v.runs.get(h).is_some_and(|r| r.dom == child)) {
1875 Some(h) => h,
1876 None => {
1877 let ri = v.runs.iter().position(|r| r.dom == child)?;
1878 let _ = js_sys::Reflect::set(&child, key, &JsValue::from_f64(ri as f64));
1879 ri
1880 }
1881 };
1882 let r = &v.runs[ri];
1883 let acc: usize = v.runs[..ri].iter().map(|r| r.len).sum();
1884 if r.dom == *node {
1885 return Some(acc + if offset == 0 { 0 } else { r.len });
1886 }
1887 Some(acc + dom_offset(&r.dom, node, offset)?.min(r.len))
1888}
1889
1890/// Code blocks longer than this many lines render as chunks of at least this size:
1891/// a line added or removed relays out the chunk it is in, so the smaller the better.
1892const CHUNK_LINES: usize = 250;
1893/// Chunks of one code block at most: every keystroke walks them.
1894const MAX_CHUNKS: usize = 8000;
1895
1896/// Lines per chunk of a code block of `total` lines.
1897fn code_chunk_lines(total: usize) -> usize {
1898 total.div_ceil(MAX_CHUNKS).max(CHUNK_LINES)
1899}
1900/// Other blocks longer than twice this many bytes render as chunks of about this
1901/// size, cut after a space.
1902const CHUNK_BYTES: usize = 8 * 1024;
1903
1904/// Splits a huge block of one text run into chunks (code at line ends, other text
1905/// after spaces), reusing the boundaries of the `old` runs wherever their text is
1906/// unchanged, so an edit rebuilds only its chunk.
1907/// `lines` is the code block's lines per chunk, set from its length.
1908fn chunk_text(new: Vec<MRun>, old: &[Run], code: bool, lines: &mut usize) -> Vec<MRun> {
1909 let [MRun::Text(text, marks, _)] = new.as_slice() else { return new };
1910 let was_chunked = old.first().is_some_and(|r| r.chunk);
1911 // Hysteresis: a chunked block goes back to one text node only well below the limit.
1912 let big = if code {
1913 let limit = if was_chunked { CHUNK_LINES / 2 } else { CHUNK_LINES };
1914 text.bytes().filter(|&b| b == b'\n').nth(limit).is_some()
1915 } else {
1916 text.len() > if was_chunked { CHUNK_BYTES } else { 2 * CHUNK_BYTES }
1917 };
1918 if !big {
1919 return new;
1920 }
1921 if code {
1922 *lines = code_chunk_lines(text.bytes().filter(|&b| b == b'\n').count());
1923 }
1924 let sep = if code { b'\n' } else { b' ' };
1925 let reusable = |r: &Run| r.chunk && r.kind == RunKind::Text && &r.marks == marks;
1926 // Unchanged leading and trailing chunks, at boundaries.
1927 let (mut a, mut i) = (0, 0);
1928 while i < old.len() && reusable(&old[i]) && text[a..].starts_with(&old[i].s) && old[i].s.as_bytes().last() == Some(&sep) {
1929 a += old[i].s.len();
1930 i += 1;
1931 }
1932 let (mut b, mut j) = (text.len(), old.len());
1933 while j > i && reusable(&old[j - 1]) && b - a >= old[j - 1].s.len() && text[..b].ends_with(&old[j - 1].s) {
1934 let start = b - old[j - 1].s.len();
1935 if start > 0 && text.as_bytes()[start - 1] != sep {
1936 break;
1937 }
1938 b = start;
1939 j -= 1;
1940 }
1941 let mut out: Vec<MRun> = (0..i).map(MRun::Keep).collect();
1942 out.extend(split_chunks(&text[a..b], marks, code, *lines));
1943 out.extend((j..old.len()).map(MRun::Keep));
1944 out
1945}
1946
1947/// Cuts text into chunks every `per` lines (code) or after CHUNK_BYTES bytes at a space.
1948fn split_chunks(text: &str, marks: &Marks, code: bool, per: usize) -> Vec<MRun> {
1949 let sep = if code { b'\n' } else { b' ' };
1950 let mut out = Vec::new();
1951 let (mut start, mut lines) = (0, 0);
1952 for (k, c) in text.bytes().enumerate() {
1953 if c == sep {
1954 lines += 1;
1955 if if code { lines == per } else { k + 1 - start >= CHUNK_BYTES } {
1956 out.push(MRun::Text(text[start..=k].to_owned(), marks.clone(), true));
1957 start = k + 1;
1958 lines = 0;
1959 }
1960 }
1961 }
1962 if start < text.len() {
1963 out.push(MRun::Text(text[start..].to_owned(), marks.clone(), true));
1964 }
1965 out
1966}