generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.ts
95 lines (83 loc) · 2.45 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { FileView, Plugin, WorkspaceLeaf } from 'obsidian';
declare module "obsidian" {
interface WorkspaceLeaf {
containerEl: Element;
}
}
export default class MyPlugin extends Plugin {
private is_file_explorer_open_previously = false;
private current_open_file_leaf: WorkspaceLeaf | null;
private is_file_explorer_open()
{
const workspace = this.app.workspace;
let is_open = false;
workspace.iterateAllLeaves((leaf) => {
if(leaf.getViewState().type === "file-explorer" && window.getComputedStyle(leaf.containerEl, null).display !== "none")
{
is_open = true;
}
});
return is_open;
}
private async reveal()
{
(this.app as any).commands.executeCommandById('file-explorer:reveal-active-file');
await this.wait_active_leaf_change();
this.app.workspace.setActiveLeaf(this.current_open_file_leaf, { focus: true });
}
private is_file(leaf: WorkspaceLeaf)
{
// This code does not verify whether it represents all files.
return (leaf.view as FileView).allowNoFile === false;
}
private is_file_explorer(leaf: WorkspaceLeaf)
{
return leaf.getViewState().type === "file-explorer";
}
onload() {
this.is_file_explorer_open_previously = this.is_file_explorer_open();
this.app.workspace.on('file-open', async (file) => {
if(!file) {
return;
}
const is_file_explorer_open_now = this.is_file_explorer_open();
if(is_file_explorer_open_now)
{
this.reveal();
}
});
this.app.workspace.on('active-leaf-change', async (leaf) => {
if(!leaf) {
return;
}
this.resolve_wait_active_leaf_change()
const is_file_explorer_open_now = this.is_file_explorer_open();
console.log(`is_file_explorer_open_previously: ${this.is_file_explorer_open_previously}, is_file_explorer_open_now: ${is_file_explorer_open_now}`);
if(this.is_file_explorer(leaf))
{
if(is_file_explorer_open_now && ! this.is_file_explorer_open_previously)
{
this.reveal();
}
}
this.is_file_explorer_open_previously = is_file_explorer_open_now;
if(this.is_file(leaf))
{
this.current_open_file_leaf = leaf;
}
})
}
// for waiting active-leaf-change event
private active_leaf_change_queue: (()=>void)[] = []
private wait_active_leaf_change() {
let resolver = null
const promise = new Promise<void>((resolve) => {
resolver = resolve;
});
this.active_leaf_change_queue.push(resolver)
return promise;
}
private resolve_wait_active_leaf_change() {
this.active_leaf_change_queue.shift()?.();
}
}