Repository navigation
Expand file tree
/
Copy pathwatch-workspace-item.js
More file actions
72 lines (59 loc) · 1.95 KB
/
Copy pathwatch-workspace-item.js
File metadata and controls
72 lines (59 loc) · 1.95 KB
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
import {CompositeDisposable} from 'atom';
import URIPattern from './atom/uri-pattern';
class ItemWatcher {
constructor(workspace, pattern, component, stateKey) {
this.workspace = workspace;
this.pattern = pattern instanceof URIPattern ? pattern : new URIPattern(pattern);
this.component = component;
this.stateKey = stateKey;
this.activeItem = this.isActiveItem();
this.subs = new CompositeDisposable();
}
isActiveItem() {
for (const pane of this.workspace.getPanes()) {
if (this.itemMatches(pane.getActiveItem())) {
return true;
}
}
return false;
}
setInitialState() {
if (!this.component.state) {
this.component.state = {};
}
this.component.state[this.stateKey] = this.activeItem;
return this;
}
subscribeToWorkspace() {
this.subs.dispose();
this.subs = new CompositeDisposable(
this.workspace.getCenter().onDidChangeActivePaneItem(this.updateActiveState),
);
return this;
}
updateActiveState = () => {
const wasActive = this.activeItem;
this.activeItem = this.isActiveItem();
// Update the component's state if it's changed as a result
if (wasActive && !this.activeItem) {
return new Promise(resolve => this.component.setState({[this.stateKey]: false}, resolve));
} else if (!wasActive && this.activeItem) {
return new Promise(resolve => this.component.setState({[this.stateKey]: true}, resolve));
} else {
return Promise.resolve();
}
}
setPattern(pattern) {
this.pattern = pattern instanceof URIPattern ? pattern : new URIPattern(pattern);
return this.updateActiveState();
}
itemMatches = item => item && item.getURI && this.pattern.matches(item.getURI()).ok()
dispose() {
this.subs.dispose();
}
}
export function watchWorkspaceItem(workspace, pattern, component, stateKey) {
return new ItemWatcher(workspace, pattern, component, stateKey)
.setInitialState()
.subscribeToWorkspace();
}