obsidianmd / obsidian-api

Type definitions for the latest Obsidian API.
https://docs.obsidian.md
MIT License
1.65k stars 192 forks source link

Request: event for custom views to know if they are visible/hidden #155

Closed ofalvai closed 4 months ago

ofalvai commented 4 months ago

I'm developing a plugin that adds a custom view to the right split. This custom view reacts to the currently active file in the root split and makes some expensive operations. I want to avoid triggering these operations when the custom view is not even visible (either because the right sidebar is collapsed, or another view is active in the split).

I asked this question on Discord, but looks like there is no reliable way to get this information.

lishid commented 4 months ago

You can easily do this by testing if your view's container is in the DOM - in Obsidian there is a helper function on an HTMLElement called isShown() and in a view you can do this by checking this.containerEl.isShown(). The function is directly mapped to check if it has an Element.offsetParent which is the browser's way of telling you if it's hooked up to be rendered.

If you need a way to detect when your element has been re-inserted/shown (so that you can re-start rendering again), we also have a helper function called onNodeInserted(callback). You'll want to make sure you only call this once in your view constructor so it does not get hooked up multiple times and cause multiple computations.

ofalvai commented 3 months ago

Thank you for the detailed explanation. isShown() works perfectly for my use case!