/
toggle-view.js
87 lines (81 loc) · 2.54 KB
/
toggle-view.js
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
/* @flow */
import ConfigFile from 'sb-config-file'
import SelectListView from 'atom-select-list'
import { CompositeDisposable, Emitter, Disposable } from 'atom'
import { getConfigFile } from './helpers'
type ToggleAction = 'enable' | 'disable'
export default class ToggleProviders {
action: ToggleAction;
config: ConfigFile;
emitter: Emitter;
providers: Array<string>;
subscriptions: CompositeDisposable;
constructor(action: ToggleAction, providers: Array<string>) {
this.action = action
this.config = null
this.emitter = new Emitter()
this.providers = providers
this.subscriptions = new CompositeDisposable()
this.subscriptions.add(this.emitter)
}
async getConfig(): Promise<ConfigFile> {
if (!this.config) {
this.config = await getConfigFile()
}
return this.config
}
async getItems(): Promise<Array<string>> {
const disabled = await (await this.getConfig()).get('disabled')
if (this.action === 'disable') {
return this.providers.filter(name => !disabled.includes(name))
}
return disabled
}
async process(name: string): Promise<void> {
const config = await this.getConfig()
const disabled: Array<string> = await config.get('disabled')
if (this.action === 'disable') {
disabled.push(name)
this.emitter.emit('did-disable', name)
} else {
const index = disabled.indexOf(name)
if (index !== -1) {
disabled.splice(index, 1)
}
}
await this.config.set('disabled', disabled)
}
async show() {
const selectListView = new SelectListView({
items: await this.getItems(),
emptyMessage: 'No matches found',
filterKeyForItem: item => item,
elementForItem: (item) => {
const li = document.createElement('li')
li.textContent = item
return li
},
didConfirmSelection: (item) => {
this.process(item).catch(e => console.error('[Linter] Unable to process toggle:', e)).then(() => this.dispose())
},
didCancelSelection: () => {
this.dispose()
},
})
const panel = atom.workspace.addModalPanel({ item: selectListView })
selectListView.focus()
this.subscriptions.add(new Disposable(function() {
panel.destroy()
}))
}
onDidDispose(callback: (() => any)): Disposable {
return this.emitter.on('did-dispose', callback)
}
onDidDisable(callback: ((name: string) => any)): Disposable {
return this.emitter.on('did-disable', callback)
}
dispose() {
this.emitter.emit('did-dispose')
this.subscriptions.dispose()
}
}