journal.rs

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