Skip to content

Instantly share code, notes, and snippets.

@RyotaUshio
Last active October 11, 2023 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyotaUshio/35064974e0c3799d070946587c5a5723 to your computer and use it in GitHub Desktop.
Save RyotaUshio/35064974e0c3799d070946587c5a5723 to your computer and use it in GitHub Desktop.
Obsidian QuickAdd script that opens & auto-updates today's daily note in the right sidebar.
module.exports = async (params) => {
const { app, obsidian } = params;
// Create WorkspaceLeaf (a tab in the right sidebar) which today's daily note will be opened in
const leaf = app.workspace.getRightLeaf(false);
// Open today's daily note in the leaf
await updateLeafFile(leaf, app, obsidian);
// Show the leaf (tab in sidebar)
app.workspace.revealLeaf(leaf);
/** Auto-update mechanism that will be disabled when closing the leaf (tab) */
// the component that manages the auto-updater's lifecycle
const component = new obsidian.Component();
component.load();
// unload the component & detach the leaf when the tab is closed
component.registerEvent(
app.workspace.on('layout-change', () => {
if (leaf.parent === null) {
leaf.detach();
component.unload();
}
})
);
// register auto-update of the daily note opened in the sidebar
const reserveUpdate = () => {
const now = obsidian.moment();
const tomorrow = obsidian.moment().add(1, 'days').startOf('day');
const delay = tomorrow - now;
setTimeout(() => updateLeafFile(leaf, app, obsidian), delay);
};
reserveUpdate();
component.registerInterval(
window.setInterval(reserveUpdate, 24 * 60 * 60 * 1000)
);
}
/**
* Get the settings of the core Daily Notes plugin.
*/
function getDailyNoteOptions(app) {
const options = Object.assign(
{},
app.internalPlugins.plugins['daily-notes'].instance.options
);
options.format = options.format || 'YYYY-MM-DD';
return options;
}
/**
* Get today's daily note as TFile.
*/
async function getTodaysDailyNote(app, obsidian) {
const { moment, normalizePath } = obsidian;
const { folder, format } = getDailyNoteOptions(app);
const path = normalizePath(`${folder}/${moment().format(format)}.md`);
let file = app.vault.getAbstractFileByPath(path);
if (!file) {
// create it if it does not exist
// !! It assumes that you use Templater’s folder template to generate a daily note.
// !! If not, it will create an empty note at the beginning of a day.
file = await app.vault.create(path, '');
}
return file;
}
/**
* Update the daily note opened in the leaf.
*/
async function updateLeafFile(leaf, app, obsidian) {
// get today's daily note as TFile
const file = await getTodaysDailyNote(app, obsidian)
await leaf.openFile(file, { active: false });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment