bezel-editor 0.2.21

A Notion-style block editor for gpui — the editing surface over the markdown document model
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
//! Anchors under a real editor: the words an anchor points at have to stay
//! the words it points at.
//!
//! Driven through key dispatch rather than by calling the mapping directly,
//! because the mapping is only half the claim — the other half is that every
//! path through `Editor::edit` reports what it did, and a path that forgets is
//! invisible to a unit test of the arithmetic.

use editor::{Anchor, AnchorId, Editor, SourceAnchor};
use gpui::{Entity, Focusable, TestAppContext, VisualTestContext, px, size};
use markdown::{Cursor, Part, Selection};

/// Three paragraphs, so there is something above an anchor to reorder and
/// something below it to shift.
const SOURCE: &str = "alpha one\n\nbravo two\n\ncharlie three";

const ID: AnchorId = AnchorId(1);

/// The primary modifier, which `editor::keys` splits the keymap on: cmd on
/// macOS, ctrl everywhere else. A test that names one chord outright passes on
/// one platform and silently does nothing on the other.
#[cfg(target_os = "macos")]
const PRIMARY: &str = "cmd";
#[cfg(not(target_os = "macos"))]
const PRIMARY: &str = "ctrl";

fn open(cx: &mut TestAppContext) -> (Entity<Editor>, VisualTestContext) {
    open_with(SOURCE, cx)
}

fn open_with(source: &str, cx: &mut TestAppContext) -> (Entity<Editor>, VisualTestContext) {
    cx.update(|cx| {
        theme::Theme::install(theme::Appearance::Dark, cx);
        editor::init(cx);
    });
    let window = cx.add_window(|_, cx| Editor::new(source, cx));
    let editor = window.root(cx).unwrap();
    let mut visual = VisualTestContext::from_window(window.into(), cx);
    visual.simulate_resize(size(px(360.0), px(600.0)));
    visual.update(|window, cx| {
        let handle = editor.read(cx).focus_handle(cx);
        window.focus(&handle, cx);
    });
    visual.run_until_parked();
    (editor, visual)
}

fn at(block: usize, offset: usize) -> Cursor {
    Cursor::new(block, Part::Body, offset)
}

/// Anchor `block`'s `from..to`, and put the caret where the test wants to type.
fn anchor(
    editor: &Entity<Editor>,
    cx: &mut VisualTestContext,
    range: (usize, usize, usize),
    caret: Cursor,
) {
    let (block, from, to) = range;
    cx.update(|_, cx| {
        let document = editor.read(cx).document().clone();
        document.update(cx, |document, cx| {
            document.set_anchors(
                vec![Anchor::new(
                    ID,
                    Selection::new(at(block, from), at(block, to)),
                )],
                cx,
            )
        });
    });
    cx.update(|_, cx| editor.update(cx, |editor, cx| editor.select(Selection::at(caret), cx)));
}

/// The anchored range, as `(block, start, end)`.
fn anchored(editor: &Entity<Editor>, cx: &mut VisualTestContext) -> (usize, usize, usize) {
    cx.update(|_, cx| {
        let anchor = &editor.read(cx).anchors()[0];
        let (start, end) = anchor.range.ordered();
        (start.block, start.offset, end.offset)
    })
}

fn detached(editor: &Entity<Editor>, cx: &mut VisualTestContext) -> bool {
    cx.update(|_, cx| editor.read(cx).anchors()[0].detached())
}

/// "one" in block 0, which is `alpha one` — offsets 6..9.
const ONE: (usize, usize, usize) = (0, 6, 9);

#[gpui::test]
fn typing_before_the_range_carries_it_along(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, ONE, at(0, 0));
    cx.simulate_input("XX");
    assert_eq!(
        anchored(&editor, &mut cx),
        (0, 8, 11),
        "both ends move by what went in ahead of them"
    );
}

#[gpui::test]
fn typing_inside_the_range_widens_it(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, ONE, at(0, 7));
    cx.simulate_input("XX");
    assert_eq!(
        anchored(&editor, &mut cx),
        (0, 6, 11),
        "the start holds and the end gives way"
    );
}

/// The left-sticky rule the marks already follow: typing at the end of a run
/// joins it, typing at the start does not.
#[gpui::test]
fn typing_at_the_end_joins_the_comment(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, ONE, at(0, 9));
    cx.simulate_input("X");
    assert_eq!(anchored(&editor, &mut cx), (0, 6, 10));
}

#[gpui::test]
fn typing_at_the_start_stays_outside_it(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, ONE, at(0, 6));
    cx.simulate_input("X");
    assert_eq!(anchored(&editor, &mut cx), (0, 7, 10));
}

#[gpui::test]
fn typing_after_the_range_leaves_it_alone(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, (0, 0, 5), at(0, 9));
    cx.simulate_input("XX");
    assert_eq!(anchored(&editor, &mut cx), (0, 0, 5));
}

#[gpui::test]
fn typing_in_a_block_above_moves_nothing(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, (1, 0, 5), at(0, 0));
    cx.simulate_input("XX");
    assert_eq!(
        anchored(&editor, &mut cx),
        (1, 0, 5),
        "an offset in another block is not an offset in this one"
    );
}

/// Enter above an anchor pushes its whole block down, which is the shift a
/// splice's block count carries.
#[gpui::test]
fn splitting_a_block_above_shifts_the_anchor_down(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, (1, 0, 5), at(0, 5));
    cx.simulate_keystrokes("enter");
    assert_eq!(
        anchored(&editor, &mut cx),
        (2, 0, 5),
        "the anchored block is one further down"
    );
}

#[gpui::test]
fn reordering_the_block_above_carries_the_anchor(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, ONE, at(0, 0));
    // Move the anchored block itself down past its neighbour.
    cx.update(|_, cx| editor.update(cx, |editor, cx| editor.move_block(0, 1, cx)));
    assert_eq!(
        anchored(&editor, &mut cx),
        (1, 6, 9),
        "the anchor rides the block it was on"
    );
}

#[gpui::test]
fn removing_a_block_above_pulls_the_anchor_up(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, (1, 0, 5), at(0, 0));
    cx.update(|_, cx| editor.update(cx, |editor, cx| editor.remove_block(0, cx)));
    assert_eq!(anchored(&editor, &mut cx), (0, 0, 5));
}

#[gpui::test]
fn removing_the_anchored_block_detaches_it(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, ONE, at(0, 0));
    cx.update(|_, cx| editor.update(cx, |editor, cx| editor.remove_block(0, cx)));
    assert!(
        detached(&editor, &mut cx),
        "the words are gone, and the thread is kept to say so"
    );
}

#[gpui::test]
fn deleting_the_anchored_words_detaches_it(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    // Select exactly the anchored word and delete it.
    anchor(&editor, &mut cx, ONE, at(0, 6));
    cx.update(|_, cx| {
        editor.update(cx, |editor, cx| {
            editor.select(Selection::new(at(0, 6), at(0, 9)), cx)
        })
    });
    cx.simulate_keystrokes("backspace");
    assert!(detached(&editor, &mut cx));
}

/// The reason the anchors live in the editor rather than in the app: an undo
/// restores a whole document, and there is no delta to map through.
#[gpui::test]
fn undo_and_redo_restore_the_anchor_with_the_document(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, ONE, at(0, 0));
    cx.simulate_input("XX");
    assert_eq!(anchored(&editor, &mut cx), (0, 8, 11));

    cx.simulate_keystrokes(&format!("{PRIMARY}-z"));
    assert_eq!(
        anchored(&editor, &mut cx),
        ONE,
        "the anchor of that moment came back with the document"
    );

    cx.simulate_keystrokes(&format!("{PRIMARY}-shift-z"));
    assert_eq!(
        anchored(&editor, &mut cx),
        (0, 8, 11),
        "and redo replays it"
    );
}

