| 1 | use gpui::{ |
| 2 | App, IntoElement, ListState, ParentElement as _, SharedString, Styled as _, Window, div, |
| 3 | }; |
| 4 | |
| 5 | use std::{ |
| 6 | ops::{Range, RangeInclusive}, |
| 7 | sync::Arc, |
| 8 | }; |
| 9 | |
| 10 | use crate::text::{ |
| 11 | SelectionFormat, |
| 12 | node::{BlockNode, NodeContext, SourceRangeSelection}, |
| 13 | }; |
| 14 | |
| 15 | /// The parsed document AST. |
| 16 | #[derive(Debug, Clone, PartialEq, Default)] |
| 17 | pub(crate) struct ParsedDocument { |
| 18 | pub(crate) source: SharedString, |
| 19 | pub(crate) blocks: Arc<Vec<BlockNode>>, |
| 20 | } |
| 21 | |
| 22 | #[derive(Default, Clone, Copy)] |
| 23 | pub(crate) struct NodeRenderOptions { |
| 24 | pub(crate) ix: usize, |
| 25 | pub(crate) in_list: bool, |
| 26 | pub(crate) todo: bool, |
| 27 | pub(crate) ordered: bool, |
| 28 | pub(crate) list_start: Option<u32>, |
| 29 | pub(crate) depth: usize, |
| 30 | pub(crate) is_last: bool, |
| 31 | } |
| 32 | |
| 33 | impl NodeRenderOptions { |
| 34 | pub(crate) fn is_last(mut self, is_last: bool) -> Self { |
| 35 | self.is_last = is_last; |
| 36 | self |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | impl ParsedDocument { |
| 41 | pub(super) fn text(&self) -> String { |
| 42 | let mut text = String::new(); |
| 43 | for block in self.blocks.iter() { |
| 44 | text.push_str(&block.text()); |
| 45 | } |
| 46 | text |
| 47 | } |
| 48 | |
| 49 | /// The selected text across all blocks, in `format`. |
| 50 | /// |
| 51 | /// In [`SelectionFormat::Source`] each block reconstructs its own Markdown |
| 52 | /// source (inline markup, and block prefixes for headings and lists), and |
| 53 | /// top-level blocks are joined with a blank line so the result re-renders |
| 54 | /// with the same block structure. |
| 55 | /// |
| 56 | /// A block only learns its selection when it is painted, so in a scrollable |
| 57 | /// (virtualized) view every block the user scrolled past reports nothing. |
| 58 | /// The selection is one continuous range, so blocks it spans that came up |
| 59 | /// empty are inside it and are emitted whole rather than dropped. `blocks` |
| 60 | /// bounds that span; it comes from the selection endpoints, which hold on to |
| 61 | /// their block index even after it scrolls out of view (the painted blocks |
| 62 | /// alone cannot bound the span, because the press that starts a drag leaves |
| 63 | /// an empty selection that never reaches paint). Without it, fall back to |
| 64 | /// the painted blocks. (Source mode is only used by non-scrollable views, |
| 65 | /// where `blocks` is `None` and every block paints.) |
| 66 | /// |
| 67 | /// A standalone image (a paragraph that is only an image) has no selectable |
| 68 | /// text run, so it never carries a selection of its own. It is therefore |
| 69 | /// included when it is *enclosed* by the selection — some block before and |
| 70 | /// some block after it are selected — mirroring how an inline image is |
| 71 | /// emitted when the selection runs into it. (Select-all returns the source |
| 72 | /// verbatim, so a leading or trailing image is still copied there.) |
| 73 | pub(super) fn selected_text( |
| 74 | &self, |
| 75 | format: SelectionFormat, |
| 76 | blocks: Option<RangeInclusive<usize>>, |
| 77 | ) -> String { |
| 78 | let requested_blocks = blocks.clone(); |
| 79 | let painted = self |
| 80 | .blocks |
| 81 | .iter() |
| 82 | .map(|block| block.has_selection()) |
| 83 | .collect::<Vec<_>>(); |
| 84 | let (Some(painted_first), Some(painted_last)) = ( |
| 85 | painted.iter().position(|painted| *painted), |
| 86 | painted.iter().rposition(|painted| *painted), |
| 87 | ) else { |
| 88 | return String::new(); |
| 89 | }; |
| 90 | |
| 91 | let last_ix = self.blocks.len().saturating_sub(1); |
| 92 | let (first, last) = match blocks { |
| 93 | Some(blocks) => (*blocks.start().min(&last_ix), *blocks.end().min(&last_ix)), |
| 94 | None => (painted_first, painted_last), |
| 95 | }; |
| 96 | |
| 97 | if format == SelectionFormat::Plain { |
| 98 | let mut text = String::new(); |
| 99 | for (ix, block) in self.blocks.iter().enumerate().take(last + 1).skip(first) { |
| 100 | let selected = block.selected_text(format); |
| 101 | let is_virtual_endpoint = requested_blocks |
| 102 | .as_ref() |
| 103 | .is_some_and(|blocks| ix == *blocks.start() || ix == *blocks.end()); |
| 104 | if requested_blocks.is_some() && !is_virtual_endpoint { |
| 105 | text.push_str(&block.text()); |
| 106 | } else if !selected.is_empty() { |
| 107 | text.push_str(&selected); |
| 108 | } else if !painted[ix] { |
| 109 | // Never painted, so it cannot report a selection of its own |
| 110 | // even though the span covers it. A painted block that came |
| 111 | // up empty really has nothing selected, and stays empty. |
| 112 | text.push_str(&block.text()); |
| 113 | } |
| 114 | } |
| 115 | return text; |
| 116 | } |
| 117 | |
| 118 | let mut out: Vec<String> = Vec::new(); |
| 119 | for (ix, block) in self.blocks.iter().enumerate().take(last + 1).skip(first) { |
| 120 | // The selection is one continuous range, so only the block it |
| 121 | // starts in and the block it ends in can be partly selected. |
| 122 | // Everything between them is covered whole, and so is any block |
| 123 | // that reports nothing — it either scrolled past without painting, |
| 124 | // or renders no selectable text run at all (a rule, a break, a |
| 125 | // custom node, a standalone image). |
| 126 | let source = if (ix == first || ix == last) && painted[ix] { |
| 127 | block.selected_text(format) |
| 128 | } else { |
| 129 | self.whole_source(block) |
| 130 | }; |
| 131 | |
| 132 | let trimmed = source.trim_end_matches('\n'); |
| 133 | if !trimmed.is_empty() { |
| 134 | out.push(trimmed.to_string()); |
| 135 | } |
| 136 | } |
| 137 | out.join("\n\n") |
| 138 | } |
| 139 | |
| 140 | /// The whole source of a block the selection covers. |
| 141 | /// |
| 142 | /// Copied straight out of the original text, which the Markdown parser |
| 143 | /// locates per block. That keeps whatever the author wrote — `_italic_` |
| 144 | /// stays `_italic_`, a reference link keeps its `[ref]` form, a table keeps |
| 145 | /// its column padding — and it needs no rule of its own per block type. |
| 146 | /// Blocks the parser could not locate fall back to reconstruction. |
| 147 | fn whole_source(&self, block: &BlockNode) -> String { |
| 148 | if let Some(span) = block.span() |
| 149 | && let Some(source) = self.source.get(span.start..span.end) |
| 150 | { |
| 151 | return source.to_string(); |
| 152 | } |
| 153 | |
| 154 | block.selected_text(SelectionFormat::Source) |
| 155 | } |
| 156 | |
| 157 | pub(super) fn selected_source_range(&self) -> Option<Range<usize>> { |
| 158 | let mut selected = SourceRangeSelection::Unselected; |
| 159 | for block in self.blocks.iter() { |
| 160 | selected.merge(block.selected_source_range()); |
| 161 | } |
| 162 | selected.into_range() |
| 163 | } |
| 164 | |
| 165 | /// Synchronously clear the selection stored in every inline state. |
| 166 | /// |
| 167 | /// This mirrors the [`selected_text`](Self::selected_text) traversal so the |
| 168 | /// stored selection can be cleared without relying on a repaint. Offscreen |
| 169 | /// (virtualized) views do not repaint, so their `InlineState.selection` |
| 170 | /// would otherwise retain stale values from the last painted frame. |
| 171 | pub(super) fn clear_selection(&self) { |
| 172 | for block in self.blocks.iter() { |
| 173 | block.clear_selection(); |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | /// Converts the node to markdown format. |
| 178 | /// |
| 179 | /// This is used to generate markdown for test. |
| 180 | #[allow(dead_code)] |
| 181 | pub(crate) fn to_markdown(&self) -> String { |
| 182 | self.blocks |
| 183 | .iter() |
| 184 | .map(|child| child.to_markdown()) |
| 185 | .collect::<Vec<_>>() |
| 186 | .join("\n\n") |
| 187 | } |
| 188 | |
| 189 | pub(super) fn render_root( |
| 190 | &self, |
| 191 | list_state: Option<ListState>, |
| 192 | node_cx: &NodeContext, |
| 193 | window: &mut Window, |
| 194 | cx: &mut App, |
| 195 | ) -> impl IntoElement { |
| 196 | let Some(list_state) = list_state else { |
| 197 | let blocks_len = self.blocks.len(); |
| 198 | return div().children(self.blocks.iter().enumerate().map(move |(ix, node)| { |
| 199 | let is_last = ix + 1 == blocks_len; |
| 200 | node.render_block( |
| 201 | NodeRenderOptions { |
| 202 | ix, |
| 203 | is_last, |
| 204 | ..Default::default() |
| 205 | }, |
| 206 | node_cx, |
| 207 | window, |
| 208 | cx, |
| 209 | ) |
| 210 | })); |
| 211 | }; |
| 212 | |
| 213 | let options = NodeRenderOptions { |
| 214 | is_last: true, |
| 215 | ..Default::default() |
| 216 | }; |
| 217 | |
| 218 | let blocks = &self.blocks; |
| 219 | if list_state.item_count() != blocks.len() { |
| 220 | list_state.reset(blocks.len()); |
| 221 | } |
| 222 | |
| 223 | div().size_full().child( |
| 224 | gpui::list(list_state, { |
| 225 | let node_cx = node_cx.clone(); |
| 226 | let blocks = blocks.clone(); |
| 227 | move |ix, window, cx| { |
| 228 | let is_last = ix + 1 == blocks.len(); |
| 229 | blocks[ix] |
| 230 | .render_block( |
| 231 | NodeRenderOptions { |
| 232 | ix, |
| 233 | is_last, |
| 234 | ..options |
| 235 | }, |
| 236 | &node_cx, |
| 237 | window, |
| 238 | cx, |
| 239 | ) |
| 240 | .into_any_element() |
| 241 | } |
| 242 | }) |
| 243 | .size_full(), |
| 244 | ) |
| 245 | } |
| 246 | } |