piki-gui 0.7.1

FLTK-based GUI for Piki personal wiki application
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
use crate::content::{ContentLoader, ContentProvider};
use crate::fltk_draw_context::FltkDrawContext;
use crate::fltk_structured_rich_display::FltkStructuredRichDisplay;
use crate::live_share::HighlightTarget;
use crate::markdown_converter::document_to_markdown;
use crate::note_ui::NoteUI;
use fltk::{app, enums::Color, prelude::*, window};
use rutle::editor::Editor;
use rutle::renderer::SearchMatch;
use rutle::structured_document::BlockType;
use rutle::tree_path::{DocumentPosition, PathSegment, TreePath};
use rutle::tree_walk::LeafInfo;
use std::any::Any;
use std::collections::{HashMap, HashSet};
use tdoc::Document;

/// Vertical breathing room, in pixels, kept above a heading when scrolling to a
/// section so it does not sit flush against the top edge of the viewport.
const ANCHOR_TOP_MARGIN: i32 = 12;

/// NoteUI adapter for rutle's `Renderer` + FLTK Group wrapper
pub struct StructuredRichUI(pub FltkStructuredRichDisplay);

impl StructuredRichUI {
    pub fn new(x: i32, y: i32, w: i32, h: i32, edit_mode: bool) -> Self {
        Self(FltkStructuredRichDisplay::new(x, y, w, h, edit_mode))
    }

    pub fn has_selection(&self) -> bool {
        self.0.display.borrow().editor().selection().is_some()
    }

    /// The web-view highlights mirroring the editor's *selection*: one
    /// [`HighlightTarget`] per top-level block (or list/checklist item) the
    /// selection touches, in document order. Empty when there is no selection,
    /// so a bare caret shows no highlight and double-clicking a word brings one
    /// back.
    pub fn highlight_targets(&self) -> Vec<HighlightTarget> {
        let disp = self.0.display.borrow();
        let editor = disp.editor();
        let Some((a, b)) = editor.selection() else {
            return Vec::new();
        };
        // Order the endpoints so a reversed drag is handled the same way.
        let (start, end) = if a <= b { (a, b) } else { (b, a) };
        selection_targets(editor.document(), &start, &end)
    }

    /// Cut the current selection to the system clipboard (HTML + Markdown).
    /// Returns `true` if there was a selection that was cut.
    pub fn cut_selection(&mut self) -> bool {
        let doc = self.0.display.borrow().editor().get_selection_document();
        let Some(doc) = doc else {
            return false;
        };
        crate::clipboard::copy_structured_to_system(&doc);
        {
            let mut disp = self.0.display.borrow_mut();
            let _ = disp.editor_mut().delete_selection();
        }
        self.0.notify_change();
        true
    }

    /// Copy the current selection to the system clipboard (HTML + Markdown).
    /// Returns `true` if there was a selection that was copied.
    pub fn copy_selection(&self) -> bool {
        let doc = self.0.display.borrow().editor().get_selection_document();
        match doc {
            Some(doc) => {
                crate::clipboard::copy_structured_to_system(&doc);
                true
            }
            None => false,
        }
    }

    pub fn paste_from_clipboard(&mut self) {
        let group = self.0.group.clone();
        app::paste(&group);
    }

    pub fn undo(&mut self) -> bool {
        let changed = {
            let mut disp = self.0.display.borrow_mut();
            disp.editor_mut().undo()
        };
        if changed {
            self.0.notify_change();
            self.0.emit_paragraph_state();
        }
        changed
    }

    pub fn redo(&mut self) -> bool {
        let changed = {
            let mut disp = self.0.display.borrow_mut();
            disp.editor_mut().redo()
        };
        if changed {
            self.0.notify_change();
            self.0.emit_paragraph_state();
        }
        changed
    }

    pub fn clear_formatting(&mut self) -> bool {
        self.apply_edit(|editor| editor.clear_formatting())
    }

    pub fn set_block_type(&mut self, block_type: BlockType) -> bool {
        self.apply_edit(move |editor| editor.set_block_type(block_type))
    }

