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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//! The floating chrome: the gutter handle, the drop indicator, and the two
//! menus.
//!
//! All four are placed from positions `markdown::BlockLayouts` recorded as it
//! painted, so none of them can drift from the text it points at.
use gpui::{
AnyElement, App, Context, CursorStyle, MouseButton, Pixels, Point, SharedString, Window, div,
prelude::*, px,
};
use markdown::{BlockKind, Part};
use motion::{Fade, Painter};
use theme::{TextStyle, Theme, Typeset};
use ui::menu::Hit;
use crate::{
editor::{Editor, HANDLE_SIZE, Line},
layout::Layout,
};
/// What a row of a table line's menu does.
type TableAction = Box<dyn Fn(&mut Editor, &mut Context<Editor>)>;
/// How thick a table's `+` strips are.
const TABLE_STRIP: f32 = 16.0;
/// A table row or column handle, across and along the edge it sits on.
const TABLE_HANDLE_THIN: f32 = 12.0;
const TABLE_HANDLE_LONG: f32 = 20.0;
/// How far the language chip reaches past the word it wraps.
const CHIP_PAD_X: f32 = 6.0;
const CHIP_PAD_Y: f32 = 3.0;
/// Selector the interaction tests look the painted menu up by.
pub const SLASH_MENU: &str = "slash-menu";
/// The gutter handle's, for the same reason.
pub const BLOCK_HANDLE: &str = "block-handle";
/// The menu that handle opens, so a test can ask whether a second press on it
/// left the menu shut rather than closed-and-reopened.
pub const BLOCK_MENU: &str = "block-menu";
impl Editor {
/// The block the handle belongs on: the one being dragged, else the one
/// under the pointer, else the one the caret is in.
pub(super) fn handle_block(&self, focused: bool) -> Option<usize> {
if !self.chrome().handle {
return None;
}
if !self.blocks() {
return None;
}
self.lifted
.map(|(from, _)| from)
.or(self.hovered)
.or_else(|| focused.then(|| self.cursor().block))
}
/// Where the handle sits for that block, in this editor's own space.
///
/// Centred on the block's first row, not dropped at the top of its box. A
/// block with nothing painted in it has no row to centre on and keeps the
/// box's top.
pub(super) fn handle_origin(&self, ix: usize, cx: &App) -> Option<Point<Pixels>> {
let bounds = self.layouts.block_bounds(ix)?;
let top = match self.layouts.first_row(ix) {
Some((row, line)) => row + (line - px(HANDLE_SIZE)) / 2.0,
None => bounds.origin.y,
};
Some(gpui::point(
bounds.origin.x - self.origin.x - px(Layout::of(cx).text_inset),
top - self.origin.y,
))
}
/// The gutter handle, on the block being dragged, else the one under the
/// pointer, else the one the caret is in.
///
/// One handle rather than one per block: a single element placed from the
/// recorded frames does the whole job and the renderer stays clear of
/// editor concerns. The caret comes last because a pointer in the document
/// is the more immediate intent — and it comes at all because reaching a
/// block by keyboard should not mean reaching for the mouse to act on it.
pub(super) fn handle(
&mut self,
focused: bool,
theme: &Theme,
cx: &mut Context<Self>,
) -> Option<AnyElement> {
let placed = self
.handle_block(focused)
.and_then(|ix| Some((ix, self.handle_origin(ix, cx)?)));
// Kept even when there is none, so [`Self::settle_handle`] compares
// like with like and does not ask for a frame over a handle that is
// not there.
self.handle_at = placed.map(|(_, at)| at);
let (ix, at) = placed?;
let handle = div()
.id(BLOCK_HANDLE)
.debug_selector(|| BLOCK_HANDLE.to_string())
.absolute()
.left(at.x)
.top(at.y)
.w(px(HANDLE_SIZE))
.h(px(HANDLE_SIZE))
.flex()
.items_center()
.justify_center()
.rounded(px(4.0))
.cursor(CursorStyle::OpenHand)
.text_style(TextStyle::Callout)
.text_color(theme.text_faint)
.hover(|el| el.bg(theme.element_hover).text_color(theme.text_muted))
.child("⠿")
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _: &gpui::MouseDownEvent, _, cx| {
this.press_claimed = true;
this.lifted = Some((ix, ix));
// The menu belongs to the release. Opened here it would
// occlude the very moves a drag downwards is made of,
// and the drop target would never leave the block it
// started on — so the press only dismisses, and the note
// `trigger_press_matching` took is what tells the
// release apart from a fresh open.
ui::popover::close_popup(this, cx, |this| &mut this.block_menu);
cx.notify();
}),
);
Some(
ui::popover::trigger_press_matching(
handle,
|this| &mut this.block_menu,
move |&(block, _)| block == ix,
cx,
)
.into_any_element(),
)
}
/// The line showing where a lifted block — or a file dragged in from
/// outside — would land.
pub(super) fn drop_indicator(&self, theme: &Theme) -> Option<AnyElement> {
if !self.blocks() {
return None;
}
let (from, to) = match self.lifted.filter(|(from, to)| from != to) {
Some(lifted) => lifted,
// A file always lands under the block it is over, so it is a drag
// that only ever moves downwards.
None => self.dropping.map(|to| (to, to + 1))?,
};
let bounds = self.layouts.block_bounds(to)?;
// Above the target when moving up, below it when moving down — which
// is where the block actually ends up.
let y = if to < from {
bounds.origin.y
} else {
bounds.origin.y + bounds.size.height
};
Some(
div()
.absolute()
.left(px(0.0))
.top(y - self.origin.y)
.w_full()
.h(px(1.0))
.bg(theme.drop_line)
.into_any_element(),
)
}
/// The `+` strips along a table's right and bottom edges, on the table
/// under the pointer or else the one the caret is in: a column and a row
/// at the end.
pub(super) fn table_strips(&self, theme: &Theme, cx: &mut Context<Self>) -> Option<AnyElement> {
if !self.blocks() {
return None;
}
let ix = [self.hovered, Some(self.cursor().block)]
.into_iter()
.flatten()
.find(|ix| {
matches!(
self.doc.blocks.get(*ix).map(|block| &block.kind),
Some(BlockKind::Table { .. })
)
})?;
let BlockKind::Table { header, rows, .. } = &self.doc.blocks[ix].kind else {
return None;
};
let columns = rows.iter().map(Vec::len).chain([header.len()]).max()?;
let end_row = rows.len() + 1;
let bounds = self.layouts.block_bounds(ix)?;
let origin = bounds.origin - self.origin;
let strip =
|id: &'static str, add: fn(&mut Self, usize, usize, &mut Context<Self>), at: usize| {
div()
.id(id)
.absolute()
.flex()
.items_center()
.justify_center()
.rounded(px(4.0))
.cursor(CursorStyle::PointingHand)
.text_style(TextStyle::Callout)
.text_color(theme.text_faint)
.hover(|el| el.bg(theme.element_hover).text_color(theme.text_muted))
.child("+")
// Held here, or the editor's own move handler takes the
// hovered block away from under the pointer.
.on_mouse_move(|_, _, cx| cx.stop_propagation())
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _: &gpui::MouseDownEvent, window, cx| {
this.press_claimed = true;
this.focus_handle.clone().focus(window, cx);
add(this, ix, at, cx);
}),
)
};
Some(
div()
.absolute()
.left(origin.x)
.top(origin.y)
.w(bounds.size.width)
.h(bounds.size.height)
.child(
strip("table-add-column", Self::add_column, columns)
.left(bounds.size.width)
.top(px(0.0))
.w(px(TABLE_STRIP))
.h(bounds.size.height),
)
.child(
strip("table-add-row", Self::add_row, end_row)
.left(px(0.0))
.top(bounds.size.height)
.w(bounds.size.width)
.h(px(TABLE_STRIP)),
)
.into_any_element(),
)
}
/// A handle on the table's left edge at the row of the hovered cell, else
/// the caret's, and one on its top edge at that cell's column. Each opens
/// its line's menu.
pub(super) fn table_handles(
&self,
theme: &Theme,
cx: &mut Context<Self>,
) -> Option<AnyElement> {
if !self.blocks() {
return None;
}
let caret = self.cursor();
let (ix, part) = self.hovered_cell.or_else(|| {
matches!(caret.part, Part::Cell { .. }).then_some((caret.block, caret.part))
})?;
let Part::Cell { row, column } = part else {
return None;
};
let table = self.layouts.block_bounds(ix)?;
let cell = self.layouts.cell_bounds(ix, part)?;
let handle = |id: &'static str, glyph: &'static str, line: Line, anchor: Point<Pixels>| {
let trigger = div()
.id(id)
.absolute()
.flex()
.items_center()
.justify_center()
.rounded(px(4.0))
.bg(theme.surface)
.border_1()
.border_color(theme.border)
.cursor(CursorStyle::PointingHand)
.text_style(TextStyle::Caption)
.text_color(theme.text_faint)
.hover(|el| el.bg(theme.element_hover).text_color(theme.text_muted))
.child(glyph)
.on_mouse_move(|_, _, cx| cx.stop_propagation())
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, _: &gpui::MouseDownEvent, _, _| this.press_claimed = true),
);
ui::popover::menu_trigger_matching(
trigger,
|this| &mut this.table_menu,
move |&(block, at, _)| block == ix && at == line,
move |_| (ix, line, anchor),
cx,
)
};
let row_mid = cell.origin.y + cell.size.height / 2.0;
let column_mid = cell.origin.x + cell.size.width / 2.0;
Some(
div()
.child(
handle(
"table-row-handle",
"⋮",
Line::Row(row),
gpui::point(table.origin.x, row_mid),
)
.left(table.origin.x - self.origin.x - px(TABLE_HANDLE_THIN / 2.0))
.top(row_mid - self.origin.y - px(TABLE_HANDLE_LONG / 2.0))
.w(px(TABLE_HANDLE_THIN))
.h(px(TABLE_HANDLE_LONG)),
)
.child(
handle(
"table-column-handle",
"⋯",
Line::Column(column),
gpui::point(column_mid, table.origin.y),
)
.left(column_mid - self.origin.x - px(TABLE_HANDLE_LONG / 2.0))
.top(table.origin.y - self.origin.y - px(TABLE_HANDLE_THIN / 2.0))
.w(px(TABLE_HANDLE_LONG))
.h(px(TABLE_HANDLE_THIN)),
)
.into_any_element(),
)
}
/// Insert before, insert after and delete, for the line a table handle
/// opened.
pub(super) fn table_menu(&self, theme: &Theme, cx: &mut Context<Self>) -> Option<AnyElement> {
if !self.blocks() {
return None;
}
let view = Painter::of(cx);
let &(ix, line, at) = self.table_menu.get()?;
let Some(BlockKind::Table { header, rows, .. }) =
self.doc.blocks.get(ix).map(|block| &block.kind)
else {
return None;
};
let width = rows.iter().map(Vec::len).chain([header.len()]).max()?;
let action = |label: &'static str, run: TableAction| {
ui::popover::menu_row(
theme,
false,
Some(Fade::new(view, format!("table-{label}"))),
)
.id(SharedString::from(format!("table-row-{label}")))
.child(label)
.on_click(cx.listener(move |this, _, _, cx| {
ui::popover::close_popup(this, cx, |this| &mut this.table_menu);
run(this, cx);
}))
};
let rows: Vec<_> = match line {
Line::Row(row) => [
(row > 0).then(|| {
action(
"Insert above",
Box::new(move |this, cx| this.add_row(ix, row, cx)),
)
}),
Some(action(
"Insert below",
Box::new(move |this, cx| this.add_row(ix, row + 1, cx)),
)),
(row > 0).then(|| {
action(
"Delete row",
Box::new(move |this, cx| this.remove_row(ix, row, cx)),
)
}),
]
.into_iter()
.flatten()
.collect(),
Line::Column(column) => [
Some(action(
"Insert left",
Box::new(move |this, cx| this.add_column(ix, column, cx)),
)),
Some(action(
"Insert right",
Box::new(move |this, cx| this.add_column(ix, column + 1, cx)),
)),
(width > 1).then(|| {
action(
"Delete column",
Box::new(move |this, cx| this.remove_column(ix, column, cx)),
)
}),
]
.into_iter()
.flatten()
.collect(),
};
Some(ui::popover::menu_at(
"table-menu",
at,
ui::popover::dismiss_on_out(
ui::popover::popover_card(theme).w(px(160.0)),
|this| &mut this.table_menu,
cx,
)
.children(rows)
.into_any_element(),
self.table_menu.closing_since(),
))
}
/// The click target over a fence's header, where its language sits.
///
/// The header paints the name; this only takes the press. A renderer holds
/// a `&Doc` and cannot change one, which is why the copy button can live
/// down there and a language picker cannot.
pub(super) fn language_chip(
&self,
theme: &Theme,
cx: &mut Context<Self>,
) -> Option<AnyElement> {
// The source is a fence too, and it has no language to pick.
if !self.chrome().language || !self.blocks() {
return None;
}
// Whichever fence the reader is at: the one under the pointer, else the
// one the caret is in.
let ix = [self.hovered, Some(self.cursor().block)]
.into_iter()
.flatten()
.find(|ix| {
matches!(
self.doc.blocks.get(*ix).map(|b| &b.kind),
Some(BlockKind::Code { .. })
)
})?;
// The label's box, grown by the chip's padding — so the wash is around
// the word and nothing else, whatever the word is.
let bounds = self.layouts.language_bounds(ix)?;
let anchor = gpui::point(
bounds.origin.x - px(CHIP_PAD_X),
bounds.origin.y + bounds.size.height + px(CHIP_PAD_Y),
);
let chip = div()
.id("language-chip")
.absolute()
.left(bounds.origin.x - self.origin.x - px(CHIP_PAD_X))
.top(bounds.origin.y - self.origin.y - px(CHIP_PAD_Y))
.w(bounds.size.width + px(2.0 * CHIP_PAD_X))
.h(bounds.size.height + px(2.0 * CHIP_PAD_Y))
.rounded(px(4.0))
.cursor(CursorStyle::PointingHand)
.hover(|el| el.bg(theme.element_hover));
Some(
ui::popover::menu_trigger_matching(
chip,
|this| &mut this.language_menu,
move |&(block, _)| block == ix,
move |_| (ix, anchor),
cx,
)
.into_any_element(),
)
}
/// The languages the installed highlighter knows, at the header that asked.
pub(super) fn language_menu(
&self,
theme: &Theme,
cx: &mut Context<Self>,
) -> Option<AnyElement> {
if !self.chrome().language || !self.blocks() {
return None;
}
let view = Painter::of(cx);
let &(ix, at) = self.language_menu.get()?;
let Some(BlockKind::Code { language, .. }) = self.doc.blocks.get(ix).map(|b| &b.kind)
else {
return None;
};
let current = language.clone();
let row = |label: SharedString, tag: Option<String>, lit: bool| {
ui::popover::menu_row(theme, false, Some(Fade::new(view, format!("lang-{label}"))))
.justify_between()
.id(SharedString::from(format!("lang-row-{label}")))
.child(label.clone())
.when(lit, |row| {
row.child(
ui::icons::icon(ui::icons::glyph::Check)
.size(px(13.0))
.text_color(theme.text),
)
})
.on_click(cx.listener(move |this, _, _, cx| {
ui::popover::close_popup(this, cx, |this| &mut this.language_menu);
this.set_language(ix, tag.clone(), cx);
}))
};
let plain = row(
markdown::render::PLAIN_LANGUAGE.into(),
None,
current.is_none(),
);
let rows: Vec<AnyElement> = markdown::languages(cx)
.to_vec()
.into_iter()
.map(|name| {
let lit = current.as_deref() == Some(name.as_ref());
row(name.clone(), Some(name.to_string()), lit).into_any_element()
})
.collect();
Some(ui::popover::menu_at(
"language-menu",
at,
ui::popover::dismiss_on_out(
ui::popover::popover_card(theme).w(px(150.0)),
|this| &mut this.language_menu,
cx,
)
.child(
ui::scroll::pane("language-menu-rows", ui::scroll::Axes::Vertical)
.max_h(px(280.0))
.child(plain)
.children(rows),
)
.into_any_element(),
self.language_menu.closing_since(),
))
}
/// Turn into / Duplicate / Delete, at the handle that opened it.
pub(super) fn block_menu(&self, theme: &Theme, cx: &mut Context<Self>) -> Option<AnyElement> {
if !self.blocks() {
return None;
}
let view = Painter::of(cx);
let &(ix, at) = self.block_menu.get()?;
let turns = crate::slash::items();
let rows = turns.into_iter().map(|(label, kind)| {
ui::popover::menu_row(theme, false, Some(Fade::new(view, format!("turn-{label}"))))
.id(SharedString::from(format!("turn-row-{label}")))
.child(label)
.on_click(cx.listener(move |this, _, _, cx| {
ui::popover::close_popup(this, cx, |this| &mut this.block_menu);
this.set_block(ix, kind.clone(), cx);
}))
});
let action = |label: &'static str, run: fn(&mut Self, usize, &mut Context<Self>)| {
ui::popover::menu_row(
theme,
false,
Some(Fade::new(view, format!("block-{label}"))),
)
.id(SharedString::from(format!("block-row-{label}")))
.child(label)
.on_click(cx.listener(move |this, _, _, cx| {
ui::popover::close_popup(this, cx, |this| &mut this.block_menu);
run(this, ix, cx);
}))
};
Some(ui::popover::menu_at(
BLOCK_MENU,
at,
ui::popover::dismiss_on_out(
ui::popover::popover_card(theme)
.debug_selector(|| BLOCK_MENU.to_string())
.w(px(190.0)),
|this| &mut this.block_menu,
cx,
)
.child(
ui::scroll::pane("block-menu-rows", ui::scroll::Axes::Vertical)
.max_h(px(320.0))
.child(ui::popover::menu_heading(theme, "Turn into"))
.children(rows)
.child(ui::popover::menu_heading(theme, "Block"))
.child(action("Duplicate", |this, ix, cx| {
this.duplicate_block(ix, cx)
}))
.child(action("Delete", |this, ix, cx| this.remove_block(ix, cx))),
)
.into_any_element(),
self.block_menu.closing_since(),
))
}
/// What a pasted URL could be, under the block it landed in.
///
/// Anchored at the block's start rather than at the caret: the caret is
/// past the end of a URL, which is as far right as a line goes, and a menu
/// hanging off there points at nothing.
pub(super) fn paste_menu(&self, theme: &Theme, cx: &mut Context<Self>) -> Option<AnyElement> {
let pasted = self.pasted.as_ref()?;
let (point, line_height) = self.layouts.position(pasted.at)?;
let rows = pasted.rows.iter().enumerate().map(|(row, &choice)| {
let label = choice.label();
ui::popover::menu_row(theme, row == pasted.active, None)
.id(SharedString::from(format!("paste-row-{label}")))
.child(label)
.on_mouse_move(cx.listener(move |this: &mut Self, _, _, cx| {
if let Some(pasted) = this.pasted.as_mut()
&& pasted.active != row
{
pasted.active = row;
cx.notify();
}
}))
.on_click(cx.listener(move |this, _, _, cx| this.confirm_paste(choice, cx)))
});
Some(ui::popover::menu_at(
"paste-menu",
gpui::point(point.x, point.y + line_height),
ui::popover::popover_card(theme)
.w(px(180.0))
// Clicking away is `Dismiss`, which is a real answer: the link
// is already in the block and stays there.
.on_mouse_down_out(cx.listener(|this, _, _, cx| {
this.pasted = None;
cx.notify();
}))
.children(rows)
.into_any_element(),
None,
))
}
/// The menu, anchored under the `/` that opened it.
///
/// The anchor comes from the same layout the caret paints against, so it
/// costs nothing beyond a lookup and it cannot drift from the text.
pub(super) fn slash_menu(
&self,
theme: &Theme,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<AnyElement> {
let slash = self.slash.as_ref()?;
let (point, line_height) = self.layouts.position(slash.at)?;
let card = ui::menu::card(
theme,
"slash",
&slash.menu(),
&slash.cursor,
window,
cx,
|this: &mut Self, hit, _, cx| match hit {
Hit::Point(path) => {
if let Some(slash) = this.slash.as_mut()
&& slash.cursor.point_at(&slash.menu(), &path)
{
cx.notify();
}
}
Hit::Choose(path) => {
let kind = this.slash.as_ref().and_then(|slash| slash.kind_at(&path));
this.confirm_slash(kind, cx);
}
Hit::Dismiss => {
this.slash = None;
cx.notify();
}
},
)
// Compiles to nothing outside a test build. It is here because the
// menu's state opening and the menu *painting* are two different
// things, and the bug that shipped was the second one failing while
// the first looked fine.
.debug_selector(|| SLASH_MENU.to_string())
.max_h(px(280.0));
Some(ui::popover::menu_at(
"slash-menu",
gpui::point(point.x, point.y + line_height),
card.into_any_element(),
None,
))
}
}