Skip to content

Instantly share code, notes, and snippets.

@panahi
Created November 7, 2022 02:57
Show Gist options
  • Save panahi/7daf125c1729aa187c7e5a461b01fc56 to your computer and use it in GitHub Desktop.
Save panahi/7daf125c1729aa187c7e5a461b01fc56 to your computer and use it in GitHub Desktop.
QuickAdd macro scripts
/**
* 1: verify that the file exists and that task is present
* 2: convert the task to a taskobject and open modal
* 3: Modal contains
* a: edit tags
* b: edit text
* c: edit priority
* 4: Update file with new task content
*/
async function editTask(params) {
const { app } = params;
const { taskFile, taskLine, taskText } = app.plugins.plugins['obsidian-advanced-uri'].lastParameters;
const fileUtils = customJS.FileUtilities;
const editor = customJS.TaskEditor;
const formatter = customJS.TaskFormatter;
console.log(`Edit Task Invoked for:\nFile:${taskFile}\nLine:${taskLine}\nText:${taskText}`);
if (!taskFile || !taskText) {
return new Notice("Edit Task is missing the file or text of the task to edit")
}
const taskObj = await fileUtils.findTaskInFile(app, taskFile, taskText);
if (!taskObj) {
return new Notice("Unable to locate task", 2500);
}
const taskAndPath = await editor.processTaskEdit(taskObj, taskFile);
if (taskAndPath && taskAndPath.task && taskAndPath.path) {
if (taskAndPath.path === taskFile) {
let updated = await fileUtils.replaceTaskInFile(app, taskFile, taskText, taskAndPath.task);
return new Notice("Task successfully updated: " + updated, 2500);
} else {
await fileUtils.appendToFile(app, taskAndPath.path, formatter.convertTaskToLine(taskAndPath.task));
await fileUtils.deleteTaskInFile(app, taskFile, taskText);
return new Notice("Task has been updated and moved to " + taskAndPath.path, 2500);
}
} else {
return new Notice("Failed to update task", 2500);
}
}
module.exports = editTask;
async function fileBookmark(params) {
//TODO move to plugin
const { app, quickAddApi } = params;
const fileUtils = customJS.FileUtilities;
const tp = window.tp;
const currentFileObj = app.workspace.getActiveFile();
const rootDirs = fileUtils.getRootJDFolderNames(app);
const targetRoot = await quickAddApi.suggester(rootDirs, rootDirs);
console.log("Target root: " + targetRoot);
if (!targetRoot) {
return new Notice("Bookmark move abandoned");
}
const secondLevelFolders = fileUtils.getChildJDFolderNames(app, targetRoot);
const secondLevel = await quickAddApi.suggester(secondLevelFolders, secondLevelFolders);
if (!secondLevel) {
return new Notice("Bookmark move abandoned");
}
const newPath = `${targetRoot}/${secondLevel}/${currentFileObj.basename}`;
return tp.file.move(newPath, currentFileObj);
}
module.exports = fileBookmark;
function getMeetingNoteDirectory(year, week) {
return `/Journal/${year}/${week}/Events/`;
}
async function fileMeetingNote(tp, year, week, fileName) {
console.log('called');
let targetDir = getMeetingNoteDirectory(year, week);
console.log('target: ' + targetDir);
let dirExists = await app.vault.exists(targetDir, 'true');
console.log('directory exists: ' + dirExists);
if (!dirExists) {
await app.vault.createFolder(targetDir);
console.log('created directory');
}
await tp.file.move(targetDir + fileName);
return "";
}
module.exports = fileMeetingNote;
async function focusTask(params) {
const { app } = params;
const { taskFile, taskLine, taskText } = app.plugins.plugins['obsidian-advanced-uri'].lastParameters;
const fileUtils = customJS.FileUtilities;
const taskUtils = customJS.TaskUtilities;
console.log(`Focus Task Invoked for:\nFile:${taskFile}\nLine:${taskLine}\nText:${taskText}`);
if (!taskFile || !taskText) {
return new Notice("Focus Task is missing the file or text of the task to edit")
}
const taskObj = await fileUtils.findTaskInFile(app, taskFile, taskText);
if (!taskObj) {
return new Notice("Unable to locate task", 2500);
}
const updatedObj = await taskUtils.addFocus(taskObj);
if (updatedObj) {
let updated = await fileUtils.replaceTaskInFile(app, taskFile, taskText, updatedObj);
return new Notice("Task successfully updated: " + updated, 2500);
} else {
return new Notice("Failed to update task", 2500);
}
}
module.exports = focusTask;
const MOBILE_HOME = "00-09 Meta/03 Waypoints/03.03 Mobile Navigation.md";
const DESKTOP_HOME = "00-09 Meta/03 Waypoints/03.01 Dashboard.md";
async function loadHomeNote(params) {
const { app } = params;
console.log("Load Home Note invoked");
let fileToOpen = app.isMobile ? MOBILE_HOME : DESKTOP_HOME;
app.workspace.activeLeaf.openFile(app.vault.getAbstractFileByPath());
app.workspace.openLinkText(fileToOpen, "/")
}
module.exports = loadHomeNote;
const fileMap = {
Activity: '90-99 Leisure/90 Activities/90.00 Activity Ideas.md',
Movie: '90-99 Leisure/91 Movies/91.00 Movie Recommendations.md',
TV: '90-99 Leisure/92 TV/92.00 TV Recommendations.md',
Reading: '90-99 Leisure/93 Reading/93.00 Reading Recommendations.md',
Music: '90-99 Leisure/94 Music/94.00 Music Recommendations.md',
PodcastOrYoutube: '90-99 Leisure/95 Podcasts and Youtube/95.00 Podcast and Youtube Recommendations.md',
Gaming: '90-99 Leisure/96 Gaming/96.00 Gaming Recommendations.md',
Travel: '90-99 Leisure/97 Travel/97.00 Travel Recommendations.md',
Restaurant: '90-99 Leisure/98 Restaurants/98.00 Restaurant Recommendations.md',
Place: '90-99 Leisure/99 Places/99.00 Place Recommendations.md',
}
async function logRecommendation(params) {
const { app, quickAddApi } = params;
const fileUtils = customJS.FileUtilities;
let recoType = await quickAddApi.suggester(Object.keys(fileMap), Object.keys(fileMap));
if (!recoType) {
return new Notice("No type chosen, abandoning recommendation", 2500);
}
let recommendation = await quickAddApi.inputPrompt("What is the recommendation?");
if (!recommendation) {
return new Notice("No recommendation provided, abandoning recommendation", 2500);
}
let recommendationContext = await quickAddApi.inputPrompt("Context?");
if (!recommendationContext) {
recommendationContext = "None";
}
let recommendationDate = window.moment().format('YYYY-MM-DD HH:mm');
let textToAdd = `| ${recommendation} | ${recommendationContext} | ${recommendationDate} |`;
await fileUtils.appendToFile(app, fileMap[recoType], textToAdd);
return new Notice("Recommendation added", 2500);
}
module.exports = logRecommendation;
const excludedDirs = [
'02 Templates',
'03 Waypoints',
'05 Scripts'
];
async function normalizeAllFiles(params) {
const { app } = params;
let files = app.vault.getFiles();
for (const file of files) {
if (file.deleted || file.saving) {
console.log(`Skipping file ${file.path} because it is saving or deleted`);
continue;
}
for (const dir of excludedDirs) {
if (file.path.indexOf(dir) >= 0) {
console.log(`Skipping file ${file.path} because it is in an excluded path ${dir}`);
continue;
}
}
if (file.extension !== 'md') {
console.log(`Skipping file ${file.path} because it is not a markdown file`);
continue;
}
await customJS.FileUtilities.formatFile(app, file.path);
}
}
module.exports = normalizeAllFiles;
async function normalizeFile(params) {
const { app } = params;
const currentFile = await app.workspace.getActiveFile().path;
customJS.FileUtilities.formatFile(app, currentFile);
}
module.exports = normalizeFile;
async function openFileByUrlId(params) {
const { app } = params;
const { fileId } = app.plugins.plugins['obsidian-advanced-uri'].lastParameters;
if (!fileId) {
return new Notice("No fileId presented in URL", 2500);
}
let files = app.vault.getMarkdownFiles();
let targetFile = null;
for (const file of files) {
let metadata = app.metadataCache.getFileCache(file)
if (metadata && metadata.frontmatter && metadata.frontmatter['id']) {
if (metadata.frontmatter['id'] === fileId) {
targetFile = file;
break;
}
}
}
if (targetFile !== null) {
app.workspace.getLeaf(false).openFile(targetFile, { active: true });
return;
} else {
return new Notice("Unable to locate file with id " + fileId, 2500);
}
}
module.exports = openFileByUrlId;
/**
* 1: verify that the file exists and that task is present
* 2: convert the task to a taskobject and open modal
* 3: Modal contains
* edit schedule
* 4: Update file with new task content
*/
async function scheduleTask(params) {
const { app } = params;
const { taskFile, taskLine, taskText } = app.plugins.plugins['obsidian-advanced-uri'].lastParameters;
const fileUtils = customJS.FileUtilities;
const scheduleHelper = customJS.ScheduleHelper;
console.log(`Schedule Task Invoked for:\nFile:${taskFile}\nLine:${taskLine}\nText:${taskText}`);
if (!taskFile || !taskText) {
return new Notice("Schedule Task is missing the file or text of the task to edit")
}
const taskObj = await fileUtils.findTaskInFile(app, taskFile, taskText);
if (!taskObj) {
return new Notice("Unable to locate task", 2500);
}
const updatedObj = await scheduleHelper.updateTaskObjectWithSchedule(taskObj);
if (updatedObj) {
let updated = await fileUtils.replaceTaskInFile(app, taskFile, taskText, updatedObj);
return new Notice("Task successfully updated: " + updated, 2500);
} else {
return new Notice("Failed to update task", 2500);
}
}
module.exports = scheduleTask;
async function toggleTaskCompletion(params) {
const { app, quickAddApi } = params;
const { taskFile, taskLine, taskText } = app.plugins.plugins['obsidian-advanced-uri'].lastParameters;
const fileUtils = customJS.FileUtilities;
const taskUtils = customJS.TaskUtilities;
console.log(`Complete Task Invoked for:\nFile:${taskFile}\nLine:${taskLine}\nText:${taskText}`);
if (!taskFile || !taskText) {
return new Notice("Complete Task is missing the file or text of the task to edit")
}
const taskObj = await fileUtils.findTaskInFile(app, taskFile, taskText);
if (!taskObj) {
return new Notice("Unable to locate task", 2500);
}
const updatedObj = await taskUtils.toggleCompletion(taskObj);
if (updatedObj) {
let updated = await fileUtils.replaceTaskInFile(app, taskFile, taskText, updatedObj);
return new Notice("Task successfully updated: " + updated, 2500);
} else {
return new Notice("Failed to update task", 2500);
}
}
module.exports = toggleTaskCompletion;
let togglApi;
let quickAddApi;
let projects;
const back = "<- Back";
const menu = {
"๐Ÿ’ผ Work": {
menuOptions: [
"๐Ÿš— Commute",
"๐Ÿค General Meeting",
"๐Ÿ‘ฅ One on One",
"โ˜ Domain Decomposition"
]
},
"๐Ÿซ€ Health": {
menuOptions: [
"๐Ÿƒโ€โ™‚๏ธ Exercise",
"๐Ÿง˜โ€โ™‚๏ธ Distraction-free Break"
]
},
"๐Ÿ“ˆ Professional Development": {
menuOptions: [
"๐Ÿ‘จโ€๐Ÿ’ป Leetcode",
"๐Ÿ‘จโ€๐Ÿ’ป A Cloud Guru",
"๐Ÿ‘จโ€๐Ÿ”ฌ Reading for career"
]
},
"๐Ÿง  Personal Development": {
menuOptions: [
"โœ๏ธ Notemaking",
"โœ… Productivity System",
"๐Ÿ‘จโ€๐Ÿ’ป Personal Software Projects",
"๐Ÿ“– Reading to Learn"
]
},
"๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ Family": {
menuOptions: [
"โ˜€๏ธ Morning Routine",
"๐Ÿš— Daycare Commute",
"๐Ÿฅฑ Bedtime Routine",
"๐Ÿ  At Home",
"๐Ÿ‘‹ Visiting",
"๐Ÿ› Shopping with Family",
"๐ŸŒฏ Restaurant with Family",
"๐ŸŒณ Activity with Family"
]
},
"๐ŸŽฎ Leisure": {
menuOptions: [
"๐Ÿ“– Reading for Fun",
"๐ŸŽฌ Watching Something",
"๐Ÿ’ง Magic",
"๐ŸŽฎ Gaming"
]
},
"๐Ÿ“ฒ Distractions": {
menuOptions: [
"๐Ÿคฏ Doomscrolling",
"๐Ÿ–ฅ๏ธ Computer Distractions"
]
},
"๐Ÿงน Maintenance": {
menuOptions: [
"๐Ÿ  Housework",
"๐Ÿ“ฅ Processing Inboxes",
"๐ŸŽฏ Planning"
]
},
"โ“ General": {
menuOptions: [
"๐Ÿ› Sleep",
"๐Ÿ• Meal",
"๐Ÿš— Driving"
]
}
};
module.exports = async function togglManager(params) {
togglApi = params.app.plugins.plugins["obsidian-toggl-integration"].toggl._apiManager;
quickAddApi = params.quickAddApi;
projects = await togglApi.getProjects();
openMainMenu(menu);
}
async function startTimer(entryName, projectID) {
await togglApi.startTimer({ description: entryName, pid: projectID });
}
async function openMainMenu(menu) {
const { suggester } = quickAddApi;
const options = Object.keys(menu);
const choice = await suggester(options, options);
if (!choice) return;
const project = menu[choice];
await openSubMenu(choice, project);
}
async function openSubMenu(projectName, projectObj) {
const { suggester } = quickAddApi;
const options = [...projectObj.menuOptions, back];
const choice = await suggester(options, options);
if (!choice) return;
if (choice === back) {
return await openMainMenu(menu);
}
const projectID = projects.find(p => p.name === projectName).id;
startTimer(choice, projectID);
}
async function unfocusTask(params) {
const { app } = params;
const { taskFile, taskLine, taskText } = app.plugins.plugins['obsidian-advanced-uri'].lastParameters;
const fileUtils = customJS.FileUtilities;
const taskUtils = customJS.TaskUtilities;
console.log(`Unfocus Task Invoked for:\nFile:${taskFile}\nLine:${taskLine}\nText:${taskText}`);
if (!taskFile || !taskText) {
return new Notice("Unfocus Task is missing the file or text of the task to edit")
}
const taskObj = await fileUtils.findTaskInFile(app, taskFile, taskText);
if (!taskObj) {
return new Notice("Unable to locate task", 2500);
}
const updatedObj = await taskUtils.removeFocus(taskObj);
if (updatedObj) {
let updated = await fileUtils.replaceTaskInFile(app, taskFile, taskText, updatedObj);
return new Notice("Task successfully updated: " + updated, 2500);
} else {
return new Notice("Failed to update task", 2500);
}
}
module.exports = unfocusTask;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment