shabegom / buttons

Buttons in Obsidian
The Unlicense
453 stars 47 forks source link

Split Does Not Open New File In Split View #172

Closed brennanmuir closed 5 months ago

brennanmuir commented 1 year ago
name New Meeting
type note(Meetings\2023-04-03 - <% tp.date.now("X") %>, split) template
action Meeting Template
templater true

When the button is pressed, a new Meeting note is created in a separate folder (\Meetings) from the note containing the button. The new note naming convention is <current-date> - <epoch-timestamp>.

The new file is created and split view opens up, but it just shows "No file is open".

I suspect it's trying to open the new note before it's created or perhaps it's not reading the new filename correctly due to it being in another directory

hberge commented 6 months ago

I have looked at a nearby part of the code today. My actual error was I had a leading slash / in front of the note path, which allowed the file to be created but it would not be opened.

For your problem, I see that the API has changed from when buttons was made so in the createNote function splitActiveLeaf and activeLeaf should be swapped with getLeaf('split') and getLeaf().

I tweaked the code so it might work better for you as well, and it now also supports opening a tab or a window as well as a split. I stopped it failing if the note already exists - now it just opens the previous file with a notice.

I'm simply editing main.js to do this. My updated createNote function looks like this:

const createNote = async (app, content, type) => {
    const path = type.match(/\(([\s\S]*?),?\s?(split|window|tab)?\)/);
    if (path) {
        try {
            var file = app.vault.getAbstractFileByPath(`${path[1]}.md`);
            if (file == null) {
                await app.vault.create(`${path[1]}.md`, content);
                file = app.vault.getAbstractFileByPath(`${path[1]}.md`);
            } else {
                new obsidian.Notice("File already existed. Opening the previous file.", 2000);
            }
            if (path[2]!==null) {
                await app.workspace.getLeaf(`${path[2]}`).openFile(file);
            }
            else {
                await app.workspace.getLeaf().openFile(file);
            }
        }
        catch (e) {
            new obsidian.Notice("There was an error! Maybe the folder doesn't exist? Leading slash?", 2000);
        }
    }
    else {
        new obsidian.Notice(`couldn't parse the path!`, 2000);
    }
};

API reference: (https://docs.obsidian.md/Reference/TypeScript+API/Workspace/getLeaf_1)