Skip to content

Commit ecab803

Browse files
authored
Add UndeferHandler to invoke a callback once the leaf is ready
1 parent 284bfdf commit ecab803

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

src/utils/UndeferHandler.ts

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { App, Component, Plugin, View, WorkspaceLeaf } from 'obsidian';
2+
3+
export class UndeferHandler extends Component {
4+
app: App;
5+
leaf: WorkspaceLeaf;
6+
view: View;
7+
callback?: (leaf: WorkspaceLeaf) => unknown;
8+
9+
constructor(leaf: WorkspaceLeaf, callback: (leaf: WorkspaceLeaf) => unknown) {
10+
super();
11+
this.app = leaf.app;
12+
this.leaf = leaf;
13+
this.view = leaf.view;
14+
this.callback = callback;
15+
16+
this.view.addChild(this);
17+
}
18+
19+
onload(): void {
20+
// Run the callback immediately if the leaf is not deferred
21+
if (!this.leaf.isDeferred) {
22+
this.view.removeChild(this);
23+
return;
24+
}
25+
26+
// Detach the handler once the plugin has been disabled/unistalled
27+
this.registerEvent(this.app.workspace.on(`custom-sort:plugin-unload`, () => this.detach()));
28+
}
29+
30+
onunload(): void {
31+
if (this.callback) this.runCallback();
32+
}
33+
34+
// Detach the handler without invoking the callback
35+
detach(): void {
36+
delete this.callback;
37+
this.view.removeChild(this);
38+
}
39+
40+
private async runCallback(): Promise<void> {
41+
// Run the callback after the actual view has been loaded
42+
await sleep(0);
43+
// Do not run the callback if the deferred view was unloaded
44+
// because of being closed
45+
if (
46+
!this.leaf.isDeferred &&
47+
this.leaf.parent &&
48+
this.leaf.view.getViewType() !== 'empty'
49+
) {
50+
this.callback?.(this.leaf);
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)