-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
104 lines (80 loc) · 2.32 KB
/
index.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
'auto'
'reverse auto'
'cancel'
*/
(function(){
function OnTab( callback ) {
var autoCompleteState = null
, autoList = [];
this.__defineGetter__( 'context', function() {
return autoList;
} );
this.__defineSetter__( 'context', function(val) {
if (Array.isArray(val)) {
autoList = val;
}
else {
autoList = [ val ];
}
} );
this.autoComplete = function( command ) {
if (!autoCompleteState && command.length) {
autoCompleteState = initAutoComplete( command );
if (autoCompleteState) {
autoCompleteState.index = autoCompleteState.options.length - 1;
}
}
if (autoCompleteState && autoCompleteState.options.length) {
++autoCompleteState.index;
autoCompleteState.index %= autoCompleteState.options.length;
applyAuto( command );
}
};
this.reverseAutoComplete = function( command ) {
if (!autoCompleteState && command.length) {
autoCompleteState = initAutoComplete( command );
}
if (autoCompleteState && autoCompleteState.options.length) {
if (autoCompleteState.index) {
--autoCompleteState.index;
}
else {
autoCompleteState.index = autoCompleteState.options.length - 1;
}
applyAuto( command );
}
};
this.cancelAutoComplete = function() {
autoCompleteState = null;
};
function initAutoComplete( command ) {
var ind = getBeginIndex( command )
, options = []
, end = command.substr( ind + 1 )
, re = new RegExp( '^' + end, "i" ); // case insensitive
autoList.forEach( function( e ) {
if (re.test( e )) {
options.push( e );
}
} );
return { index: 0, options: options, position: ind };
}
function getBeginIndex( command ) {
var a = command.lastIndexOf( ' ' )
, b = command.lastIndexOf( '/' );
return b > a ? b : a;
}
function applyAuto( command ) {
var value = command.substr( 0, autoCompleteState.position + 1 )
+ autoCompleteState.options[autoCompleteState.index];
callback( value );
}
}
if (typeof module !== 'undefined') {
module.exports = OnTab;
}
else {
window.OnTab = OnTab;
}
})();