Insert a time heading when creating a journal entry

This commit is contained in:
Nathan Sobo 2021-12-18 10:38:54 -07:00
parent 9e8ef31452
commit e4f18947de
6 changed files with 70 additions and 39 deletions

View file

@ -7,10 +7,10 @@ edition = "2021"
path = "src/journal.rs"
[dependencies]
editor = { path = "../editor" }
gpui = { path = "../gpui" }
util = { path = "../util" }
workspace = { path = "../workspace" }
anyhow = "1.0"
chrono = "0.4"
dirs = "4.0"
log = "0.4"

View file

@ -1,8 +1,7 @@
use std::{fs::OpenOptions, sync::Arc};
use anyhow::anyhow;
use chrono::{Datelike, Local};
use chrono::{Datelike, Local, Timelike};
use editor::{Autoscroll, Editor};
use gpui::{action, keymap::Binding, MutableAppContext};
use std::{fs::OpenOptions, sync::Arc};
use util::TryFutureExt as _;
use workspace::AppState;
@ -14,27 +13,37 @@ pub fn init(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
}
pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
let paths = cx.background().spawn(async move {
let now = Local::now();
let home_dir = dirs::home_dir().ok_or_else(|| anyhow!("can't determine home directory"))?;
let journal_dir = home_dir.join("journal");
let month_dir = journal_dir
.join(now.year().to_string())
.join(now.month().to_string());
let entry_path = month_dir.join(format!("{}.md", now.day()));
let now = Local::now();
let home_dir = match dirs::home_dir() {
Some(home_dir) => home_dir,
None => {
log::error!("can't determine home directory");
return;
}
};
std::fs::create_dir_all(dbg!(month_dir))?;
let journal_dir = home_dir.join("journal");
let month_dir = journal_dir
.join(now.year().to_string())
.join(now.month().to_string());
let entry_path = month_dir.join(format!("{}.md", now.day()));
let now = now.time();
let (pm, hour) = now.hour12();
let am_or_pm = if pm { "PM" } else { "AM" };
let entry_heading = format!("# {}:{} {}\n\n", hour, now.minute(), am_or_pm);
let create_entry = cx.background().spawn(async move {
std::fs::create_dir_all(month_dir)?;
OpenOptions::new()
.create(true)
.write(true)
.open(dbg!(&entry_path))?;
Ok::<_, anyhow::Error>((journal_dir, entry_path))
.open(&entry_path)?;
Ok::<_, std::io::Error>((journal_dir, entry_path))
});
cx.spawn(|mut cx| {
async move {
let (journal_dir, entry_path) = paths.await?;
let (journal_dir, entry_path) = create_entry.await?;
let workspace = cx
.update(|cx| workspace::open_paths(&[journal_dir], &app_state, cx))
.await;
@ -46,7 +55,16 @@ pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
.await;
if let Some(Some(Ok(item))) = opened.first() {
log::info!("opened an item!");
if let Some(editor) = item.to_any().downcast::<Editor>() {
editor.update(&mut cx, |editor, cx| {
let len = editor.buffer().read(cx).len();
editor.select_ranges([len..len], Some(Autoscroll::Center), cx);
if len > 0 {
editor.insert("\n\n", cx);
}
editor.insert(&entry_heading, cx);
});
}
}
Ok(())