forked from yuku/textcomplete
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.textcomplete.js
736 lines (665 loc) · 22 KB
/
jquery.textcomplete.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
/*!
* jQuery.textcomplete.js
*
* Repositiory: https://github.com/yuku-t/jquery-textcomplete
* License: MIT
* Author: Yuku Takahashi
*/
;(function ($) {
'use strict';
/**
* Exclusive execution control utility.
*/
var lock = function (func) {
var free, locked, queuedArgsToReplay;
free = function () { locked = false; };
return function () {
var args = toArray(arguments);
if (locked) {
// Keep a copy of this argument list to replay later.
// OK to overwrite a previous value because we only replay the last one.
queuedArgsToReplay = args;
return;
}
locked = true;
var that = this;
args.unshift(function replayOrFree() {
if (queuedArgsToReplay) {
// Other request(s) arrived while we were locked.
// Now that the lock is becoming available, replay
// the latest such request, then call back here to
// unlock (or replay another request that arrived
// while this one was in flight).
var replayArgs = queuedArgsToReplay;
queuedArgsToReplay = undefined;
replayArgs.unshift(replayOrFree);
func.apply(that, replayArgs);
} else {
locked = false;
}
});
func.apply(this, args);
};
};
/**
* Convert arguments into a real array.
*/
var toArray = function (args) {
var result;
result = Array.prototype.slice.call(args);
return result;
};
/**
* Get the styles of any element from property names.
*/
var getStyles = (function () {
var color;
color = $('<div></div>').css(['color']).color;
if (typeof color !== 'undefined') {
return function ($el, properties) {
return $el.css(properties);
};
} else { // for jQuery 1.8 or below
return function ($el, properties) {
var styles;
styles = {};
$.each(properties, function (i, property) {
styles[property] = $el.css(property);
});
return styles;
};
}
})();
/**
* Default template function.
*/
var identity = function (obj) { return obj; };
/**
* Memoize a search function.
*/
var memoize = function (func) {
var memo = {};
return function (term, callback) {
if (memo[term]) {
callback(memo[term]);
} else {
func.call(this, term, function (data) {
memo[term] = (memo[term] || []).concat(data);
callback.apply(null, arguments);
});
}
};
};
/**
* Determine if the array contains a given value.
*/
var include = function (array, value) {
var i, l;
if (array.indexOf) return array.indexOf(value) != -1;
for (i = 0, l = array.length; i < l; i++) {
if (array[i] === value) return true;
}
return false;
};
/**
* Textarea manager class.
*/
var Completer = (function () {
var html, css, $baseList, _id;
html = {
list: '<ul class="dropdown-menu"></ul>'
};
css = {
// Removed the 'top' property to support the placement: 'top' option
list: {
position: 'absolute',
left: 0,
zIndex: '100',
display: 'none'
}
};
$baseList = $(html.list).css(css.list);
_id = 0;
function Completer($el, option) {
var focus;
this.el = $el.get(0); // textarea element
focus = this.el === document.activeElement;
this.$el = $el;
this.id = 'textComplete' + _id++;
this.strategies = [];
this.option = option;
if (focus) {
this.initialize();
this.$el.focus();
} else {
this.$el.one('focus.textComplete', $.proxy(this.initialize, this));
}
}
/**
* Completer's public methods
*/
$.extend(Completer.prototype, {
/**
* Prepare ListView and bind events.
*/
initialize: function () {
var $list, globalEvents, appendTo, height;
$list = $baseList.clone();
this.listView = new ListView($list, this);
this.$el.on({
'keyup.textComplete': $.proxy(this.onKeyup, this),
'keydown.textComplete': $.proxy(this.listView.onKeydown, this.listView)
});
appendTo = this.option.appendTo;
if (appendTo) {
// Append ListView to specified element.
$list.appendTo(appendTo instanceof $ ? appendTo : $(appendTo));
} else {
$list.appendTo($('body'));
}
height = this.option.height;
if (height) {
$list.css("overflow-y", "auto");
$list.height(height);
}
globalEvents = {};
globalEvents['click.' + this.id] = $.proxy(this.onClickDocument, this);
globalEvents['keyup.' + this.id] = $.proxy(this.onKeyupDocument, this);
$(document).on(globalEvents);
},
/**
* Register strategies to the completer.
*/
register: function (strategies) {
this.strategies = this.strategies.concat(strategies);
},
/**
* Show autocomplete list next to the caret.
*/
renderList: function (data) {
if (this.clearAtNext) {
this.listView.clear();
this.clearAtNext = false;
}
if (data.length) {
this.listView.strategy = this.strategy;
if (!this.listView.shown) {
this.listView
.setPosition(this.getCaretPosition())
.clear()
.activate();
}
data = data.slice(0, this.strategy.maxCount);
this.listView.render(data);
}
if (!this.listView.data.length && this.listView.shown) {
this.listView.deactivate();
}
},
searchCallbackFactory: function (free) {
var self = this;
return function (data, keep) {
self.renderList(data);
if (!keep) {
// This is the last callback for this search.
free();
self.clearAtNext = true;
}
};
},
/**
* Keyup event handler.
*/
onKeyup: function (e) {
if (this.skipSearch(e)) { return; }
this.trigger(null, true);
},
/**
* Public interface for invoking textcomplete.
*/
trigger: function (text, suppress) {
var searchQuery, term;
text || (text = this.getTextFromHeadToCaret());
searchQuery = this.extractSearchQuery(text);
if (searchQuery.length) {
term = searchQuery[1];
if (suppress && this.term === term) {
return; // Ignore shift-key or something.
}
this.term = term;
this.search(searchQuery);
} else {
this.term = null;
this.listView.deactivate();
}
},
/**
* Suppress searching if it returns true.
*/
skipSearch: function (e) {
switch (e.keyCode) {
case 40: // DOWN
case 38: // UP
return true;
}
if (e.ctrlKey) switch (e.keyCode) {
case 78: // Ctrl-N
case 80: // Ctrl-P
return true;
}
},
onSelect: function (value) {
var pre, post, newSubStr, sel, range, selection, remainder;
pre = this.getTextFromHeadToCaret();
remainder = pre.length;
if (this.el.isContentEditable) {
sel = window.getSelection();
range = sel.getRangeAt(0);
selection = range.cloneRange();
selection.selectNodeContents(range.startContainer);
var content = selection.toString();
post = content.substring(range.startOffset);
} else {
post = this.el.value.substring(this.el.selectionEnd);
}
newSubStr = this.strategy.replace(value);
if ($.isArray(newSubStr)) {
post = newSubStr[1] + post;
newSubStr = newSubStr[0];
}
pre = pre.replace(this.strategy.match, newSubStr);
remainder = remainder - pre.length;
if (this.el.isContentEditable) {
for (var x = 0; x < remainder; ++x) {
document.execCommand('delete', false);
}
if (post) {
document.execCommand('insertHTML', false, post);
}
} else {
this.$el.val(pre + post);
this.el.selectionStart = this.el.selectionEnd = pre.length;
}
this.$el.trigger('change')
.trigger('textComplete:select', value);
this.el.focus();
},
/**
* Global click event handler.
*/
onClickDocument: function (e) {
if (e.originalEvent && !e.originalEvent.keepTextCompleteDropdown) {
this.listView.deactivate();
}
},
/**
* Global keyup event handler.
*/
onKeyupDocument: function (e) {
if (this.listView.shown && e.keyCode === 27) { // ESC
this.listView.deactivate();
this.$el.focus();
}
},
/**
* Remove all event handlers.
*/
destroy: function () {
this.$el.off('.textComplete');
$(document).off('.' + this.id);
if (this.listView) { this.listView.destroy(); }
this.$el.removeData('textComplete');
this.$el = null;
},
// Helper methods
// ==============
getCaretPosition: function () {
var caretPosition, textareaOffset;
caretPosition = this.getCaretRelativePosition();
textareaOffset = this.$el.offset();
caretPosition.top += textareaOffset.top;
caretPosition.left += textareaOffset.left;
return caretPosition;
},
/**
* Returns caret's relative coordinates from textarea's left top corner.
*/
getCaretRelativePosition: function () {
var properties, css, $div, $span, position, dir, scrollbar, range, node, $node;
if (!this.el.isContentEditable) {
// Browser native API does not provide the way to know the position of
// caret in pixels, so that here we use a kind of hack to accomplish
// the aim. First of all it puts a div element and completely copies
// the textarea's style to the element, then it inserts the text and a
// span element into the textarea.
// Consequently, the span element's position is the thing what we want.
properties = ['border-width', 'font-family', 'font-size', 'font-style',
'font-variant', 'font-weight', 'height', 'letter-spacing',
'word-spacing', 'line-height', 'text-decoration', 'text-align',
'width', 'padding-top', 'padding-right', 'padding-bottom',
'padding-left', 'margin-top', 'margin-right', 'margin-bottom',
'margin-left', 'border-style', 'box-sizing'
];
scrollbar = this.$el[0].scrollHeight > this.$el[0].offsetHeight;
css = $.extend({
position: 'absolute',
overflow: scrollbar ? 'scroll' : 'auto',
'white-space': 'pre-wrap',
top: 0,
left: -9999,
direction: dir
}, getStyles(this.$el, properties));
$div = $('<div></div>').css(css).text(this.getTextFromHeadToCaret());
$span = $('<span></span>').text('.').appendTo($div);
this.$el.before($div);
position = $span.position();
position.top += $span.height() - this.$el.scrollTop();
$div.remove();
} else {
range = window.getSelection().getRangeAt(0).cloneRange();
node = document.createElement('span');
range.insertNode(node);
range.selectNodeContents(node);
range.deleteContents();
$node = $(node);
position = $node.offset();
position.left -= this.$el.offset().left;
position.top += $node.height() - this.$el.offset().top;
}
dir = this.$el.attr('dir') || this.$el.css('direction');
if (dir === 'rtl') { position.left -= this.listView.$el.width(); }
return position;
},
getTextFromHeadToCaret: function () {
var text, selectionEnd, range;
if (this.el.isContentEditable) {
if (window.getSelection) {
// IE9+ and non-IE
var range = window.getSelection().getRangeAt(0);
var selection = range.cloneRange();
selection.selectNodeContents(range.startContainer);
text = selection.toString().substring(0, range.startOffset);
}
} else {
selectionEnd = this.el.selectionEnd;
if (typeof selectionEnd === 'number') {
text = this.el.value.substring(0, selectionEnd);
} else if (document.selection) {
range = this.el.createTextRange();
range.moveStart('character', 0);
range.moveEnd('textedit');
text = range.text;
}
}
return text;
},
/**
* Parse the value of textarea and extract search query.
*/
extractSearchQuery: function (text) {
var i, l, strategy, match;
for (i = 0, l = this.strategies.length; i < l; i++) {
strategy = this.strategies[i];
match = text.match(strategy.match);
if (match) { return [strategy, match[strategy.index]]; }
}
return [];
},
search: lock(function (free, searchQuery) {
var term;
this.strategy = searchQuery[0];
term = searchQuery[1];
this.strategy.search(term, this.searchCallbackFactory(free));
})
});
return Completer;
})();
/**
* Dropdown menu manager class.
*/
var ListView = (function () {
function ListView($el, completer) {
this.data = [];
this.$el = $el;
this.index = 0;
this.completer = completer;
if (completer.option.listPosition) {
this.setPosition = completer.option.listPosition;
}
this.$el.on('mousedown.textComplete', 'li.textcomplete-item',
$.proxy(this.onClick, this));
this.$el.on('mouseover.textComplete', 'li.textcomplete-item',
$.proxy(this.onMouseover, this));
}
$.extend(ListView.prototype, {
shown: false,
render: function (data) {
var html, i, l, index, val, str;
html = '';
if(this.strategy.header) {
if ($.isFunction(this.strategy.header)) {
str = this.strategy.header(data);
} else {
str = this.strategy.header;
}
html += '<li class="textcomplete-header">' + str + '</li>';
}
for (i = 0, l = data.length; i < l; i++) {
val = data[i];
if (include(this.data, val)) continue;
index = this.data.length;
this.data.push(val);
html += '<li class="textcomplete-item" data-index="' + index + '"><a>';
html += this.strategy.template(val);
html += '</a></li>';
if (this.data.length === this.strategy.maxCount) break;
}
if(this.strategy.footer) {
if ($.isFunction(this.strategy.footer)) {
str = this.strategy.footer(data);
} else {
str = this.strategy.footer;
}
html += '<li class="textcomplete-footer">' + str + '</li>';
}
this.$el.append(html);
if (!this.data.length) {
this.deactivate();
} else {
this.activateIndexedItem();
this.setScroll();
}
},
clear: function () {
this.data = [];
this.$el.html('');
this.index = 0;
return this;
},
activateIndexedItem: function () {
this.$el.find('.active').removeClass('active');
this.getActiveItem().addClass('active');
},
getActiveItem: function () {
return $(this.$el.children('.textcomplete-item').get(this.index));
},
activate: function () {
if (!this.shown) {
this.$el.show();
this.completer.$el.trigger('textComplete:show');
this.shown = true;
}
return this;
},
deactivate: function () {
if (this.shown) {
this.$el.hide();
this.completer.$el.trigger('textComplete:hide');
this.shown = false;
this.data = [];
this.index = null;
}
return this;
},
setPosition: function (position) {
var fontSize;
// If the strategy has the 'placement' option set to 'top', move the
// position above the element
if(this.strategy.placement.indexOf('top') > -1) {
// Move it to be in line with the match character
fontSize = parseInt(this.$el.css('font-size'));
// Overwrite the position object to set the 'bottom' property instead of the top.
position = {
top: 'auto',
bottom: this.$el.parent().height() - position.top + fontSize,
left: position.left
};
} else {
// Overwrite 'bottom' property because once `placement: 'top'`
// strategy is shown, $el keeps the property.
position.bottom = 'auto';
}
if (this.strategy.placement.indexOf('absleft') > -1) {
position.left = 0;
}
if (this.strategy.placement.indexOf('absright') > -1) {
position.right = 0;
position.left = 'auto';
}
this.$el.css(position);
return this;
},
setScroll: function (e) {
var $activeItem = this.getActiveItem();
var itemTop = $activeItem.position().top;
var itemHeight = $activeItem.outerHeight();
var visibleHeight = this.$el.innerHeight();
var visibleTop = this.$el.scrollTop();
if (this.index === 0 || this.index === this.data.length - 1 || itemTop < 0) {
this.$el.scrollTop(itemTop + visibleTop);
} else if (itemTop + itemHeight > visibleHeight) {
this.$el.scrollTop(itemTop + itemHeight + visibleTop - visibleHeight);
}
},
select: function (index) {
var self = this;
this.completer.onSelect(this.data[index]);
// Deactive at next tick to allow other event handlers to know whether
// the dropdown has been shown or not.
setTimeout(function () { self.deactivate(); }, 0);
},
onKeydown: function (e) {
if (!this.shown) return;
var modifiers = e.ctrlKey || e.altKey || e.metaKey || e.shiftKey;
if (e.keyCode === 38 || (e.ctrlKey && e.keyCode === 80)) { // UP, or Ctrl-P
e.preventDefault();
if (this.index === 0) {
this.index = this.data.length-1;
} else {
this.index -= 1;
}
this.activateIndexedItem();
this.setScroll();
} else if (e.keyCode === 40 || (e.ctrlKey && e.keyCode === 78)) { // DOWN, or Ctrl-N
e.preventDefault();
if (this.index === this.data.length - 1) {
this.index = 0;
} else {
this.index += 1;
}
this.activateIndexedItem();
this.setScroll();
} else if (!modifiers && (e.keyCode === 13 || e.keyCode === 9)) { // ENTER or TAB
e.preventDefault();
this.select(parseInt(this.getActiveItem().data('index'), 10));
}
else if (e.keyCode === 33) { // PAGEUP
e.preventDefault();
var target = 0;
var threshold = this.getActiveItem().position().top - this.$el.innerHeight();
this.$el.children().each(function (i) {
if ($(this).position().top + $(this).outerHeight() > threshold) {
target = i;
return false;
}
});
this.index = target;
this.activateIndexedItem();
this.setScroll();
}
else if (e.keyCode === 34) { // PAGEDOWN
e.preventDefault();
var target = this.data.length - 1;
var threshold = this.getActiveItem().position().top + this.$el.innerHeight();
this.$el.children().each(function (i) {
if ($(this).position().top > threshold) {
target = i;
return false;
}
});
this.index = target;
this.activateIndexedItem();
this.setScroll();
}
},
onClick: function (e) {
var $e = $(e.target);
e.preventDefault();
e.originalEvent.keepTextCompleteDropdown = true;
if (!$e.hasClass('textcomplete-item')) {
$e = $e.parents('li.textcomplete-item');
}
this.select(parseInt($e.data('index'), 10));
},
onMouseover: function (e){
var $e = $(e.target);
e.preventDefault();
if(!$e.hasClass('textcomplete-item')) {
$e = $e.parents('li.textcomplete-item');
}
this.index = parseInt($e.data('index'), 10)
this.activateIndexedItem();
},
destroy: function () {
this.deactivate();
this.$el.off('click.textComplete').remove();
this.$el = null;
}
});
return ListView;
})();
$.fn.textcomplete = function (strategies, option) {
var i, l, strategy, dataKey;
dataKey = 'textComplete';
option || (option = {});
if (strategies === 'destroy') {
return this.each(function () {
var completer = $(this).data(dataKey);
if (completer) { completer.destroy(); }
});
}
for (i = 0, l = strategies.length; i < l; i++) {
strategy = strategies[i];
if (!strategy.template) {
strategy.template = identity;
}
if (strategy.index == null) {
strategy.index = 2;
}
if (strategy.cache) {
strategy.search = memoize(strategy.search);
}
strategy.maxCount || (strategy.maxCount = 10);
}
return this.each(function () {
var $this, completer;
$this = $(this);
completer = $this.data(dataKey);
if (!completer) {
completer = new Completer($this, option);
$this.data(dataKey, completer);
}
completer.register(strategies);
});
};
})(window.jQuery || window.Zepto);