    pub fn toggle_quote(&mut self) -> bool {
        self.apply_edit(|editor| editor.toggle_quote())
    }

    pub fn toggle_code_block(&mut self) -> bool {
        self.apply_edit(|editor| editor.toggle_code_block())
    }

    pub fn toggle_list(&mut self) -> bool {
        self.apply_edit(|editor| editor.toggle_list())
    }

    pub fn toggle_checklist(&mut self) -> bool {
        self.apply_edit(|editor| editor.toggle_checklist())
    }

    pub fn toggle_ordered_list(&mut self) -> bool {
        self.apply_edit(|editor| editor.toggle_ordered_list())
    }

    pub fn toggle_bold(&mut self) -> bool {
        self.apply_edit(|editor| editor.toggle_bold())
    }

    pub fn toggle_italic(&mut self) -> bool {
        self.apply_edit(|editor| editor.toggle_italic())
    }

    pub fn toggle_code(&mut self) -> bool {
        self.apply_edit(|editor| editor.toggle_code())
    }

    pub fn toggle_strikethrough(&mut self) -> bool {
        self.apply_edit(|editor| editor.toggle_strikethrough())
    }

    pub fn toggle_underline(&mut self) -> bool {
        self.apply_edit(|editor| editor.toggle_underline())
    }

    pub fn toggle_highlight(&mut self) -> bool {
        self.apply_edit(|editor| editor.toggle_highlight())
    }

    pub fn current_block_type(&self) -> Option<BlockType> {
        let disp = self.0.display.borrow();
        Some(disp.editor().current_block_type())
    }

    /// The anchor slug of the heading the caret is currently inside, or `None`
    /// when the caret is not in a heading. Duplicate headings are disambiguated
    /// exactly as [`Self::scroll_to_anchor`] resolves them, so the slug links
    /// back to *this* heading and not an earlier namesake.
    pub fn current_heading_anchor(&self) -> Option<String> {
        let disp = self.0.display.borrow();
        let cursor = disp.editor().cursor();
        // A heading is always a top-level leaf, so its caret path starts with a
        // `Paragraph(i)` segment that indexes `Document.paragraphs`.
        let para = match cursor.path.segments().first() {
            Some(PathSegment::Paragraph(i)) => *i,
            _ => return None,
        };
        heading_anchor_map(disp.editor().document())
            .into_iter()
            .find(|(idx, _)| *idx == para)
            .map(|(_, anchor)| anchor)
    }

    /// Scroll so the heading whose anchor slug equals `anchor` sits near the top
    /// of the viewport. Returns `false` if no heading matches.
    pub fn scroll_to_anchor(&mut self, anchor: &str) -> bool {
        let target = {
            let disp = self.0.display.borrow();
            heading_anchor_map(disp.editor().document())
                .into_iter()
                .find(|(_, a)| a == anchor)
                .map(|(idx, _)| idx)
        };
        match target {
            Some(idx) => self.scroll_to_block(idx),
            None => false,
        }
    }

    /// Scroll so top-level block `block_index` sits near the top of the viewport.
    ///
    /// The renderer exposes no public block→pixel mapping, so this moves the
    /// caret into the target block and reuses the caret→pixel bridge
    /// (`cursor_content_y`) after a layout pass. Returns `false` if the index is
    /// out of range.
    pub fn scroll_to_block(&mut self, block_index: usize) -> bool {
        let mut ctx = FltkDrawContext::new(true, true);
        let mut disp = self.0.display.borrow_mut();
        if block_index >= disp.editor().document().paragraphs.len() {
            return false;
        }
        disp.editor_mut()
            .set_cursor(DocumentPosition::new(block_index, 0));
        // Lay out with real font metrics so `cursor_content_y` is populated.
        disp.ensure_cursor_visible(&mut ctx);
        if let Some((content_y, _line_h)) = disp.cursor_content_y(&mut ctx) {
            let max_scroll = (disp.content_height() - disp.h()).max(0);
            let target = (content_y - ANCHOR_TOP_MARGIN).max(0).min(max_scroll);
            disp.set_scroll(target);
        }
        drop(disp);
        self.0.group.redraw();
        true
    }

    /// Set horizontal padding (for write room mode)
    pub fn set_horizontal_padding(&mut self, padding: i32) {
        self.0.display.borrow_mut().set_horizontal_padding(padding);
        self.0.group.redraw();
    }

    /// Get current horizontal padding
    pub fn horizontal_padding(&self) -> i32 {
        self.0.display.borrow().horizontal_padding()
    }

    /// Whether reveal-codes mode is active (rutle's inline-style tags, e.g.
    /// `[Bold>`…`<Bold]`, shown inline).
    pub fn reveal_codes(&self) -> bool {
        self.0.display.borrow().reveal_codes()
    }

    /// Toggle reveal-codes mode, returning the new state. This is purely a view
    /// change — not a document edit — so it deliberately skips the change/undo
    /// machinery; the tags appearing inline are their own feedback.
    pub fn toggle_reveal_codes(&mut self) -> bool {
        let new_state = !self.0.display.borrow().reveal_codes();
        self.0.display.borrow_mut().set_reveal_codes(new_state);
        self.0.group.redraw();
        new_state
    }

    /// Resize the editor widget
    pub fn resize(&mut self, x: i32, y: i32, w: i32, h: i32) {
        self.0.group.resize(x, y, w, h);
        self.0.group.redraw();
    }

    /// Get current height
    pub fn height(&self) -> i32 {
        self.0.group.height()
    }

    /// Get current width
    pub fn width(&self) -> i32 {
        self.0.group.width()
    }

    /// Get current x position
    pub fn x(&self) -> i32 {
        self.0.group.x()
    }

    /// Get current y position
    pub fn y(&self) -> i32 {
        self.0.group.y()
    }

    // ==================== Search Methods ====================

    /// Perform a case-insensitive search for the given term
    pub fn search(&mut self, term: &str) -> usize {
        self.0.display.borrow_mut().search(term)
    }

    /// Clear the search state
    pub fn clear_search(&mut self) {
        self.0.display.borrow_mut().clear_search();
    }

    /// Get all search matches
    pub fn search_matches(&self) -> Vec<SearchMatch> {
        self.0.display.borrow().search_matches().to_vec()
    }

    /// Get the current match index
    pub fn search_current_index(&self) -> Option<usize> {
        self.0.display.borrow().search_current_index()
    }

    /// Move to the next match
    pub fn next_match(&mut self) -> bool {
        self.0.display.borrow_mut().next_match()
    }

    /// Move to the previous match
    pub fn prev_match(&mut self) -> bool {
        self.0.display.borrow_mut().prev_match()
    }

    /// Scroll to make the current match visible
    pub fn scroll_to_current_match(&mut self) {
        let mut ctx = FltkDrawContext::new(true, true);
        self.0
            .display
            .borrow_mut()
            .scroll_to_current_match(&mut ctx);
        self.0.group.redraw();
    }

    /// Focus the editor widget
    pub fn take_focus(&mut self) {
        let _ = self.0.group.take_focus();
    }

    fn apply_edit<F>(&mut self, edit: F) -> bool
    where
        F: FnOnce(&mut Editor) -> rutle::editor::EditResult,
    {
        let result = {
            let mut disp = self.0.display.borrow_mut();
            let editor = disp.editor_mut();
            edit(editor)
        };
        if result.is_ok() {
            self.0.notify_change();
            self.0.emit_paragraph_state();
            true
        } else {
            false
        }
    }
}

/// The web-view [`HighlightTarget`]s for the selection `[start, end]`: one per
/// top-level block or list/checklist item the selection touches, in document
/// order, deduplicated.
///
/// Every leaf between the endpoints (inclusive) maps to its highlight element via
/// [`leaf_element`]; leaves of the same element (a multi-paragraph list item, a
/// multi-child quote) collapse to one entry. A selection ending exactly at the
/// start of a leaf does not include that leaf (nothing of it is selected).
fn selection_targets(
    doc: &Document,
    start: &DocumentPosition,
    end: &DocumentPosition,
) -> Vec<HighlightTarget> {
    let leaves = rutle::tree_walk::enumerate_leaves(doc);
    let li_of = build_li_index(&leaves);

    let mut out = Vec::new();
    let mut seen = HashSet::new();
    for leaf in &leaves {
        if leaf.path < start.path || leaf.path > end.path {
            continue;
        }
        // A selection ending at offset 0 of a leaf stops before it, so that leaf
        // carries no selected content (unless it is also the start leaf).
        if leaf.path == end.path && end.offset == 0 && start.path != end.path {
            continue;
        }
        let target = leaf_element(&li_of, &leaf.path);
        if seen.insert(target.clone()) {
            out.push(target);
        }
    }
    out
}

/// Map each list/checklist marker leaf (the leaf that begins a `<li>`) to that
/// `<li>`'s 0-based document-order index within its top-level block. This is the
/// same ordering tdoc emits `<li>` tags in, so it lines up with the server's
/// k-th-`<li>` marking.
fn build_li_index(leaves: &[LeafInfo]) -> HashMap<TreePath, usize> {
    let mut map = HashMap::new();
    let mut cur_block = None;
    let mut counter = 0;
    for leaf in leaves {
        let block = match leaf.path.segments().first() {
            Some(PathSegment::Paragraph(i)) => *i,
            _ => continue,
        };
        if cur_block != Some(block) {
            cur_block = Some(block);
            counter = 0;
        }
        if leaf.marker.is_some() {
            map.insert(leaf.path.clone(), counter);
            counter += 1;
        }
    }
    map
}

/// The highlight element a leaf at `path` belongs to: its top-level block, plus
/// the enclosing `<li>` index when the leaf is inside a list/checklist (a
/// continuation paragraph maps back to its item's marker leaf).
fn leaf_element(li_of: &HashMap<TreePath, usize>, path: &TreePath) -> HighlightTarget {
    let block = match path.segments().first() {
        Some(PathSegment::Paragraph(i)) => *i,
        _ => 0,
    };
    let li = enclosing_li_path(path).and_then(|p| li_of.get(&p).copied());
    HighlightTarget { block, li }
}

/// The path of the marker leaf for the `<li>` enclosing `path`, or `None` when
/// `path` is not inside a list/checklist. Found by truncating at the last
/// list/checklist segment; a list entry's continuation paragraph is folded back
/// to that entry's first paragraph (`para: 0`), which is the marker leaf.
fn enclosing_li_path(path: &TreePath) -> Option<TreePath> {
    let segs = path.segments();
    let last_item = segs.iter().rposition(|s| {
        matches!(
            s,
            PathSegment::ListEntry { .. } | PathSegment::ChecklistItem(_)
        )
    })?;
    let mut li_segs = segs[..=last_item].to_vec();
    if let Some(PathSegment::ListEntry { entry, .. }) = li_segs.last() {
        let entry = *entry;
        *li_segs.last_mut().unwrap() = PathSegment::ListEntry { entry, para: 0 };
    }
    Some(TreePath(li_segs))
}

/// Map each top-level heading to its unique anchor slug, in document order.
///
/// Uses rutle's tree helpers so link resolution stays in lockstep with how the
/// editor classifies blocks, and delegates slug/duplicate handling to
/// [`crate::section_link`] so generation and resolution share one algorithm.
fn heading_anchor_map(doc: &tdoc::Document) -> Vec<(usize, String)> {
    let mut indices = Vec::new();
    let mut texts = Vec::new();
    for i in 0..doc.paragraphs.len() {
        let path = TreePath::root(i);
        if matches!(
            rutle::tree_walk::effective_block_type(doc, &path),
            BlockType::Heading { .. }
        ) {
            texts.push(rutle::tree_walk::leaf_plain_text(doc, &path));
            indices.push(i);
        }
    }
    indices
        .into_iter()
        .zip(crate::section_link::heading_anchors(&texts))
        .collect()
}

impl ContentProvider for StructuredRichUI {
    fn get_content(&self) -> String {
        let disp = self.0.display.borrow();
        document_to_markdown(disp.editor().document())
    }
}

impl ContentLoader for StructuredRichUI {
    fn set_content_from_markdown(&mut self, markdown: &str) {
        let mut disp = self.0.display.borrow_mut();
        // Loading a different note starts a fresh undo history (set_document resets it).
        let mut doc = crate::markdown_converter::markdown_to_document(markdown);
        // A brand-new note loads as an empty document (no paragraphs). rutle's
        // block-level commands (headings, lists, quotes) act on existing leaves,
        // so with nothing to convert the first Cmd-Alt-1 would silently no-op
        // until a character was typed and deleted. Seed one empty paragraph so
        // formatting works immediately; document_to_markdown maps a lone empty
        // paragraph back to the empty string, so an untouched new note stays
        // empty on disk.
        if doc.paragraphs.is_empty() {
            doc.add_paragraph(tdoc::Paragraph::new_text());
        }
        disp.editor_mut().set_document(doc);
        disp.set_scroll(0);
        // The hovered link (mouse or caret) belongs to the document we just
        // replaced: keep it and a link at the same position in the new note
        // would render as hovered, and no hover event would fire to correct it.
        disp.set_hovered_link(None);
        drop(disp);
        self.0.emit_paragraph_state();
    }
}

impl NoteUI for StructuredRichUI {
    fn on_change(&mut self, f: Box<dyn FnMut() + 'static>) {
        self.0.set_change_callback(Some(f));
    }

    fn set_readonly(&mut self, readonly: bool) {
        self.0.display.borrow_mut().set_cursor_visible(!readonly);
    }

    fn is_readonly(&self) -> bool {
        !self.0.display.borrow().cursor_visible()
    }

    fn scroll_pos(&self) -> i32 {
        self.0.display.borrow().scroll_offset()
    }

    fn set_scroll_pos(&mut self, pos: i32) {
        self.0.display.borrow_mut().set_scroll(pos.max(0));
    }

    fn cursor_pos(&self) -> Option<DocumentPosition> {
        Some(self.0.display.borrow().editor().cursor())
    }

    fn set_cursor_pos(&mut self, pos: DocumentPosition) {
        // `set_cursor` clamps to the current document, so a position remembered
        // against slightly stale content is corrected rather than rejected. It
        // does not move the viewport — the scroll offset is restored separately.
        self.0.display.borrow_mut().editor_mut().set_cursor(pos);
    }

    fn set_bg_color(&mut self, color: Color) {
        self.0.group.set_color(color);
    }

    fn set_resizable(&self, wind: &mut window::Window) {
        wind.resizable(&self.0.group);
    }

    fn on_link_click(&mut self, f: Box<dyn Fn(String) + 'static>) {
        self.0.set_link_callback(Some(f));
    }

    fn tick(&mut self, ms_since_start: u64) {
        self.0.tick(ms_since_start);
    }

    fn on_link_hover(&mut self, f: Box<dyn Fn(Option<String>) + 'static>) {
        self.0.set_link_hover_callback(Some(f));
    }

    fn on_paragraph_style_change(&mut self, f: Box<dyn FnMut(BlockType) + 'static>) {
        self.0.set_paragraph_callback(Some(f));
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn hide(&mut self) {
        self.0.group.hide();
    }

    fn take_focus(&mut self) {
        let _ = self.0.group.take_focus();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The highlight element a single leaf maps to (block + enclosing `<li>`).
    fn target_at(doc: &Document, path: &TreePath) -> HighlightTarget {
        let leaves = rutle::tree_walk::enumerate_leaves(doc);
        leaf_element(&build_li_index(&leaves), path)
    }

    /// Highlight targets for every marker-bearing (list/checklist) leaf of a
    /// block, in document order — the order that lines up with the emitted
    /// `<li>` tags. Keyed nowhere; the caller asserts on the sequence.
    fn item_targets(doc: &Document, block: usize) -> Vec<HighlightTarget> {
        rutle::tree_walk::enumerate_leaves(doc)
            .iter()
            .filter(|l| {
                l.marker.is_some()
                    && l.path.segments().first() == Some(&PathSegment::Paragraph(block))
            })
            .map(|l| target_at(doc, &l.path))
            .collect()
    }

    #[test]
    fn highlight_target_uses_block_for_non_list_leaves() {
        let md = "# Title\n\nA paragraph\n";
        let doc = crate::markdown_converter::markdown_to_document(md);
        let leaves = rutle::tree_walk::enumerate_leaves(&doc);
        // Heading → block 0, whole block; paragraph → block 1, whole block.
        assert_eq!(
            target_at(&doc, &leaves[0].path),
            HighlightTarget { block: 0, li: None }
        );
        assert_eq!(
            target_at(&doc, &leaves[1].path),
            HighlightTarget { block: 1, li: None }
        );
    }

    #[test]
    fn highlight_target_indexes_flat_list_items() {
        let md = "intro\n\n- one\n- two\n- three\n";
        let doc = crate::markdown_converter::markdown_to_document(md);
        // Block 1 is the list; its three items get li 0, 1, 2.
        assert_eq!(
            item_targets(&doc, 1),
            vec![
                HighlightTarget {
                    block: 1,
                    li: Some(0)
                },
                HighlightTarget {
                    block: 1,
                    li: Some(1)
                },
                HighlightTarget {
                    block: 1,
                    li: Some(2)
                },
            ]
        );
    }

    #[test]
    fn highlight_target_indexes_nested_list_items_in_document_order() {
        // a, (nested) b, c, d — the same order tdoc emits the four `<li>` tags.
        let md = "- a\n  - b\n  - c\n- d\n";
        let doc = crate::markdown_converter::markdown_to_document(md);
        assert_eq!(
            item_targets(&doc, 0),
            vec![
                HighlightTarget {
                    block: 0,
                    li: Some(0)
                },
                HighlightTarget {
                    block: 0,
                    li: Some(1)
                },
                HighlightTarget {
                    block: 0,
                    li: Some(2)
                },
                HighlightTarget {
                    block: 0,
                    li: Some(3)
                },
            ]
        );
    }

    #[test]
    fn highlight_target_indexes_checklist_items() {
        let md = "- [ ] x\n- [x] y\n";
        let doc = crate::markdown_converter::markdown_to_document(md);
        assert_eq!(
            item_targets(&doc, 0),
            vec![
                HighlightTarget {
                    block: 0,
                    li: Some(0)
                },
                HighlightTarget {
                    block: 0,
                    li: Some(1)
                },
            ]
        );
    }

    #[test]
    fn selection_spanning_paragraphs_yields_one_target_each() {
        let md = "# Title\n\nfirst\n\nsecond\n\nthird\n";
        let doc = crate::markdown_converter::markdown_to_document(md);
        let leaves = rutle::tree_walk::enumerate_leaves(&doc);
        // From "first" (block 1) to inside "third" (block 3): blocks 1, 2, 3.
        let start = DocumentPosition::at(leaves[1].path.clone(), 0);
        let end = DocumentPosition::at(leaves[3].path.clone(), 1);
        assert_eq!(
            selection_targets(&doc, &start, &end),
            vec![
                HighlightTarget { block: 1, li: None },
                HighlightTarget { block: 2, li: None },
                HighlightTarget { block: 3, li: None },
            ]
        );
    }

    #[test]
    fn selection_spanning_list_items_yields_each_item() {
        let md = "- one\n- two\n- three\n";
        let doc = crate::markdown_converter::markdown_to_document(md);
        let leaves = rutle::tree_walk::enumerate_leaves(&doc);
        // From item 0 into item 1: two adjacent `<li>` targets.
        let start = DocumentPosition::at(leaves[0].path.clone(), 0);
        let end = DocumentPosition::at(leaves[1].path.clone(), 1);
        assert_eq!(
            selection_targets(&doc, &start, &end),
            vec![
                HighlightTarget {
                    block: 0,
                    li: Some(0)
                },
                HighlightTarget {
                    block: 0,
                    li: Some(1)
                },
            ]
        );
    }

    #[test]
    fn selection_from_paragraph_into_a_list() {
        let md = "intro\n\n- one\n- two\n";
        let doc = crate::markdown_converter::markdown_to_document(md);
        let leaves = rutle::tree_walk::enumerate_leaves(&doc);
        // "intro" (whole block) then the first list item.
        let start = DocumentPosition::at(leaves[0].path.clone(), 0);
        let end = DocumentPosition::at(leaves[1].path.clone(), 1);
        assert_eq!(
            selection_targets(&doc, &start, &end),
            vec![
                HighlightTarget { block: 0, li: None },
                HighlightTarget {
                    block: 1,
                    li: Some(0)
                },
            ]
        );
    }

    #[test]
    fn selection_ending_at_a_block_start_excludes_it() {
        let md = "one\n\ntwo\n\nthree\n";
        let doc = crate::markdown_converter::markdown_to_document(md);
        let leaves = rutle::tree_walk::enumerate_leaves(&doc);
        // Drag from "one" and release at the very start of "three": "three" has
        // nothing selected, so only blocks 0 and 1 are highlighted.
        let start = DocumentPosition::at(leaves[0].path.clone(), 0);
        let end = DocumentPosition::at(leaves[2].path.clone(), 0);
        assert_eq!(
            selection_targets(&doc, &start, &end),
            vec![
                HighlightTarget { block: 0, li: None },
                HighlightTarget { block: 1, li: None },
            ]
        );
    }

    #[test]
    fn heading_anchor_map_slugs_and_dedup() {
        // Top-level headings (in tdoc `#`/`##`/`###` are all top-level blocks),
        // interleaved with a paragraph and with duplicate heading texts.
        let md = "# Overview\n\nsome text\n\n## Details\n\n## Details\n\n# Overview\n";
        let doc = crate::markdown_converter::markdown_to_document(md);

        let map = heading_anchor_map(&doc);
        let slugs: Vec<&str> = map.iter().map(|(_, s)| s.as_str()).collect();
        assert_eq!(slugs, ["overview", "details", "details-1", "overview-1"]);

        // Every returned index really points at a heading block.
        for (idx, _) in &map {
            assert!(matches!(
                rutle::tree_walk::effective_block_type(&doc, &TreePath::root(*idx)),
                BlockType::Heading { .. }
            ));
        }
    }

    /// A brand-new note has no paragraphs, so rutle's block-level commands have
    /// no leaf to convert: `set_block_type` is a silent no-op. This is the bug
    /// the seeded empty paragraph in `set_content_from_markdown` fixes.
    #[test]
    fn block_type_is_a_no_op_on_an_empty_document() {
        let mut editor = Editor::with_tdoc(tdoc::Document::new());
        let _ = editor.set_block_type(BlockType::Heading { level: 1 });
        assert_eq!(editor.current_block_type(), BlockType::Paragraph);
    }

    /// With the seeded empty paragraph a fresh note carries a leaf, so the very
    /// first Cmd-Alt-1 converts it to a heading without needing a keystroke.
    #[test]
    fn seeded_empty_paragraph_accepts_a_heading() {
        let mut doc = tdoc::Document::new();
        assert!(doc.paragraphs.is_empty());
        doc.add_paragraph(tdoc::Paragraph::new_text());

        let mut editor = Editor::with_tdoc(doc);
        assert!(
            editor
                .set_block_type(BlockType::Heading { level: 1 })
                .is_ok()
        );
        assert_eq!(editor.current_block_type(), BlockType::Heading { level: 1 });
    }
}