From 33ddb45f310848a4116e076766e39163fd1b4234 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9B=B7=E7=94=B5=E8=8A=BD=E8=A1=A3?= Date: Mon, 12 Oct 2026 01:40:41 -0400 Subject: [PATCH] MarkdownDocument: blocks open on a read of the text as it is, top lines wait for their read and keep their place in tall blocks Co-Authored-By: Claude Opus 5.5 (1M context) --- AGENTS.md | 2 +- src/documents/document/edit.rs | 2 +- src/documents/document/mod.rs | 22 ++++--- src/documents/document/place.rs | 105 ++++++++++++++++++++++++------- src/documents/document/tests.rs | 98 +++++++++++++++++++++++++++-- src/documents/document/visual.rs | 4 +- 6 files changed, 195 insertions(+), 38 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index acd1874..b5e3824 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ Ely GPUI Component. A component library for GPUI, in light and dark. - Web views: `wry` 0.57 (Apache-2.0 OR MIT, default features off, macOS only) lays a child WKWebView over the window. - Terminal: `alacritty_terminal` 0.26 (Apache-2.0, default features off, native only) for the grid, its parser and the pseudo-terminal; `futures` carries its events. `vte` 0.15 (Apache-2.0 OR MIT), the parser it re-exports, reads `AnsiText`'s codes alone, so colored output builds for wasm32. - Diffs: `similar` 3.2 (Apache-2.0) for line and word diffs and three-way merges; its `unicode` feature splits words at punctuation. -- Markdown: `markdown` 1.0.0 (markdown-rs, MIT) reads GitHub's flavor and math into a syntax tree with byte positions for `MarkdownRenderer`, `MarkdownEditor`, the highlights, block ranges and outline. `MarkdownRenderer` draws display math through `typography::Latex`, a ```` ```mermaid ```` block through `documents::Diagram`, and pictures from the owner's folder (`base`) or `data:` addresses (`base64` 0.22, MIT OR Apache-2.0); web pictures stay unloaded. Inline math shows as TeX: gpui text carries no inline pictures. `MarkdownDocument` holds a whole file in one `CodeEditor` (text and undo, colored by `CodeEditor::highlighter` with `markdown_highlights`): visual draws the file's top-level blocks in a gpui `list`, a pressed block opening as its source in a `TextInput` whose typing is the document's text at once and whose write-back is one undo step; source is the editor; preview draws without presses. Texts up to 128 KiB are read at once, longer ones on the background executor, and a new read keeps the list's blocks alike at both ends. One caret serves every mode: the editor's selection, which a written-back block moves; `set_caret` and `set_top_line` set caret and view apart, and a mode switch keeps the top line. A pressed block keeps its identity across the write-back of the one before it. Blocks are Tab stops that Enter or Space opens; preview takes no presses, undo or redo. `CodeEditor` keeps at most 64 MiB of undo and redo text, dropping the oldest undo and then the farthest redo after every record, composition, undo and redo. `BlockData::from_markdown` and its export still read with `pulldown-cmark` 0.13 (MIT, default features off); it adds GitHub's alerts, a callout's form, and reads each field's inline Markdown from the source by offset, as written. +- Markdown: `markdown` 1.0.0 (markdown-rs, MIT) reads GitHub's flavor and math into a syntax tree with byte positions for `MarkdownRenderer`, `MarkdownEditor`, the highlights, block ranges and outline. `MarkdownRenderer` draws display math through `typography::Latex`, a ```` ```mermaid ```` block through `documents::Diagram`, and pictures from the owner's folder (`base`) or `data:` addresses (`base64` 0.22, MIT OR Apache-2.0); web pictures stay unloaded. Inline math shows as TeX: gpui text carries no inline pictures. `MarkdownDocument` holds a whole file in one `CodeEditor` (text and undo, colored by `CodeEditor::highlighter` with `markdown_highlights`): visual draws the file's top-level blocks in a gpui `list`, a pressed block opening as its source in a `TextInput` whose typing is the document's text at once and whose write-back is one undo step; source is the editor; preview draws without presses. Texts up to 128 KiB are read at once, longer ones on the background executor, and a new read keeps the list's blocks alike at both ends. One caret serves every mode: the editor's selection, which a written-back block moves; `set_caret` and `set_top_line` set caret and view apart; a top line asked before its text is read waits for the read, lands on its block, then a frame later at its share of the block's height; a switch between source and the list keeps the top line, one between visual and preview keeps the list's scroll as it is. A block opens only when the read is of the text as it is now. A pressed block keeps its identity across the write-back of the one before it. Blocks are Tab stops that Enter or Space opens; preview takes no presses, undo or redo. `CodeEditor` keeps at most 64 MiB of undo and redo text, dropping the oldest undo and then the farthest redo after every record, composition, undo and redo. `BlockData::from_markdown` and its export still read with `pulldown-cmark` 0.13 (MIT, default features off); it adds GitHub's alerts, a callout's form, and reads each field's inline Markdown from the source by offset, as written. - Pictures: `image` 0.25 (MIT OR Apache-2.0), the crate gpui decodes with, default features off; it turns decoded frames and rims map tiles. - Math and diagrams: RaTeX 0.1.14 (`ratex-parser`, `ratex-layout`, `ratex-svg` with `embed-fonts`, `ratex-types`; MIT, KaTeX's fonts OFL) typesets `Latex` to SVG with outlined glyphs; `mermaid-rs-renderer` 0.3.1 (MIT, default features off) draws `Diagram`. Both go through gpui's `SvgRenderer` at the window's scale, loaded as gpui assets off the main thread; `usvg` 0.46, gpui's own, reads a diagram's size. A RaTeX or Mermaid panic on parsed input becomes the element's error. Each element holds its picture through `primitives::held`: a new source, or the element leaving the window, removes the old asset from gpui's cache and drops its image from the atlas after the frame. - Maps: Natural Earth's 110m countries (public domain). `assets/maps/countries.geojson`, trimmed by `scripts/countries.py` to an ISO code, a name and positions to 0.01°, backs `maps::WorldMap`; the gallery's tiles are cut from the same file, z0 to z3, by `scripts/tiles.py` with Pillow. diff --git a/src/documents/document/edit.rs b/src/documents/document/edit.rs index 090febf..f4535d0 100644 --- a/src/documents/document/edit.rs +++ b/src/documents/document/edit.rs @@ -38,7 +38,7 @@ impl MarkdownDocument { if written.is_some() { self.reparse(cx); } - if !self.read_now() { + if !self.read_now(cx) { return log::warn!("markdown document: pressed while the text is read again"); } let text = self.editor.read(cx).text(); diff --git a/src/documents/document/mod.rs b/src/documents/document/mod.rs index 8e0096d..ace25a2 100644 --- a/src/documents/document/mod.rs +++ b/src/documents/document/mod.rs @@ -50,12 +50,14 @@ pub struct MarkdownDocument { mode: MarkdownMode, base: Option>, parsed: Arc, - /// Text changes counted; `read` is the one parsed. + /// Text changes counted; a read of an older one lapses. edits: u64, - read: u64, _parsing: Option>, list: ListState, open: Option, + /// A top line asked for, until the view holds it. + top: Option, + placing: bool, /// Its own write-backs whose changes are still to come. writes: usize, focus: FocusHandle, @@ -100,10 +102,11 @@ impl MarkdownDocument { base: None, parsed: Arc::default(), edits: 0, - read: u64::MAX, _parsing: None, list: ListState::new(1, ListAlignment::Top, overdraw), open: None, + top: None, + placing: false, writes: 0, focus: cx.focus_handle(), on_link: None, @@ -136,9 +139,13 @@ impl MarkdownDocument { pub fn set_mode(&mut self, mode: MarkdownMode, window: &mut Window, cx: &mut Context) { self.commit(cx); log::info!("markdown document: {:?} to {mode:?}", self.mode); - let top = self.top_line(cx); + let listed = |mode| matches!(mode, MarkdownMode::Visual | MarkdownMode::Preview); + // Visual and preview share one list and its scroll. + let top = (!(listed(self.mode) && listed(mode))).then(|| self.top_line(cx)); self.mode = mode; - self.set_top_line(top, cx); + if let Some(top) = top { + self.set_top_line(top, window, cx); + } let focus = self.focus_handle(cx); window.focus(&focus, cx); cx.notify(); @@ -184,8 +191,8 @@ impl MarkdownDocument { } /// Whether the blocks shown read the text now. - pub fn read_now(&self) -> bool { - self.read == self.edits + pub fn read_now(&self, cx: &App) -> bool { + self.parsed.text == self.editor.read(cx).text() } fn changed(&mut self, cx: &mut Context) { @@ -226,7 +233,6 @@ impl MarkdownDocument { self.list .splice(head..old - tail, read.blocks.len() - head - tail); self.parsed = Arc::new(read); - self.read = edits; cx.emit(DocumentEvent::Parsed); cx.notify(); } diff --git a/src/documents/document/place.rs b/src/documents/document/place.rs index 79a5e45..85eafc8 100644 --- a/src/documents/document/place.rs +++ b/src/documents/document/place.rs @@ -46,40 +46,99 @@ impl MarkdownDocument { cx.notify(); } - /// The first line in view. + /// The first line in view; block lines share its height. pub fn top_line(&self, cx: &App) -> usize { + if let Some(line) = self.top { + return line; + } let editor = self.editor.read(cx); match self.mode { MarkdownMode::Source | MarkdownMode::Split => editor.top_line().unwrap_or(0), MarkdownMode::Visual | MarkdownMode::Preview => { - let ix = self.list.logical_scroll_top().item_ix; - let at = self - .parsed - .blocks - .get(ix) - .map_or(editor.text().len(), |block| block.range.start); - editor.buffer.line_of(at.min(editor.text().len())) + let ListOffset { + item_ix, + offset_in_item, + } = self.list.logical_scroll_top(); + let Some(block) = self.parsed.blocks.get(item_ix) else { + return editor.buffer.lines() - 1; + }; + let first = editor.buffer.line_of(block.range.start); + let lines = editor.buffer.line_of(block.range.end) + 1 - first; + let into = self.list.bounds_for_item(item_ix).map_or(0.0, |bounds| { + offset_in_item.as_f32() / bounds.size.height.as_f32().max(1.0) + }); + first + ((into * lines as f32).round() as usize).min(lines - 1) } } } /// Scrolls `line` to the top; the caret stays. - pub fn set_top_line(&mut self, line: usize, cx: &mut Context) { - let editor = self.editor.read(cx); - let line = line.min(editor.buffer.lines() - 1); - let (scroll, at) = (editor.scroll.clone(), editor.buffer.line_range(line).start); - match self.mode { - MarkdownMode::Source | MarkdownMode::Split => { - scroll.scroll_to_item_strict(line, ScrollStrategy::Top) - } - MarkdownMode::Visual | MarkdownMode::Preview => { - let item_ix = self.block_at(at); - self.list.scroll_to(ListOffset { - item_ix, - offset_in_item: px(0.), - }); - } + pub fn set_top_line(&mut self, line: usize, window: &mut Window, cx: &mut Context) { + let lines = self.editor.read(cx).buffer.lines(); + self.top = Some(line.min(lines - 1)); + self.place_top(window, cx); + } + + /// Moves the view to the asked top, once text is read. + pub(super) fn place_top(&mut self, window: &mut Window, cx: &mut Context) { + let Some(line) = self.top.filter(|_| !self.placing) else { + return; + }; + if matches!(self.mode, MarkdownMode::Source | MarkdownMode::Split) { + let scroll = self.editor.read(cx).scroll.clone(); + scroll.scroll_to_item_strict(line, ScrollStrategy::Top); + self.placing = true; + // The editor's offset holds it from the next frame. + return cx.on_next_frame(window, move |document, window, cx| { + document.placed(line, None, window, cx) + }); } + if !self.read_now(cx) { + return; + } + let editor = self.editor.read(cx); + let at = editor.buffer.line_range(line).start; + let item_ix = self.block_at(at); + let Some(block) = self.parsed.blocks.get(item_ix) else { + self.top = None; + return; + }; + let first = editor.buffer.line_of(block.range.start); + let lines = editor.buffer.line_of(block.range.end) + 1 - first; + let into = line.saturating_sub(first) as f32 / lines as f32; + self.list.scroll_to(ListOffset { + item_ix, + offset_in_item: px(0.), + }); + self.placing = true; + cx.notify(); + // A block's height is known once drawn. + cx.on_next_frame(window, move |document, window, cx| { + document.placed(line, Some((item_ix, into)), window, cx) + }); + } + + /// A frame after placing `line`; a newer ask goes next. + fn placed( + &mut self, + line: usize, + within: Option<(usize, f32)>, + window: &mut Window, + cx: &mut Context, + ) { + self.placing = false; + if self.top != Some(line) { + return self.place_top(window, cx); + } + if let Some((item_ix, into)) = within + && let Some(bounds) = self.list.bounds_for_item(item_ix) + { + self.list.scroll_to(ListOffset { + item_ix, + offset_in_item: bounds.size.height * into, + }); + } + self.top = None; cx.notify(); } diff --git a/src/documents/document/tests.rs b/src/documents/document/tests.rs index b796b0c..502042c 100644 --- a/src/documents/document/tests.rs +++ b/src/documents/document/tests.rs @@ -184,14 +184,14 @@ fn reset_starts_undo_afresh(cx: &mut TestAppContext) { fn a_long_text_reads_off_the_main_thread(cx: &mut TestAppContext) { let long = "A paragraph of prose.\n\n".repeat(AT_ONCE / 20); let (document, cx) = open(&long, MarkdownMode::Visual, cx); - let (read, blocks) = document.read_with(cx, |document, _| { - (document.read_now(), document.parsed.blocks.len()) + let (read, blocks) = document.read_with(cx, |document, cx| { + (document.read_now(cx), document.parsed.blocks.len()) }); assert!(read, "read once parked"); assert_eq!(blocks, AT_ONCE / 20); document.update(cx, |document, cx| document.set_text("# Short\n", cx)); assert!( - document.read_with(cx, |document, _| document.read_now()), + document.read_with(cx, |document, cx| document.read_now(cx)), "a short text reads at once" ); } @@ -353,7 +353,9 @@ fn caret_and_view_set_apart_and_carry_across_modes(cx: &mut TestAppContext) { let long = (0..60).map(|n| format!("Line {n}\n\n")).collect::(); let (document, cx) = open(&long, MarkdownMode::Source, cx); document.update(cx, |document, cx| document.set_caret(4, 3, cx)); - document.update(cx, |document, cx| document.set_top_line(40, cx)); + document.update_in(cx, |document, window, cx| { + document.set_top_line(40, window, cx) + }); frames(cx); let source = document.read_with(cx, |document, cx| document.top_line(cx)); assert_eq!(source, 40, "the source scrolled"); @@ -393,3 +395,91 @@ fn a_change_under_an_open_block_closes_it(cx: &mut TestAppContext) { assert!(document.read_with(cx, |document, _| document.open.is_none())); assert_eq!(text(&document, cx), format!("x{TEXT}")); } + +#[gpui::test] +fn a_press_after_a_write_back_waits_for_the_long_read(cx: &mut TestAppContext) { + let long = format!("A\n\nB\n\nCCCC\n\n{}", "Prose.\n\n".repeat(AT_ONCE / 8 + 1)); + let (document, cx) = open(&long, MarkdownMode::Visual, cx); + document.update_in(cx, |document, window, cx| { + document.open(Some(0), false, window, cx); + let input = document.open.as_ref().expect("open").input.clone(); + input.update(cx, |input, cx| input.set_text("AAAA", cx)); + // B is pressed before the new read lands. + document.open(Some(1), false, window, cx); + assert!(document.open.is_none(), "a stale range opens nothing"); + }); + cx.run_until_parked(); + type_in(&document, Some(1), None, cx); + assert_eq!(opened(&document, cx), "B", "once read, B opens whole"); +} + +/// A fenced block of `lines` lines, then a paragraph. +fn fenced(lines: usize) -> String { + let body: String = (0..lines).map(|n| format!("line {n}\n")).collect(); + format!("```\n{body}```\n\nAfter.\n") +} + +#[gpui::test] +fn a_top_line_inside_a_tall_block_survives_modes(cx: &mut TestAppContext) { + let (document, cx) = open(&fenced(100), MarkdownMode::Source, cx); + document.update_in(cx, |document, window, cx| { + document.set_top_line(40, window, cx) + }); + frames(cx); + document.update_in(cx, |document, window, cx| { + document.set_mode(MarkdownMode::Visual, window, cx) + }); + frames(cx); + let top = document.read_with(cx, |document, cx| document.top_line(cx)); + assert_eq!(top, 40); +} + +#[gpui::test] +fn visual_to_preview_keeps_the_offset_in_a_block(cx: &mut TestAppContext) { + let (document, cx) = open(&fenced(100), MarkdownMode::Visual, cx); + document.update(cx, |document, cx| { + document.list.scroll_to(gpui::ListOffset { + item_ix: 0, + offset_in_item: px(500.0), + }); + cx.notify(); + }); + frames(cx); + let before = document.read_with(cx, |document, _| document.list.logical_scroll_top()); + document.update_in(cx, |document, window, cx| { + document.set_mode(MarkdownMode::Preview, window, cx) + }); + frames(cx); + let after = document.read_with(cx, |document, _| document.list.logical_scroll_top()); + assert_eq!( + (after.item_ix, after.offset_in_item), + (before.item_ix, before.offset_in_item) + ); + assert_eq!(after.offset_in_item, px(500.0)); +} + +#[gpui::test] +fn a_top_line_asked_with_new_text_lands_once_read(cx: &mut TestAppContext) { + let (document, cx) = open("old", MarkdownMode::Visual, cx); + let fresh: String = (0..100).map(|n| format!("Paragraph {n}\n\n")).collect(); + document.update_in(cx, |document, window, cx| { + document.reset(fresh, cx); + document.set_top_line(40, window, cx); + }); + frames(cx); + let top = document.read_with(cx, |document, cx| document.top_line(cx)); + assert_eq!(top, 40); +} + +#[gpui::test] +fn a_second_top_line_asked_while_placing_wins(cx: &mut TestAppContext) { + let fresh: String = (0..100).map(|n| format!("Paragraph {n}\n\n")).collect(); + let (document, cx) = open(&fresh, MarkdownMode::Source, cx); + document.update_in(cx, |document, window, cx| { + document.set_mode(MarkdownMode::Visual, window, cx); + document.set_top_line(60, window, cx); + }); + frames(cx); + let top = document.read_with(cx, |document, cx| document.top_line(cx)); + assert_eq!(top, 60); +} diff --git a/src/documents/document/visual.rs b/src/documents/document/visual.rs index c7a1c2e..b3a796e 100644 --- a/src/documents/document/visual.rs +++ b/src/documents/document/visual.rs @@ -133,7 +133,9 @@ impl MarkdownDocument { } impl Render for MarkdownDocument { - fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + // A top line asked before its text was read. + self.place_top(window, cx); let colors = cx.theme().colors.clone(); let root = div() .size_full()