bezel-editor 0.2.20

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
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use super::*;
use crate::AppExt as _;
use std::rc::Rc;
use ui::AppExt as _;

impl Render for Editor {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        if let Some(mention) = &mut self.mention {
            mention.refresh(cx);
        }
        let theme = Theme::of(cx).clone();
        let layout = cx.editor_layout();
        let focused = self.focus_handle.is_focused(window);
        // The only place the blink starts: `caret_moved` drops the task, so the
        // next render brings it back in phase, lit beat first.
        if focused && cx.caret_blink() {
            if self.blink.is_none() {
                self.start_blink(cx);
            }
        } else {
            self.blink = None;
            self.caret_on = true;
        }
        let selection = focused.then_some(self.selection);
        // The source line a reveal owed in source mode lands on.
        let reveal_line = match self.mode {
            Mode::Source => {
                self.refresh_source_view(cx);
                self.source_view().line_of(self.selection.head.offset)
            }
            Mode::Blocks => {
                self.drop_source_view();
                0
            }
        };
        // gpui ends an outside file drag — left the window or released
        // elsewhere — without a drop here, so the indicator goes with it.
        if !cx.has_active_drag() {
            self.dropping = None;
        }

        // Typed text and IME reach an entity only through an input handler
        // registered during *paint*, against the bounds it should be anchored
        // to. There is no custom element here to do that from, so a zero-cost
        // canvas over the document supplies the paint phase. Without this the
        // key bindings still fire and nothing types.
        let handle = self.focus_handle.clone();
        let entity = cx.entity();
        let in_drag = self.in_drag();
        let input = canvas(
            |_, _, _| (),
            move |bounds, _, window, cx| {
                // `on_mouse_move` hears the pointer only over this box, and a
                // drag goes on past it. Registering it is paint's alone.
                if in_drag {
                    let entity = entity.clone();
                    window.on_mouse_event(move |event: &gpui::MouseMoveEvent, phase, _, cx| {
                        if phase == gpui::DispatchPhase::Bubble && event.dragging() {
                            entity.update(cx, |this, cx| this.drag_to(event.position, cx));
                        }
                    });
                }
                // The gutter handle is placed from positions recorded in window
                // coordinates, so the box they have to be measured against is
                // taken here — the one place that knows it.
                entity.update(cx, |this, _| {
                    this.origin = bounds.origin;
                    this.width = bounds.size.width;
                });
                window.handle_input(
                    &handle,
                    ElementInputHandler::new(bounds, entity.clone()),
                    cx,
                );
            },
        )
        .absolute()
        .size_full();

        // A tab stop, so the editor is reachable the same way every other
        // control in the library is.
        let handle = self.focus_handle.clone().tab_stop(true);

