bezel-markdown 0.2.9

A Notion-style block document model for gpui — markdown in, markdown out
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Hit-testing and caret geometry over the rows a frame painted.

use super::*;

/// Where each block's text landed, recorded as it painted.
///
/// A caret has to be placeable by pointer, and only paint knows where a glyph
/// ended up. An editor hands one of these in, the renderer fills it, and the
/// next click resolves against it. Read-only callers pass nothing and pay
/// nothing.
#[derive(Clone, Default)]
pub struct BlockLayouts(Rc<RefCell<Frames>>);

#[derive(Default)]
pub(super) struct Frames {
    texts: Vec<Painted>,
    rows: Vec<PaintedRow>,
    /// Each block's whole box, which a text layout does not give: a rule and
    /// an image hold no text at all, and a gutter handle still has to find them.
    blocks: Vec<(usize, Bounds<Pixels>)>,
    /// A fenced block's language label, which a host may want to hang a
    /// picker on.
    languages: Vec<(usize, Bounds<Pixels>)>,
    /// An image block's picture, which is not its block: the block runs the
    /// full column and carries the caption, and a resize handle belongs on the
    /// edge of the picture itself.
    pictures: Vec<(usize, Bounds<Pixels>)>,
    /// A painted block that can be resized: a painted fence, or a card
    /// [`crate::Form::Embed`] spells.
    painted: Vec<(usize, Bounds<Pixels>)>,
    /// A task block's checkbox, which is not its marker column: the column is
    /// gutter either side of the box, and a click there places a caret.
    checkboxes: Vec<(usize, Bounds<Pixels>)>,
    /// A table cell's box, padding included.
    cells: Vec<(usize, Part, Bounds<Pixels>)>,
    /// Kept across frames: [`Self::clear`] leaves it.
    heights: Heights,
    /// Kept across frames until the column has shown it.
    reveal: Option<Reveal>,
}

/// Where [`BlockLayouts::reveal_with`] puts a range that is not showing. A
/// range already showing does not move either way.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RevealMode {
    /// In the middle of the view.
    #[default]
    Center,
    /// The least scroll that shows it, 16px in from the edge it came in
    /// over. Taller than the view, its top shows.
    Nearest,
}

/// The room [`RevealMode::Nearest`] leaves between a range and the view's
/// edge, in pixels.
pub(super) const REVEAL_MARGIN: f32 = 16.0;

/// A range waiting to be scrolled into view.
#[derive(Clone, Copy)]
pub(super) struct Reveal {
    pub(super) range: Selection,
    pub(super) mode: RevealMode,
    /// Frames it has scrolled in.
    pub(super) tries: u8,
    /// Whether any of them moved the document.
    pub(super) scrolled: bool,
    /// Where the column item holding it was placed last frame, in window
    /// coordinates. `None` before it has been built.
    pub(super) top: Option<Pixels>,
}

/// Block heights kept across frames, so a block off-screen is placed without
/// being built.
#[derive(Default)]
pub(super) struct Heights {
    /// A block's height by [`block_key`], as last measured at whatever width
    /// the column had then.
    by_key: HashMap<u64, Pixels>,
    /// The height last measured at each column index, whatever block was
    /// there.
    by_index: Vec<Option<Pixels>>,
}

/// One shaped run and the slice of its part it covers.
///
/// A paragraph is one entry over all of its text; a code block is one entry per
/// line. The range is what lets both resolve a click the same way — the layout
/// answers in its own coordinates and the base puts the answer back into the
/// part's.
pub(super) struct Painted {
    block: usize,
    part: Part,
    range: Range<usize>,
    layout: TextLayout,
    shown: Shown,
}

pub(super) struct PaintedRow {
    painted: usize,
    block: usize,
    part: Part,
    range: Range<usize>,
    bounds: Bounds<Pixels>,
    /// Where its line starts in the painted text's [`Shown`] offsets.
    line_start: usize,
    wrapped_row: usize,
}

impl BlockLayouts {
    /// The position under `point`.
    ///
    /// Falls back to the nearest text vertically, so clicking the margin
    /// beside a line — or below the last one — still lands somewhere useful
    /// rather than doing nothing.
    pub fn hit(&self, point: Point<Pixels>) -> Option<Cursor> {
        let frames = self.0.borrow();
        if let Some(row) = frames.rows.iter().find(|row| row.bounds.contains(&point)) {
            return cursor_in_row(&frames, row, point.x);
        }
        frames
            .rows
            .iter()
            .min_by_key(|row| {
                let bounds = row.bounds;
                let above = (bounds.origin.y - point.y).abs();
                let below = (bounds.origin.y + bounds.size.height - point.y).abs();
                f32::from(above.min(below)) as i64
            })
            .and_then(|row| cursor_in_row(&frames, row, point.x))
    }

    /// Where a position painted last frame, and how tall its line is.
    ///
    /// Vertical motion is geometry rather than arithmetic on line numbers, so
    /// a wrapped row and a hard newline are the same case and neither needs
    /// counting — the rule `ui::TextField` arrived at.
    pub fn position(&self, at: Cursor) -> Option<(Point<Pixels>, Pixels)> {
        let frames = self.0.borrow();
        let painted = frames.texts.iter().find(|painted| {
            painted.block == at.block
                && painted.part == at.part
                && painted.range.start <= at.offset
                && at.offset <= painted.range.end
        })?;
        let point = painted
            .layout
            .position_for_index(painted.shown.at(at.offset - painted.range.start))?;
        Some((point, painted.layout.line_height()))
    }

    /// The painted rows of a range, in document order — what a bar centred over
    /// a selection is placed against, and what a highlight of a caller's own is
    /// drawn from.
    ///
    /// One rect per visual row rather than one box: a selection that wraps or
    /// crosses blocks has no single box, and a caller given one would paint
    /// over the gaps.
    pub fn rects(&self, selection: Selection) -> Vec<Bounds<Pixels>> {
        let (start, end) = selection.ordered();
        self.0
            .borrow()
            .texts
            .iter()
            .filter_map(|painted| {
                let here = Cursor::new(painted.block, painted.part, 0);
                let (from, to) = (
                    Cursor::new(start.block, start.part, 0),
                    Cursor::new(end.block, end.part, 0),
                );
                if here < from || here > to {
                    return None;
                }
                // The offsets only matter at the two ends: in between, the
                // whole of the text is covered.
                let len = painted.range.len();
                let first = if here == from { start.offset } else { 0 };
                let last = if here == to { end.offset } else { usize::MAX };
                let range = first.saturating_sub(painted.range.start).min(len)
                    ..last.saturating_sub(painted.range.start).min(len);
                let range = painted.shown.range(&range);
                (range.start < range.end).then(|| range_rects(&painted.layout, &range, 0.0, 0.0))
            })
            .flatten()
            .collect()
    }

    /// The position one painted row above or below `at`, and the row it landed
    /// on. Walks the recorded runs in paint order — which is document order.
    ///
    /// Two things make this refuse to be a hit test. The gap between blocks
    /// belongs to no run, so a probe there answers with whichever run is
    /// nearest — and at a boundary that is the block being *left*, whose bottom
    /// edge is zero pixels away while the next block's top is a whole gap. And
    /// `from` is passed in rather than derived from `at`, because an offset at
    /// a soft wrap belongs to two rows and `position_for_index` always answers
    /// with the first: derive it and every step down recomputes the same row.
    pub fn step_row(
        &self,
        at: Cursor,
        from: Point<Pixels>,
        down: bool,
    ) -> Option<(Cursor, Pixels)> {
        let frames = self.0.borrow();
        let ix = frames
            .rows
            .iter()
            .position(|row| {
                row.block == at.block
                    && row.part == at.part
                    && row_contains(row, at.offset)
                    && row.bounds.origin.y <= from.y
                    && from.y < row.bounds.origin.y + row.bounds.size.height
            })
            .or_else(|| {
                frames.rows.iter().position(|row| {
                    row.block == at.block && row.part == at.part && row_contains(row, at.offset)
                })
            })?;
        let next = match down {
            true => frames.rows.get(ix + 1)?,
            false => frames.rows.get(ix.checked_sub(1)?)?,
        };
        Some((cursor_in_row(&frames, next, from.x)?, next.bounds.origin.y))
    }

    /// Whether `point` is inside painted text.
    ///
    /// [`Self::hit`] answers with the nearest run wherever it is asked, which
    /// is what a click wants and what a *pointer* must not have: an I-beam
    /// belongs where a caret would land, not everywhere an editor's box
    /// reaches.
    pub fn over_text(&self, point: Point<Pixels>) -> bool {
        self.0
            .borrow()
            .texts
            .iter()
            .any(|painted| painted.layout.bounds().contains(&point))
    }

    /// The block under `point`, for a gutter handle and a drop target.
    pub fn block_at(&self, point: Point<Pixels>) -> Option<usize> {
        let blocks = &self.0.borrow().blocks;
        blocks
            .iter()
            .find(|(_, bounds)| bounds.contains(&point))
            .or_else(|| {
                blocks.iter().min_by_key(|(_, bounds)| {
                    let above = (bounds.origin.y - point.y).abs();
                    let below = (bounds.origin.y + bounds.size.height - point.y).abs();
                    f32::from(above.min(below)) as i64
                })
            })
            .map(|(ix, _)| *ix)
    }

    /// Where a block's first painted row sits, and how tall that row is — what
    /// a mark in the gutter has to line up with.
    ///
    /// [`Self::block_bounds`] is not that: it spans every row the block holds,
    /// and a heading's single row is taller than a paragraph's, so anything
    /// placed from the top of the box rides above the text it points at.
    /// `None` for a block that paints no text at all, a rule being the one
    /// that does.
    pub fn first_row(&self, ix: usize) -> Option<(Pixels, Pixels)> {
        let texts = &self.0.borrow().texts;
        let painted = texts.iter().find(|painted| painted.block == ix)?;
        Some((
            painted.layout.bounds().origin.y,
            painted.layout.line_height(),
        ))
    }

    /// Where a block painted last frame, in window coordinates.
    pub fn block_bounds(&self, ix: usize) -> Option<Bounds<Pixels>> {
        self.0
            .borrow()
            .blocks
            .iter()
            .find(|(block, _)| *block == ix)
            .map(|(_, bounds)| *bounds)
    }

    /// Where a fenced block's language label painted — the box a host hangs its
    /// picker on. Recorded rather than derived: the word's width is the text
    /// system's answer, and padding arithmetic would be wrong the first time
    /// any of it changed.
    pub fn language_bounds(&self, ix: usize) -> Option<Bounds<Pixels>> {
        self.0
            .borrow()
            .languages
            .iter()
            .find(|(block, _)| *block == ix)
            .map(|(_, bounds)| *bounds)
    }

    /// Where a resizable painted block painted last frame — a painted fence,
    /// or an embed card — and `None` for any other block.
    pub fn painted_bounds(&self, ix: usize) -> Option<Bounds<Pixels>> {
        self.0
            .borrow()
            .painted
            .iter()
            .find(|(at, _)| *at == ix)
            .map(|(_, bounds)| *bounds)
    }

    /// Where an image block's picture painted, which
    /// [`BlockLayouts::block_bounds`] does not give: that box spans the column
    /// and takes in the caption, so a handle placed from it sits off the edge
    /// of any picture narrower than the page.
    pub fn picture_bounds(&self, ix: usize) -> Option<Bounds<Pixels>> {
        self.0
            .borrow()
            .pictures
            .iter()
            .find(|(block, _)| *block == ix)
            .map(|(_, bounds)| *bounds)
    }

    /// Where a task block's checkbox painted, which is the box itself and not
    /// the marker column it sits in — a press outside it is a press on the
    /// gutter, and belongs to whatever handles one.
    pub fn checkbox_bounds(&self, ix: usize) -> Option<Bounds<Pixels>> {
        self.0
            .borrow()
            .checkboxes
            .iter()
            .find(|(block, _)| *block == ix)
            .map(|(_, bounds)| *bounds)
    }

    /// Where a table cell painted, padding included.
    pub fn cell_bounds(&self, ix: usize, part: Part) -> Option<Bounds<Pixels>> {
        self.0
            .borrow()
            .cells
            .iter()
            .find(|(block, at, _)| *block == ix && *at == part)
            .map(|(_, _, bounds)| *bounds)
    }

    /// The table cell under `point`: its block and part.
    pub fn cell_at(&self, point: Point<Pixels>) -> Option<(usize, Part)> {
        self.0
            .borrow()
            .cells
            .iter()
            .find(|(_, _, bounds)| bounds.contains(&point))
            .map(|(block, part, _)| (*block, *part))
    }

    /// Scrolls the document until the start of `range` shows, centring it
    /// when it does not.
    ///
    /// Answered over the next few frames by a document rendered with these
    /// layouts and an [`Editing::scroll`]; without one the request is dropped
    /// at the next frame. A later call replaces an earlier one.
    pub fn reveal(&self, range: Selection) {
        self.reveal_with(range, RevealMode::Center);
    }

    /// [`Self::reveal`], placing the start of `range` by `mode`.
    pub fn reveal_with(&self, range: Selection, mode: RevealMode) {
        self.0.borrow_mut().reveal = Some(Reveal {
            range,
            mode,
            tries: 0,
            scrolled: false,
            top: None,
        });
    }

    pub(super) fn revealing(&self) -> Option<Reveal> {
        self.0.borrow().reveal
    }

    pub(super) fn set_revealing(&self, reveal: Option<Reveal>) {
        self.0.borrow_mut().reveal = reveal;
    }

    pub(super) fn record(
        &self,
        block: usize,
        part: Part,
        range: Range<usize>,
        layout: TextLayout,
        shown: Shown,
    ) {
        let mut frames = self.0.borrow_mut();
        let painted = frames.texts.len();
        record_rows(
            &mut frames.rows,
            painted,
            block,
            part,
            &range,
            &layout,
            &shown,
        );
        frames.texts.push(Painted {
            block,
            part,
            range,
            layout,
            shown,
        });
    }