#[gpui::test]
fn a_click_finds_the_comment_under_it(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, ONE, at(0, 0));
    let bounds = cx
        .update(|_, cx| editor.read(cx).anchor_bounds(ID))
        .expect("the anchor painted somewhere");
    assert_eq!(
        cx.update(|_, cx| editor.read(cx).anchor_at(bounds.origin)),
        Some(ID),
        "a point on the range answers with its thread"
    );
}

/// A block shortcut puts its prefix in and takes it back out. Only the second
/// half of that is a mutation nothing typed, and an anchor that maps through
/// one and not the other lands that many bytes down the line.
#[gpui::test]
fn a_block_shortcut_takes_its_prefix_back_off_the_anchor(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, ONE, at(0, 0));
    cx.simulate_input("## ");
    assert_eq!(
        anchored(&editor, &mut cx),
        ONE,
        "the hashes went in and came out; the word they turned into a heading did not move"
    );
}

/// The marker line an alert is promoted from goes the same way.
#[gpui::test]
fn promoting_an_alert_takes_its_marker_off_the_anchor(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, ONE, at(0, 0));
    cx.simulate_input("> ");
    cx.simulate_input("[!NOTE]");
    cx.simulate_keystrokes("shift-enter");
    assert_eq!(
        anchored(&editor, &mut cx),
        ONE,
        "the marker and its break left the body they were written above"
    );
}

/// An inline rule is the third mutation the author does not type: `**x**` goes
/// in and four delimiters come out.
#[gpui::test]
fn an_inline_rule_takes_its_delimiters_off_the_anchor(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, ONE, at(0, 0));
    cx.simulate_input("**x**");
    assert_eq!(
        anchored(&editor, &mut cx),
        (0, 7, 10),
        "one bold letter is what is left ahead of the word"
    );
}

/// The words an anchor points at, read out of whichever form is shown.
fn anchored_text(editor: &Entity<Editor>, cx: &mut VisualTestContext) -> String {
    cx.update(|_, cx| {
        let editor = editor.read(cx);
        let (start, end) = editor.anchors()[0].range.ordered();
        let text = editor.doc().blocks[start.block]
            .text_at(start.part)
            .unwrap();
        text.text[start.offset..end.offset].to_string()
    })
}

fn toggle_source(editor: &Entity<Editor>, cx: &mut VisualTestContext) {
    cx.update(|_, cx| editor.update(cx, |editor, cx| editor.toggle_source(cx)));
    cx.run_until_parked();
}

#[gpui::test]
fn an_anchor_follows_the_source_and_comes_back(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    // "two" in `bravo two`.
    anchor(&editor, &mut cx, (1, 6, 9), at(0, 0));
    toggle_source(&editor, &mut cx);
    assert_eq!(
        anchored_text(&editor, &mut cx),
        "two",
        "the same words in the source"
    );

    // The caret crossed at the very start.
    cx.simulate_input("XX");
    assert_eq!(
        anchored_text(&editor, &mut cx),
        "two",
        "a source edit carries it along"
    );

    toggle_source(&editor, &mut cx);
    assert_eq!(anchored(&editor, &mut cx), (1, 6, 9));
    assert_eq!(
        anchored_text(&editor, &mut cx),
        "two",
        "and back onto the blocks"
    );
}

#[gpui::test]
fn an_anchor_end_in_the_markup_comes_back_detached(cx: &mut TestAppContext) {
    let (editor, mut cx) = open_with("# Title", cx);
    toggle_source(&editor, &mut cx);
    // Between `#` and its space: no block owns that position.
    let code = |offset| Cursor::new(0, Part::Code, offset);
    cx.update(|_, cx| {
        let document = editor.read(cx).document().clone();
        document.update(cx, |document, cx| {
            document.set_anchors(vec![Anchor::new(ID, Selection::new(code(1), code(7)))], cx)
        })
    });
    toggle_source(&editor, &mut cx);
    assert!(
        detached(&editor, &mut cx),
        "not stretched from the document start"
    );
}

#[gpui::test]
fn anchors_cross_to_and_from_the_markdown(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    let bravo = SOURCE.find("bravo").unwrap();
    cx.update(|_, cx| {
        let document = editor.read(cx).document().clone();
        document.update(cx, |document, cx| {
            document.set_source_anchors(
                SOURCE,
                vec![SourceAnchor {
                    id: ID,
                    range: bravo..bravo + 5,
                    state: markdown::Annotation::Open,
                    actionable: true,
                }],
                cx,
            )
        })
    });
    assert_eq!(anchored(&editor, &mut cx), (1, 0, 5));
    let actionable = cx.update(|_, cx| editor.read(cx).anchors()[0].actionable);
    assert!(actionable, "the flag comes through with the range");
    let (source, ranges) =
        cx.update(|_, cx| editor.read(cx).document().read(cx).source_with_anchors());
    assert_eq!(source, SOURCE);
    assert_eq!(ranges, vec![(ID, Some(bravo..bravo + 5))]);
}

#[gpui::test]
fn anchor_tops_follow_the_document_down(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    let (alpha, charlie) = (
        SOURCE.find("alpha").unwrap(),
        SOURCE.find("charlie").unwrap(),
    );
    cx.update(|_, cx| {
        let document = editor.read(cx).document().clone();
        document.update(cx, |document, cx| {
            document.set_source_anchors(
                SOURCE,
                vec![
                    SourceAnchor {
                        id: AnchorId(2),
                        range: charlie..charlie + 7,
                        state: markdown::Annotation::Open,
                        actionable: false,
                    },
                    SourceAnchor {
                        id: ID,
                        range: alpha..alpha + 5,
                        state: markdown::Annotation::Open,
                        actionable: false,
                    },
                ],
                cx,
            )
        })
    });
    cx.run_until_parked();
    cx.update(|window, _| window.refresh());
    cx.run_until_parked();
    let tops = cx.update(|_, cx| editor.read(cx).anchor_tops());
    let ids: Vec<_> = tops.iter().map(|(id, _)| *id).collect();
    assert_eq!(ids, vec![ID, AnchorId(2)], "in document order");
    assert!(tops[0].1 < tops[1].1, "{tops:?}");
}

#[gpui::test]
fn washes_leave_the_anchors_alone(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    let hit = Selection::new(at(0, 0), at(0, 5));
    cx.update(|_, cx| {
        editor.update(cx, |editor, cx| {
            editor.set_washes(vec![(hit, markdown::Annotation::Match)], cx)
        })
    });
    cx.update(|_, cx| {
        assert!(editor.read(cx).anchors().is_empty());
        assert_eq!(
            editor.read(cx).washes(),
            &[(hit, markdown::Annotation::Match)]
        );
    });
}

#[gpui::test]
fn the_pointer_over_anchored_text_names_the_anchor(cx: &mut TestAppContext) {
    let (editor, mut cx) = open(cx);
    anchor(&editor, &mut cx, ONE, at(0, 0));
    let heard = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
    cx.update(|_, cx| {
        let heard = heard.clone();
        cx.subscribe(&editor, move |_, event: &editor::EditorEvent, _| {
            if let editor::EditorEvent::AnchorHovered(over) = event {
                heard.borrow_mut().push(*over);
            }
        })
        .detach();
    });
    let bounds = cx
        .update(|_, cx| editor.read(cx).anchor_bounds(ID))
        .expect("the anchor painted somewhere");
    let on = bounds.origin + gpui::point(px(2.0), bounds.size.height / 2.0);
    cx.simulate_mouse_move(on, None, gpui::Modifiers::none());
    cx.run_until_parked();
    assert_eq!(heard.borrow().as_slice(), &[Some(ID)]);
}