pjeby_note-folder-autorename/plugin.js

72 lines
2.7 KiB
JavaScript
Raw Permalink Normal View History

2021-02-03 02:04:20 +00:00
import {Plugin, Notice} from "obsidian";
import * as obsidian from "obsidian";
export default class NotesAsFolders extends Plugin {
onload() {
this.addCommand(
{id: "make-folder-note", name: "Make this note a folder note", checkCallback: this.noteToFolder.bind(this)}
)
this.registerEvent(this.app.vault.on("rename", this.onRenameFile.bind(this)));
}
noteToFolder(check) {
const note = this.app.workspace.getActiveFile();
if ( !note || note.extension !== "md" || isFolderNote(note.path)) return false;
if (check) return true;
return (async () => {
const destination = dirname(note.path) + "/" + note.basename;
const existing = this.app.vault.getAbstractFileByPath(destination);
if ( !existing ) {
await this.app.vault.createFolder(destination);
} else {
return new Notice(`A file or folder named ${note.basename} is in the way; can't create folder`);
2021-02-03 02:04:20 +00:00
}
// Move the note into the folder
2021-02-07 05:25:53 +00:00
await this.safeRename(note, destination + "/" + note.name);
2021-02-03 02:04:20 +00:00
})()
}
2021-02-07 05:25:53 +00:00
async safeRename(file, newName) {
return await this.app.fileManager.renameFile(file, newName);
2021-02-03 02:04:20 +00:00
}
async onRenameFile(file, oldName) {
// We only care about notes that were already folder notes
2021-02-07 05:25:53 +00:00
if (file.extension !== "md" || !isFolderNote(oldName)) return;
2021-02-03 02:04:20 +00:00
const
oldDir = folderBasename(oldName),
oldPath = dirname(oldName),
newPath = dirname(file.path),
oldFolder = this.app.vault.getAbstractFileByPath(oldPath)
;
// If a folder note was renamed inside its folder, rename the folder to match
if (oldPath === newPath) {
const destination = dirname(oldPath) + "/" + file.basename;
2021-02-07 05:25:53 +00:00
await this.safeRename(oldFolder, destination);
2021-02-03 02:04:20 +00:00
}
// If a folder note was moved out of its old folder to a new folder,
else if (oldFolder && file.basename === oldDir) {
2021-02-03 02:04:20 +00:00
const destination = newPath + "/" + oldDir;
// Move the folder alongside the note,
2021-02-07 05:25:53 +00:00
await this.safeRename(oldFolder, destination);
2021-02-03 02:04:20 +00:00
// Then move the note back into the folder
2021-02-07 05:25:53 +00:00
await this.safeRename(file, destination + "/" + file.name);
2021-02-03 02:04:20 +00:00
return;
}
}
}
function folderBasename(path) { return path.split("/").slice(-2, -1).pop(); }
function basename(path) { return path.split("/").pop(); }
function dirname(path) { return path.split("/").slice(0, -1).join("/"); }
function isFolderNote(path) { return basename(path) === folderBasename(path) + ".md"; }