rucola-notes 0.9.0

Terminal-based markdown note manager.
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
use crate::{data, ui};
use rand::seq::SliceRandom;
use ratatui::{prelude::*, widgets::*};
use std::collections::HashMap;

/// A struct describing statistics to a note in relation to a containing environment.
#[derive(Debug, Clone)]
pub struct NoteEnvStatistics {
    /// The notes id
    pub id: String,
    /// The fuzzy match score of this note with the filter used to create the environment
    match_score: i64,
    /// The amount of links pointing to this note from anywhere.
    inlinks_global: usize,
    /// The amount of links pointing to this note from other notes within the environment.
    inlinks_local: usize,
    /// The amount of links going out from this note to other notes within the environment.
    outlinks_local: usize,
    /// The amount of links going out from this note to other notes.
    /// Differs from the length of the 'links' table by not counting broken links.
    outlinks_global: usize,
    /// The amount of links originating from this note that do not have a valid target anywhere.
    broken_links: usize,
}

impl NoteEnvStatistics {
    /// Creates a new instance of NoteEnvStatistics with only the two passed fields filled out.
    fn new_empty(id: String, match_score: i64) -> Self {
        Self {
            id,
            match_score,
            inlinks_global: 0,
            inlinks_local: 0,
            outlinks_local: 0,
            outlinks_global: 0,
            broken_links: 0,
        }
    }

    /// Extracts a certain data point (given by the entry) from this NoteEnvStatistics and returns a formatted string of the specified length (or possibly longer) that contains it.
    /// The actual lenght will later be capped by the width of the column ratatui renders this in.
    fn to_data_string(
        &self,
        index: data::NoteIndexContainer,
        note_entry: NoteColumn,
        min_width: usize,
    ) -> String {
        index
            .borrow()
            .get(&self.id)
            .map(|note| match note_entry {
                NoteColumn::Shuffle => " ".repeat(min_width),
                NoteColumn::Name => note.display_name.clone(),
                NoteColumn::Words => format!("{:min_width$}", note.words),
                NoteColumn::Chars => format!("{:min_width$}", note.characters),
                NoteColumn::GlobalOutLinks => format!("{:min_width$}", self.outlinks_global),
                NoteColumn::LocalOutLinks => format!("{:min_width$}", self.outlinks_local),
                NoteColumn::GlobalInLinks => format!("{:min_width$}", self.inlinks_global),
                NoteColumn::LocalInLinks => format!("{:min_width$}", self.inlinks_local),
                NoteColumn::Score => format!("{:min_width$}", self.match_score),
                NoteColumn::Broken => format!("{:min_width$}", self.broken_links),
                NoteColumn::LastModified => format!(
                    "{:min_width$}",
                    note.last_modification
                        .map(
                            |dt| std::convert::Into::<chrono::DateTime<chrono::Local>>::into(dt)
                                .format("%Y-%m-%d %H:%M")
                                .to_string()
                        )
                        .unwrap_or_default()
                ),
            })
            .unwrap_or_default()
    }
}

/// Describes a column of the note table. Can be used to sort by it on in the config to specify which columns to show.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum NoteColumn {
    Shuffle,
    Name,
    Words,
    Chars,
    GlobalOutLinks,
    LocalOutLinks,
    GlobalInLinks,
    LocalInLinks,
    Score,
    Broken,
    LastModified,
}

impl NoteColumn {
    /// Given a title for a column containing data of this type, returns a ratatui constraint to specify that columns width.
    pub fn to_width(self, title: &str) -> Constraint {
        let l = title.len() as u16;
        match self {
            NoteColumn::Name => Constraint::Min(25.max(l)),
            NoteColumn::Shuffle
            | NoteColumn::Words
            | NoteColumn::Chars
            | NoteColumn::GlobalOutLinks
            | NoteColumn::LocalOutLinks
            | NoteColumn::GlobalInLinks
            | NoteColumn::LocalInLinks
            | NoteColumn::Score
            | NoteColumn::Broken
            | NoteColumn::LastModified => Constraint::Length(l),
        }
    }

    /// Takes an aspiring title to a column of this type and converts it a line, where the title is split in such a way that the first appearance of the sorting hotkey is highlighted (if possible)
    pub fn title_line(self, title: &str, normal_style: Style, hotkey_style: Style) -> Line<'_> {
        let key = match self {
            NoteColumn::Shuffle => 'S',
            NoteColumn::Name => 'A',
            NoteColumn::Words => 'W',
            NoteColumn::Chars => 'C',
            NoteColumn::GlobalOutLinks => 'O',
            NoteColumn::LocalOutLinks => 'U',
            NoteColumn::GlobalInLinks => 'I',
            NoteColumn::LocalInLinks => 'N',
            NoteColumn::Broken => 'B',
            NoteColumn::LastModified => 'M',
            NoteColumn::Score => 'E',
        };
        let occ = title.find([key, key.to_ascii_lowercase()]);
        Line::from(if let Some(occ) = occ {
            vec![
                Span::styled(title.split_at(occ).0, normal_style),
                Span::styled(&title[occ..occ + 1], hotkey_style),
                Span::styled(title.split_at(occ + 1).1, normal_style),
            ]
        } else {
            vec![Span::styled(title, normal_style)]
        })
    }
}

/// A data struct containing statistical information about a (subset of a) user's notes.
/// This subset is called an 'environment' and is described by a filter passed to the constructor.
#[derive(Debug, Clone)]
pub struct EnvironmentStats {
    /// The total amount of words in the notes in this environment.
    /// What is a word and what not mirrors the definition from Note.words.
    word_count_total: usize,
    /// The total amount of characters, including whitespace, in the notes of this environment.
    char_count_total: usize,
    /// The total amount of notes in this environment.
    note_count_total: usize,
    /// The total amount of _unique_ tags in this environment.
    tag_count_total: usize,
    /// Total amount of links from a note within the environment to another note within the environment.
    local_local_links: usize,
    /// Total amount of links from a note within the environment to any note.
    local_global_links: usize,
    /// Total amount of links from any note to a note within the environment.
    global_local_links: usize,
    /// A vector of all notes within the environment.
    filtered_stats: Vec<NoteEnvStatistics>,
    /// Counts how many links among notes within the environment do not have a valid target anywhere.
    broken_links: usize,
}

impl EnvironmentStats {
    /// Creates a new set of statistics from the subset of the passed index that matches the given filter.
    pub fn new_with_filter(index: &super::NoteIndexContainer, filter: data::Filter) -> Self {
        let index = index.borrow();

        // Filter the index -> Create an iterator
        let mut filtered_index = index
            .inner
            .iter()
            .filter_map(|(id, note)| {
                filter.apply(note, &index).map(|score| {
                    (
                        id.clone(),
                        (NoteEnvStatistics::new_empty(id.clone(), score), note),
                    )
                })
            })
            .collect::<HashMap<_, _>>();

        // Count links by iterating over unfiltered index
        for (id, note) in index.inner.iter() {
            // Remember if source is from within the environment.
            let local_source = filtered_index.contains_key(id);
            // Keep track of found local targets.
            let mut local_targets = 0;
            // Keep track of found targets.
            let mut global_targets = 0;

            // Then go over its links.
            for link in &note.links {
                // Check if target exists
                if index.inner.contains_key(link) {
                    // and increase count of valid targets if so.
                    global_targets += 1;

                    // Now check if target is local.
                    if let Some((target, _)) = filtered_index.get_mut(link) {
                        // Always count up global inlink count of target.
                        target.inlinks_global += 1;
                        // If id of source is also in filtered index, also count up local inlink count of target.
                        if local_source {
                            target.inlinks_local += 1;
                        }
                        // Since this target was in the environment, increment the counter.
                        local_targets += 1;
                    }
                }
            }
            // If source was local, we are interested in its stats.
            // Add the found local/global targets to the statistics (this could be an assignment).
            if let Some((source, _)) = filtered_index.get_mut(id) {
                source.outlinks_local += local_targets;
                source.outlinks_global += global_targets;
                source.broken_links = note.links.len() - global_targets;
            }
        }

        Self {
            // Word count: Just map over the stats.
            word_count_total: filtered_index.values().map(|(_, stats)| stats.words).sum(),
            // Char count: Just map over the stats
            char_count_total: filtered_index
                .values()
                .map(|(_, stats)| stats.characters)
                .sum(),
            // Total notes: Just the length of the filtered index.
            note_count_total: filtered_index.len(),
            // Total tags: Collect all tag vectors of notes into a HashSet, then take its length.
            tag_count_total: filtered_index
                .values()
                .flat_map(|(_, stats)| &stats.tags)
                .collect::<std::collections::HashSet<_>>()
                .len(),
            // Local-Local links: Check outgoing local links of all notes. Could also check incoming local links of all notes.
            local_local_links: filtered_index
                .values()
                .map(|(env_stats, _)| env_stats.outlinks_local)
                .sum(),
            // Local-Global links: Check outgoing global links of all notes.
            local_global_links: filtered_index
                .values()
                .map(|(env_stats, _)| env_stats.outlinks_global)
                .sum(),
            // Global-Local Links: Check incoming links of all notes.
            global_local_links: filtered_index
                .values()
                .map(|(env_stats, _)| env_stats.inlinks_global)
                .sum(),
            // Broken links: Again, just sum it up.
            broken_links: filtered_index
                .values()
                .map(|(env_stats, _)| env_stats.broken_links)
                .sum(),
            // Finally, reduce the vector to just the env stats
            filtered_stats: {
                let mut fs = filtered_index
                    .into_values()
                    .map(|(env_stats, _)| env_stats)
                    .collect::<Vec<_>>();

                // Default sort: By match score, descending.
                fs.sort_by_cached_key(|env_stats| env_stats.match_score);
                fs.reverse();

                fs
            },
        }
    }

    /// Returns the nth element of the underlying sorted vector
    pub fn get_selected(&self, index: usize) -> Option<&NoteEnvStatistics> {
        self.filtered_stats.get(index)
    }

    /// Reverses the underlying vec
    pub fn reverse_order(&mut self) {
        self.filtered_stats.reverse();
    }

    /// Sorts the underlying vec
    pub fn sort(&mut self, index: data::NoteIndexContainer, mode: NoteColumn, ascending: bool) {
        // Always sort by name first
        self.filtered_stats
            .sort_by_cached_key(|env_stats| env_stats.id.clone());

        // If the column to sort by is not name or shuffle, now sort by the actual column.
        if mode != NoteColumn::Name && mode != NoteColumn::Shuffle {
            // If sorting in reverse is desired, pre-reverse this, so when reversing again later, the list will still be sub-sorted by name ascendingly.
            if !ascending {
                self.filtered_stats.reverse();
            }
            // all others are usize and can be done in one thing
            self.filtered_stats.sort_by_cached_key(|env_stats| {
                if let Some(note) = index.borrow().get(&env_stats.id) {
                    match mode {
                        // This should not appear
                        NoteColumn::Shuffle | NoteColumn::Name => 0,
                        // These should appear
                        NoteColumn::Words => note.words,
                        NoteColumn::Chars => note.characters,
                        NoteColumn::GlobalOutLinks => env_stats.outlinks_global,
                        NoteColumn::LocalOutLinks => env_stats.outlinks_local,
                        NoteColumn::GlobalInLinks => env_stats.inlinks_global,
                        NoteColumn::LocalInLinks => env_stats.inlinks_local,
                        NoteColumn::Score => env_stats.match_score as usize,
                        NoteColumn::Broken => env_stats.broken_links,
                        NoteColumn::LastModified => {
                            // Get the file's modification time as seconds since epoch
                            note.last_modification
                                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                                .map(|d| d.as_secs() as usize)
                                // If no time since modification can be determined, use a value that will put this note at the end of the sorted list.
                                .unwrap_or(if ascending { usize::MAX } else { usize::MIN })
                        }
                    }
                } else {
                    0
                }
            })
        // if the column is shuffle, then shuffle the list
        } else if mode == NoteColumn::Shuffle {
            self.filtered_stats.shuffle(&mut rand::rng());
        }

        // Potentially reverse sorting
        if !ascending {
            self.filtered_stats.reverse();
        }
    }

    /// Returns the amount of notes in this environment.
    pub fn len(&self) -> usize {
        self.filtered_stats.len()
    }

    /// Converts this environment to a table of rows with the (sorted) notes contained in it.
    pub fn to_note_table(
        &self,
        index: data::NoteIndexContainer,
        styles: &ui::UiStyles,
        column_config: &[(String, NoteColumn)],
    ) -> Table<'_> {
        // Calculate widths
        let notes_table_widths = column_config
            .iter()
            .map(|(title, mode)| mode.to_width(title));

        // Construct rows
        let notes_rows = self
            .filtered_stats
            .iter()
            .map(|note_env| {
                Row::new(column_config.iter().map(|(title, mode)| {
                    note_env.to_data_string(index.clone(), *mode, title.len())
                }))
                .style(styles.text_style)
            })
            .collect::<Vec<Row>>();

        Table::new(notes_rows, notes_table_widths).column_spacing(1)
    }

    /// Converts this environment statistics struct to a ratatui table with the basic, global stats.
    pub fn to_global_stats_table(&self, styles: &ui::UiStyles) -> Table<'_> {
        // Horizontal layout
        let stats_widths = [
            Constraint::Length(20),
            Constraint::Length(16),
            Constraint::Length(20),
            Constraint::Length(16),
            Constraint::Min(0),
        ];

        //  === Global stats ===

        let global_stats_rows = [
            Row::new(vec![
                Cell::from("Total notes:").style(styles.text_style),
                Cell::from(format!("{:7}", self.note_count_total)).style(styles.text_style),
                Cell::from("Total words:").style(styles.text_style),
                Cell::from(format!("{:7}", self.word_count_total)).style(styles.text_style),
            ]),
            Row::new(vec![
                Cell::from("Total unique tags:").style(styles.text_style),
                Cell::from(format!("{:7}", self.tag_count_total)).style(styles.text_style),
                Cell::from("Total characters:").style(styles.text_style),
                Cell::from(format!("{:7}", self.char_count_total)).style(styles.text_style),
            ]),
            Row::new(vec![
                Cell::from("Total links:").style(styles.text_style),
                Cell::from(format!("{:7}", self.local_local_links)).style(styles.text_style),
                Cell::from("Broken links:").style(styles.text_style),
                Cell::from(format!("{:7}", self.broken_links)).style(styles.text_style),
            ]),
        ];

        Table::new(global_stats_rows, stats_widths).column_spacing(1)
    }

    /// Converts this environment statistics struct to a ratatui table with the full, local stats.
    pub fn to_local_stats_table(&self, global: &Self, styles: &ui::UiStyles) -> Table<'_> {
        // Horizontal layout
        let stats_widths = [
            Constraint::Length(20),
            Constraint::Length(16),
            Constraint::Length(20),
            Constraint::Length(16),
            Constraint::Min(0),
        ];

        //  === Local stats ===
        let local_stats_rows = [
            Row::new(vec![
                Cell::from("Total notes:").style(styles.text_style),
                Cell::from(format!(
                    "{:7} ({:3}%)",
                    self.note_count_total,
                    self.note_count_total * 100 / global.note_count_total.max(1)
                ))
                .style(styles.text_style),
                Cell::from("Total words:").style(styles.text_style),
                Cell::from(format!(
                    "{:7} ({:3}%)",
                    self.word_count_total,
                    self.word_count_total * 100 / global.word_count_total.max(1)
                ))
                .style(styles.text_style),
            ]),
            Row::new(vec![
                Cell::from("Total unique tags:").style(styles.text_style),
                Cell::from(format!(
                    "{:7} ({:3}%)",
                    self.tag_count_total,
                    self.tag_count_total * 100 / global.tag_count_total.max(1)
                ))
                .style(styles.text_style),
                Cell::from("Total characters:").style(styles.text_style),
                Cell::from(format!(
                    "{:7} ({:3}%)",
                    self.char_count_total,
                    self.char_count_total * 100 / global.char_count_total.max(1)
                ))
                .style(styles.text_style),
            ]),
            Row::new(vec![
                Cell::from("Incoming links:").style(styles.text_style),
                Cell::from(format!(
                    "{:7} ({:3}%)",
                    self.global_local_links,
                    self.global_local_links * 100 / global.local_local_links.max(1),
                ))
                .style(styles.text_style),
                Cell::from("Outgoing links:").style(styles.text_style),
                Cell::from(format!(
                    "{:7} ({:3}%)",
                    self.local_global_links,
                    self.local_global_links * 100 / global.local_local_links.max(1),
                ))
                .style(styles.text_style),
            ]),
            Row::new(vec![
                Cell::from("Internal links:").style(styles.text_style),
                Cell::from(format!(
                    "{:7} ({:3}%)",
                    self.local_local_links,
                    self.local_local_links * 100 / global.local_local_links.max(1),
                ))
                .style(styles.text_style),
                Cell::from("Broken links:").style(styles.text_style),
                Cell::from(format!(
                    "{:7} ({:3}%)",
                    self.broken_links,
                    self.broken_links * 100 / global.broken_links.max(1)
                ))
                .style(styles.text_style),
            ]),
        ];

        Table::new(local_stats_rows, stats_widths).column_spacing(1)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{data, io};
    use pretty_assertions::assert_eq;

    #[test]
    fn test_env_stats_1_tags_any() {
        let config = crate::Config {
            vault_path: Some(std::env::current_dir().unwrap().join("tests")),
            ..Default::default()
        };
        let tracker = io::FileTracker::new(&config).unwrap();
        let builder = io::HtmlBuilder::new(&config);
        let index = data::NoteIndex::new(tracker, builder, &config).0;

        assert_eq!(index.inner.len(), 12);

        let index = std::rc::Rc::new(std::cell::RefCell::new(index));

        // === Filter 1 ===

        let filter1 = data::Filter {
            any: true,
            tag_match: data::TagMatch::Exact,
            tags: vec![
                ("#topology".to_string(), true),
                ("#diffgeo".to_string(), true),
            ],
            links: vec![],
            blinks: vec![],
            title: String::new(),
            full_text: None,
        };

        let env1 = EnvironmentStats::new_with_filter(&index, filter1);

        assert_eq!(env1.note_count_total, 5);
        assert_eq!(env1.tag_count_total, 3);
        assert_eq!(env1.local_local_links, 10);
        assert_eq!(env1.local_global_links, 11);
        assert_eq!(env1.global_local_links, 13);
        assert_eq!(env1.broken_links, 1);
    }

    #[test]
    fn test_env_stats_2_tags_all() {
        let config = crate::Config {
            vault_path: Some(std::env::current_dir().unwrap().join("tests")),
            ..Default::default()
        };
        let tracker = io::FileTracker::new(&config).unwrap();
        let builder = io::HtmlBuilder::new(&config);
        let index = data::NoteIndex::new(tracker, builder, &config).0;

        assert_eq!(index.inner.len(), 12);

        let index = std::rc::Rc::new(std::cell::RefCell::new(index));
        // === Filter 2 ===

        let filter2 = data::Filter {
            any: false,
            tag_match: data::TagMatch::Exact,
            tags: vec![
                ("#topology".to_string(), true),
                ("#diffgeo".to_string(), true),
            ],
            links: vec![],
            blinks: vec![],
            title: String::new(),
            full_text: None,
        };
        let env2 = EnvironmentStats::new_with_filter(&index, filter2);

        assert_eq!(env2.note_count_total, 2);
        assert_eq!(env2.tag_count_total, 2);
        assert_eq!(env2.local_local_links, 1);
        assert_eq!(env2.local_global_links, 5);
        assert_eq!(env2.global_local_links, 6);
        assert_eq!(env2.broken_links, 1);

        env2.filtered_stats
            .iter()
            .filter(|env_stats| env_stats.id == "manifold")
            .for_each(|ma| {
                assert_eq!(ma.inlinks_global, 5);
                assert_eq!(ma.inlinks_local, 1);
                assert_eq!(ma.outlinks_local, 0);
                assert_eq!(ma.outlinks_global, 4);
                assert_eq!(ma.broken_links, 0);
            });
    }

    #[test]
    fn test_env_stats_3_title() {
        let config = crate::Config {
            vault_path: Some(std::env::current_dir().unwrap().join("tests")),
            ..Default::default()
        };
        let tracker = io::FileTracker::new(&config).unwrap();
        let builder = io::HtmlBuilder::new(&config);
        let index = data::NoteIndex::new(tracker, builder, &config).0;

        assert_eq!(index.inner.len(), 12);

        let index = std::rc::Rc::new(std::cell::RefCell::new(index));

        // === Filter 3 ===

        let filter3 = data::Filter {
            any: false,
            tag_match: data::TagMatch::Exact,
            tags: vec![],
            links: vec![],
            blinks: vec![],
            title: "operating".to_string(),
            full_text: None,
        };
        let env3 = EnvironmentStats::new_with_filter(&index, filter3);

        assert_eq!(env3.note_count_total, 1);
        assert_eq!(env3.tag_count_total, 1);
        assert_eq!(env3.local_local_links, 0);
        assert_eq!(env3.local_global_links, 6);
        assert_eq!(env3.global_local_links, 0);
        assert_eq!(env3.broken_links, 0);
    }

    #[test]
    fn test_env_stats_4_blinks() {
        let config = crate::Config {
            vault_path: Some(std::env::current_dir().unwrap().join("tests")),
            ..Default::default()
        };
        let tracker = io::FileTracker::new(&config).unwrap();
        let builder = io::HtmlBuilder::new(&config);
        let index = data::NoteIndex::new(tracker, builder, &config).0;

        assert_eq!(index.inner.len(), 12);

        let index = std::rc::Rc::new(std::cell::RefCell::new(index));

        // === Filter 4 ===

        let filter4 = data::Filter {
            any: true,
            tag_match: data::TagMatch::Exact,
            tags: vec![],
            links: vec![],
            blinks: vec![("atlas".to_string(), true)],
            title: String::new(),
            full_text: None,
        };
        let env4 = EnvironmentStats::new_with_filter(&index, filter4);

        assert_eq!(env4.note_count_total, 3);
        assert_eq!(env4.tag_count_total, 2);
        assert_eq!(env4.local_local_links, 2);
        assert_eq!(env4.local_global_links, 5);
        assert_eq!(env4.global_local_links, 9);
        assert_eq!(env4.broken_links, 1);
    }

    #[test]
    fn test_env_stats_5_links_blinks() {
        let config = crate::Config {
            vault_path: Some(std::env::current_dir().unwrap().join("tests")),
            ..Default::default()
        };
        let tracker = io::FileTracker::new(&config).unwrap();
        let builder = io::HtmlBuilder::new(&config);
        let index = data::NoteIndex::new(tracker, builder, &config).0;

        assert_eq!(index.inner.len(), 12);

        let index = std::rc::Rc::new(std::cell::RefCell::new(index));

        // === Filter 5 ===

        let filter5 = data::Filter {
            any: true,
            tag_match: data::TagMatch::Exact,
            tags: vec![],
            links: vec![("smooth-map".to_string(), true)],
            blinks: vec![("atlas".to_string(), true)],
            title: String::new(),
            full_text: None,
        };
        let env5 = EnvironmentStats::new_with_filter(&index, filter5);

        assert_eq!(env5.note_count_total, 4);
        assert_eq!(env5.tag_count_total, 3);
        assert_eq!(env5.local_local_links, 5);
        assert_eq!(env5.local_global_links, 8);
        assert_eq!(env5.global_local_links, 10);
        assert_eq!(env5.broken_links, 1);
    }
}