Renaming Folder Names and Drag-and-Drop Events in File Explorer

I am currently developing a plugin to synchronize books between Obsidian and a website.

There is one issue that I’m having trouble with, so I’m asking for help.

When renaming a folder in File Explorer or moving a file to another folder via drag-and-drop, the “rename” event is triggered in both cases. However, it’s difficult to distinguish between the two actions with just the “rename” event. Is there an event that can help differentiate between renaming a folder and moving a file through drag-and-drop?

1 Like

If you drag-and-drop, you will have only one rename event for the changed file path.

If you rename the folder, you will have have rename event for the folder and then rename events for each file in the folder.

That’s how you can distinguish

1 Like

Thank you for your response.

However, even so, when writing event-handling code, it seems challenging to determine whether the rename event was triggered by a drag-and-drop action or by renaming a folder. What do you think?

1 Like

It is a bit tricky but not too challenging

const recentRenamedFolderPaths = new Set<string>();
this.registerEvent(this.app.vault.on('rename', (file, oldPath) {
  if (file instanceof TFolder) {
    recentRenamedFolderPaths.add(file.path);

    setTimeout(() => {
      recentRenamedFolderPaths.delete(file.path)
    }, 500); // some reasonable timeout
  } else {
    if (recentRenamedFolderPaths.has(file.parent.path) {
      // after renamed folder
    } else {
      // after drag-and-drop
    }
  }
});
3 Likes

You’re really smart!

I applied the code you provided, and it works perfectly. Thank you!

2 Likes

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.