mirador 1.22.2

An opinionated personal dashboard for your terminal: world clocks, a calendar, weather, tasks, notes, a market watchlist, and live CPU and network graphs.
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
//! Free-form notes and their persisted store.
//!
//! A note is deliberately thinner than a task: a title, a body, and the dates
//! it was written and last touched. There is no due date, no priority and no
//! done flag, because a note is not work to be tracked — it is something you
//! wrote down so you would not have to remember it.
//!
//! Storage mirrors [`crate::task`]: a plain TOML file you can edit by hand or
//! keep in git, written atomically (temp file in the same directory, then
//! rename) so an interrupted save can never truncate the file you already had.

use std::path::{Path, PathBuf};

use anyhow::Result;
use jiff::civil::Date;
use serde::{Deserialize, Serialize};

/// One note.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Note {
    pub id: u64,
    pub title: String,
    /// Free text. Empty is legitimate — a title-only note is a reminder.
    #[serde(default)]
    pub body: String,
    pub created: Date,
    /// Set only once the note has been edited after creation, so the list can
    /// show when something actually changed rather than repeating `created`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub updated: Option<Date>,
}

impl Note {
    pub fn new(id: u64, title: impl Into<String>, today: Date) -> Self {
        Self {
            id,
            title: title.into(),
            body: String::new(),
            created: today,
            updated: None,
        }
    }

    /// The date the list should show: when it last changed, else when it was
    /// written.
    pub fn shown_date(&self) -> Date {
        self.updated.unwrap_or(self.created)
    }

    /// Case-insensitive match against the title *and* the body.
    ///
    /// Searching the body matters more here than it does for tasks: the whole
    /// reason to keep a note is the text inside it, and a title you wrote in a
    /// hurry is often not what you later search for.
    pub fn matches(&self, needle: &str) -> bool {
        let needle = crate::task::Needle::new(needle.trim());
        if needle.is_empty() {
            return true;
        }
        needle.is_in(&self.title) || needle.is_in(&self.body)
    }
}

/// Serialisation wrapper so the file reads as a list of `[[note]]` tables.
///
/// Owned when read and borrowed when written, as the task file's is, so a
/// save does not copy every note to serialise it.
#[derive(Debug, Default, Serialize, Deserialize)]
struct NoteFile<L = Vec<Note>> {
    #[serde(default, rename = "note")]
    notes: L,
}

/// The notes file's header, and what its errors call it.
const FILE: crate::store::TomlFile = crate::store::TomlFile {
    what: "notes",
    header: "# mirador notes. Safe to edit by hand or keep in version control.\n\
             # Fields: id, title, body, created (YYYY-MM-DD), updated.",
};

/// An owned, persisted collection of notes.
#[derive(Debug)]
pub struct NoteStore {
    path: PathBuf,
    notes: Vec<Note>,
    dirty: bool,
    /// High-water mark for ids, which only ever climbs.
    ///
    /// Deriving the next id from `max(id) + 1` would hand a deleted note's id
    /// straight to the next one written, so anything still holding the old id
    /// — a selection, a pending edit — would silently point at a different
    /// note. The mark is rebuilt from the file on load, which is safe: nothing
    /// holds an id across a restart.
    next_id: u64,
    /// The last save error, surfaced in the panel so failures are never silent.
    pub last_error: Option<String>,
}

impl NoteStore {
    /// Load from `path`, treating a missing file as an empty list.
    pub fn load(path: impl Into<PathBuf>) -> Result<Self> {
        let path = path.into();
        let mut notes = FILE
            .read::<NoteFile>(&path)?
            .map(|file| file.notes)
            .unwrap_or_default();

        let mut next_id = notes.iter().map(|n| n.id).max().unwrap_or(0) + 1;
        let dirty =
            crate::task::renumber_repeated_ids(notes.iter_mut().map(|n| &mut n.id), &mut next_id);
        Ok(Self {
            path,
            notes,
            dirty,
            next_id,
            last_error: None,
        })
    }

    /// Load, seeding one example note when there is no file yet.
    ///
    /// Same reasoning as the task list: an empty master-detail panel shows
    /// neither a list nor a body, so first run is the one moment it explains
    /// nothing at all. One note rather than several — the panel's whole point
    /// is that you can read a body without pressing anything, and a single
    /// selected note demonstrates that better than a list to scroll.
    ///
    /// Seeded only when the file is *absent*, so deleting it is permanent.
    pub fn load_or_seed(path: impl Into<PathBuf>, today: Date) -> Result<Self> {
        let path = path.into();
        let first_run = !path.exists();
        let mut store = Self::load(path)?;
        if first_run {
            store.add(example_note(today));
            store.save_reporting();
        }
        Ok(store)
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    pub fn notes(&self) -> &[Note] {
        &self.notes
    }

    /// Append a note and return its id.
    pub fn add(&mut self, mut note: Note) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        note.id = id;
        self.notes.push(note);
        self.dirty = true;
        id
    }

    pub fn get(&self, id: u64) -> Option<&Note> {
        self.notes.iter().find(|n| n.id == id)
    }

    /// Mutate a note in place, stamping `updated` if anything changed.
    ///
    /// The stamp is driven by an actual before/after comparison rather than by
    /// the fact that an editor was opened, so opening a note and pressing Esc
    /// does not make it look like you revised it.
    pub fn with_note<F: FnOnce(&mut Note)>(&mut self, id: u64, today: Date, f: F) -> bool {
        let Some(slot) = self.notes.iter_mut().find(|n| n.id == id) else {
            return false;
        };
        let before = slot.clone();
        f(slot);
        if slot.title != before.title || slot.body != before.body {
            slot.updated = Some(today);
            self.dirty = true;
            return true;
        }
        // Restore in case the closure touched `updated` without changing text.
        slot.updated = before.updated;
        false
    }

    /// Remove by id. Returns whether anything was removed.
    pub fn remove(&mut self, id: u64) -> bool {
        let before = self.notes.len();
        self.notes.retain(|n| n.id != id);
        let removed = self.notes.len() != before;
        self.dirty |= removed;
        removed
    }

    /// Ids in display order: most recently touched first.
    ///
    /// Notes have no priority to sort by, and the one you want is almost always
    /// the one you were last in.
    pub fn view(&self, filter: &str) -> Vec<u64> {
        let mut visible: Vec<&Note> = self.notes.iter().filter(|n| n.matches(filter)).collect();
        visible.sort_by(|a, b| {
            b.shown_date()
                .cmp(&a.shown_date())
                // Ties broken by id descending so a day's notes stay in a
                // stable order instead of shuffling on every redraw.
                .then(b.id.cmp(&a.id))
        });
        visible.iter().map(|n| n.id).collect()
    }

    /// Write to disk atomically if there are pending changes.
    pub fn save(&mut self) -> Result<()> {
        if !self.dirty {
            return Ok(());
        }

        FILE.write(
            &self.path,
            &NoteFile {
                notes: self.notes.as_slice(),
            },
        )?;

        self.dirty = false;
        Ok(())
    }

    /// Save, recording any failure rather than propagating it, so a read-only
    /// disk shows up in the panel instead of vanishing.
    pub fn save_reporting(&mut self) {
        crate::store::report(self.save(), &mut self.last_error);
    }
}

/// The note written on first run. The id is assigned by the store.
fn example_note(today: Date) -> Note {
    Note {
        body: "You are reading it in the detail pane. That is the point of the \
               panel: a note's whole value is the text inside it, so making you \
               press a key to see any of it would turn \"glance at the \
               dashboard\" into \"operate the dashboard\".\n\n\
               a writes a new note and e edits this one. Tab moves between the \
               title and the body, Enter inside the body is an ordinary new \
               line, and Ctrl+S saves. d deletes, and / searches bodies as well \
               as titles — the title you wrote in a hurry is often not what you \
               later search for.\n\n\
               Notes live in a plain TOML file next to your tasks, written \
               atomically, and you can edit it by hand or keep it in git. \
               Delete this one once you have your own."
            .into(),
        ..Note::new(0, "This is a note", today)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::testing::TempDir;

    fn store(name: &str) -> (NoteStore, TempDir) {
        let dir = TempDir::new(&format!("note-{name}"));
        let store = NoteStore::load(dir.join("notes.toml")).unwrap();
        (store, dir)
    }

    fn today() -> Date {
        Date::new(2026, 7, 25).unwrap()
    }

    #[test]
    fn a_first_run_is_seeded_and_an_emptied_file_stays_empty() {
        let dir = TempDir::new("note-seed");
        let path = dir.join("notes.toml");

        let mut s = NoteStore::load_or_seed(&path, jiff::civil::date(2026, 7, 25)).unwrap();
        assert_eq!(s.notes().len(), 1, "first run must show one example note");
        assert_eq!(s.last_error, None, "seeding must not fail silently");
        assert!(
            path.exists(),
            "the seed must be written, not held in memory"
        );
        assert!(
            !s.notes()[0].body.is_empty(),
            "an empty body defeats the point: the detail pane would be blank"
        );

        // Deleting it writes an empty file; meeting it again next run would
        // make it impossible to get rid of.
        let id = s.notes()[0].id;
        s.remove(id);
        s.save().unwrap();

        let reopened = NoteStore::load_or_seed(&path, jiff::civil::date(2026, 7, 25)).unwrap();
        assert!(
            reopened.notes().is_empty(),
            "an emptied file must stay empty across a restart"
        );
    }

    #[test]
    fn a_missing_file_loads_as_an_empty_store() {
        let (s, _g) = store("missing");
        assert!(s.notes().is_empty(), "{:?}", s.notes());
    }

    #[test]
    fn notes_survive_a_save_and_reload() {
        let (mut s, _g) = store("roundtrip");
        let id = s.add(Note::new(0, "Groceries", today()));
        s.with_note(id, today(), |n| n.body = "milk\neggs".into());
        s.save().unwrap();

        let reloaded = NoteStore::load(s.path()).unwrap();
        assert_eq!(reloaded.notes().len(), 1);
        let note = &reloaded.notes()[0];
        assert_eq!(note.title, "Groceries");
        assert_eq!(note.body, "milk\neggs", "newlines must survive TOML");
    }

    /// A notes file exactly as 1.20.0 wrote it, captured from that build's
    /// store: a body with a blank line, a non-ASCII dash and a quote against
    /// the closing delimiter, an `updated` stamp, and an empty body.
    const WRITTEN_BY_1_20_0: &str = r#"# mirador notes. Safe to edit by hand or keep in version control.
# Fields: id, title, body, created (YYYY-MM-DD), updated.

[[note]]
id = 1
title = "Recipe"
body = """
Flour

Water — 300 g
"quoted""""
created = "2026-10-01"
updated = "2026-10-03"

[[note]]
id = 2
title = "Empty body"
body = ""
created = "2026-10-02"
"#;

    /// Same promise as the task file's: the shared reader and writer in
    /// [`crate::store`] put back what they were given, byte for byte. The
    /// file is removed before the save, so the comparison is of what the
    /// save wrote rather than of what was left standing.
    #[test]
    fn a_file_from_1_20_0_is_written_back_byte_for_byte() {
        let (_, guard) = store("bytes");
        let path = guard.join("notes.toml");
        std::fs::write(&path, WRITTEN_BY_1_20_0).unwrap();

        let mut s = NoteStore::load(&path).unwrap();
        assert_eq!(s.notes().len(), 2, "every note was read");
        std::fs::remove_file(&path).unwrap();
        s.dirty = true;
        s.save().unwrap();

        assert_eq!(std::fs::read_to_string(&path).unwrap(), WRITTEN_BY_1_20_0);
    }

    #[test]
    fn editing_stamps_updated_but_opening_and_changing_nothing_does_not() {
        let (mut s, _g) = store("stamp");
        let id = s.add(Note::new(0, "Title", today()));
        assert_eq!(s.get(id).unwrap().updated, None);

        let later = Date::new(2026, 8, 1).unwrap();
        assert!(!s.with_note(id, later, |_| {}), "no change, no stamp");
        assert_eq!(s.get(id).unwrap().updated, None);

        assert!(s.with_note(id, later, |n| n.body = "something".into()));
        assert_eq!(s.get(id).unwrap().updated, Some(later));
    }

    #[test]
    fn the_list_shows_the_most_recently_touched_note_first() {
        let (mut s, _g) = store("order");
        let old = s.add(Note::new(0, "old", Date::new(2026, 1, 1).unwrap()));
        let new = s.add(Note::new(0, "new", Date::new(2026, 6, 1).unwrap()));
        assert_eq!(s.view(""), vec![new, old]);

        // Touching the old one moves it to the top.
        s.with_note(old, Date::new(2026, 12, 1).unwrap(), |n| {
            n.body = "revised".into();
        });
        assert_eq!(s.view(""), vec![old, new]);
    }

    #[test]
    fn filtering_searches_the_body_as_well_as_the_title() {
        let (mut s, _g) = store("filter");
        let id = s.add(Note::new(0, "Meeting", today()));
        s.with_note(id, today(), |n| n.body = "ask about the invoice".into());

        assert_eq!(s.view("invoice"), vec![id], "the body must be searchable");
        assert_eq!(s.view("MEETING"), vec![id], "matching is case-insensitive");
        let found = s.view("nothing here");
        assert!(found.is_empty(), "{found:?}");
        assert_eq!(s.view("   "), vec![id], "a blank filter matches everything");
    }

    /// The task filter shares this search's case folding, and both are held
    /// to a letter outside ASCII so the two cannot drift apart again: the
    /// task list folded only `A`–`Z` while this folded everything.
    #[test]
    fn the_search_ignores_case_beyond_ascii() {
        let mut note = Note::new(1, "Übung", today());
        note.body = "Ärger mit der Bahn".into();
        for needle in ["übung", "ÜBUNG", "ärger"] {
            assert!(note.matches(needle), "{needle}");
        }
        assert!(!note.matches("übungen"));

        // A capital sigma ending the typed text folds to `ς`, and inside the
        // title to `σ`, unless the fold goes a letter at a time.
        let greek = Note::new(2, "ΚΩΣΤΑΣ", today());
        for needle in ["ΚΩΣ", "κως", "κωστας"] {
            assert!(greek.matches(needle), "{needle}");
        }
    }

    #[test]
    fn ids_are_never_reused_after_a_removal() {
        let (mut s, _g) = store("ids");
        let first = s.add(Note::new(0, "one", today()));
        let second = s.add(Note::new(0, "two", today()));
        assert!(s.remove(second));
        let third = s.add(Note::new(0, "three", today()));
        assert_ne!(third, second, "a reused id would alias the removed note");
        assert_ne!(third, first);
    }

    /// The notes file has the task list's shape and the same hazard: a
    /// `[[note]]` block copied by hand keeps its id, and `d` on either note
    /// deleted both.
    #[test]
    fn a_repeated_id_in_the_file_is_renumbered_so_each_key_acts_on_one_note() {
        let (_, guard) = store("dup");
        let path = guard.join("notes.toml");
        let block = |title: &str| {
            format!("[[note]]\nid = 2\ntitle = \"{title}\"\ncreated = \"2026-07-25\"\n\n")
        };
        std::fs::write(&path, block("original") + &block("copy")).unwrap();

        let mut s = NoteStore::load(&path).unwrap();
        let ids: Vec<u64> = s.notes().iter().map(|n| n.id).collect();
        assert_eq!(ids[0], 2, "the first keeps the id the file gave it");
        assert_ne!(ids[1], 2, "the copy needs one of its own: {ids:?}");

        assert!(s.with_note(ids[1], today(), |n| n.title = "edited".into()));
        assert_eq!(s.get(ids[0]).unwrap().title, "original");
        assert!(s.remove(ids[1]));
        let titles: Vec<&str> = s.notes().iter().map(|n| n.title.as_str()).collect();
        assert_eq!(titles, ["original"], "one key, one note");
        assert!(s.add(Note::new(0, "new", today())) > ids[1]);

        // The file is put right by the next save, even with nothing changed.
        let mut untouched = NoteStore::load(&path).unwrap();
        untouched.save().unwrap();
        // Read the text, not a reload: loading renumbers again in memory,
        // so a reloaded store looks repaired whether or not the file is.
        let written = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            written.matches("id = 2\n").count(),
            1,
            "the save must write the new id:\n{written}"
        );
    }

    #[test]
    fn saving_is_a_no_op_when_nothing_changed() {
        let (mut s, _g) = store("clean");
        s.add(Note::new(0, "one", today()));
        s.save().unwrap();
        let stamp = std::fs::metadata(s.path()).unwrap().modified().unwrap();

        s.save().unwrap();
        assert_eq!(
            std::fs::metadata(s.path()).unwrap().modified().unwrap(),
            stamp,
            "a clean store must not rewrite the file"
        );
    }
}