        div()
            // Stateful only so the pointer leaving can be heard: `on_hover` is
            // what tells the gutter handle to stop pointing at a block the
            // pointer left behind.
            .id("bezel-editor")
            // The mark is what keeps `tab`: without it traversal answers the
            // key first and the caret never sees it.
            .key_context(key_context())
            .track_focus(&handle)
            // Tracking focus does not take it. Without this, clicking into the
            // document blurs the editor instead of putting a caret in it, and
            // the caret vanishes on the first click.
            .on_mouse_down(
                MouseButton::Left,
                cx.listener(|this, event: &gpui::MouseDownEvent, window, cx| {
                    // The handle's own listener runs first and claims the
                    // press; without the flag this would close the menu it
                    // just opened. `ui::popover::Popup` solves it the same way.
                    if std::mem::take(&mut this.press_claimed) {
                        this.focus_handle.clone().focus(window, cx);
                    } else {
                        this.pressed(
                            event.position,
                            event.click_count,
                            event.modifiers,
                            window,
                            cx,
                        );
                    }
                    // What `press` reads to skip a press this box already
                    // took. It also stops gpui's own focus transfer, which runs
                    // after this listener, so both arms focus by hand.
                    window.prevent_default();
                }),
            )
            .on_mouse_down(
                MouseButton::Right,
                cx.listener(|this, event: &gpui::MouseDownEvent, window, cx| {
                    if this.blocks()
                        && let Some((block, Part::Cell { row, column })) =
                            this.layouts.cell_at(event.position)
                    {
                        this.table_menu.open(Dropped::new(
                            (block, TableTarget::Cell { row, column }),
                            event.position,
                        ));
                        this.focus_handle.focus(window, cx);
                    } else {
                        this.right_pressed(event.position, window, cx);
                    }
                    window.prevent_default();
                    cx.stop_propagation();
                    cx.notify();
                }),
            )
            // The drag has to be tracked from the container rather than from a
            // payload: a text selection has nothing to carry, and gpui's drag
            // payload is for things being dropped somewhere.
            .on_hover(cx.listener(|this, hovered: &bool, _, cx| {
                if !*hovered && (this.hovered.take().is_some() | this.hovered_cell.take().is_some())
                {
                    cx.notify();
                }
                if !*hovered && this.over_anchor.take().is_some() {
                    cx.emit(EditorEvent::AnchorHovered(None));
                    cx.notify();
                }
            }))
            .on_mouse_move(cx.listener(|this, event: &gpui::MouseMoveEvent, _, cx| {
                // Ahead of every drag branch below, because the pointer's shape
                // is about where it *is* rather than about what it is doing.
                let over_text = this.layouts.over_text(event.position);
                if over_text != this.over_text {
                    this.over_text = over_text;
                    cx.notify();
                }
                // A drag in flight is followed by the window-wide listener
                // `render` registers; otherwise the pointer only decides which
                // block wears the handle.
                if this.in_drag() {
                    return;
                }
                let over = match this.over_text {
                    true => this.anchor_at(event.position),
                    false => None,
                };
                if over != this.over_anchor {
                    this.over_anchor = over;
                    cx.emit(EditorEvent::AnchorHovered(over));
                    // The pointer's shape follows the anchor under it.
                    cx.notify();
                }
                let hovered = this.layouts.block_at(event.position);
                let cell = this.layouts.cell_at(event.position).or_else(|| {
                    // Keep the target while crossing its control lanes.
                    this.hovered_cell.filter(|(block, _)| {
                        this.layouts
                            .block_bounds(*block)
                            .is_some_and(|bounds| bounds.contains(&event.position))
                    })
                });
                if hovered != this.hovered || cell != this.hovered_cell {
                    this.hovered = hovered;
                    this.hovered_cell = cell;
                    cx.notify();
                }
            }))
            // Both, because a release can land anywhere on screen and only the
            // first fires over the editor. A resize left running would leave
            // its stand-in picture painted over the document for good.
            .on_mouse_up_out(
                MouseButton::Left,
                cx.listener(|this, event: &gpui::MouseUpEvent, window, cx| {
                    this.drag_table_to(event.position, cx);
                    this.dragging = None;
                    this.drop_resize(window, cx);
                    this.drop_height(cx);
                    this.drop_table_drag(cx);
                }),
            )
            .on_mouse_up(
                MouseButton::Left,
                cx.listener(|this, event: &gpui::MouseUpEvent, window, cx| {
                    this.drag_table_to(event.position, cx);
                    this.dragging = None;
                    if this.drop_table_drag(cx) {
                        return;
                    }
                    if this.drop_resize(window, cx) {
                        return;
                    }
                    if this.drop_height(cx) {
                        return;
                    }
                    let Some((from, to)) = this.lifted.take() else {
                        return;
                    };
                    if from == to {
                        // A press that never moved is a click, and a click on
                        // the handle is what opens the menu — unless that same
                        // press is what dismissed it, which the note taken on
                        // the way down is the only way to tell.
                        if !this.block_menu.take_press_was_open() {
                            let rows = crate::slash::Rows::new(crate::block_menu::installed(cx));
                            this.block_menu
                                .open(Dropped::new((from, rows), event.position));
                        }
                        return cx.notify();
                    }
                    this.edit(EditKind::Structure, cx, |this| {
                        // `move_block` steps one sibling at a time, so a drop
                        // several blocks away is that many steps. Bounded by
                        // the block count, which no drag can exceed.
                        let delta = if to > from { 1 } else { -1 };
                        let mut at = from;
                        // Each step is its own move, so each is its own delta —
                        // folding them into one would have to compose the
                        // hops, and they are already in order.
                        let mut deltas = Vec::new();
                        for _ in 0..this.doc.blocks.len() {
                            let span = this.doc.subtree(at);
                            let Some(next) = this.doc.edit().move_block(at, delta) else {
                                break;
                            };
                            deltas.push(Delta::Moved {
                                at: span,
                                to: Some(next),
                            });
                            at = next;
                            if (delta > 0 && at >= to) || (delta < 0 && at <= to) {
                                break;
                            }
                        }
                        this.selection =
                            Selection::at(Cursor::new(at, Part::Body, 0).clamp(&this.doc));
                        deltas
                    });
                }),
            )
            .on_action(cx.listener(Self::backspace))
            .on_action(cx.listener(Self::delete))
            .on_action(cx.listener(|this, _: &KillLine, _, cx| this.delete_to(true, line_end, cx)))
            .on_action(cx.listener(|this, _: &DeleteWordLeft, _, cx| {
                this.delete_to(false, Cursor::word_left, cx)
            }))
            .on_action(cx.listener(|this, _: &DeleteWordRight, _, cx| {
                this.delete_to(true, Cursor::word_right, cx)
            }))
            .on_action(cx.listener(|this, _: &DeleteToHome, _, cx| {
                this.delete_to(false, |at, _| at.home(), cx)
            }))
            .on_action(cx.listener(Self::split_block))
            .on_action(cx.listener(Self::soft_break))
            .on_action(cx.listener(Self::insert_paragraph))
            .on_action(cx.listener(Self::indent))
            .on_action(cx.listener(Self::increase_text_size))
            .on_action(cx.listener(Self::decrease_text_size))
            .on_action(cx.listener(Self::reset_text_size))
            .on_action(cx.listener(Self::outdent))
            .on_action(cx.listener(Self::dismiss))
            .on_action(cx.listener(Self::select_all))
            .on_action(cx.listener(Self::copy))
            .on_action(cx.listener(Self::cut))
            .on_action(cx.listener(Self::paste))
            .on_action(cx.listener(Self::undo))
            .on_action(cx.listener(Self::redo))
            .on_action(cx.listener(Self::confirm_url))
            .on_action(cx.listener(Self::cancel_url))
            // A file crossing the document lights the same indicator a lifted
            // block does, so a drop from outside lands where it looks like it
            // will.
            .on_drag_move(cx.listener(
                |this, event: &gpui::DragMoveEvent<gpui::ExternalPaths>, _, cx| {
                    let at = event.event.position;
                    let over = event
                        .bounds
                        .contains(&at)
                        .then(|| this.layouts.block_at(at))
                        .flatten();
                    if over != this.dropping {
                        this.dropping = over;
                        cx.notify();
                    }
                },
            ))
            .on_drop(
                cx.listener(|this, paths: &gpui::ExternalPaths, window, cx| {
                    this.focus_handle.clone().focus(window, cx);
                    this.drop_paths(paths, cx);
                }),
            )
            .on_action(cx.listener(|this, _: &ToggleBold, _, cx| this.toggle_mark(Mark::Bold, cx)))
            .on_action(
                cx.listener(|this, _: &ToggleItalic, _, cx| this.toggle_mark(Mark::Italic, cx)),
            )
            .on_action(
                cx.listener(|this, _: &ToggleStrike, _, cx| this.toggle_mark(Mark::Strike, cx)),
            )
            .on_action(cx.listener(|this, _: &ToggleCode, _, cx| this.toggle_mark(Mark::Code, cx)))
            .on_action(cx.listener(|this, _: &ToggleHighlight, _, cx| {
                if this.marks.delimiter(HIGHLIGHT_MARK).is_some() {
                    this.toggle_mark(Mark::Custom(HIGHLIGHT_MARK.into()), cx);
                }
            }))
            .on_action(cx.listener(|this, _: &MoveBlockUp, _, cx| {
                this.move_block(this.cursor().block, -1, cx)
            }))
            .on_action(cx.listener(|this, _: &MoveBlockDown, _, cx| {
                this.move_block(this.cursor().block, 1, cx)
            }))
            .on_action(cx.listener(|this, _: &DuplicateBlock, _, cx| {
                this.duplicate_block(this.cursor().block, cx)
            }))
            .on_action(cx.listener(|this, _: &RemoveBlock, _, cx| {
                this.remove_block(this.cursor().block, cx)
            }))
            // Motion is one method with a `Cursor` function and an "extend"
            // flag, so a shift variant cannot drift from the key it shadows.
            .on_action(cx.listener(|this, _: &Left, _, cx| {
                if !this.menu_side(false, cx) {
                    this.horizontal(false, false, cx)
                }
            }))
            .on_action(cx.listener(|this, _: &Right, _, cx| {
                if !this.menu_side(true, cx) {
                    this.horizontal(true, false, cx)
                }
            }))
            .on_action(cx.listener(|this, _: &Up, _, cx| this.vertical(false, false, cx)))
            .on_action(cx.listener(|this, _: &Down, _, cx| this.vertical(true, false, cx)))
            .on_action(cx.listener(|this, _: &Home, _, cx| this.row_edge(false, false, cx)))
            .on_action(cx.listener(|this, _: &End, _, cx| this.row_edge(true, false, cx)))
            .on_action(cx.listener(|this, _: &DocumentStart, _, cx| {
                this.moved(false, |_, doc| Selection::all(doc).anchor, cx)
            }))
            .on_action(cx.listener(|this, _: &DocumentEnd, _, cx| {
                this.moved(false, |_, doc| Selection::all(doc).head, cx)
            }))
            .on_action(
                cx.listener(|this, _: &WordLeft, _, cx| this.moved(false, Cursor::word_left, cx)),
            )
            .on_action(
                cx.listener(|this, _: &WordRight, _, cx| this.moved(false, Cursor::word_right, cx)),
            )
            .on_action(cx.listener(|this, _: &SelectLeft, _, cx| this.horizontal(false, true, cx)))
            .on_action(cx.listener(|this, _: &SelectRight, _, cx| this.horizontal(true, true, cx)))
            .on_action(cx.listener(|this, _: &SelectUp, _, cx| this.vertical(false, true, cx)))
            .on_action(cx.listener(|this, _: &SelectDown, _, cx| this.vertical(true, true, cx)))
            .on_action(cx.listener(|this, _: &SelectHome, _, cx| this.row_edge(false, true, cx)))
            .on_action(cx.listener(|this, _: &SelectEnd, _, cx| this.row_edge(true, true, cx)))
            .on_action(cx.listener(|this, _: &SelectDocumentStart, _, cx| {
                this.moved(true, |_, doc| Selection::all(doc).anchor, cx)
            }))
            .on_action(cx.listener(|this, _: &SelectDocumentEnd, _, cx| {
                this.moved(true, |_, doc| Selection::all(doc).head, cx)
            }))
            .on_action(cx.listener(|this, _: &SelectWordLeft, _, cx| {
                this.moved(true, Cursor::word_left, cx)
            }))
            .on_action(cx.listener(|this, _: &SelectWordRight, _, cx| {
                this.moved(true, Cursor::word_right, cx)
            }))
            .w_full()
            // Text under the pointer, so the pointer says so — and only there,
            // or while a drag is still sweeping one out. The editor's box
            // reaches over its gutter, the margin beside a short line, a rule,
            // an image and a card, none of which a caret can be put into.
            // Where it has nothing to say it stays quiet rather than
            // overriding the page with an arrow of its own. Over an actionable
            // anchor it is a hand: a press there does what the app says.
            .map(|el| {
                if self.dragging.is_none() && self.over_actionable() {
                    el.cursor(CursorStyle::PointingHand)
                } else if self.over_text || self.dragging.is_some() {
                    el.cursor(CursorStyle::IBeam)
                } else {
                    el
                }
            })
            // No focus ring. A ring says *widget*, and a document is not one —
            // the caret already paints only while focused, so a box around the
            // whole page is a second, louder signal for the same fact.
            .relative()
            .child(input)
            // A height drag holds the resize cursor wherever the pointer
            // runs, over the editor's text and the card's own cursors alike.
            .when(self.sizing.is_some(), |el| {
                el.child(
                    canvas(
                        |_, _, _| (),
                        |_, _, window, _| window.set_window_cursor_style(CursorStyle::ResizeUpDown),
                    )
                    .absolute()
                    .size_0(),
                )
            })
            // The document is inset by the gutter so the handle has somewhere
            // to sit *inside* the editor. Outside it the handle is clipped by
            // any scrolling ancestor, and a pointer over it never reaches
            // `on_mouse_move`, which fires only while this element is the one
            // under the pointer.
            .child(
                div()
                    .w_full()
                    .pl(gpui::px(layout.text_inset))
                    .child(match self.mode {
                        // The source is one text, so it paints as one text —
                        // the same caret, the same clicks, no block chrome to
                        // suppress a piece at a time.
                        Mode::Source => markdown::render_source(
                            self.source_view(),
                            markdown::Editing {
                                selection,
                                caret_on: self.caret_on,
                                layouts: Some(&self.layouts),
                                annotations: &self.annotations(),
                                keep: if self.reveal.is_some() {
                                    std::slice::from_ref(&reveal_line)
                                } else {
                                    &[]
                                },
                                scroll: self.scroll.as_ref(),
                                typography: Some(cx.typography().scaled(
                                    text_size::resolve(self.text_size, cx)
                                        / theme::base_text_size(),
                                )),
                                ..Default::default()
                            },
                            cx,
                        ),
                        Mode::Blocks => markdown::render_with(
                            &self.doc,
                            markdown::Editing {
                                selection,
                                caret_on: self.caret_on,
                                layouts: Some(&self.layouts),
                                annotations: &self.annotations(),
                                placeholder: focused.then(|| PLACEHOLDER.into()),
                                // A caret goes into the caption here, so it is always
                                // painted — an editor that could hide it would be
                                // hiding a place you can already be typing.
                                caption: markdown::Caption::Shown,
                                // The size is absolute, so the factor the ladder
                                // is already scaled by comes back out of it —
                                // otherwise the app's size and this one multiply.
                                typography: Some(cx.typography().scaled(
                                    text_size::resolve(self.text_size, cx)
                                        / theme::base_text_size(),
                                )),
                                // The editor's own press hit-tests
                                // `checkbox_bounds`, which is what keeps a
                                // toggle in the undo history.
                                toggle: Some(markdown::Toggle::HitTested),
                                table_controls: true,
                                image_overlay: self.image_overlay.clone(),
                                image_overlay_corner: self.image_overlay_corner,
                                sizing: self.held_height(),
                                fence: Some(markdown::FenceHost {
                                    rewrite: {
                                        let editor = cx.entity().downgrade();
                                        Rc::new(move |ix, code, _, cx| {
                                            editor
                                                .update(cx, |this, cx| this.set_code(ix, code, cx))
                                                .ok();
                                        })
                                    },
                                    resize: Some({
                                        let editor = cx.entity().downgrade();
                                        Rc::new(move |ix, y, _, cx| {
                                            editor
                                                .update(cx, |this, cx| this.start_height(ix, y, cx))
                                                .ok();
                                        })
                                    }),
                                    leave: {
                                        let editor = cx.entity().downgrade();
                                        Rc::new(move |ix, window, cx| {
                                            editor
                                                .update(cx, |this, cx| {
                                                    this.leave_block(ix, window, cx)
                                                })
                                                .ok();
                                        })
                                    },
                                }),
                                base: self.base.as_deref(),
                                // A reveal owed to a caret nobody is focused on
                                // still needs its block built to find it.
                                keep: if self.reveal.is_some() {
                                    std::slice::from_ref(&self.selection.head.block)
                                } else {
                                    &[]
                                },
                                scroll: self.scroll.as_ref(),
                                jump: Some({
                                    let editor = cx.entity().downgrade();
                                    Rc::new(move |ix, _, cx| {
                                        let at = Selection::at(Cursor::new(ix, Part::Body, 0));
                                        editor
                                            .update(cx, |this, cx| this.select_to_top(at, cx))
                                            .ok();
                                    })
                                }),
                                ..Default::default()
                            },
                            window,
                            cx,
                        ),
                    }),
            )
            // Last, so the layouts it reads are this frame's rather than the
            // one before — children paint in order.
            .child(
                canvas(|_, _, _| (), {
                    let entity = cx.entity();
                    move |_, _, window, cx| {
                        entity.update(cx, |this, cx| {
                            this.reveal_caret(window);
                            this.settle_handle(window, cx);
                        });
                    }
                })
                .absolute()
                .size(gpui::px(0.0)),
            )
            .children(self.slash_menu(&theme, window, cx))
            .children(self.mention_menu(&theme, window, cx))
            .children(self.paste_menu(&theme, window, cx))
            .children(self.url_prompt(&theme, cx))
            .children(self.image_target(cx))
            .children(self.resize_preview())
            .children(self.handle(focused, &theme, cx))
            .children(self.resize_handle(&theme, cx))
            .children(self.drop_indicator(&theme))
            .children(self.table_strips(&theme, cx))
            .children(self.table_handles(&theme, cx))
            .children(self.table_drop_indicator(&theme))
            .children(self.dropdown(menu::Dropdown::Table, &theme, window, cx))
            .children(self.language_chip(&theme, cx))
            .children(self.dropdown(menu::Dropdown::Block, &theme, window, cx))
            .children(self.dropdown(menu::Dropdown::Language, &theme, window, cx))
            .children(self.dropdown(menu::Dropdown::Text, &theme, window, cx))
            .children(self.dropdown(menu::Dropdown::Image, &theme, window, cx))
    }
}