journal.rs

  1use chrono::{Datelike, Local, NaiveTime, Timelike};
  2use editor::{scroll::autoscroll::Autoscroll, Editor};
  3use gpui::{actions, AppContext};
  4use settings::{HourFormat, Settings};
  5use std::{
  6    fs::OpenOptions,
  7    path::{Path, PathBuf},
  8    sync::Arc,
  9};
 10use util::TryFutureExt as _;
 11use workspace::AppState;
 12
 13actions!(journal, [NewJournalEntry]);
 14
 15pub fn init(app_state: Arc<AppState>, cx: &mut AppContext) {
 16    cx.add_global_action(move |_: &NewJournalEntry, cx| new_journal_entry(app_state.clone(), cx));
 17}
 18
 19pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut AppContext) {
 20    let settings = cx.global::<Settings>();
 21    let journal_dir = match journal_dir(&settings) {
 22        Some(journal_dir) => journal_dir,
 23        None => {
 24            log::error!("Can't determine journal directory");
 25            return;
 26        }
 27    };
 28
 29    let now = Local::now();
 30    let month_dir = journal_dir
 31        .join(format!("{:02}", now.year()))
 32        .join(format!("{:02}", now.month()));
 33    let entry_path = month_dir.join(format!("{:02}.md", now.day()));
 34    let now = now.time();
 35    let hour_format = &settings.journal_overrides.hour_format;
 36    let entry_heading = heading_entry(now, &hour_format);
 37
 38    let create_entry = cx.background().spawn(async move {
 39        std::fs::create_dir_all(month_dir)?;
 40        OpenOptions::new()
 41            .create(true)
 42            .write(true)
 43            .open(&entry_path)?;
 44        Ok::<_, std::io::Error>((journal_dir, entry_path))
 45    });
 46
 47    cx.spawn(|mut cx| {
 48        async move {
 49            let (journal_dir, entry_path) = create_entry.await?;
 50            let (workspace, _) = cx
 51                .update(|cx| workspace::open_paths(&[journal_dir], &app_state, None, cx))
 52                .await;
 53
 54            let opened = workspace
 55                .update(&mut cx, |workspace, cx| {
 56                    workspace.open_paths(vec![entry_path], true, cx)
 57                })
 58                .await;
 59
 60            if let Some(Some(Ok(item))) = opened.first() {
 61                if let Some(editor) = item.downcast::<Editor>() {
 62                    editor.update(&mut cx, |editor, cx| {
 63                        let len = editor.buffer().read(cx).len(cx);
 64                        editor.change_selections(Some(Autoscroll::center()), cx, |s| {
 65                            s.select_ranges([len..len])
 66                        });
 67                        if len > 0 {
 68                            editor.insert("\n\n", cx);
 69                        }
 70                        editor.insert(&entry_heading, cx);
 71                        editor.insert("\n\n", cx);
 72                    });
 73                }
 74            }
 75
 76            anyhow::Ok(())
 77        }
 78        .log_err()
 79    })
 80    .detach();
 81}
 82
 83fn journal_dir(settings: &Settings) -> Option<PathBuf> {
 84    let journal_dir = settings
 85        .journal_overrides
 86        .path
 87        .as_ref()
 88        .unwrap_or(settings.journal_defaults.path.as_ref()?);
 89
 90    let expanded_journal_dir = shellexpand::full(&journal_dir) //TODO handle this better
 91        .ok()
 92        .map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"));
 93
 94    return expanded_journal_dir;
 95}
 96
 97fn heading_entry(now: NaiveTime, hour_format: &Option<HourFormat>) -> String {
 98    match hour_format {
 99        Some(HourFormat::Hour24) => {
100            let hour = now.hour();
101            format!("# {}:{:02}", hour, now.minute())
102        }
103        _ => {
104            let (pm, hour) = now.hour12();
105            let am_or_pm = if pm { "PM" } else { "AM" };
106            format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
107        }
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    mod heading_entry_tests {
114        use super::super::*;
115
116        #[test]
117        fn test_heading_entry_defaults_to_hour_12() {
118            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
119            let actual_heading_entry = heading_entry(naive_time, &None);
120            let expected_heading_entry = "# 3:00 PM";
121
122            assert_eq!(actual_heading_entry, expected_heading_entry);
123        }
124
125        #[test]
126        fn test_heading_entry_is_hour_12() {
127            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
128            let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour12));
129            let expected_heading_entry = "# 3:00 PM";
130
131            assert_eq!(actual_heading_entry, expected_heading_entry);
132        }
133
134        #[test]
135        fn test_heading_entry_is_hour_24() {
136            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
137            let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour24));
138            let expected_heading_entry = "# 15:00";
139
140            assert_eq!(actual_heading_entry, expected_heading_entry);
141        }
142    }
143}