UNPKG

1.56 kBPlain TextView Raw
1import abbrev from 'abbrev';
2
3interface CmdObj {
4 runFn: Function;
5 desc: string | Function;
6 options?: Array<object>;
7 pluginName?: string;
8}
9
10interface Store {
11 [key: string]: CmdObj;
12}
13
14interface StrObj {
15 [key: string]: string;
16}
17export default class Commander {
18 private store: Store;
19 private invisibleStore: Store;
20 private alias: StrObj;
21 private onRegistered?: Function;
22
23 constructor(onRegistered?: Function) {
24 this.store = {};
25 this.invisibleStore = {};
26 this.alias = {};
27 if (typeof onRegistered === 'function') this.onRegistered = onRegistered;
28 }
29
30 get(name: string) {
31 if (Object.prototype.toString.call(name) !== '[object String]') {
32 return;
33 }
34 name = name.toLowerCase();
35 const invisibleCommand = this.invisibleStore[name];
36 if (invisibleCommand) {
37 return invisibleCommand;
38 }
39 return this.store[this.alias[name]];
40 }
41
42 list() {
43 return this.store;
44 }
45
46 register(name: string, desc: string | Function, fn: Function, options?: Array<object>, pluginName?: string) {
47 const storeKey = name.toLowerCase();
48 this.store[storeKey] = {
49 runFn: fn,
50 desc,
51 options,
52 pluginName
53 };
54 this.alias = abbrev(Object.keys(this.store));
55 if (this.onRegistered) {
56 this.onRegistered(storeKey);
57 }
58 }
59
60 registerInvisible(name: string, fn: Function, options?: Array<object>, pluginName?: string) {
61 const storeKey = name.toLowerCase();
62 this.invisibleStore[storeKey] = {
63 runFn: fn,
64 desc: '',
65 options,
66 pluginName
67 };
68 }
69}