iced-markdown-editor 0.3.2

A Word-style WYSIWYG CommonMark editor widget for Iced
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
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
use super::*;
use crate::doc::ColumnAlign;
use crate::extension::{BlockRenderer, Frame, Rectangle, RenderRequest, Size};
use crate::features::Features;
use crate::images::{ImageRejection, ImageSettings, PastedImage};
use crate::layout::Decor;
use crate::markdown::{parse, serialize};

fn round(doc: &Document) -> String {
    serialize(doc)
}

/// A 1×1 PNG.
const PNG: &[u8] = &[
    0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,
    0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4,
    0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0xF8, 0xCF, 0xC0, 0xF0,
    0x1F, 0x00, 0x05, 0x00, 0x01, 0xFF, 0x89, 0x99, 0x3D, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
    0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
];

#[test]
fn tab_nests_and_shift_tab_unnests_list_items() {
    let mut doc = parse("- a\n- b\n- c\n");
    assert!(nest_item(&mut doc, 1));
    assert_eq!(round(&doc), "- a\n  - b\n- c\n");
    assert!(nest_item(&mut doc, 2));
    assert_eq!(round(&doc), "- a\n  - b\n  - c\n");
    assert!(unnest_item(&mut doc, 1));
    assert_eq!(round(&doc), "- a\n- b\n  - c\n");
    assert!(unnest_item(&mut doc, 0));
    assert_eq!(round(&doc), "a\n\n- b\n  - c\n");
}

#[test]
fn first_item_cannot_be_nested() {
    let mut doc = parse("- a\n- b\n");
    assert!(!nest_item(&mut doc, 0));
}

#[test]
fn enter_in_list_creates_new_item() {
    let mut doc = parse("- ab\n");
    let pos = doc.split_block(Pos::new(0, 1));
    assert_eq!(pos, Pos::new(1, 0));
    assert_eq!(round(&doc), "- a\n- b\n");
}

#[test]
fn enter_in_task_creates_unchecked_task() {
    let mut doc = parse("- [x] ab\n");
    doc.split_block(Pos::new(0, 1));
    assert_eq!(round(&doc), "- [x] a\n- [ ] b\n");
}

#[test]
fn nesting_keeps_task_state() {
    let mut doc = parse("- [ ] a\n- [x] b\n");
    assert!(nest_item(&mut doc, 1));
    assert_eq!(round(&doc), "- [ ] a\n  - [x] b\n");
    assert!(unnest_item(&mut doc, 1));
    assert_eq!(round(&doc), "- [ ] a\n- [x] b\n");
}

#[test]
fn wrap_and_join_lists_and_quotes() {
    let mut doc = parse("- a\n\nb\n");
    wrap_list(&mut doc, 1, 1, false, 1, None);
    assert_eq!(round(&doc), "- a\n- b\n");
    let mut doc = parse("x\n\ny\n");
    wrap_quote(&mut doc, 0, 1);
    assert_eq!(round(&doc), "> x\n>\n> y\n");
    let mut doc = parse("x\n");
    wrap_list(&mut doc, 0, 0, false, 1, Some(false));
    assert_eq!(round(&doc), "- [ ] x\n");
}

#[test]
fn toggle_task_state() {
    let mut doc = parse("- [ ] a\n");
    doc.set_task(0, 0, Some(true));
    assert_eq!(round(&doc), "- [x] a\n");
    doc.set_task(0, 0, None);
    assert_eq!(round(&doc), "- a\n");
}

fn insert(editor: &mut EditorState, bytes: &[u8]) -> Vec<Event> {
    editor
        .execute(Command::InsertImage {
            bytes: bytes.to_vec(),
            name: Some("photo.png".into()),
        })
        .events
}

fn pasted(events: &[Event]) -> PastedImage {
    events
        .iter()
        .find_map(|event| match event {
            Event::ImagePasted(image) => Some(image.clone()),
            _ => None,
        })
        .expect("no ImagePasted event")
}

#[test]
fn disabled_images_are_rejected() {
    let mut editor = EditorState::with_markdown("text");
    let events = insert(&mut editor, PNG);
    assert!(events.contains(&Event::ImageRejected {
        source: ImageSource::Insert,
        reason: ImageRejection::Disabled,
    }));
    assert_eq!(editor.markdown(), "text\n");
}

#[test]
fn embedded_images_become_data_urls() {
    let mut editor = EditorState::with_markdown("").images(ImageSettings::embed());
    insert(&mut editor, PNG);
    let markdown = editor.markdown();
    assert!(markdown.starts_with("![photo](data:image/png;base64,iVBORw0KGgo"));
}

#[test]
fn embedded_images_are_short_in_source_mode() {
    let url = format!("data:image/png;base64,{}", "A".repeat(500));
    let text = format!("x ![a]({url}) y\n");
    let mut editor = EditorState::with_markdown(&text);
    editor.set_mode(Mode::Source);
    let line = editor.doc.blocks[0].text();
    assert_eq!(line, "x ![a](data:image/png;embedded,1) y");
    assert_eq!(editor.markdown(), text);
    editor.set_mode(Mode::Wysiwyg);
    assert_eq!(editor.markdown(), text);
    // Switching again keeps the same number.
    editor.set_mode(Mode::Source);
    assert_eq!(editor.doc.blocks[0].text(), line);
}

#[test]
fn delegated_images_are_resolved_or_cancelled() {
    let mut editor = EditorState::with_markdown("").images(ImageSettings::delegate());
    let image = pasted(&insert(&mut editor, PNG));
    assert_eq!(image.mime, "image/png");
    assert_eq!(image.extension(), "png");
    assert_eq!(image.file_name(), "photo.png");
    assert_eq!(editor.markdown(), "\n");
    assert_eq!(editor.pending_images(), 1);

    editor.execute(Command::ResolveImage {
        id: image.id,
        url: "assets/photo.png".into(),
        alt: "A photo".into(),
    });
    assert_eq!(editor.markdown(), "![A photo](assets/photo.png)\n");
    assert_eq!(editor.pending_images(), 0);

    editor.execute(Command::Undo);
    editor.execute(Command::Redo);
    assert_eq!(editor.markdown(), "![A photo](assets/photo.png)\n");

    let second = pasted(&insert(&mut editor, PNG));
    editor.execute(Command::CancelImage { id: second.id });
    assert_eq!(editor.markdown(), "![A photo](assets/photo.png)\n");
}

#[test]
fn delegated_images_in_source_mode() {
    let mut editor = EditorState::with_markdown("a")
        .images(ImageSettings::delegate())
        .mode(Mode::Source);
    editor.execute(Command::SelectAll);
    editor.execute(Command::InsertText("x ".into()));
    let image = pasted(&insert(&mut editor, PNG));
    assert_eq!(editor.markdown(), "x ");
    editor.execute(Command::ResolveImage {
        id: image.id,
        url: "a.png".into(),
        alt: String::new(),
    });
    assert_eq!(editor.markdown(), "x ![](a.png)");
}

#[test]
fn rejects_unknown_types_and_large_images() {
    let mut editor = EditorState::new().images(ImageSettings::embed().max_bytes(10));
    let events = insert(&mut editor, b"%PDF-1.7");
    assert!(events.iter().any(|event| matches!(
        event,
        Event::ImageRejected {
            reason: ImageRejection::UnsupportedType(_),
            ..
        }
    )));
    let events = insert(&mut editor, PNG);
    assert!(events.iter().any(|event| matches!(
        event,
        Event::ImageRejected {
            reason: ImageRejection::TooLarge { .. },
            ..
        }
    )));
}

#[test]
fn image_button_requests_an_image() {
    let mut editor = EditorState::new().images(ImageSettings::embed());
    let events = editor.execute(Command::RequestImage).events;
    assert!(events.contains(&Event::ImageRequested));
}

#[test]
fn insert_table_and_type_in_cells() {
    let mut editor = EditorState::with_markdown("intro\n");
    editor.sel = Selection::caret(Pos::new(0, 5));
    editor.execute(Command::InsertTable {
        rows: 2,
        columns: 2,
    });
    assert_eq!(editor.sel.head, Pos::new(1, 0));
    editor.execute(Command::InsertText("a".into()));
    editor.execute(Command::Indent);
    editor.execute(Command::InsertText("b".into()));
    editor.execute(Command::Indent);
    editor.execute(Command::InsertText("1\n2".into()));
    assert_eq!(
        editor.markdown(),
        "intro\n\n| a   | b   |\n| --- | --- |\n| 1 2 |     |\n"
    );
    assert_eq!(
        editor.doc.plain_text(Pos::new(1, 0), Pos::new(4, 0)),
        "a\tb\n1 2\t"
    );
}

#[test]
fn tab_moves_between_cells_and_adds_rows() {
    let mut editor = EditorState::with_markdown("| a |\n| - |\n| 1 |\n");
    editor.sel = Selection::caret(Pos::new(1, 1));
    editor.execute(Command::Indent);
    assert_eq!(editor.doc.blocks.len(), 3);
    assert_eq!(editor.sel, Selection::caret(Pos::new(2, 0)));
    editor.execute(Command::Outdent);
    assert_eq!(
        editor.sel,
        Selection {
            anchor: Pos::new(1, 0),
            head: Pos::new(1, 1),
        }
    );
}

#[test]
fn enter_moves_down_adds_rows_and_leaves_the_table() {
    let mut editor = EditorState::with_markdown("| a | b |\n| - | - |\n| 1 | 2 |\n");
    editor.sel = Selection::caret(Pos::new(1, 1));
    let _ = editor.enter(false);
    assert_eq!(editor.sel.head, Pos::new(3, 1));
    let _ = editor.enter(false);
    assert_eq!(editor.doc.blocks.len(), 6);
    assert_eq!(editor.sel.head, Pos::new(5, 0));
    let _ = editor.enter(false);
    assert_eq!(editor.doc.blocks.len(), 5);
    assert_eq!(editor.doc.blocks[4].leaf, Leaf::Paragraph);
    assert_eq!(editor.sel.head, Pos::new(4, 0));
    editor.execute(Command::InsertText("after".into()));
    assert_eq!(
        editor.markdown(),
        "| a   | b   |\n| --- | --- |\n| 1   | 2   |\n\nafter\n"
    );
}

#[test]
fn typing_a_header_row_creates_a_table() {
    let mut editor = EditorState::new();
    editor.execute(Command::InsertText("| Name | Age |".into()));
    let _ = editor.enter(false);
    assert_eq!(editor.sel.head, Pos::new(2, 0));
    editor.execute(Command::InsertText("Ann".into()));
    assert_eq!(
        editor.markdown(),
        "| Name | Age |\n| ---- | --- |\n| Ann  |     |\n"
    );
}

#[test]
fn backspace_and_delete_keep_cells() {
    let mut editor = EditorState::with_markdown("| a | b |\n| - | - |\n\nx\n");
    editor.sel = Selection::caret(Pos::new(1, 0));
    let _ = editor.backspace(false);
    assert_eq!(editor.doc.blocks.len(), 3);
    editor.sel = Selection::caret(Pos::new(0, 1));
    let _ = editor.delete_forward(false);
    assert_eq!(editor.doc.blocks[0].text(), "a");
    // At the start of the paragraph after the table: into the last cell.
    editor.sel = Selection::caret(Pos::new(2, 0));
    let _ = editor.backspace(false);
    assert_eq!(editor.sel.head, Pos::new(1, 1));
    assert_eq!(editor.markdown(), "| a   | b   |\n| --- | --- |\n\nx\n");
    // Block kinds that would split the table do nothing.
    editor.sel = Selection::caret(Pos::new(0, 0));
    editor.execute(Command::SetBlock(BlockKind::Bullet));
    editor.execute(Command::SetBlock(BlockKind::Heading(1)));
    editor.execute(Command::InsertRule);
    assert_eq!(editor.markdown(), "| a   | b   |\n| --- | --- |\n\nx\n");
}

#[test]
fn deleting_across_a_table() {
    let mut doc = parse("before\n\n| a | b |\n| - | - |\n| 1 | 2 |\n\nafter\n");
    let pos = doc.delete_range(Pos::new(2, 0), Pos::new(5, 2));
    assert_eq!(pos, Pos::new(2, 0));
    assert_eq!(
        round(&doc),
        "before\n\n| a   |     |\n| --- | --- |\n|     |     |\n\nter\n"
    );

    let mut doc = parse("before\n\n| a | b |\n| - | - |\n\nafter\n");
    let pos = doc.delete_range(Pos::new(0, 3), Pos::new(3, 2));
    assert_eq!(pos, Pos::new(0, 3));
    assert_eq!(round(&doc), "befter\n");
}

#[test]
fn row_and_column_commands() {
    let mut editor = EditorState::with_markdown("| a | b |\n| - | - |\n| 1 | 2 |\n");
    editor.sel = Selection::caret(Pos::new(0, 0));
    editor.execute(Command::SetColumnAlign(ColumnAlign::Center));
    assert_eq!(editor.formatting().column_align, Some(ColumnAlign::Center));
    editor.execute(Command::InsertColumn { right: true });
    editor.execute(Command::InsertRow { below: false });
    assert_eq!(
        editor.markdown(),
        "|     |     |     |\n| :-: | --- | --- |\n| a   |     | b   |\n| 1   |     | 2   |\n"
    );
    editor.execute(Command::DeleteRow);
    editor.execute(Command::DeleteColumn);
    assert_eq!(
        editor.markdown(),
        "| a   | b   |\n| :-: | --- |\n| 1   | 2   |\n"
    );
    editor.execute(Command::Undo);
    editor.execute(Command::DeleteTable);
    assert_eq!(editor.markdown(), "\n");
    assert!(!editor.formatting().table);
}

#[test]
fn table_layout_and_navigation() {
    let editor = EditorState::with_markdown("| a | b |\n| - | - |\n| 1 | 2 |\n\nend\n");
    let layout = editor.layout.borrow();
    let (ax, ay, _) = layout.caret(Pos::new(0, 0)).unwrap();
    let (bx, by, _) = layout.caret(Pos::new(1, 0)).unwrap();
    let (_, y1, _) = layout.caret(Pos::new(2, 0)).unwrap();
    assert_eq!(ay, by);
    assert!(bx > ax);
    assert!(y1 > ay);
    assert_eq!(layout.hit(bx + 1.0, by + 1.0).block, 1);
    assert_eq!(layout.vertical(Pos::new(1, 0), bx, 1), Some(Pos::new(3, 0)));
    assert_eq!(
        layout.vertical(Pos::new(3, 0), bx, 1).map(|p| p.block),
        Some(4)
    );
    assert_eq!(
        layout.vertical(Pos::new(4, 0), ax, -1).map(|p| p.block),
        Some(2)
    );
}

#[test]
fn insert_table_in_source_mode() {
    let mut editor = EditorState::with_markdown("x").mode(Mode::Source);
    editor.execute(Command::InsertTable {
        rows: 2,
        columns: 2,
    });
    assert_eq!(
        editor.markdown(),
        "x\n\n|     |     |\n| --- | --- |\n|     |     |\n"
    );
}

#[test]
fn scrolling_is_clamped() {
    let text = "line\n\n".repeat(400);
    let mut editor = EditorState::with_markdown(&text);
    editor.update(Action(Inner::ScrollBy { dx: 0.0, dy: 500.0 }));
    assert_eq!(editor.scroll_y, 500.0);
    editor.update(Action(Inner::ScrollBy {
        dx: 0.0,
        dy: -9999.0,
    }));
    assert_eq!(editor.scroll_y, 0.0);
    editor.update(Action(Inner::ScrollTo {
        x: None,
        y: Some(1.0e9),
    }));
    assert_eq!(editor.scroll_y, editor.max_scroll().1);
}

fn type_text(editor: &mut EditorState, text: &str) {
    for c in text.chars() {
        editor.execute(Command::InsertText(c.to_string()));
    }
}

#[test]
fn disabled_features_are_not_created() {
    let mut editor = EditorState::new().features(Features::COMMONMARK);
    type_text(&mut editor, "| a | b |");
    let _ = editor.enter(false);
    type_text(&mut editor, "- [ ] x");
    editor.execute(Command::InsertTable {
        rows: 2,
        columns: 2,
    });
    editor.execute(Command::SetBlock(BlockKind::Task));
    editor.execute(Command::SelectAll);
    editor.execute(Command::ToggleStrike);
    assert_eq!(editor.markdown(), "\\| a \\| b \\|\n\n- \\[ \\] x\n");
    assert!(!Features::COMMONMARK.allows(&Command::ToggleChecked));
    assert!(Features::COMMONMARK.allows(&Command::ToggleBold));
}

#[test]
fn switching_features_reads_the_document_again() {
    let mut editor = EditorState::with_markdown("- [x] done ~~old~~\n\n| a |\n| - |\n");
    editor.set_features(Features {
        task_lists: false,
        tables: false,
        ..Features::ALL
    });
    // The table is written (padded) first, then read as text.
    assert_eq!(
        editor.markdown(),
        "- \\[x\\] done ~~old~~\n\n\\| a   \\|\n\\| --- \\|\n"
    );
    assert!(!editor.formatting().table);
}

/// Draws ```` ```box ```` blocks as a 100 × 50 box.
struct Boxes;

impl BlockRenderer for Boxes {
    fn languages(&self) -> Vec<String> {
        vec!["box".into()]
    }

    fn measure(&self, request: &RenderRequest<'_>) -> Option<Size> {
        (request.code != "invalid").then(|| Size::new(100.0, 50.0))
    }

    fn draw(&self, _: &mut Frame, _: Rectangle, _: &RenderRequest<'_>) {}
}

fn rendered(editor: &EditorState, block: usize) -> bool {
    let layout = editor.layout.borrow();
    let custom = layout
        .decor
        .iter()
        .any(|decor| matches!(decor, Decor::Custom { block: b, .. } if *b == block));
    let lines: Vec<_> = layout
        .lines
        .iter()
        .filter(|line| line.block == block)
        .collect();
    if custom {
        assert_eq!(lines.len(), 1);
        assert_eq!((lines[0].end, lines[0].height), (0, 50.0));
    }
    custom
}

#[test]
fn rendered_blocks_show_code_while_editing() {
    let text = "intro\n\n```box\nx\n```\n\n```box\ninvalid\n```\n\nend\n";
    let mut editor = EditorState::with_markdown(text).block_renderer(Boxes);
    assert!(editor.code_languages().contains(&"box".to_string()));
    assert!(rendered(&editor, 1));
    assert!(!rendered(&editor, 2), "the renderer declined");

    // A click on the block puts the caret in it and shows the code.
    let (x, y) = {
        let layout = editor.layout.borrow();
        let line = layout.lines.iter().find(|line| line.block == 1).unwrap();
        (line.xs[0] + 10.0, line.y + 10.0)
    };
    editor.update(Action(Inner::Press { x, y, clicks: 1 }));
    assert_eq!(editor.sel.head.block, 1);
    assert!(!rendered(&editor, 1));

    editor.execute(Command::InsertText("y".into()));
    editor.update(Action(Inner::Key(
        Key::Named(Named::ArrowDown),
        Modifiers::empty(),
        None,
    )));
    assert_ne!(editor.sel.head.block, 1);
    assert!(rendered(&editor, 1));
    assert_eq!(
        editor.markdown(),
        "intro\n\n```box\nyx\n```\n\n```box\ninvalid\n```\n\nend\n"
    );

    // Source mode shows the Markdown.
    editor.set_mode(Mode::Source);
    assert!(!rendered(&editor, 2));
}

#[test]
fn end_moves_to_the_end_of_the_line() {
    let end = |text: &str, mode: Mode| {
        let mut editor = EditorState::with_markdown(text);
        editor.set_mode(mode);
        let (x, y) = {
            let layout = editor.layout.borrow();
            (layout.lines[0].xs[0], layout.lines[0].y + 1.0)
        };
        editor.update(Action(Inner::Press { x, y, clicks: 1 }));
        editor.update(Action(Inner::Key(
            Key::Named(Named::End),
            Modifiers::empty(),
            None,
        )));
        editor.sel.head
    };
    assert_eq!(end("hello world\n", Mode::Wysiwyg), Pos::new(0, 11));
    assert_eq!(end("hello world\n", Mode::Source), Pos::new(0, 11));
    // A hard break ends the line before the break.
    assert_eq!(end("a  \nbreak line\n", Mode::Wysiwyg), Pos::new(0, 1));
    // Wrapped lines end before the space they break at.
    assert_eq!(end(&"word ".repeat(80), Mode::Wysiwyg), Pos::new(0, 74));
}

/// Document coordinates inside the character at `pos`.
fn point_at(editor: &EditorState, pos: Pos) -> (f32, f32) {
    let (x, y, height) = editor.layout.borrow().caret(pos).unwrap();
    (x + 1.0, y + height / 2.0)
}

fn right_click(editor: &mut EditorState, pos: Pos) {
    let (x, y) = point_at(editor, pos);
    editor.update(Action(Inner::ContextMenu {
        at: iced::Point::new(5.0, 5.0),
        x,
        y,
    }));
}

#[test]
fn right_click_in_the_selection_keeps_it() {
    let mut editor = EditorState::with_markdown("hello world\n");
    let selection = Selection {
        anchor: Pos::new(0, 0),
        head: Pos::new(0, 5),
    };
    editor.sel = selection;
    right_click(&mut editor, Pos::new(0, 2));
    assert_eq!(editor.sel, selection);
    assert!(editor.context_menu.is_some());
    assert!(editor.focused);

    // A menu entry runs its command and closes the menu.
    editor.execute(Command::ToggleBold);
    assert!(editor.context_menu.is_none());
    assert_eq!(editor.markdown(), "**hello** world\n");
}

#[test]
fn right_click_outside_the_selection_moves_the_caret() {
    let mut editor = EditorState::with_markdown("hello world\n");
    editor.sel = Selection {
        anchor: Pos::new(0, 0),
        head: Pos::new(0, 3),
    };
    right_click(&mut editor, Pos::new(0, 8));
    assert_eq!(editor.sel, Selection::caret(Pos::new(0, 8)));
    assert!(editor.context_menu.is_some());
}

#[test]
fn escape_closes_the_menu_only() {
    let mut editor = EditorState::with_markdown("hello world\n");
    let selection = Selection {
        anchor: Pos::new(0, 0),
        head: Pos::new(0, 5),
    };
    editor.sel = selection;
    right_click(&mut editor, Pos::new(0, 1));
    let escape = Key::Named(Named::Escape);
    editor.update(Action(Inner::Key(escape.clone(), Modifiers::empty(), None)));
    assert!(editor.context_menu.is_none());
    assert_eq!(editor.sel, selection);
    // Without a menu, Escape collapses the selection as before.
    editor.update(Action(Inner::Key(escape, Modifiers::empty(), None)));
    assert_eq!(editor.sel, Selection::caret(Pos::new(0, 5)));
}

#[test]
fn scrolling_and_clicking_close_the_menu() {
    let mut editor = EditorState::with_markdown("hello world\n");
    right_click(&mut editor, Pos::new(0, 1));
    editor.update(Action(Inner::Blink));
    assert!(editor.context_menu.is_some());
    editor.update(Action(Inner::ScrollBy { dx: 0.0, dy: 10.0 }));
    assert!(editor.context_menu.is_none());

    right_click(&mut editor, Pos::new(0, 1));
    let (x, y) = point_at(&editor, Pos::new(0, 3));
    editor.update(Action(Inner::Press { x, y, clicks: 1 }));
    assert!(editor.context_menu.is_none());
}

#[test]
fn right_click_in_a_table_cell_then_insert_column_left() {
    let mut editor = EditorState::with_markdown("| a | b |\n| - | - |\n| 1 | 2 |\n");
    right_click(&mut editor, Pos::new(1, 0));
    assert_eq!(editor.sel.head.block, 1);
    editor.execute(Command::InsertColumn { right: false });
    assert_eq!(
        editor.markdown(),
        "| a   |     | b   |\n| --- | --- | --- |\n| 1   |     | 2   |\n"
    );
}

fn select(editor: &mut EditorState, anchor: Pos, head: Pos) {
    editor.sel = Selection { anchor, head };
}

fn link_dialog(editor: &mut EditorState) -> &crate::widget::dialog::LinkDialog {
    editor.update(Action(Inner::LinkDialog));
    editor.link_dialog.as_ref().expect("dialog is open")
}

#[test]
fn link_dialog_links_the_selection() {
    let mut editor = EditorState::with_markdown("hello world\n");
    select(&mut editor, Pos::new(0, 0), Pos::new(0, 5));
    let dialog = link_dialog(&mut editor);
    assert_eq!(dialog.text.as_deref(), Some("hello"));
    assert!(!dialog.editing);
    assert_eq!(editor.link_url.as_deref(), Some("https://"));
    editor.update(Action(Inner::LinkUrl("https://example.org".into())));
    editor.update(Action(Inner::LinkApply));
    assert!(editor.link_dialog.is_none());
    assert!(editor.link_url.is_none());
    assert_eq!(editor.markdown(), "[hello](https://example.org) world\n");
}

#[test]
fn link_dialog_changes_the_text_to_display() {
    let mut editor = EditorState::with_markdown("**hello** world\n");
    select(&mut editor, Pos::new(0, 0), Pos::new(0, 5));
    link_dialog(&mut editor);
    editor.update(Action(Inner::LinkText("hi there".into())));
    editor.update(Action(Inner::LinkUrl("https://example.org".into())));
    editor.update(Action(Inner::LinkApply));
    assert_eq!(
        editor.markdown(),
        "[**hi there**](https://example.org) world\n"
    );
    editor.execute(Command::Undo);
    assert_eq!(editor.markdown(), "**hello** world\n");
}

#[test]
fn link_dialog_edits_and_removes_a_link() {
    let mut editor = EditorState::with_markdown("[hello](https://a.org) world\n");
    select(&mut editor, Pos::new(0, 1), Pos::new(0, 3));
    let dialog = link_dialog(&mut editor);
    assert!(dialog.editing);
    // The word at the caret is not widened, the selection is used as is.
    assert_eq!(dialog.text.as_deref(), Some("el"));
    assert_eq!(editor.link_url.as_deref(), Some("https://a.org"));

    select(&mut editor, Pos::new(0, 0), Pos::new(0, 5));
    link_dialog(&mut editor);
    editor.update(Action(Inner::LinkUrl("https://b.org".into())));
    editor.update(Action(Inner::LinkApply));
    assert_eq!(editor.markdown(), "[hello](https://b.org) world\n");

    select(&mut editor, Pos::new(0, 0), Pos::new(0, 5));
    link_dialog(&mut editor);
    editor.update(Action(Inner::LinkRemove));
    assert_eq!(editor.markdown(), "hello world\n");
}

#[test]
fn link_dialog_cancel_changes_nothing() {
    let mut editor = EditorState::with_markdown("hello world\n");
    select(&mut editor, Pos::new(0, 0), Pos::new(0, 5));
    link_dialog(&mut editor);
    editor.update(Action(Inner::LinkUrl("https://example.org".into())));
    editor.update(Action(Inner::LinkCancel));
    assert!(editor.link_dialog.is_none());
    assert!(editor.link_url.is_none());
    assert_eq!(editor.markdown(), "hello world\n");
    assert!(!editor.can_undo());
}

#[test]
fn link_dialog_keeps_text_it_cannot_retype() {
    let mut editor = EditorState::with_markdown("one\n\ntwo\n");
    select(&mut editor, Pos::new(0, 1), Pos::new(1, 2));
    assert!(link_dialog(&mut editor).text.is_none());
    editor.update(Action(Inner::LinkText("ignored".into())));
    editor.update(Action(Inner::LinkUrl("https://example.org".into())));
    editor.update(Action(Inner::LinkApply));
    assert_eq!(
        editor.markdown(),
        "o[ne](https://example.org)\n\n[tw](https://example.org)o\n"
    );
}

#[test]
fn link_dialog_without_text_inserts_the_address() {
    let mut editor = EditorState::with_markdown("");
    assert_eq!(link_dialog(&mut editor).text.as_deref(), Some(""));
    editor.update(Action(Inner::LinkUrl("https://example.org".into())));
    editor.update(Action(Inner::LinkApply));
    // Text equal to the address is written as an autolink.
    assert_eq!(editor.markdown(), "<https://example.org>\n");
}

#[test]
fn link_dialog_in_source_mode_writes_markdown() {
    let mut editor = EditorState::with_markdown("hello\n").mode(Mode::Source);
    select(&mut editor, Pos::new(0, 0), Pos::new(0, 5));
    editor.update(Action(Inner::LinkDialog));
    assert!(editor.link_dialog.is_none());
    assert_eq!(editor.markdown(), "[hello](https://)\n");
}