    pub(super) fn record_block(&self, ix: usize, bounds: Bounds<Pixels>) {
        self.0.borrow_mut().blocks.push((ix, bounds));
    }

    pub(super) fn record_language(&self, ix: usize, bounds: Bounds<Pixels>) {
        self.0.borrow_mut().languages.push((ix, bounds));
    }

    pub(super) fn record_picture(&self, ix: usize, bounds: Bounds<Pixels>) {
        self.0.borrow_mut().pictures.push((ix, bounds));
    }

    pub(super) fn record_painted(&self, ix: usize, bounds: Bounds<Pixels>) {
        self.0.borrow_mut().painted.push((ix, bounds));
    }

    pub(super) fn record_checkbox(&self, ix: usize, bounds: Bounds<Pixels>) {
        self.0.borrow_mut().checkboxes.push((ix, bounds));
    }

    pub(super) fn record_cell(&self, ix: usize, part: Part, bounds: Bounds<Pixels>) {
        self.0.borrow_mut().cells.push((ix, part, bounds));
    }

    /// The height last measured for `key`, or else for whatever block was
    /// last at `ix`.
    pub(super) fn height(&self, ix: usize, key: u64) -> Option<Pixels> {
        let heights = &self.0.borrow().heights;
        heights
            .by_key
            .get(&key)
            .copied()
            .or_else(|| heights.by_index.get(ix).copied().flatten())
    }

    pub(super) fn record_height(&self, ix: usize, key: u64, height: Pixels) {
        let heights = &mut self.0.borrow_mut().heights;
        heights.by_key.insert(key, height);
        if heights.by_index.len() <= ix {
            heights.by_index.resize(ix + 1, None);
        }
        heights.by_index[ix] = Some(height);
    }

    /// Drops the heights of blocks no longer in the document once they
    /// outnumber the ones that are.
    pub(super) fn prune(&self, keys: &[u64]) {
        let heights = &mut self.0.borrow_mut().heights;
        heights.by_index.truncate(keys.len());
        if heights.by_key.len() > 2 * keys.len() {
            let keep: std::collections::HashSet<u64> = keys.iter().copied().collect();
            heights.by_key.retain(|key, _| keep.contains(key));
        }
    }

    pub(super) fn clear(&self) {
        let mut frames = self.0.borrow_mut();
        frames.texts.clear();
        frames.rows.clear();
        frames.blocks.clear();
        frames.languages.clear();
        frames.pictures.clear();
        frames.painted.clear();
        frames.checkboxes.clear();
        frames.cells.clear();
    }
}

pub(super) fn row_contains(row: &PaintedRow, offset: usize) -> bool {
    row.range.start <= offset && offset <= row.range.end
}

pub(super) fn cursor_in_row(frames: &Frames, row: &PaintedRow, x: Pixels) -> Option<Cursor> {
    let painted = &frames.texts[row.painted];
    let line = painted.layout.line_layout_for_index(row.line_start)?;
    let height = row.bounds.size.height;
    let local = point(
        x - row.bounds.origin.x,
        height * (row.wrapped_row as f32 + 0.5),
    );
    let (Ok(offset) | Err(offset)) = line.closest_index_for_position(local, height);
    let offset = painted.range.start + painted.shown.offset(row.line_start + offset);
    Some(Cursor::new(row.block, row.part, offset.min(row.range.end)))
}

pub(super) fn record_rows(
    rows: &mut Vec<PaintedRow>,
    painted: usize,
    block: usize,
    part: Part,
    range: &Range<usize>,
    layout: &TextLayout,
    shown: &Shown,
) {
    let line_height = layout.line_height();
    let bounds = layout.bounds();
    let mut origin = bounds.origin;
    let mut line_start = 0;
    for line in layout.line_layouts() {
        let shaped = &line.unwrapped_layout;
        let row_ends = line
            .wrap_boundaries()
            .iter()
            .map(|wrap| shaped.runs[wrap.run_ix].glyphs[wrap.glyph_ix].index)
            .chain([line.len()]);
        let mut row_start = 0;
        for (row, row_end) in row_ends.enumerate() {
            rows.push(PaintedRow {
                painted,
                block,
                part,
                range: range.start + shown.offset(line_start + row_start)
                    ..range.start + shown.offset(line_start + row_end),
                bounds: Bounds::new(
                    origin + point(px(0.0), line_height * row as f32),
                    size(bounds.size.width, line_height),
                ),
                line_start,
                wrapped_row: row,
            });
            row_start = row_end;
        }
        origin.y += line.size(line_height).height;
        line_start += line.len() + 1;
    }
}