journal.rs

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