Coverage Report

Created: 2026-11-19 08:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/builds/framezero/productivity/src/ui/notes/blocks.rs
Line
Count
Source
1
//! The block editor (Notes → Blocks): the open note drawn as formatted blocks, Notion-like,
2
//! where clicking a block edits just that block's Markdown.
3
//!
4
//! It edits the same draft as Write. The note's source stays the only document; the block
5
//! being edited has its own small text field, and every change to it replaces exactly that
6
//! block's range in the draft, after checking the range still holds what the block last
7
//! wrote. So the draft, autosave, conflicts, and dirty guards are Write's own, and text
8
//! outside the block is never rewritten.
9
10
use gpui::{AnyElement, Entity, EntityId, SharedString, Subscription, div, prelude::*, px, rgb};
11
use gpui_component::{
12
    Icon, IconName, Sizable as _,
13
    button::{Button, ButtonVariants as _},
14
    input::{InputEvent, Textarea, TextareaState},
15
};
16
use productivity::core::{
17
    note_blocks::{
18
        BlockEnter, BlockKind, NoteBlock, block_enter, new_block_separator, note_blocks,
19
    },
20
    note_edit::{KeyOutcome, toggle_tasks},
21
    note_preview::{PreparedPreview, prepare_preview_with_links, safe_link_url},
22
};
23
24
use std::ops::Range;
25
26
use super::{
27
    super::Workspace,
28
    super::theme::t,
29
    NoteFormat, apply_markdown_edit, format_edit, section_label,
30
    slash::{matching, slash_query},
31
};
32
33
/// Replaces the whole text of a block field, placing the caret at `caret`.
34
7
fn set_block_text(
35
7
    input: &Entity<TextareaState>,
36
7
    text: &str,
37
7
    caret: usize,
38
7
    window: &mut gpui::Window,
39
7
    cx: &mut gpui::App,
40
7
) {
41
7
    input.update(cx, |input, cx| {
42
7
        let end = input.value().len();
43
7
        input.set_selected_range(0..end, cx);
44
7
        input.replace(text.to_owned(), window, cx);
45
7
        input.set_selected_range(caret..caret, cx);
46
7
    });
47
7
}
48
49
/// The widest block column, as in Live Edit.
50
const COLUMN_WIDTH: f32 = 760.;
51
52
/// Text size and line height shared by drawn blocks and the block being edited, so a block
53
/// keeps its size when clicked.
54
const BLOCK_TEXT: f32 = 15.;
55
const BLOCK_LINE: f32 = 1.6;
56
/// Horizontal room around a block's text, and the field's own inset inside it.
57
const BLOCK_PAD_X: f32 = 8.;
58
const FIELD_PAD_X: f32 = 4.;
59
60
/// The heading level of a block's text (`# ` to `###### `).
61
111
fn heading_level(text: &str) -> Option<u8> {
62
111
    let hashes = text.len() - text.trim_start_matches('#').len();
63
111
    ((1..=6).contains(&hashes) && 
text[hashes..].starts_with(' ')7
).then_some(hashes as u8)
64
111
}
65
66
/// Text size and line height the preview draws a heading at (gpui-base's heading metrics).
67
7
fn heading_text(level: u8) -> (f32, f32) {
68
7
    match level {
69
6
        1 => (BLOCK_TEXT * 1.8, 1.25),
70
1
        2 => (BLOCK_TEXT * 4. / 3., 1.35),
71
0
        3 => (BLOCK_TEXT * 17. / 15., 1.35),
72
0
        4 => (BLOCK_TEXT, 1.35),
73
0
        5 => (BLOCK_TEXT * 14. / 15., 1.35),
74
0
        _ => (BLOCK_TEXT * 13. / 15., 1.35),
75
    }
76
7
}
77
78
#[derive(Default)]
79
pub(in crate::ui) struct BlocksState {
80
    shown: Option<Shown>,
81
    active: Option<ActiveBlock>,
82
    /// Why editing stopped or is unavailable.
83
    pub(in crate::ui) message: Option<&'static str>,
84
    /// The "/" menu under the block being edited.
85
    slash: Option<BlockSlash>,
86
}
87
88
/// A `/word` typed at a line start in the block, and the highlighted command.
89
struct BlockSlash {
90
    range: Range<usize>,
91
    query: String,
92
    selected: usize,
93
}
94
95
/// The blocks drawn for one version of the draft.
96
struct Shown {
97
    source: EntityId,
98
    generation: u64,
99
    /// `None` when the note is too large to split while editing.
100
    blocks: Option<Vec<ShownBlock>>,
101
}
102
103
pub(in crate::ui) struct ShownBlock {
104
    block: NoteBlock,
105
    text: String,
106
    preview: Result<PreparedPreview, String>,
107
}
108
109
struct ActiveBlock {
110
    /// The block being edited, or `None` for a new block not yet in the blocks.
111
    index: Option<usize>,
112
    /// Where the block starts in the draft, and the text the draft holds there.
113
    start: usize,
114
    written: String,
115
    /// Around a new block's text once it has any: the line breaks separating it from its
116
    /// neighbours. An empty new block leaves the draft untouched.
117
    before: &'static str,
118
    after: &'static str,
119
    input: Entity<TextareaState>,
120
    _subscription: Subscription,
121
}
122
123
impl ActiveBlock {
124
    /// The draft text for what is typed in the block.
125
73
    fn compose(&self, typed: &str) -> String {
126
73
        match self.index {
127
55
            None if typed.is_empty() => 
String::new()2
,
128
53
            None => format!("{}{typed}{}", self.before, self.after),
129
18
            Some(_) => typed.to_owned(),
130
        }
131
73
    }
132
}
133
134
/// `text` split into blocks, each prepared for drawing; `None` when it is too large.
135
42
pub(in crate::ui) fn preview_blocks(text: &str, note_path: &str) -> Option<Vec<ShownBlock>> {
136
42
    note_blocks(text).map(|blocks| {
137
42
        blocks
138
42
            .into_iter()
139
            .map(|block| ShownBlock {
140
361
                preview: prepare_preview_with_links(&text[block.body.clone()], note_path),
141
361
                text: text[block.range.clone()].to_owned(),
142
361
                block,
143
361
            })
144
            .collect()
145
42
    })
146
42
}
147
148
impl Workspace {
149
    /// Edits block `index` of the open draft, as a click on it does.
150
1
    pub(in crate::ui) fn edit_note_block_at(
151
1
        &mut self,
152
1
        index: usize,
153
1
        window: &mut gpui::Window,
154
1
        cx: &mut gpui::Context<Self>,
155
1
    ) {
156
1
        self.edit_note_block(Some(index), None, window, cx);
157
1
    }
158
159
    /// A click on a block: in Browse, before the note is open for editing, it opens it in
160
    /// place at that block; otherwise it edits the block.
161
13
    fn click_note_block(
162
13
        &mut self,
163
13
        index: usize,
164
13
        window: &mut gpui::Window,
165
13
        cx: &mut gpui::Context<Self>,
166
13
    ) {
167
13
        if self.view == crate::ui::View::NotesBrowse && 
!self.editor_holds_selected_note()3
{
168
2
            self.edit_selected_note_block(index, window, cx);
169
        } else {
170
11
            self.edit_note_block(Some(index), None, window, cx);
171
        }
172
13
    }
173
174
    /// Browse's preview as blocks of the saved note; clicking one starts editing there.
175
39
    pub(in crate::ui) fn browse_preview_blocks(
176
39
        &self,
177
39
        blocks: &[ShownBlock],
178
39
        cx: &mut gpui::Context<Self>,
179
39
    ) -> AnyElement {
180
39
        let mut column = div()
181
39
            .debug_selector(|| "notes-browse-blocks".into())
182
            .flex()
183
            .flex_col()
184
            .gap_1();
185
39
        for (index, block) in blocks.iter().enumerate() {
186
953
            column = column.child(self.shown_block(index, block, cx));
187
        }
188
39
        column.into_any_element()
189
39
    }
190
191
    /// Browse's preview while the note is open: the block editor embedded in the card.
192
23
    pub(in crate::ui) fn browse_block_editor(&self, cx: &mut gpui::Context<Self>) -> AnyElement {
193
23
        self.blocks_column(
194
23
            div()
195
23
                .debug_selector(|| "notes-browse-blocks".into())
196
                .flex()
197
                .flex_col()
198
                .gap_1(),
199
23
            cx,
200
        )
201
        .into_any_element()
202
23
    }
203
204
    /// Splits the draft into blocks again when it changed. Nothing changes while a block is
205
    /// being edited: its own field shows the current text.
206
192
    pub(in crate::ui) fn refresh_note_blocks(&mut self, cx: &mut gpui::Context<Self>) {
207
192
        if self.notes.blocks.active.is_some() {
208
111
            return;
209
81
        }
210
81
        let Some(editor) = &self.notes.editor else {
211
0
            self.notes.blocks.shown = None;
212
0
            return;
213
        };
214
81
        let key = (editor.source.entity_id(), editor.generation);
215
81
        if self
216
81
            .notes
217
81
            .blocks
218
81
            .shown
219
81
            .as_ref()
220
67
            .is_some_and(|shown| (shown.source, shown.generation) == key)
221
        {
222
59
            return;
223
22
        }
224
22
        let text = editor.source.read(cx).value().to_string();
225
22
        let path = self.note_path_for(editor.note_id);
226
22
        let blocks = preview_blocks(&text, &path);
227
22
        self.notes.blocks.shown = Some(Shown {
228
22
            source: key.0,
229
22
            generation: key.1,
230
22
            blocks,
231
22
        });
232
192
    }
233
234
126
    fn can_edit_blocks(&self) -> bool {
235
126
        self.notes
236
126
            .editor
237
126
            .as_ref()
238
126
            .is_some_and(|editor| editor.conflict.is_none())
239
126
    }
240
241
16
    fn shown_blocks(&self) -> &[ShownBlock] {
242
16
        self.notes
243
16
            .blocks
244
16
            .shown
245
16
            .as_ref()
246
16
            .and_then(|shown| shown.blocks.as_deref())
247
            .unwrap_or_default()
248
16
    }
249
250
17
    fn draft_text(&self, cx: &gpui::App) -> Option<String> {
251
17
        let editor = self.notes.editor.as_ref()
?0
;
252
17
        Some(editor.source.read(cx).value().to_string())
253
17
    }
254
255
    /// Starts editing block `index` with the caret at `caret` (its end for `None`), or a new
256
    /// block at the end of the note for `index: None`.
257
16
    fn edit_note_block(
258
16
        &mut self,
259
16
        index: Option<usize>,
260
16
        caret: Option<usize>,
261
16
        window: &mut gpui::Window,
262
16
        cx: &mut gpui::Context<Self>,
263
16
    ) {
264
16
        self.finish_note_block(cx);
265
16
        self.refresh_note_blocks(cx);
266
16
        let Some(source) = self.draft_text(cx) else {
267
0
            return;
268
        };
269
16
        match index {
270
            Some(index) => {
271
14
                let Some(block) = self.shown_blocks().get(index) else {
272
0
                    return;
273
                };
274
14
                let (start, text) = (block.block.range.start, block.text.clone());
275
14
                let caret = caret.unwrap_or(text.len()).min(text.len());
276
14
                self.begin_note_block(Some(index), start, "", "", text, caret, window, cx);
277
            }
278
            None => {
279
2
                let separator = new_block_separator(&source);
280
2
                self.begin_note_block(
281
2
                    None,
282
2
                    source.len(),
283
2
                    separator,
284
2
                    "",
285
2
                    String::new(),
286
2
                    0,
287
2
                    window,
288
2
                    cx,
289
2
                );
290
            }
291
        }
292
16
    }
293
294
    /// Opens the block field. An existing block's `text` is what the draft holds at `start`;
295
    /// a new block starting with `text` is written into the draft at once.
296
    #[allow(clippy::too_many_arguments)]
297
21
    fn begin_note_block(
298
21
        &mut self,
299
21
        index: Option<usize>,
300
21
        start: usize,
301
21
        before: &'static str,
302
21
        after: &'static str,
303
21
        text: String,
304
21
        caret: usize,
305
21
        window: &mut gpui::Window,
306
21
        cx: &mut gpui::Context<Self>,
307
21
    ) {
308
21
        if !self.can_edit_blocks() {
309
0
            return;
310
21
        }
311
21
        let input = cx.new(|cx| {
312
21
            let mut state = TextareaState::new(window, cx)
313
21
                .auto_grow(1, 40)
314
21
                .placeholder("Type Markdown…");
315
21
            state.set_value(text.clone(), window, cx);
316
21
            state
317
21
        });
318
62
        let subscription = 
cx21
.subscribe_in(
&input21
,
window21
, |this, _, event, window, cx| {
319
62
            if matches!(event, InputEvent::Change) {
320
60
                this.write_note_block(window, cx);
321
2
            }
322
62
        });
323
21
        input.update(cx, |input, cx| {
324
21
            input.set_selected_range(caret..caret, cx);
325
21
            input.focus(window, cx);
326
21
        });
327
21
        self.notes.blocks.message = None;
328
21
        self.notes.blocks.active = Some(ActiveBlock {
329
21
            written: if index.is_some() {
330
14
                text.clone()
331
            } else {
332
7
                String::new()
333
            },
334
21
            index,
335
21
            start,
336
21
            before,
337
21
            after,
338
21
            input,
339
21
            _subscription: subscription,
340
        });
341
21
        if index.is_none() && 
!text.is_empty()7
{
342
3
            self.write_note_block(window, cx);
343
18
        }
344
21
        cx.notify();
345
21
    }
346
347
    /// Copies the edited block into the draft, replacing only its own range.
348
73
    fn write_note_block(&mut self, window: &mut gpui::Window, cx: &mut gpui::Context<Self>) {
349
73
        let Some(active) = &self.notes.blocks.active else {
350
0
            return;
351
        };
352
73
        let text = active.compose(&active.input.read(cx).value());
353
73
        let range = active.start..active.start + active.written.len();
354
73
        if self.replace_in_draft(range, &active.written.clone(), &text, window, cx)
355
72
            && let Some(active) = &mut self.notes.blocks.active
356
        {
357
72
            active.written = text;
358
1
        }
359
73
        self.update_block_slash(cx);
360
73
    }
361
362
    /// Opens, filters, or closes the "/" menu for the text before the caret.
363
73
    fn update_block_slash(&mut self, cx: &mut gpui::Context<Self>) {
364
73
        let Some(active) = &self.notes.blocks.active else {
365
1
            self.notes.blocks.slash = None;
366
1
            return;
367
        };
368
72
        let input = active.input.read(cx);
369
72
        let caret = input.selected_range();
370
72
        let found = caret
371
72
            .is_empty()
372
66
            .then(|| slash_query(&input.value(), caret.start))
373
            .flatten()
374
6
            .filter(|(_, query)| matching(query).next().is_some());
375
72
        let previous = self.notes.blocks.slash.take();
376
72
        self.notes.blocks.slash = found.map(|(range, query)| 
{6
377
6
            let count = matching(&query).count();
378
6
            let selected = previous
379
3
                .filter(|previous| previous.range.start == range.start)
380
6
                .map_or(0, |previous| 
previous.selected3
.min(
count - 13
));
381
6
            BlockSlash {
382
6
                range,
383
6
                query,
384
6
                selected,
385
6
            }
386
6
        });
387
72
        cx.notify();
388
73
    }
389
390
    /// Replaces the typed `/word` with the chosen command's Markdown.
391
2
    fn choose_block_slash(
392
2
        &mut self,
393
2
        index: usize,
394
2
        window: &mut gpui::Window,
395
2
        cx: &mut gpui::Context<Self>,
396
2
    ) {
397
        let (Some(slash), Some(active)) =
398
2
            (self.notes.blocks.slash.take(), &self.notes.blocks.active)
399
        else {
400
0
            return;
401
        };
402
2
        let Some(command) = matching(&slash.query).nth(index) else {
403
0
            return;
404
        };
405
2
        let caret = command.caret(slash.range.start);
406
2
        active.input.update(cx, |input, cx| {
407
2
            input.set_selected_range(slash.range.clone(), cx);
408
2
            input.replace(command.insert.to_owned(), window, cx);
409
2
            input.set_selected_range(caret..caret, cx);
410
2
            input.focus(window, cx);
411
2
        });
412
2
        self.write_note_block(window, cx);
413
2
    }
414
415
    /// Up and Down move through an open "/" menu; otherwise they move the caret.
416
5
    fn note_block_arrow(
417
5
        &mut self,
418
5
        down: bool,
419
5
        window: &mut gpui::Window,
420
5
        cx: &mut gpui::Context<Self>,
421
5
    ) {
422
5
        if let Some(slash) = &mut self.notes.blocks.slash {
423
5
            let count = matching(&slash.query).count();
424
5
            slash.selected = if down {
425
2
                (slash.selected + 1) % count
426
            } else {
427
3
                (slash.selected + count - 1) % count
428
            };
429
5
            cx.notify();
430
5
            return;
431
0
        }
432
0
        if down {
433
0
            window.dispatch_action(Box::new(gpui_component::input::MoveDown), cx);
434
        } else {
435
0
            window.dispatch_action(Box::new(gpui_component::input::MoveUp), cx);
436
        }
437
5
    }
438
439
    /// Applies Write's formatting to the block being edited.
440
4
    pub(in crate::ui) fn format_note_block(
441
4
        &mut self,
442
4
        format: NoteFormat,
443
4
        window: &mut gpui::Window,
444
4
        cx: &mut gpui::Context<Self>,
445
4
    ) {
446
4
        let Some(active) = &self.notes.blocks.active else {
447
1
            return;
448
        };
449
3
        active.input.update(cx, |input, cx| {
450
3
            if let Some(edit) = format_edit(format, &input.value(), input.selected_range()) {
451
3
                input.set_selected_range(edit.range, cx);
452
3
                input.replace(edit.text, window, cx);
453
3
                input.set_selected_range(edit.select, cx);
454
0
            }
455
3
            input.focus(window, cx);
456
3
        });
457
3
        self.write_note_block(window, cx);
458
4
    }
459
460
    /// Replaces `range` of the draft with `text` if it still holds `expected`; otherwise
461
    /// closes the block, so a change made elsewhere is never overwritten.
462
74
    fn replace_in_draft(
463
74
        &mut self,
464
74
        range: Range<usize>,
465
74
        expected: &str,
466
74
        text: &str,
467
74
        window: &mut gpui::Window,
468
74
        cx: &mut gpui::Context<Self>,
469
74
    ) -> bool {
470
74
        let Some(editor) = self
471
74
            .notes
472
74
            .editor
473
74
            .as_ref()
474
74
            .filter(|editor| editor.conflict.is_none())
475
        else {
476
0
            self.stop_note_block("The note can no longer be edited here.", cx);
477
0
            return false;
478
        };
479
74
        if editor.source.read(cx).value().get(range.clone()) != Some(expected) {
480
1
            self.stop_note_block("The note changed elsewhere, so this block was closed.", cx);
481
1
            return false;
482
73
        }
483
73
        let end = range.start + text.len();
484
73
        editor.source.update(cx, |source, cx| {
485
73
            source.set_selected_range(range, cx);
486
73
            source.replace(text.to_owned(), window, cx);
487
73
            source.set_selected_range(end..end, cx);
488
73
        });
489
73
        true
490
74
    }
491
492
    /// Enter in a block, as in Notion: splits it at the caret into a new block below (the
493
    /// next list item in lists), ends a list on an empty item, opens a block above at the
494
    /// very start, and breaks the line inside code. Shift+Enter always breaks the line.
495
9
    pub(in crate::ui) fn note_block_enter(
496
9
        &mut self,
497
9
        window: &mut gpui::Window,
498
9
        cx: &mut gpui::Context<Self>,
499
9
    ) {
500
9
        if let Some(slash) = &self.notes.blocks.slash {
501
2
            let index = slash.selected;
502
2
            self.choose_block_slash(index, window, cx);
503
2
            return;
504
7
        }
505
7
        let Some(active) = &self.notes.blocks.active else {
506
0
            return;
507
        };
508
7
        let input = active.input.clone();
509
7
        let typed = input.read(cx).value().to_string();
510
7
        let selection = input.read(cx).selected_range();
511
7
        let pending = active.index.is_none();
512
7
        let content_start = active.start + if pending { 
active.before.len()4
} else {
03
};
513
7
        match block_enter(&typed, selection) {
514
1
            BlockEnter::LineBreak => window.dispatch_action(
515
1
                Box::new(gpui_component::input::Enter {
516
1
                    secondary: false,
517
1
                    shift: true,
518
1
                }),
519
1
                cx,
520
1
            ),
521
1
            BlockEnter::EndList => set_block_text(&input, "", 0, window, cx),
522
            BlockEnter::Above => {
523
0
                self.finish_note_block(cx);
524
0
                self.refresh_note_blocks(cx);
525
0
                self.begin_note_block(
526
0
                    None,
527
0
                    content_start,
528
0
                    "",
529
0
                    "\n\n",
530
0
                    String::new(),
531
0
                    0,
532
0
                    window,
533
0
                    cx,
534
0
                );
535
            }
536
            // An empty new block has nothing to split; it stays open.
537
5
            BlockEnter::Split { .. } if pending && 
typed.is_empty()2
=>
{}0
538
            BlockEnter::Split {
539
                current,
540
                next,
541
                caret,
542
                separator,
543
            } => {
544
5
                let end = current.len();
545
5
                set_block_text(&input, &current, end, window, cx);
546
                // The field reports its change later; the draft must have it before the
547
                // next block opens.
548
5
                self.write_note_block(window, cx);
549
5
                let Some(active) = &self.notes.blocks.active else {
550
0
                    return;
551
                };
552
5
                let after = if pending && 
!active.written.is_empty()2
{
553
2
                    active.after.len()
554
                } else {
555
3
                    0
556
                };
557
5
                let insertion = active.start + active.written.len() - after;
558
5
                self.finish_note_block(cx);
559
5
                self.refresh_note_blocks(cx);
560
5
                self.begin_note_block(None, insertion, separator, "", next, caret, window, cx);
561
            }
562
        }
563
9
    }
564
565
    /// Backspace at the start of an empty block removes it and continues at the end of the
566
    /// block before; anywhere else it deletes as usual.
567
3
    pub(in crate::ui) fn note_block_backspace(
568
3
        &mut self,
569
3
        window: &mut gpui::Window,
570
3
        cx: &mut gpui::Context<Self>,
571
3
    ) {
572
3
        let Some(active) = &self.notes.blocks.active else {
573
0
            return;
574
        };
575
3
        let input = active.input.read(cx);
576
3
        if !input.value().is_empty() || 
!input.selected_range().is_empty()2
{
577
1
            window.dispatch_action(Box::new(gpui_component::input::Backspace), cx);
578
1
            return;
579
2
        }
580
        let (start, pending, written) =
581
2
            (active.start, active.index.is_none(), active.written.clone());
582
2
        if !pending {
583
            // The block is empty in the draft; drop the blank lines that separated it.
584
1
            let Some(source) = self.draft_text(cx) else {
585
0
                return;
586
            };
587
1
            let gap = source[..start].len() - source[..start].trim_end().len();
588
1
            let range = start - gap..start + written.len();
589
1
            let expected = source[range.clone()].to_owned();
590
1
            if !self.replace_in_draft(range, &expected, "", window, cx) {
591
0
                return;
592
1
            }
593
1
        }
594
2
        self.finish_note_block(cx);
595
2
        self.refresh_note_blocks(cx);
596
2
        let previous = self
597
2
            .shown_blocks()
598
2
            .iter()
599
2
            .rposition(|block| block.block.range.end <= start);
600
2
        if let Some(previous) = previous {
601
2
            self.edit_note_block(Some(previous), None, window, cx);
602
0
        }
603
3
    }
604
605
1
    fn stop_note_block(&mut self, message: &'static str, cx: &mut gpui::Context<Self>) {
606
1
        self.notes.blocks.active = None;
607
1
        self.notes.blocks.message = Some(message);
608
1
        cx.notify();
609
1
    }
610
611
    /// Stops editing the current block; its text is already in the draft.
612
326
    pub(in crate::ui) fn finish_note_block(&mut self, cx: &mut gpui::Context<Self>) {
613
326
        self.notes.blocks.slash = None;
614
326
        if self.notes.blocks.active.take().is_some() {
615
14
            cx.notify();
616
312
        }
617
326
    }
618
619
    /// Checks or unchecks a task item without opening it.
620
1
    fn toggle_note_block_task(
621
1
        &mut self,
622
1
        index: usize,
623
1
        window: &mut gpui::Window,
624
1
        cx: &mut gpui::Context<Self>,
625
1
    ) {
626
1
        self.finish_note_block(cx);
627
1
        self.refresh_note_blocks(cx);
628
1
        if !self.can_edit_blocks() {
629
0
            return;
630
1
        }
631
1
        let Some(start) = self
632
1
            .notes
633
1
            .blocks
634
1
            .shown
635
1
            .as_ref()
636
1
            .and_then(|shown| shown.blocks.as_ref())
637
1
            .and_then(|blocks| blocks.get(index))
638
1
            .map(|block| block.block.range.start)
639
        else {
640
0
            return;
641
        };
642
1
        let Some(editor) = &self.notes.editor else {
643
0
            return;
644
        };
645
1
        editor.source.update(cx, |source, cx| {
646
1
            if let KeyOutcome::Edit(edit) = toggle_tasks(&source.value(), start..start) {
647
1
                apply_markdown_edit(source, edit, window, cx);
648
0
            }
649
1
        });
650
1
        cx.notify();
651
1
    }
652
653
144
    pub(in crate::ui) fn notes_blocks_view(&self, cx: &mut gpui::Context<Self>) -> AnyElement {
654
144
        let root = div()
655
144
            .id("notes-blocks")
656
144
            .debug_selector(|| "notes-blocks".into())
657
            .flex()
658
            .flex_col()
659
            .items_center()
660
            .px_4()
661
            .flex_1()
662
            .min_h_0()
663
            .overflow_y_scroll()
664
            // A click beside the blocks ends editing.
665
144
            .on_click(cx.listener(|this, _, _, cx| 
this0
.finish_note_block(
cx0
)));
666
        // The note sits on its own page, set apart from the app around it.
667
144
        let column = div()
668
144
            .debug_selector(|| "notes-blocks-column".into())
669
            .w_full()
670
144
            .max_w(px(COLUMN_WIDTH))
671
            .flex_shrink_0()
672
            .flex()
673
            .flex_col()
674
            .gap_1()
675
            .my_4()
676
            .px_10()
677
            .py_8()
678
            .rounded_lg()
679
            .border_1()
680
144
            .border_color(rgb(t().line))
681
144
            .bg(rgb(t().card))
682
            .shadow_sm();
683
144
        root.child(self.blocks_column(column, cx))
684
144
            .into_any_element()
685
144
    }
686
687
    /// The blocks of the open draft, the block being edited, and the click area below them
688
    /// that starts a new block, in `column`.
689
167
    fn blocks_column(&self, column: gpui::Div, cx: &mut gpui::Context<Self>) -> gpui::Div {
690
167
        let Some(editor) = &self.notes.editor else {
691
0
            return column.child(
692
0
                div()
693
0
                    .text_color(rgb(t().muted))
694
0
                    .child("Open a note from Browse, or create one with New Note."),
695
0
            );
696
        };
697
167
        let mut column = column.when_some(self.notes.blocks.message, |this, message| 
{1
698
1
            this.child(
699
1
                div()
700
1
                    .debug_selector(|| "notes-blocks-message".into())
701
                    .text_sm()
702
1
                    .text_color(rgb(t().warning))
703
                    .pb_2()
704
1
                    .child(message),
705
            )
706
1
        });
707
167
        if editor.conflict.is_some() {
708
0
            column =
709
0
                column.child(
710
0
                    div().text_sm().text_color(rgb(t().warning)).pb_2().child(
711
0
                        "This note changed on disk. Resolve it in Edit before editing blocks.",
712
0
                    ),
713
0
                );
714
167
        }
715
167
        let Some(shown) = &self.notes.blocks.shown else {
716
0
            return column;
717
        };
718
167
        let Some(blocks) = &shown.blocks else {
719
0
            return column.child(
720
0
                div()
721
0
                    .text_color(rgb(t().muted))
722
0
                    .child("This note is too large for the block editor; edit it in Edit."),
723
0
            );
724
        };
725
167
        let active = self.notes.blocks.active.as_ref();
726
167
        let slash = self.notes.blocks.slash.as_ref();
727
        // A new block shows where it goes in the note: before the first block after it.
728
167
        let mut pending = active.filter(|active| 
active.index111
.is_none());
729
167
        for (index, block) in blocks.iter().enumerate() {
730
270
            if let Some(new) = pending.filter(|new| 
block.block.range.start91
>=
new.start91
) {
731
12
                column = column.child(block_editor(new, slash, cx));
732
12
                pending = None;
733
258
            }
734
270
            if let Some(active) = active.filter(|active| 
active.index174
==
Some(index)174
) {
735
48
                column = column.child(block_editor(active, slash, cx));
736
            } else {
737
222
                column = column.child(self.shown_block(index, block, cx));
738
            }
739
        }
740
167
        match pending {
741
51
            Some(new) => column = column.child(block_editor(new, slash, cx)),
742
116
            None if active.is_some_and(|active| 
active.index60
.is_none()) =>
{}12
743
            None => {
744
                // No add button: clicking the empty line below the last block starts a new
745
                // block there, as Enter at the end of the last block does.
746
104
                let empty = blocks.is_empty();
747
104
                let editable = self.can_edit_blocks();
748
104
                column = column.child(
749
104
                    div()
750
104
                        .id("notes-blocks-add")
751
104
                        .debug_selector(|| "notes-blocks-add".into())
752
104
                        .min_h(px(48.))
753
                        .pt_1()
754
104
                        .text_color(rgb(t().muted))
755
104
                        .when(editable, |this| {
756
104
                            this.cursor_text()
757
104
                                .on_click(cx.listener(|this, _, window, cx| 
{2
758
2
                                    cx.stop_propagation();
759
2
                                    this.edit_note_block(None, None, window, cx)
760
2
                                }))
761
104
                        })
762
104
                        .when(empty, |this| 
{0
763
0
                            this.child("Empty note. Click to start writing")
764
0
                        }),
765
                );
766
            }
767
        }
768
167
        column
769
167
    }
770
771
1.17k
    fn shown_block(
772
1.17k
        &self,
773
1.17k
        index: usize,
774
1.17k
        shown: &ShownBlock,
775
1.17k
        cx: &mut gpui::Context<Self>,
776
1.17k
    ) -> AnyElement {
777
1.17k
        let id = SharedString::from(format!("note-block-{index}"));
778
1.17k
        let selector = id.clone();
779
1.17k
        let content: AnyElement = match shown.block.kind {
780
0
            BlockKind::FrontMatter => div()
781
0
                .flex()
782
0
                .flex_col()
783
0
                .gap_1()
784
0
                .child(section_label("FRONT MATTER"))
785
0
                .child(
786
0
                    div()
787
0
                        .text_xs()
788
0
                        .text_color(rgb(t().muted))
789
0
                        .child(shown.text.clone()),
790
0
                )
791
0
                .into_any_element(),
792
            BlockKind::ListItem {
793
                checked: Some(checked),
794
                ..
795
            } => {
796
30
                let check = SharedString::from(format!("note-block-check-{index}"));
797
30
                div()
798
30
                    .flex()
799
30
                    .items_start()
800
30
                    .gap_2()
801
                    .child(
802
30
                        div()
803
30
                            .id(check.clone())
804
30
                            .debug_selector(move || check.to_string())
805
30
                            .mt(px(5.))
806
30
                            .size(px(16.))
807
                            .flex_shrink_0()
808
                            .flex()
809
                            .items_center()
810
                            .justify_center()
811
                            .rounded_sm()
812
                            .border_1()
813
30
                            .border_color(rgb(if checked { 
t().accent17
} else {
t().muted13
}))
814
30
                            .when(checked, |this| 
{17
815
17
                                this.bg(rgb(t().accent)).child(
816
17
                                    Icon::new(IconName::Check)
817
17
                                        .size_3()
818
17
                                        .text_color(rgb(t().on_accent)),
819
17
                                )
820
17
                            })
821
                            .cursor_pointer()
822
30
                            .on_click(cx.listener(move |this, _, window, cx| 
{2
823
2
                                cx.stop_propagation();
824
                                // A Browse preview not yet open edits instead, so it never
825
                                // toggles another note's draft.
826
2
                                if this.view == crate::ui::View::NotesBrowse
827
1
                                    && !this.editor_holds_selected_note()
828
                                {
829
1
                                    this.click_note_block(index, window, cx)
830
                                } else {
831
1
                                    this.toggle_note_block_task(index, window, cx)
832
                                }
833
2
                            })),
834
                    )
835
                    .child(
836
30
                        div()
837
30
                            .flex_1()
838
30
                            .min_w_0()
839
30
                            .when(checked, |this| 
{17
840
17
                                this.text_color(rgb(t().muted)).line_through()
841
17
                            })
842
30
                            .child(self.block_preview(index, id.clone(), shown, cx)),
843
                    )
844
                    .into_any_element()
845
            }
846
1.14k
            _ => self.block_preview(index, id.clone(), shown, cx),
847
        };
848
1.17k
        div()
849
1.17k
            .id(id)
850
1.17k
            .debug_selector(move || selector.to_string())
851
1.17k
            .text_size(px(BLOCK_TEXT))
852
1.17k
            .line_height(gpui::relative(BLOCK_LINE))
853
1.17k
            .px(px(BLOCK_PAD_X))
854
            .py_0p5()
855
            .rounded_md()
856
            .cursor_text()
857
1.17k
            .hover(|style| style.bg(rgb(t().paper)))
858
1.17k
            .on_click(cx.listener(move |this, _, window, cx| 
{11
859
11
                cx.stop_propagation();
860
11
                this.click_note_block(index, window, cx)
861
11
            }))
862
1.17k
            .child(content)
863
            .into_any_element()
864
1.17k
    }
865
866
    /// A block drawn formatted. Its links are blue and open in the browser with Ctrl (or
867
    /// Cmd) held; a plain click on one edits the block like a click anywhere else in it.
868
1.17k
    fn block_preview(
869
1.17k
        &self,
870
1.17k
        index: usize,
871
1.17k
        id: SharedString,
872
1.17k
        shown: &ShownBlock,
873
1.17k
        cx: &mut gpui::Context<Self>,
874
1.17k
    ) -> AnyElement {
875
1.17k
        match &shown.preview {
876
            Ok(preview) => {
877
1.17k
                let workspace = cx.entity().downgrade();
878
1.17k
                self.markdown_preview(id, preview, cx)
879
2
                    .on_link_click(move |url, event, window, cx| {
880
2
                        cx.stop_propagation();
881
2
                        let modifiers = event.modifiers();
882
2
                        if modifiers.control || 
modifiers.platform1
{
883
1
                            if let Some(url) = safe_link_url(url) {
884
1
                                cx.open_url(url);
885
0
                            }
886
                        } else {
887
1
                            let _ = workspace
888
1
                                .update(cx, |this, cx| this.click_note_block(index, window, cx));
889
                        }
890
2
                    })
891
1
                    .link_tooltip(|url, window, cx| {
892
1
                        let open = if cfg!(target_os = "macos") {
893
0
                            "Cmd"
894
                        } else {
895
1
                            "Ctrl"
896
                        };
897
1
                        gpui_component::tooltip::Tooltip::new(format!(
898
1
                            "{url}\n{open}+click to open"
899
1
                        ))
900
1
                        .build(window, cx)
901
1
                    })
902
                    .into_any_element()
903
            }
904
0
            Err(_) => div().child(shown.text.clone()).into_any_element(),
905
        }
906
1.17k
    }
907
}
908
909
111
fn block_editor(
910
111
    active: &ActiveBlock,
911
111
    slash: Option<&BlockSlash>,
912
111
    cx: &mut gpui::Context<Workspace>,
913
111
) -> AnyElement {
914
    let format =
915
666
        |id: &'static str, icon: &'static str, tooltip: &'static str, format: NoteFormat| {
916
666
            div().debug_selector(move || id.into()).child(
917
666
                Button::new(id)
918
666
                    .icon(Icon::default().path(icon))
919
666
                    .ghost()
920
666
                    .xsmall()
921
666
                    .tooltip(tooltip)
922
666
                    .on_click(cx.listener(move |this, _, window, cx| 
{2
923
2
                        cx.stop_propagation();
924
2
                        this.format_note_block(format, window, cx)
925
2
                    })),
926
            )
927
666
        };
928
111
    let separator = || div().w(px(1.)).h(px(14.)).mx_0p5().bg(rgb(t().line));
929
    // Formatting for the block, as in Write's toolbar.
930
    // It floats above the block, so opening the block does not move its text.
931
111
    let toolbar = div()
932
111
        .debug_selector(|| "note-block-toolbar".into())
933
        .absolute()
934
111
        .top(px(-30.))
935
111
        .left(px(BLOCK_PAD_X - 2.))
936
        .flex()
937
        .items_center()
938
        .p_0p5()
939
        .rounded_md()
940
        .border_1()
941
111
        .border_color(rgb(t().line))
942
111
        .bg(rgb(t().card))
943
        .shadow_sm()
944
111
        .child(format(
945
111
            "note-block-bold",
946
111
            "icons/bold.svg",
947
111
            "Bold",
948
111
            NoteFormat::Bold,
949
111
        ))
950
111
        .child(format(
951
111
            "note-block-italic",
952
111
            "icons/italic.svg",
953
111
            "Italic",
954
111
            NoteFormat::Italic,
955
111
        ))
956
111
        .child(format(
957
111
            "note-block-code",
958
111
            "icons/code.svg",
959
111
            "Inline code",
960
111
            NoteFormat::Code,
961
111
        ))
962
111
        .child(format(
963
111
            "note-block-link",
964
111
            "icons/link.svg",
965
111
            "Link",
966
111
            NoteFormat::Link,
967
111
        ))
968
111
        .child(separator())
969
111
        .child(format(
970
111
            "note-block-quote",
971
111
            "icons/text-quote.svg",
972
111
            "Quote",
973
111
            NoteFormat::Quote,
974
111
        ))
975
111
        .child(format(
976
111
            "note-block-code-block",
977
111
            "icons/square-code.svg",
978
111
            "Code block",
979
111
            NoteFormat::CodeBlock,
980
111
        ));
981
    // The field looks like the drawn block: same insets, text size, and line height, and a
982
    // heading keeps its size and weight while its `#` markers show.
983
111
    let heading = heading_level(&active.input.read(cx).value());
984
111
    let (text_size, line_height) = heading.map_or((BLOCK_TEXT, BLOCK_LINE), heading_text);
985
111
    let field = div()
986
111
        .debug_selector(|| "note-block-field".into())
987
111
        .px(px(BLOCK_PAD_X - FIELD_PAD_X))
988
        .py_0p5()
989
        .rounded_md()
990
111
        .bg(rgb(t().paper))
991
        .child(
992
111
            Textarea::new(&active.input)
993
111
                .xsmall()
994
111
                .appearance(false)
995
111
                .text_size(px(text_size))
996
111
                .line_height(gpui::relative(line_height))
997
111
                .when(heading.is_some(), |this| 
{7
998
7
                    this.font_weight(gpui::FontWeight::SEMIBOLD)
999
7
                }),
1000
        );
1001
111
    div()
1002
111
        .id("note-block-editor")
1003
111
        .debug_selector(|| "note-block-editor".into())
1004
        .relative()
1005
        .flex()
1006
        .flex_col()
1007
        .gap_1()
1008
0
        .on_click(|_, _, cx| cx.stop_propagation())
1009
        // Escape closes the "/" menu, or ends editing, keeping what was typed.
1010
111
        .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, _, cx| 
{65
1011
65
            if event.keystroke.key == "escape" {
1012
5
                if this.notes.blocks.slash.take().is_none() {
1013
4
                    this.finish_note_block(cx);
1014
1
                }
1015
5
                cx.notify();
1016
60
            }
1017
65
        }))
1018
111
        .key_context("NoteBlock")
1019
        .on_action(
1020
111
            cx.listener(|this, _: &crate::ui::NoteBlockEnter, window, cx| 
{9
1021
9
                this.note_block_enter(window, cx)
1022
9
            }),
1023
        )
1024
        .on_action(
1025
111
            cx.listener(|this, _: &crate::ui::NoteBlockBackspace, window, cx| 
{3
1026
3
                this.note_block_backspace(window, cx)
1027
3
            }),
1028
        )
1029
111
        .on_action(cx.listener(|this, _: &crate::ui::NoteBlockUp, window, cx| 
{3
1030
3
            this.note_block_arrow(false, window, cx)
1031
3
        }))
1032
        .on_action(
1033
111
            cx.listener(|this, _: &crate::ui::NoteBlockDown, window, cx| 
{2
1034
2
                this.note_block_arrow(true, window, cx)
1035
2
            }),
1036
        )
1037
111
        .child(field)
1038
111
        .child(toolbar)
1039
111
        .when_some(slash, |this, slash| 
{12
1040
12
            this.child(
1041
12
                div()
1042
12
                    .debug_selector(|| "block-slash-menu".into())
1043
                    .flex()
1044
                    .flex_col()
1045
                    .self_start()
1046
12
                    .w(px(280.))
1047
                    .p_1()
1048
                    .rounded_md()
1049
                    .border_1()
1050
12
                    .border_color(rgb(t().line))
1051
12
                    .bg(rgb(t().card))
1052
                    .shadow_md()
1053
75
                    .children(
matching(&slash.query).enumerate()12
.map(|(index, command)| {
1054
75
                        let selected = index == slash.selected;
1055
75
                        let id = SharedString::from(format!("block-slash-item-{index}"));
1056
75
                        let selector = id.clone();
1057
75
                        div()
1058
75
                            .id(id)
1059
75
                            .debug_selector(move || selector.to_string())
1060
                            .flex()
1061
                            .flex_col()
1062
                            .px_2()
1063
                            .py_1()
1064
                            .rounded_sm()
1065
                            .cursor_pointer()
1066
75
                            .when(selected, |this| 
this12
.bg(
rgb(t().accent_soft)12
))
1067
75
                            .hover(|style| style.bg(rgb(t().accent_soft)))
1068
75
                            .on_click(cx.listener(move |this, _, window, cx| 
{0
1069
0
                                cx.stop_propagation();
1070
0
                                this.choose_block_slash(index, window, cx)
1071
0
                            }))
1072
75
                            .child(div().text_sm().child(command.label))
1073
                            .child(
1074
75
                                div()
1075
75
                                    .text_xs()
1076
75
                                    .text_color(rgb(t().muted))
1077
75
                                    .child(command.detail),
1078
                            )
1079
75
                    })),
1080
            )
1081
12
        })
1082
        .into_any_element()
1083
111
}
1084
1085
#[cfg(all(test, feature = "ui-tests"))]
1086
mod tests {
1087
    use super::*;
1088
    use crate::ui::{View, tests::setup_with_settings};
1089
    use productivity::core::settings::DisplaySettings;
1090
1091
10
    fn open_blocks<'a>(
1092
10
        cx: &'a mut gpui::TestAppContext,
1093
10
        text: &str,
1094
10
    ) -> (
1095
10
        tempfile::TempDir,
1096
10
        Entity<Workspace>,
1097
10
        Entity<gpui_component::input::EditorState>,
1098
10
        &'a mut gpui::VisualTestContext,
1099
10
    ) {
1100
10
        let settings = DisplaySettings {
1101
10
            notes_visible: true,
1102
10
            ..Default::default()
1103
10
        };
1104
10
        let (directory, workspace, cx) = setup_with_settings(cx, vec![], settings);
1105
10
        let source = cx.update(|window, cx| {
1106
10
            workspace.update(cx, |state, cx| {
1107
10
                state.new_note_draft(window, cx);
1108
10
                let source = state.notes.editor.as_ref().unwrap().source.clone();
1109
10
                source.update(cx, |input, cx| input.replace(text, window, cx));
1110
10
                state.set_notes_mode(super::super::NotesMode::Blocks, window, cx);
1111
10
                source
1112
10
            })
1113
10
        });
1114
10
        cx.run_until_parked();
1115
10
        (directory, workspace, source, cx)
1116
10
    }
1117
1118
15
    fn click(cx: &mut gpui::VisualTestContext, selector: &str) {
1119
15
        let selector: &'static str = Box::leak(selector.to_owned().into_boxed_str());
1120
15
        let bounds = cx.debug_bounds(selector).unwrap();
1121
15
        cx.simulate_click(bounds.center(), gpui::Modifiers::default());
1122
15
        cx.run_until_parked();
1123
15
    }
1124
1125
8
    fn type_in_block(workspace: &Entity<Workspace>, text: &str, cx: &mut gpui::VisualTestContext) {
1126
8
        cx.update(|window, cx| {
1127
8
            let input = workspace
1128
8
                .read(cx)
1129
8
                .notes
1130
8
                .blocks
1131
8
                .active
1132
8
                .as_ref()
1133
8
                .unwrap()
1134
8
                .input
1135
8
                .clone();
1136
8
            input.update(cx, |input, cx| {
1137
8
                let end = input.value().len();
1138
8
                input.set_selected_range(0..end, cx);
1139
8
                input.replace(text, window, cx);
1140
8
            });
1141
8
        });
1142
8
        cx.run_until_parked();
1143
8
    }
1144
1145
    #[gpui::test]
1146
1
    fn editing_a_block_rewrites_only_its_range_in_the_draft(cx: &mut gpui::TestAppContext) {
1147
1
        let text = "# Plan\n\nFirst   paragraph\n\n\n- one\n- two\n";
1148
1
        let (_directory, workspace, source, cx) = open_blocks(cx, text);
1149
1
        for index in 0..4 {
1150
4
            assert!(
1151
4
                cx.debug_bounds(Box::leak(format!("note-block-{index}").into_boxed_str()))
1152
4
                    .is_some()
1153
            );
1154
        }
1155
1
        assert!(cx.debug_bounds("note-block-editor").is_none());
1156
1
        click(cx, "note-block-1");
1157
1
        assert!(cx.debug_bounds("note-block-editor").is_some());
1158
1
        cx.update(|_, cx| {
1159
1
            let state = workspace.read(cx);
1160
1
            let active = state.notes.blocks.active.as_ref().unwrap();
1161
1
            assert_eq!(active.input.read(cx).value(), "First   paragraph");
1162
1
        });
1163
1
        type_in_block(&workspace, "Second **draft**", cx);
1164
        // Every change is in the draft at once; the blank lines and other blocks are kept.
1165
1
        let expected = "# Plan\n\nSecond **draft**\n\n\n- one\n- two\n";
1166
1
        cx.update(|_, cx| {
1167
1
            assert_eq!(source.read(cx).value(), expected);
1168
1
            assert!(workspace.read(cx).notes.editor.as_ref().unwrap().dirty(cx));
1169
1
        });
1170
1
        type_in_block(&workspace, "Third", cx);
1171
1
        cx.update(|_, cx| {
1172
1
            assert_eq!(
1173
1
                source.read(cx).value(),
1174
1
                "# Plan\n\nThird\n\n\n- one\n- two\n"
1175
            )
1176
1
        });
1177
        // Escape ends editing and shows the block formatted again.
1178
1
        cx.simulate_keystrokes("escape");
1179
1
        cx.run_until_parked();
1180
1
        assert!(cx.debug_bounds("note-block-editor").is_none());
1181
1
        cx.update(|_, cx| assert!(workspace.read(cx).notes.blocks.active.is_none()));
1182
        // The draft is Write's: the same text is there.
1183
1
        cx.update(|window, cx| {
1184
1
            workspace.update(cx, |state, cx| {
1185
1
                state.switch_view(View::NotesWrite, window, cx)
1186
1
            })
1187
1
        });
1188
1
        cx.run_until_parked();
1189
1
        cx.update(|_, cx| {
1190
1
            assert_eq!(
1191
1
                source.read(cx).value(),
1192
1
                "# Plan\n\nThird\n\n\n- one\n- two\n"
1193
            )
1194
1
        });
1195
1
    }
1196
1197
    #[gpui::test]
1198
1
    fn checkboxes_toggle_and_new_blocks_append_after_a_blank_line(cx: &mut gpui::TestAppContext) {
1199
1
        let (_directory, workspace, source, cx) = open_blocks(cx, "- [ ] call\nText");
1200
1
        click(cx, "note-block-check-0");
1201
1
        cx.update(|_, cx| {
1202
1
            assert_eq!(source.read(cx).value(), "- [x] call\nText");
1203
1
            assert!(workspace.read(cx).notes.blocks.active.is_none());
1204
1
        });
1205
1
        click(cx, "notes-blocks-add");
1206
        // Nothing is added until something is typed.
1207
1
        cx.update(|_, cx| assert_eq!(source.read(cx).value(), "- [x] call\nText"));
1208
1
        type_in_block(&workspace, "## Next", cx);
1209
1
        cx.update(|_, cx| assert_eq!(source.read(cx).value(), "- [x] call\nText\n\n## Next"));
1210
1
        type_in_block(&workspace, "", cx);
1211
1
        cx.update(|_, cx| assert_eq!(source.read(cx).value(), "- [x] call\nText"));
1212
1
    }
1213
1214
    #[gpui::test]
1215
1
    fn a_block_changed_elsewhere_is_closed_instead_of_overwritten(cx: &mut gpui::TestAppContext) {
1216
1
        let (_directory, workspace, source, cx) = open_blocks(cx, "One\n\nTwo\n");
1217
1
        click(cx, "note-block-1");
1218
1
        cx.update(|window, cx| {
1219
1
            source.update(cx, |input, cx| {
1220
1
                input.set_selected_range(5..8, cx);
1221
1
                input.replace("Changed", window, cx);
1222
1
            })
1223
1
        });
1224
1
        type_in_block(&workspace, "Mine", cx);
1225
1
        cx.update(|_, cx| {
1226
1
            assert_eq!(source.read(cx).value(), "One\n\nChanged\n");
1227
1
            let blocks = &workspace.read(cx).notes.blocks;
1228
1
            assert!(blocks.active.is_none());
1229
1
            assert!(blocks.message.is_some());
1230
1
        });
1231
1
        assert!(cx.debug_bounds("notes-blocks-message").is_some());
1232
1
    }
1233
1234
    #[gpui::test]
1235
1
    fn blocks_is_a_layout_of_edit_and_leaving_it_ends_editing(cx: &mut gpui::TestAppContext) {
1236
1
        let (_directory, workspace, _source, cx) = open_blocks(cx, "One\n");
1237
1
        cx.update(|_, cx| assert!(workspace.read(cx).view == View::NotesWrite));
1238
        // Blocks sits after Live Edit in the layout switcher.
1239
1
        let live = cx.debug_bounds("notes-mode-live").unwrap();
1240
1
        let blocks = cx.debug_bounds("notes-mode-blocks").unwrap();
1241
1
        assert!(blocks.left() >= live.right());
1242
1
        assert!(cx.debug_bounds("notes-markdown-source").is_none());
1243
1
        assert!(cx.debug_bounds("note-format-toolbar").is_none());
1244
1
        click(cx, "note-block-0");
1245
1
        click(cx, "notes-mode-live");
1246
1
        cx.update(|_, cx| {
1247
1
            let state = workspace.read(cx);
1248
1
            assert!(state.notes.blocks.active.is_none());
1249
1
            assert_eq!(state.notes.mode, super::super::NotesMode::Live);
1250
1
        });
1251
1
        assert!(cx.debug_bounds("notes-blocks").is_none());
1252
1
    }
1253
1254
13
    fn active_text(workspace: &Entity<Workspace>, cx: &mut gpui::VisualTestContext) -> String {
1255
13
        cx.update(|_, cx| {
1256
13
            let state = workspace.read(cx);
1257
13
            let active = state.notes.blocks.active.as_ref().unwrap();
1258
13
            active.input.read(cx).value().to_string()
1259
13
        })
1260
13
    }
1261
1262
1
    fn caret_at(workspace: &Entity<Workspace>, offset: usize, cx: &mut gpui::VisualTestContext) {
1263
1
        cx.update(|_, cx| {
1264
1
            let input = workspace
1265
1
                .read(cx)
1266
1
                .notes
1267
1
                .blocks
1268
1
                .active
1269
1
                .as_ref()
1270
1
                .unwrap()
1271
1
                .input
1272
1
                .clone();
1273
1
            input.update(cx, |input, cx| input.set_selected_range(offset..offset, cx));
1274
1
        });
1275
1
    }
1276
1277
    #[gpui::test]
1278
1
    fn enter_starts_the_next_block_and_shift_enter_breaks_the_line(cx: &mut gpui::TestAppContext) {
1279
1
        let (_directory, workspace, source, cx) = open_blocks(cx, "Hello world\n\nEnd\n");
1280
1
        click(cx, "note-block-0");
1281
        // Enter at the end opens an empty block below; typing fills it in the draft.
1282
1
        cx.simulate_keystrokes("enter");
1283
1
        cx.run_until_parked();
1284
1
        assert_eq!(active_text(&workspace, cx), "");
1285
1
        cx.update(|_, cx| assert_eq!(source.read(cx).value(), "Hello world\n\nEnd\n"));
1286
1
        cx.simulate_input("Next");
1287
1
        cx.run_until_parked();
1288
1
        cx.update(|_, cx| assert_eq!(source.read(cx).value(), "Hello world\n\nNext\n\nEnd\n"));
1289
        // The new block is drawn between the two it sits between.
1290
1
        let first = cx.debug_bounds("note-block-0").unwrap();
1291
1
        let editor = cx.debug_bounds("note-block-editor").unwrap();
1292
1
        let end = cx.debug_bounds("note-block-1").unwrap();
1293
1
        assert!(first.bottom() <= editor.top() && editor.bottom() <= end.top());
1294
        // Enter inside the text splits the block at the caret.
1295
1
        caret_at(&workspace, 2, cx);
1296
1
        cx.simulate_keystrokes("enter");
1297
1
        cx.run_until_parked();
1298
1
        assert_eq!(active_text(&workspace, cx), "xt");
1299
1
        cx.update(|_, cx| assert_eq!(source.read(cx).value(), "Hello world\n\nNe\n\nxt\n\nEnd\n"));
1300
        // Shift+Enter is a line break inside the block.
1301
1
        cx.simulate_keystrokes("shift-enter");
1302
1
        cx.simulate_input("more");
1303
1
        cx.run_until_parked();
1304
1
        assert_eq!(active_text(&workspace, cx), "\nmorext");
1305
1
    }
1306
1307
    #[gpui::test]
1308
1
    fn enter_continues_and_ends_lists_and_backspace_removes_empty_blocks(
1309
1
        cx: &mut gpui::TestAppContext,
1310
1
    ) {
1311
1
        let (_directory, workspace, source, cx) = open_blocks(cx, "- [x] one\n");
1312
1
        click(cx, "note-block-0");
1313
1
        cx.simulate_keystrokes("enter");
1314
1
        cx.run_until_parked();
1315
1
        assert_eq!(active_text(&workspace, cx), "- [ ] ");
1316
1
        cx.simulate_input("two");
1317
1
        cx.run_until_parked();
1318
1
        cx.update(|_, cx| assert_eq!(source.read(cx).value(), "- [x] one\n- [ ] two\n"));
1319
1
        cx.simulate_keystrokes("enter");
1320
1
        cx.run_until_parked();
1321
        // Enter on the empty item ends the list; Backspace then removes the empty block.
1322
1
        cx.simulate_keystrokes("enter");
1323
1
        cx.run_until_parked();
1324
1
        assert_eq!(active_text(&workspace, cx), "");
1325
1
        cx.update(|_, cx| assert_eq!(source.read(cx).value(), "- [x] one\n- [ ] two\n"));
1326
1
        cx.simulate_keystrokes("backspace");
1327
1
        cx.run_until_parked();
1328
1
        assert_eq!(active_text(&workspace, cx), "- [ ] two");
1329
        // Backspace in text deletes as usual.
1330
1
        cx.simulate_keystrokes("backspace");
1331
1
        cx.run_until_parked();
1332
1
        assert_eq!(active_text(&workspace, cx), "- [ ] tw");
1333
        // Emptying an existing block and pressing Backspace removes it and its gap.
1334
1
        cx.update(|window, cx| {
1335
1
            let input = workspace
1336
1
                .read(cx)
1337
1
                .notes
1338
1
                .blocks
1339
1
                .active
1340
1
                .as_ref()
1341
1
                .unwrap()
1342
1
                .input
1343
1
                .clone();
1344
1
            set_block_text(&input, "", 0, window, cx);
1345
1
        });
1346
1
        cx.run_until_parked();
1347
1
        cx.simulate_keystrokes("backspace");
1348
1
        cx.run_until_parked();
1349
1
        assert_eq!(active_text(&workspace, cx), "- [x] one");
1350
1
        cx.update(|_, cx| assert_eq!(source.read(cx).value(), "- [x] one\n"));
1351
1
    }
1352
1353
    #[gpui::test]
1354
1
    fn the_block_toolbar_formats_the_selection(cx: &mut gpui::TestAppContext) {
1355
1
        let (_directory, workspace, source, cx) = open_blocks(cx, "run make now\n");
1356
1
        click(cx, "note-block-0");
1357
1
        assert!(cx.debug_bounds("note-block-toolbar").is_some());
1358
1
        cx.update(|_, cx| {
1359
1
            let input = workspace
1360
1
                .read(cx)
1361
1
                .notes
1362
1
                .blocks
1363
1
                .active
1364
1
                .as_ref()
1365
1
                .unwrap()
1366
1
                .input
1367
1
                .clone();
1368
1
            input.update(cx, |input, cx| input.set_selected_range(4..8, cx));
1369
1
        });
1370
1
        click(cx, "note-block-code");
1371
1
        assert_eq!(active_text(&workspace, cx), "run `make` now");
1372
1
        click(cx, "note-block-quote");
1373
1
        assert_eq!(active_text(&workspace, cx), "> run `make` now");
1374
1
        cx.update(|_, cx| assert_eq!(source.read(cx).value(), "> run `make` now\n"));
1375
        // Write's shortcuts format the block too.
1376
1
        let modifier = if cfg!(target_os = "macos") {
1377
0
            "cmd"
1378
        } else {
1379
1
            "ctrl"
1380
        };
1381
1
        cx.update(|_, cx| {
1382
1
            let input = workspace
1383
1
                .read(cx)
1384
1
                .notes
1385
1
                .blocks
1386
1
                .active
1387
1
                .as_ref()
1388
1
                .unwrap()
1389
1
                .input
1390
1
                .clone();
1391
1
            input.update(cx, |input, cx| input.set_selected_range(2..5, cx));
1392
1
        });
1393
1
        cx.simulate_keystrokes(&format!("{modifier}-b"));
1394
1
        cx.run_until_parked();
1395
1
        assert_eq!(active_text(&workspace, cx), "> **run** `make` now");
1396
1
    }
1397
1398
    #[gpui::test]
1399
1
    fn slash_in_a_block_offers_blocks_and_places_the_caret(cx: &mut gpui::TestAppContext) {
1400
1
        let (_directory, workspace, source, cx) = open_blocks(cx, "Intro\n");
1401
1
        click(cx, "note-block-0");
1402
1
        cx.simulate_keystrokes("enter");
1403
1
        cx.simulate_input("/");
1404
1
        cx.run_until_parked();
1405
1
        assert!(cx.debug_bounds("block-slash-menu").is_some());
1406
1
        cx.simulate_input("co");
1407
1
        cx.run_until_parked();
1408
        // "co" matches Code block only; Escape closes the menu but keeps editing.
1409
1
        assert!(cx.debug_bounds("block-slash-item-0").is_some());
1410
1
        assert!(cx.debug_bounds("block-slash-item-1").is_none());
1411
1
        cx.simulate_keystrokes("escape");
1412
1
        cx.run_until_parked();
1413
1
        assert!(cx.debug_bounds("block-slash-menu").is_none());
1414
1
        assert!(cx.debug_bounds("note-block-editor").is_some());
1415
        // Typing again reopens it; arrows move through it and Enter chooses.
1416
1
        type_in_block(&workspace, "/", cx);
1417
1
        cx.simulate_keystrokes("down down");
1418
1
        cx.run_until_parked();
1419
1
        cx.update(|_, cx| {
1420
1
            assert_eq!(
1421
1
                workspace
1422
1
                    .read(cx)
1423
1
                    .notes
1424
1
                    .blocks
1425
1
                    .slash
1426
1
                    .as_ref()
1427
1
                    .unwrap()
1428
1
                    .selected,
1429
1
                2
1430
            )
1431
1
        });
1432
1
        cx.simulate_keystrokes("up up up");
1433
1
        cx.run_until_parked();
1434
1
        cx.update(|_, cx| {
1435
1
            let slash = workspace.read(cx).notes.blocks.slash.as_ref().unwrap();
1436
1
            assert_eq!(slash.selected, matching("").count() - 1);
1437
1
        });
1438
1
        type_in_block(&workspace, "/code", cx);
1439
1
        cx.simulate_keystrokes("enter");
1440
1
        cx.run_until_parked();
1441
1
        assert!(cx.debug_bounds("block-slash-menu").is_none());
1442
        // The caret is between the fences, where Enter is a line break.
1443
1
        cx.simulate_input("let a = 1;");
1444
1
        cx.simulate_keystrokes("enter");
1445
1
        cx.simulate_input("let b = 2;");
1446
1
        cx.run_until_parked();
1447
1
        assert_eq!(
1448
1
            active_text(&workspace, cx),
1449
1
            "```\nlet a = 1;\nlet b = 2;\n```"
1450
        );
1451
1
        cx.update(|_, cx| {
1452
1
            assert_eq!(
1453
1
                source.read(cx).value(),
1454
1
                "Intro\n\n```\nlet a = 1;\nlet b = 2;\n```\n"
1455
            )
1456
1
        });
1457
        // Links put the caret where their text goes.
1458
1
        cx.simulate_keystrokes("escape");
1459
1
        click(cx, "notes-blocks-add");
1460
1
        type_in_block(&workspace, "/link", cx);
1461
1
        cx.simulate_keystrokes("enter");
1462
1
        cx.simulate_input("site");
1463
1
        cx.run_until_parked();
1464
1
        assert_eq!(active_text(&workspace, cx), "[site](https://)");
1465
1
    }
1466
1467
    #[gpui::test]
1468
1
    fn links_in_blocks_open_with_ctrl_and_the_note_is_a_page(cx: &mut gpui::TestAppContext) {
1469
        let (_directory, workspace, _source, cx) =
1470
1
            open_blocks(cx, "[Site](https://x.test)\n\nText\n");
1471
1
        cx.update(|_, cx| {
1472
1
            let shown = workspace.read(cx).notes.blocks.shown.as_ref().unwrap();
1473
1
            let first = &shown.blocks.as_ref().unwrap()[0];
1474
1
            assert!(
1475
1
                first
1476
1
                    .preview
1477
1
                    .as_ref()
1478
1
                    .unwrap()
1479
1
                    .markdown
1480
1
                    .contains("(<https://x.test>)")
1481
            );
1482
1
        });
1483
        // The link text starts at the block's left edge.
1484
1
        let block = cx.debug_bounds("note-block-0").unwrap();
1485
1
        let on_link = gpui::point(block.left() + gpui::px(16.), block.center().y);
1486
1
        cx.simulate_click(on_link, gpui::Modifiers::control());
1487
1
        cx.run_until_parked();
1488
1
        assert_eq!(cx.opened_url().as_deref(), Some("https://x.test"));
1489
1
        cx.update(|_, cx| assert!(workspace.read(cx).notes.blocks.active.is_none()));
1490
        // A plain click on the link edits the block instead.
1491
1
        cx.simulate_click(on_link, gpui::Modifiers::default());
1492
1
        cx.run_until_parked();
1493
1
        cx.update(|_, cx| {
1494
1
            let active = workspace.read(cx).notes.blocks.active.as_ref().unwrap();
1495
1
            assert_eq!(active.index, Some(0));
1496
1
        });
1497
        // The page is set apart from the app: inset from the editor area on every side.
1498
1
        let root = cx.debug_bounds("notes-blocks").unwrap();
1499
1
        let page = cx.debug_bounds("notes-blocks-column").unwrap();
1500
1
        assert!(page.left() > root.left() && page.right() < root.right());
1501
1
        assert!(page.top() > root.top());
1502
1
    }
1503
1504
    #[gpui::test]
1505
1
    fn opening_a_block_keeps_its_size_and_place(cx: &mut gpui::TestAppContext) {
1506
        let (_directory, _workspace, _source, cx) =
1507
1
            open_blocks(cx, "# Plan\n\nSome words that stay where they are.\n");
1508
1
        for index in 0..2 {
1509
2
            let selector: &'static str = Box::leak(format!("note-block-{index}").into_boxed_str());
1510
2
            let shown = cx.debug_bounds(selector).unwrap();
1511
2
            click(cx, selector);
1512
2
            let field = cx.debug_bounds("note-block-field").unwrap();
1513
2
            assert!(
1514
2
                (field.size.height - shown.size.height).abs() <= gpui::px(2.),
1515
                "block {index}: {shown:?} became {field:?}"
1516
            );
1517
2
            assert!(
1518
2
                (field.top() - shown.top()).abs() <= gpui::px(1.),
1519
                "block {index}"
1520
            );
1521
            // The toolbar floats above the block instead of pushing it down.
1522
2
            let toolbar = cx.debug_bounds("note-block-toolbar").unwrap();
1523
2
            assert!(toolbar.bottom() <= field.top());
1524
2
            cx.simulate_keystrokes("escape");
1525
2
            cx.run_until_parked();
1526
        }
1527
1
    }
1528
}