A simple script that can be used with Obsidian's Dataview plugin to display daily streaks of habits from your daily notes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For this script to work properly, each daily habit has to start with a unique emoji, | |
// which will also be displayed next to the daily streak for each habit. | |
// Daily streaks are calculated for the currently opened daily note, and end on the first day | |
// that the habit was not ticked off. They are displayed in order of highest to lowest length. | |
// To display the result of this script in your daily notes, you can use this snippet: | |
// ```dataviewjs | |
// dv.view("path/to/Obsidian Daily Streaks.js"); | |
// ``` | |
// This is the directory that your daily notes are in | |
const daily = '"path/to/daily/notes"'; | |
let streaks = new Map(); | |
for (let task of dv.current().file.tasks) { | |
let emoji = task.text.substring(0, task.text.indexOf(" ")); | |
streaks.set(emoji, { | |
value: 0, | |
done: false | |
}); | |
} | |
let foundToday = false; | |
for (let page of dv.pages(daily).sort(p => p.file.name, "desc")) { | |
// skip all notes that are newer than the current note | |
if (!foundToday) { | |
if (page.file.name == dv.current().file.name) | |
foundToday = true; | |
continue; | |
} | |
for (const [emoji, streak] of streaks.entries()) { | |
// if a streak is marked as done, it means we reached the end already | |
if (streak.done) | |
continue; | |
for (let task of page.file.tasks) { | |
if (!task.text.startsWith(emoji)) | |
continue; | |
if (task.completed) { | |
streak.value++; | |
} else { | |
streak.done = true; | |
} | |
break; | |
} | |
} | |
} | |
// iterate streaks in order of length and display them | |
for (let [emoji, streak] of Array.from(streaks.entries()).sort((kv1, kv2) => kv2[1].value - kv1[1].value)) | |
dv.span(`${emoji} ${streak.value} `); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment