-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathotobox.js
1230 lines (1003 loc) · 35.8 KB
/
otobox.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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* otobox - Simple and fast JavaScript/HTML5 library to create autocomplete inputs
*
* Afshin Mehrabani [@afshinmeh]
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else {
// Browser globals
root.otobox = factory();
}
}(this, function () {
/**
* To init basic settings and variables
*/
function _init (selector) {
/**
* Default options
*/
this._options = {
/* value key */
valueKey: 'value',
/* CSS classes and IDs prefix */
namingPrefix: 'otobox-',
/* Should otobox update the target object with text or html? */
useText: true,
/* Default templates */
templates: {
suggestion: '<a href="javascript:void(0);" data-value="{{otobox_value}}">{{display}}</a>',
choice: '<a data-value="{{otobox_value}}" data-key="{{otobox_key}}" data-activator="{{otobox_activator}}" data-choice="" class="otobox-choiceItem">{{otobox_key}}{{display}}</a>'
}
};
//an empty list for activators
this._activators = [];
//an stack to keep pressed keys
this._stack = '';
//to hold the key that called the activator
this._stackActivator = '';
//modes
// 0 == normal
// 1 == insert
this._modes = {
normal: 0,
insert: 1
}
//current mode of otobox
this._currentMode = this._modes.normal;
//current activator
this._currentActivator = null;
//wrapper
this._wrapper = null;
//to collect current filtered results
this._sourceResult = null;
//custom events
this._events = {};
//ok lets find the target object according to the given parameters
var targetObject = null;
if (typeof (selector) == 'object') {
targetObject = selector;
} else if (typeof (selector) == 'string') {
var queryObject = document.querySelector(selector);
if (queryObject != null) {
targetObject = queryObject;
} else {
_error.call(this,'Unable to find the target object with the given CSS selector.');
}
} else {
_error.call(this, 'Unable to initiate with the given parameter for init.');
}
if (targetObject != null) {
this._targetObject = targetObject;
//wrap the target object in the otobox container
_wrapIn.call(this, targetObject);
} else {
_error.call(this, 'targetObject is empty.');
}
};
/**
* Get the name + prefix
* For classNames and IDs
*/
function _c (name) {
return this._options.namingPrefix + name;
};
/**
* Wrap the target element in otobox container
*/
function _wrapIn (targetObject) {
var targetObjectSize = targetObject.getBoundingClientRect();
var wrapperDiv = this._wrapper = document.createElement('div');
wrapperDiv.className = _c.call(this, 'wrapper');
if (targetObject.className != '') {
wrapperDiv.className += ' ' + targetObject.className;
}
//append wrapper right before the target object
targetObject.parentNode.insertBefore(wrapperDiv, targetObject);
targetObject.className += ' ' + _c.call(this, 'input');
//add the target object
wrapperDiv.appendChild(targetObject);
//div for editing
var editableDiv = document.createElement('div');
editableDiv.setAttribute('name', _c.call(this, 'editableDiv'));
editableDiv.setAttribute('contenteditable', true);
editableDiv.setAttribute('data-placeholder', targetObject.placeholder);
editableDiv.className = _c.call(this, 'editableDiv');
//set width and height to the wrapper
wrapperDiv.style.width = targetObjectSize.width + 'px';
//if it's textarea
if (targetObject.nodeName.toLowerCase() == 'textarea') {
editableDiv.className += ' ' + _c.call(this, 'textarea-target');
wrapperDiv.style.height = targetObjectSize.height + 'px';
} else {
editableDiv.className += ' ' + _c.call(this, 'input-target');
}
wrapperDiv.appendChild(editableDiv);
//ul for choices list
var ulWrapper = document.createElement('ul');
ulWrapper.className = _c.call(this, 'choices');
wrapperDiv.appendChild(ulWrapper);
//loading element
var loadingElement = document.createElement("div");
loadingElement.className = _c.call(this, 'loadingElement');
wrapperDiv.appendChild(loadingElement);
//bind keys to the target object
_addBindingKeys.call(this, targetObject);
};
/**
* Add an activator to activators list
*
* An example of activator object:
*
* {
* name: 'mention.array',
* key: /./,
* source: 'http://example.com/boo.json',
* allowedChars: /[a-zA-Z]+/,
* valueKey: 'value',
* mode: 'select'
* }
*/
function _addActivator (activatorObject) {
if (activatorObject != null) {
if (typeof (activatorObject.key) != 'undefined' && typeof (activatorObject.source) != 'undefined' && typeof (activatorObject.name) != 'undefined') {
//check allowed chars regex
activatorObject.allowedChars = _normalizeActivatorAllowedCharsRegExp.call(this, activatorObject);
//save the activator key because we are changing the `key` property
//this tempKey is used for the `setChoiceManually` function. Maybe we should use a better approach here
activatorObject.tempKey = activatorObject.key;
//normalize activator key regex
activatorObject.key = _normalizeActivatorKeyRegExp.call(this, activatorObject);
//can user enter a custom choice?
activatorObject.customChoice = !!activatorObject.customChoice;
//check and set correct value key
activatorObject.valueKey = activatorObject.valueKey || this._options.valueKey;
//set templates
if (typeof (activatorObject.templates) != 'object') {
activatorObject.templates = this._options.templates;
}
this._activators.push(activatorObject);
} else {
_error.call(this, 'Name, key and source fields are mandatory for activator object.');
}
} else {
_error.call(this, 'Activator object is empty.');
}
};
/**
* Get an activator by name
*/
function _getActivator (name) {
for (var i = 0; i < this._activators.length; i++) {
var activator = this._activators[i];
if (activator.name == name)
return activator;
}
return null;
};
/**
* Normalize activator's activator key regex
*/
function _normalizeActivatorKeyRegExp (activator) {
var regex = null;
if (typeof (activator.key) == 'string') {
//converting string to RegExp
try {
regex = new RegExp(activator.key);
} catch (exp) {
_error.call(this, exp.message);
}
} else if (typeof (activator.key) == 'object' && activator.key instanceof RegExp) {
regex = activator.key;
} else {
error.call(this, 'Unable to match the entered character against activator key.')
}
return regex;
};
/**
* Normalize activator's allowed character allowed chars
*/
function _normalizeActivatorAllowedCharsRegExp (activator) {
return activator.allowedChars || /.+/;
};
/**
* Is the pressed key is an activator key?
*/
function _isActivatorKey (str, targetObject) {
if (this._activators.length > 0) {
for (var i = 0; i < this._activators.length; i++) {
var activator = this._activators[i];
var regex = _normalizeActivatorKeyRegExp.call(this, activator);
//lets compare using lovely regex :)
if (regex.test(str)) {
return activator;
break;
}
}
}
return null;
};
/**
* To get the source name + prefix
*/
function _getSourceName (sourceName) {
return sourceName + 'Source';
};
/**
* Check the source and call corresponding method to lookup
*/
function _routeToSource () {
if (this._currentActivator != null) {
var activator = this._currentActivator;
var sourceName = null;
if (typeof (activator.sourceType) == 'string') {
sourceName = activator.sourceType;
} else if (typeof (activator.source) == 'object') {
//array, object, etc.
if (activator.source instanceof Array) {
sourceName = 'array';
}
} else if (typeof (activator.source) == 'string') {
//xhr source
sourceName = 'xhr';
}
if (sourceName != null) {
if (typeof (otobox.prototype[_getSourceName.call(this, sourceName)]) == 'function') {
return otobox.prototype[_getSourceName.call(this, sourceName)];
} else {
_error.call(this, 'No source with name "' + _getSourceName.call(this, sourceName) + '" found.');
}
} else {
_error.call(this, 'Activator\'s source is unknown.');
}
} else {
_error.call(this, 'Current activator is empty.');
}
};
/**
* Clear choices list
*/
function _clearChoicesList () {
var liList = this._wrapper.querySelectorAll('ul.' + _c.call(this, 'choices') + ' > li');
if (liList != null && liList.length > 0) {
for (var i = 0; i < liList.length; i++) {
liList[i].parentNode.removeChild(liList[i]);
}
}
};
/**
* Remove hint from targetobject
*/
function _clearHint () {
var targetObject = this._targetObject;
var editableDiv = this._wrapper.querySelector('.' + _c.call(this, 'editableDiv'));
var hintElement = editableDiv.querySelector('.' + _c.call(this, 'hint'));
if (hintElement != null) {
hintElement.parentNode.removeChild(hintElement);
}
_setTargetObjectValue.call(this, this._options.useText ? editableDiv.textContent : editableDiv.innerHTML);
};
/**
* Generate choice element
*/
function _generateChoiceElement (activatorKey, item, activator) {
//fist of all, fill 'data-*' attributes
var choiceElementTemplate = _format(activator.templates.choice, { otobox_key: activatorKey, otobox_activator: activator.name });
//then replace items that is related to
choiceElementTemplate = _format(choiceElementTemplate, item);
//convert string to dom
var tempDom = document.createElement('div');
tempDom.innerHTML = choiceElementTemplate;
var choiceElement = tempDom.firstChild;
//we use this attribute to:
//1) create css queries to get choices
//2) compare the textContent in onkeyup and handleChoice function and detect changes in the choice
choiceElement.setAttribute('data-choice', choiceElement.textContent);
return choiceElement;
};
/**
* Set the choice
*/
function _setChoice (item) {
var editableDiv = this._wrapper.querySelector('.' + _c.call(this, 'editableDiv'));
var selectedRange = document.getSelection();
var activator = this._currentActivator;
var choiceLink = _generateChoiceElement.call(this, this._stackActivator, item, activator);
var textNode = document.createTextNode('\u00A0');
selectedRange.getRangeAt(0).insertNode(textNode);
selectedRange.getRangeAt(0).insertNode(choiceLink);
//TODO: compatible it with older version of IE
var createdRange = document.createRange();
createdRange.setStart(textNode, 1);
createdRange.collapse(true);
selectedRange.removeAllRanges();
selectedRange.addRange(createdRange);
_changeMode.call(this, this._modes.normal);
_toggleChoiceListState.call(this, false);
_setTargetObjectValue.call(this, this._options.useText ? editableDiv.textContent : editableDiv.innerHTML);
};
/**
* Manually set a choice
*/
function _setChoiceManually (activatorName, item) {
var editableDiv = this._wrapper.querySelector('.' + _c.call(this, 'editableDiv'));
var activator = _getActivator.call(this, activatorName);
//generate the choice link
var choiceLink = _generateChoiceElement.call(this, activator.tempKey, item, activator);
editableDiv.appendChild(choiceLink);
};
/**
* Fill choices list with the corresponding source
*/
function _fillChoicesList (source) {
var self = this;
//don't call the source when stack is empty
if (this._stack == '') {
return;
}
//add loading to the container
if (!/loading/.test(this._wrapper.className)) {
this._wrapper.className += ' ' + _c.call(this, 'loading');
}
source.call(this, this._currentActivator, this._stack, this._options, function (result) {
var activator = self._currentActivator;
//set temp result array
self._sourceResult = result;
//clear items first
_clearChoicesList.call(self);
if (typeof (result) == 'object' && result instanceof Array) {
var ulWrapper = self._wrapper.querySelector('ul.' + _c.call(self, 'choices'));
if (result.length > 0) {
for (var i = 0; i < result.length; i++) {
var resultItem = result[i];
var li = document.createElement('li');
//get and parse choice template
var suggestionTemplate = _format(activator.templates.suggestion, resultItem);
var tempDom = document.createElement('div');
tempDom.innerHTML = suggestionTemplate;
var anchor = tempDom.firstChild;
(function (resultItem) {
anchor.onclick = function () {
//clear the hint first
_clearHint.call(self);
_setChoice.call(self, resultItem);
};
}(resultItem));
li.appendChild(anchor);
ulWrapper.appendChild(li);
}
} else {
var li = document.createElement('li');
var span = document.createElement('span');
span.className = _c.call(self, 'empty');
span.textContent = 'No result';
li.appendChild(span);
ulWrapper.appendChild(li);
}
} else {
_error.call(self, 'Source returned bad data type.');
}
//remove loading class
self._wrapper.className = self._wrapper.className.replace(new RegExp(_c.call(self, 'loading')), '').trim();
});
};
/**
* Set choices list to active or deactive
*/
function _toggleChoiceListState (isActive) {
isActive = !!isActive;
var wrapper = this._wrapper;
//remove active class first
wrapper.className = wrapper.className.replace(/otobox-active/gi, '').trim();
if (isActive === true) {
wrapper.className += ' otobox-active';
}
};
/**
* Change otobox mode
*/
function _changeMode (mode) {
if (mode == this._modes.normal) {
this._stack = '';
this._stackActivator = '';
this._currentMode = this._modes.normal;
if (this._currentActivator != null) {
if (!this._currentActivator.customChoice) {
//remove the hint box and convert it to text
_convertHintToText.call(this);
} else {
_convertHintToChoice.call(this);
}
}
this._currentActivator = null;
} else if (mode == this._modes.insert) {
this._stack = '';
this._stackActivator = '';
this._currentMode = this._modes.insert;
}
};
/**
* Convert hint to the choice element
*/
function _convertHintToChoice () {
var editableDiv = this._wrapper.querySelector('.' + _c.call(this, 'editableDiv'));
var hintElement = editableDiv.querySelector('.' + _c.call(this, 'hint'));
if (hintElement != null) {
var activatorParts = _isActivatorText.call(this, hintElement.textContent);
var choiceElement = _generateChoiceElement.call(this, activatorParts.activatorKey, { otobox_value: activatorParts.hintText }, activatorParts.activator);
hintElement.parentNode.insertBefore(choiceElement, hintElement);
hintElement.parentNode.removeChild(hintElement);
}
};
/**
* Remove hint element and change it to a text element
*/
function _convertHintToText () {
var editableDiv = this._wrapper.querySelector('.' + _c.call(this, 'editableDiv'));
var hintElement = editableDiv.querySelector('.' + _c.call(this, 'hint'));
if (hintElement != null) {
var textElement = document.createTextNode(hintElement.textContent);
//add the text element and remove the hint element
hintElement.parentNode.insertBefore(textElement, hintElement);
hintElement.parentNode.removeChild(hintElement);
var selectedRange = document.getSelection();
//TODO: compatible it with older versions of IE
var createdRange = document.createRange();
createdRange.setStart(textElement, hintElement.textContent.length);
selectedRange.removeAllRanges();
selectedRange.addRange(createdRange);
}
};
/**
* Set value to target object
*/
function _setTargetObjectValue (value) {
var targetObject = this._targetObject;
if (typeof (targetObject.value) != 'undefined') {
//input
targetObject.value = value;
} else {
//textarea
targetObject.textContent = value;
}
};
/**
* Get current value of targetObject
*/
function _getTargetObjectValue () {
var targetObject = this._targetObject;
if (typeof (targetObject.value) != 'undefined') {
//input
return targetObject.value;
} else {
//textarea
return targetObject.textContent;
}
};
/**
* Check to see if the user is typing in a hint area
* e.g.: Hello world @afshin...
*/
function _isHintArea () {
var editableDiv = this._wrapper.querySelector('.' + _c.call(this, 'editableDiv'));
//TODO: compatible it with older versions of IE
var selectedRange = document.getSelection().getRangeAt(0);
//hint elements should be inside the editable div
if (selectedRange.startContainer.parentNode != editableDiv)
return;
if (selectedRange.startContainer.nodeType == 3) {
var inputValue = selectedRange.startContainer.textContent;
} else {
var inputValue = editableDiv.textContent;
}
var before = '';
for (var i = selectedRange.startOffset - 1; i >= 0; i--) {
var currentValue = inputValue[i];
//whitespace is a breaking word
if (/\s/.test(currentValue)) {
break;
}
before = currentValue + before;
}
var after = '';
for (var i = selectedRange.startOffset; i < inputValue.length; i++) {
var currentValue = inputValue[i];
//whitespace is a breaking word
if (/\s/.test(currentValue)) {
break;
}
after += currentValue;
}
return _isActivatorText.call(this, before + after);
};
/**
* Check if the given text can match against one of activators
*/
function _isActivatorText (text) {
if (this._activators.length > 0) {
var activatorKey = text[0];
var hint = text.substr(1, text.length - 1);
for (var i = 0; i < this._activators.length; i++) {
var activator = this._activators[i];
//first match the activatorkey
if (activator.key.test(activatorKey)) {
//then check if the whole part of the text is match
if (activator.allowedChars.test(hint)) {
return {
activator: activator,
activatorKey: activatorKey,
hintText: hint
};
}
}
}
}
return null;
};
/**
* Place hint element at the current range
*/
function _placeHintElement (text, activator) {
var hintElement = document.createElement('span');
hintElement.className = _c.call(this, 'hint');
hintElement.setAttribute('data-activator', activator.name);
hintElement.textContent = text;
var selectedRange = document.getSelection();
selectedRange.getRangeAt(0).insertNode(hintElement);
//TODO: compatible it with older versions of IE
var createdRange = document.createRange();
createdRange.setStart(hintElement, 1);
selectedRange.removeAllRanges();
selectedRange.addRange(createdRange);
return hintElement;
};
/**
* check if the pressed key is in the hint area
*/
function _handleHintArea (e) {
var targetObject = this._targetObject;
if (this._currentMode == this._modes.normal) {
//check and see if user is typing in a hint area that is not considered as a hint element already
var activatorParts = _isHintArea.call(this);
if (activatorParts != null) {
_changeMode.call(this, this._modes.insert);
this._currentActivator = activatorParts.activator;
this._stackActivator = activatorParts.activatorKey;
this._stack = activatorParts.hintText;
//place the hint element first
var hintElement = _placeHintElement.call(this, this._stackActivator + this._stack, activatorParts.activator);
//and them eliminate the text
var prevElement = hintElement.previousSibling;
if (prevElement.nodeType == 3) {
prevElement.textContent = prevElement.textContent.replace(this._stackActivator + this._stack, '');
}
}
}
};
/**
* check if the pressed key is for one of activators
*/
function _handleActivatorKey (e) {
var targetObject = this._targetObject;
var activatorObject = _isActivatorKey.call(this, String.fromCharCode(e.which), targetObject);
var focusNode = document.getSelection().focusNode;
//there should be an space before the choice element
if (this._currentMode == this._modes.normal && activatorObject != null && /\s/.test(focusNode.textContent[document.getSelection().focusOffset - 1])) {
//set correct mode and current activator
_changeMode.call(this, this._modes.insert);
this._currentActivator = activatorObject;
this._stackActivator = String.fromCharCode(e.which);
//append hint element
_placeHintElement.call(this, String.fromCharCode(e.which), activatorObject);
e.preventDefault()
} else {
if (this._currentMode == this._modes.insert && /hint/.test(focusNode.parentNode.className)) {
var activator = this._currentActivator;
//check if the entered character is valid or not
if (activator.allowedChars.test(String.fromCharCode(e.which))) {
this._stack += String.fromCharCode(e.which);
var sourceFunction = _routeToSource.call(this);
_fillChoicesList.call(this, sourceFunction);
//show choices list
_toggleChoiceListState.call(this, true);
} else {
_changeMode.call(this, this._modes.normal);
_toggleChoiceListState.call(this, false);
}
}
}
};
/**
* Check and see if user has changed one of choices
*/
function _handleChoiceChange (e) {
var focusNode = document.getSelection().focusNode;
//so this is a choice element
if (this._currentMode == this._modes.normal && focusNode != null && focusNode.parentNode.hasAttribute('data-choice')) {
var choiceElement = focusNode.parentNode;
//since we consider whitespace as a global separator character, we handle it
//more carefully when it comes into choice elements
if (/\s/.test(String.fromCharCode(e.which))) {
var selection = document.getSelection();
var selectionRange = selection.getRangeAt(0);
var startOffset = selectionRange.startOffset;
var textNodeContent = '';
//we are at the end of the choice element
if (choiceElement.textContent.length == startOffset) {
textNodeContent = '\u00A0';
} else {
//other parts of the choice element
var beforeStr = choiceElement.textContent.substr(0, startOffset).trim();
var afterStr = choiceElement.textContent.substr(startOffset, choiceElement.textContent.length);
//first alter the content of the choice link
choiceElement.textContent = beforeStr;
textNodeContent = '\u00A0' + afterStr;
}
var textNode = document.createTextNode(textNodeContent);
choiceElement.parentNode.insertBefore(textNode, choiceElement.nextSibling);
var createdRange = document.createRange();
createdRange.setStart(textNode, 1);
createdRange.collapse(true);
selection.removeAllRanges();
selection.addRange(createdRange);
//well, we should remove the whitepsace that user is pressed
//I think this approach is the best
choiceElement.textContent = choiceElement.textContent.trim();
}
var activator = _getActivator.call(this, choiceElement.getAttribute('data-activator'));
//it seems user is changing the choice content
if (activator.customChoice) {
//its okay if user change the content of the choice
//we will alter attributes for the choice as well
var activatorParts = _isActivatorText.call(this, choiceElement.textContent);
if (activatorParts != null) {
//I'm not sure whether this is a good approach to update an attribute or not
//TODO: review this part
choiceElement.setAttribute('data-value', activatorParts.hintText);
choiceElement.setAttribute('data-choice', activatorParts.activatorKey + activatorParts.hintText);
}
}
}
//then check all choices and cleanup those that doesn't in a correct format
var choices = this._wrapper.querySelectorAll('*[data-choice]');
for (var i = 0; i < choices.length; i++) {
var choice = choices[i];
var activator = _getActivator.call(this, choice.getAttribute('data-activator'));
if (!_isActivatorText.call(this, choice.textContent) || (!activator.customChoice && choice.getAttribute('data-choice') != choice.textContent)) {
var textElement = document.createTextNode(choice.textContent);
var selectedRange = document.getSelection();
var startOffset = selectedRange.getRangeAt(0).startOffset;
var createdRange = document.createRange();
//add the text element and remove the hint element
choice.parentNode.insertBefore(textElement, choice);
choice.parentNode.removeChild(choice);
if (!/\s/.test(String.fromCharCode(e.which)) && textElement.textContent.length >= startOffset) {
createdRange.setStart(textElement, startOffset);
createdRange.collapse(true);
selectedRange.removeAllRanges();
selectedRange.addRange(createdRange);
}
}
}
};
/**
* Check and remove hint element if it's empty
*/
function _handleEmptyHintElement () {
if (this._currentMode == this._modes.insert) {
var hintElement = this._wrapper.querySelector('.' + _c.call(this, 'editableDiv') + ' .' + _c.call(this, 'hint'));
if (hintElement == null || hintElement.textContent == '' || hintElement.textContent == this._stackActivator) {
_changeMode.call(this, this._modes.normal);
_toggleChoiceListState.call(this, false);
}
}
};
/**
* Update and show the new suggestions list
*/
function _handleUpdatedChoices () {
if (this._currentMode == this._modes.insert) {
var sourceFunction = _routeToSource.call(this);
_fillChoicesList.call(this, sourceFunction);
//show choices list
_toggleChoiceListState.call(this, true);
}
};
/**
* Update and set the new stack value according to the hint element
*/
function _updateStack () {
if (this._currentMode == this._modes.insert) {
var hintElement = this._wrapper.querySelector('.' + _c.call(this, 'editableDiv') + ' .' + _c.call(this, 'hint'));
if (hintElement != null) {
var activatorName = hintElement.getAttribute('data-activator');
var activator = _getActivator.call(this, activatorName);
var activatorParts = _isActivatorText.call(this, hintElement.textContent);
if (activatorParts != null)
this._stack = activatorParts.hintText;
}
}
};
/**
* Go to next choice and make it active
*/
function _selectChoice (e, up) {
if (this._currentMode == this._modes.insert) {
var currentChoice = this._wrapper.querySelector('.' + _c.call(this, 'active'));
if (currentChoice != null) {
currentChoice.className = '';
if (up) {
var previousItem = currentChoice.previousSibling;
if (previousItem != null) {
previousItem.className = _c.call(this, 'active')
}
} else {
var nextItem = currentChoice.nextSibling;
if (nextItem != null) {
nextItem.className = _c.call(this, 'active')
}
}
} else {
if (up) {
var lastItem = this._wrapper.querySelector('ul.' + _c.call(this, 'choices') + ' > li:last-child');
if (lastItem != null) {
lastItem.className = _c.call(this, 'active');
}
} else {
var firstItem = this._wrapper.querySelector('ul.' + _c.call(this, 'choices') + ' > li:first-child');
if (firstItem != null) {
firstItem.className = _c.call(this, 'active');
}
}
}
e.preventDefault();
}
};
/**
* Get item by value
*/
function _getItem (value, activator) {
var arr = this._sourceResult;
for (var i = 0; i < arr.length; i++) {
var arrItem = arr[i];
if (arrItem[activator.valueKey] == value) {
return arrItem;
}
}
};
/**
* Get all available choices
*/
function _getChoices () {
var result = {};
var choices = this._wrapper.querySelectorAll('.' + _c.call(this, 'editableDiv') + ' *[data-choice]');
for (var i = 0; i < choices.length; i++) {
var choiceItem = choices[i];
var activator = choiceItem.getAttribute('data-activator');
if (typeof (result[activator]) == 'undefined') {
result[activator] = [];
}
result[activator].push(choiceItem.getAttribute('data-value'));
}
return result;
};
/**
* Add binding keys
*/
function _addBindingKeys (targetObject) {
var self = this;
var editableDiv = this._wrapper.querySelector('.' + _c.call(this, 'editableDiv'));
editableDiv.onkeypress = function (e) {
_handleHintArea.call(self, e);
_handleActivatorKey.call(self, e);
};
editableDiv.onkeydown = function (e) {
if (e.keyCode == 38) {
//up
_selectChoice.call(self, e, true);
}
if (e.keyCode == 40) {
//down
_selectChoice.call(self, e, false);
}
if (e.keyCode == 13) {
//enter
if (self._currentMode == self._modes.insert) {
//now we should select an item
var currentAnchor = self._wrapper.querySelector('li.' + _c.call(self, 'active') + ' a');
var itemObject = _getItem.call(self, currentAnchor.getAttribute('data-value'), self._currentActivator);
//clear the hint first