forked from cisco-open-source/qtwebdriver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.keyboard.js
1683 lines (1514 loc) · 59.9 KB
/
jquery.keyboard.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
/*!
jQuery UI Virtual Keyboard
Version 1.17.18
Author: Jeremy Satterfield
Modified: Rob Garrison (Mottie on github)
-----------------------------------------
Licensed under the MIT License
Caret code modified from jquery.caret.1.02.js
Licensed under the MIT License:
http://www.opensource.org/licenses/mit-license.php
-----------------------------------------
An on-screen virtual keyboard embedded within the browser window which
will popup when a specified entry field is focused. The user can then
type and preview their input before Accepting or Canceling.
As a plugin to jQuery UI styling and theme will automatically
match that used by jQuery UI with the exception of the required CSS.
Requires:
jQuery
jQuery UI (position utility only) & CSS theme
Setup/Usage:
Please refer to https://github.com/Mottie/Keyboard/wiki
*/
/*jshint browser:true, jquery:true, unused:false */
;(function($){
"use strict";
$.keyboard = function(el, options){
var base = this, o;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Add a reverse reference to the DOM object
base.$el.data("keyboard", base);
base.init = function(){
base.options = o = $.extend(true, {}, $.keyboard.defaultOptions, options);
// Shift and Alt key toggles, sets is true if a layout has more than one keyset
// used for mousewheel message
base.shiftActive = base.altActive = base.metaActive = base.sets = base.capsLock = false;
base.lastKeyset = [false, false, false]; // [shift, alt, meta]
// Class names of the basic key set - meta keysets are handled by the keyname
base.rows = [ '', '-shift', '-alt', '-alt-shift' ];
base.acceptedKeys = [];
base.mappedKeys = {}; // for remapping manually typed in keys
$('<!--[if lte IE 8]><script>jQuery("body").addClass("oldie");</script><![endif]--><!--[if IE]>' +
'<script>jQuery("body").addClass("ie");</script><![endif]-->').appendTo('body').remove();
base.msie = $('body').hasClass('oldie'); // Old IE flag, used for caret positioning
base.allie = $('body').hasClass('ie');
base.inPlaceholder = base.$el.attr('placeholder') || '';
// html 5 placeholder/watermark
base.watermark = (typeof(document.createElement('input').placeholder) !== 'undefined' &&
base.inPlaceholder !== '');
// save default regex (in case loading another layout changes it)
base.regex = $.keyboard.comboRegex;
// determine if US "." or European "," system being used
base.decimal = ( /^\./.test(o.display.dec) ) ? true : false;
// convert mouse repeater rate (characters per second) into a time in milliseconds.
base.repeatTime = 1000/(o.repeatRate || 20);
// delay in ms to prevent mousedown & touchstart from both firing events at the same time
o.preventDoubleEventTime = o.preventDoubleEventTime || 100;
// flag indication that a keyboard is open
base.isOpen = false;
// Check if caret position is saved when input is hidden or loses focus
// (*cough* all versions of IE and I think Opera has/had an issue as well
base.temp = $('<input style="position:absolute;left:-9999em;top:-9999em;" type="text" value="testing">')
.appendTo('body').caret(3,3);
// Also save caret position of the input if it is locked
base.checkCaret = (o.lockInput || base.temp.hide().show().caret().start !== 3 ) ? true : false;
base.temp.remove();
base.lastCaret = { start:0, end:0 };
base.temp = [ '', 0, 0 ]; // used when building the keyboard - [keyset element, row, index]
// Bind events
$.each('initialized beforeVisible visible hidden canceled accepted beforeClose'.split(' '), function(i,f){
if ($.isFunction(o[f])){
base.$el.bind(f + '.keyboard', o[f]);
}
});
// Close with esc key & clicking outside
if (o.alwaysOpen) { o.stayOpen = true; }
$(document).bind('mousedown keyup touchstart checkkeyboard'.split(' ').join('.keyboard '), function(e){
if (base.opening) { return; }
base.escClose(e);
// needed for IE to allow switching between keyboards smoothly
if ( e.target && $(e.target).hasClass('ui-keyboard-input') ) {
var kb = $(e.target).data('keyboard');
if (kb && kb.options.openOn) {
kb.focusOn();
}
}
});
// Display keyboard on focus
base.$el
.addClass('ui-keyboard-input ' + o.css.input)
.attr({ 'aria-haspopup' : 'true', 'role' : 'textbox' });
// add disabled/readonly class - dynamically updated on reveal
if (base.$el.is(':disabled') || (base.$el.attr('readonly') &&
!base.$el.hasClass('ui-keyboard-lockedinput'))) {
base.$el.addClass('ui-keyboard-nokeyboard');
}
if (o.openOn) {
base.$el.bind(o.openOn + '.keyboard', function(){
base.focusOn();
});
}
// Add placeholder if not supported by the browser
if (!base.watermark && base.$el.val() === '' && base.inPlaceholder !== '' &&
base.$el.attr('placeholder') !== '') {
base.$el
.addClass('ui-keyboard-placeholder') // css watermark style (darker text)
.val( base.inPlaceholder );
}
base.$el.trigger( 'initialized.keyboard', [ base, base.el ] );
// initialized with keyboard open
if (o.alwaysOpen) {
base.reveal();
}
};
base.setCurrent = function(){
// ui-keyboard-has-focus is applied in case multiple keyboards have alwaysOpen = true and are stacked
$('.ui-keyboard-has-focus').removeClass('ui-keyboard-has-focus');
$('.ui-keyboard-input-current').removeClass('ui-keyboard-input-current');
base.$el.addClass('ui-keyboard-input-current');
base.$keyboard.addClass('ui-keyboard-has-focus');
base.isCurrent(true);
base.isOpen = true;
};
base.isCurrent = function(set){
var cur = $.keyboard.currentKeyboard || false;
if (set) {
cur = $.keyboard.currentKeyboard = base.el;
} else if (set === false && cur === base.el) {
cur = $.keyboard.currentKeyboard = '';
}
return cur === base.el;
};
base.isVisible = function() {
if (typeof(base.$keyboard) === 'undefined') {
return false;
}
return base.$keyboard.is(":visible");
};
base.focusOn = function(){
if (o.usePreview && base.$el.is(':visible')) {
// caret position is always 0,0 in webkit; and nothing is focused at this point... odd
// save caret position in the input to transfer it to the preview
base.lastCaret = base.$el.caret();
}
if (!base.isVisible()) {
clearTimeout(base.timer);
base.reveal();
}
if (o.alwaysOpen) {
base.setCurrent();
}
};
base.reveal = function(){
base.opening = true;
// close all keyboards
$('.ui-keyboard').not('.ui-keyboard-always-open').hide();
// Don't open if disabled
if (base.$el.is(':disabled') || (base.$el.attr('readonly') &&
!base.$el.hasClass('ui-keyboard-lockedinput'))) {
base.$el.addClass('ui-keyboard-nokeyboard');
return;
} else {
base.$el.removeClass('ui-keyboard-nokeyboard');
}
// Unbind focus to prevent recursion - openOn may be empty if keyboard is opened externally
if (o.openOn) {
base.$el.unbind( o.openOn + '.keyboard' );
}
// build keyboard if it doesn't exist
if (typeof(base.$keyboard) === 'undefined') { base.startup(); }
// clear watermark
if (!base.watermark && base.el.value === base.inPlaceholder) {
base.$el
.removeClass('ui-keyboard-placeholder')
.val('');
}
// save starting content, in case we cancel
base.originalContent = base.$el.val();
base.$preview.val( base.originalContent );
// disable/enable accept button
if (o.acceptValid) { base.checkValid(); }
var p, s;
base.position = o.position;
// get single target position || target stored in element data (multiple targets) || default @ element
base.position.of = base.position.of || base.$el.data('keyboardPosition') || base.$el;
base.position.collision = base.position.collision || (o.usePreview ? 'fit fit' : 'flip flip');
if (o.resetDefault) {
base.shiftActive = base.altActive = base.metaActive = false;
base.showKeySet();
}
// basic positioning before it is set by position utility
base.$keyboard.css({ position: 'absolute', left: 0, top: 0 });
// beforeVisible event
base.$el.trigger( 'beforeVisible.keyboard', [ base, base.el ] );
base.setCurrent();
// show keyboard
base.$keyboard.show();
// adjust keyboard preview window width - save width so IE won't keep expanding (fix issue #6)
if (o.usePreview && base.msie) {
if (typeof base.width === 'undefined') {
base.$preview.hide(); // preview is 100% browser width in IE7, so hide the damn thing
base.width = Math.ceil(base.$keyboard.width()); // set input width to match the widest keyboard row
base.$preview.show();
}
base.$preview.width(base.width);
}
// position after keyboard is visible (required for UI position utility) and appropriately sized
if ($.ui.position) {
base.$keyboard.position(base.position);
}
if (o.initialFocus) {
base.$preview.focus();
}
base.checkDecimal();
// get preview area line height
// add roughly 4px to get line height from font height, works well for font-sizes from 14-36px
// needed for textareas
base.lineHeight = parseInt( base.$preview.css('lineHeight'), 10) ||
parseInt(base.$preview.css('font-size') ,10) + 4;
if (o.caretToEnd) {
s = base.originalContent.length;
base.lastCaret = {
start: s,
end : s
};
}
// IE caret haxx0rs
if (base.allie){
// ensure caret is at the end of the text (needed for IE)
s = base.lastCaret.start || base.originalContent.length;
p = { start: s, end: s };
// set caret at end of content, if undefined
if (!base.lastCaret) { base.lastCaret = p; }
// sometimes end = 0 while start is > 0
if (base.lastCaret.end === 0 && base.lastCaret.start > 0) {
base.lastCaret.end = base.lastCaret.start;
}
// IE will have start -1, end of 0 when not focused (see demo: http://jsfiddle.net/Mottie/fgryQ/3/)
if (base.lastCaret.start < 0) { base.lastCaret = p; }
}
// opening keyboard flag; delay allows switching between keyboards without immediately closing
// the keyboard
setTimeout(function(){
base.opening = false;
if (o.initialFocus) {
base.$preview.caret( base.lastCaret.start, base.lastCaret.end );
}
base.$el.trigger( 'visible.keyboard', [ base, base.el ] );
}, 10);
// return base to allow chaining in typing extension
return base;
};
base.startup = function(){
if ( $.isFunction(o.create) ) {
base.$keyboard = o.create(base);
}
if ( typeof base.$keyboard === 'undefined' ) {
base.$keyboard = base.buildKeyboard();
}
base.preview = base.$preview[0];
base.$decBtn = base.$keyboard.find('.ui-keyboard-dec');
base.wheel = $.isFunction( $.fn.mousewheel ); // is mousewheel plugin loaded?
// keyCode of keys always allowed to be typed - caps lock, page up & down, end, home, arrow, insert &
// delete keys
base.alwaysAllowed = [20,33,34,35,36,37,38,39,40,45,46];
// add enter to allowed keys; fixes #190
if (o.enterNavigation || base.el.tagName === "TEXTAREA") { base.alwaysAllowed.push(13); }
base.bindKeyboard();
if (o.appendLocally) {
base.$el.after( base.$keyboard );
} else {
base.$keyboard.appendTo('body');
}
base.bindKeys();
// adjust with window resize
$(window).bind('resize.keyboard', function(){
if (base.isVisible()) {
base.$keyboard.position(base.position);
}
});
};
base.bindKeyboard = function(){
base.$preview
.unbind('keypress keyup keydown mouseup touchend '.split(' ').join('.keyboard '))
.bind('keypress.keyboard', function(e){
var k = base.lastKey = String.fromCharCode(e.charCode || e.which);
base.$lastKey = []; // not a virtual keyboard key
if (base.checkCaret) { base.lastCaret = base.$preview.caret(); }
// update caps lock - can only do this while typing =(
base.capsLock = (((k >= 65 && k <= 90) && !e.shiftKey) ||
((k >= 97 && k <= 122) && e.shiftKey)) ? true : false;
// restrict input - keyCode in keypress special keys:
// see http://www.asquare.net/javascript/tests/KeyCode.html
if (o.restrictInput) {
// allow navigation keys to work - Chrome doesn't fire a keypress event (8 = bksp)
if ( (e.which === 8 || e.which === 0) && $.inArray( e.keyCode, base.alwaysAllowed ) ) { return; }
if ($.inArray(k, base.acceptedKeys) === -1) { e.preventDefault(); } // quick key check
} else if ( (e.ctrlKey || e.metaKey) && (e.which === 97 || e.which === 99 || e.which === 118 ||
(e.which >= 120 && e.which <=122)) ) {
// Allow select all (ctrl-a:97), copy (ctrl-c:99), paste (ctrl-v:118) & cut (ctrl-x:120) &
// redo (ctrl-y:121)& undo (ctrl-z:122); meta key for mac
return;
}
// Mapped Keys - allows typing on a regular keyboard and the mapped key is entered
// Set up a key in the layout as follows: "m(a):label"; m = key to map, (a) = actual keyboard key
// to map to (optional), ":label" = title/tooltip (optional)
// example: \u0391 or \u0391(A) or \u0391:alpha or \u0391(A):alpha
if (base.hasMappedKeys) {
if (base.mappedKeys.hasOwnProperty(k)){
base.lastKey = base.mappedKeys[k];
base.insertText( base.lastKey );
e.preventDefault();
}
}
base.checkMaxLength();
})
.bind('keyup.keyboard', function(e){
switch (e.which) {
// Insert tab key
case 9 :
// Added a flag to prevent from tabbing into an input, keyboard opening, then adding the tab to the keyboard preview
// area on keyup. Sadly it still happens if you don't release the tab key immediately because keydown event auto-repeats
if (base.tab && o.tabNavigation && !o.lockInput) {
base.shiftActive = e.shiftKey;
// when switching inputs, the tab keyaction returns false
var notSwitching = $.keyboard.keyaction.tab(base);
base.tab = false;
if (!notSwitching) { return false; }
} else {
e.preventDefault();
}
break;
// Escape will hide the keyboard
case 27:
base.close();
return false;
}
// throttle the check combo function because fast typers will have an incorrectly positioned caret
clearTimeout(base.throttled);
base.throttled = setTimeout(function(){
// fix error in OSX? see issue #102
if (base.isVisible()) {
base.checkCombos();
}
}, 100);
base.checkMaxLength();
// change callback is no longer bound to the input element as the callback could be
// called during an external change event with all the necessary parameters (issue #157)
if ($.isFunction(o.change)){ o.change( $.Event("change"), base, base.el ); }
base.$el.trigger( 'change.keyboard', [ base, base.el ] );
})
.bind('keydown.keyboard', function(e){
switch (e.which) {
// prevent tab key from leaving the preview window
case 9 :
if (o.tabNavigation) {
// allow tab to pass through - tab to next input/shift-tab for prev
base.tab = true;
return false;
} else {
base.tab = true; // see keyup comment above
return false;
}
break; // adding a break here to make jsHint happy
case 13:
$.keyboard.keyaction.enter(base, null, e);
break;
// Show capsLock
case 20:
base.shiftActive = base.capsLock = !base.capsLock;
base.showKeySet(this);
break;
case 86:
// prevent ctrl-v/cmd-v
if (e.ctrlKey || e.metaKey) {
if (o.preventPaste) { e.preventDefault(); return; }
base.checkCombos(); // check pasted content
}
break;
}
})
.bind('mouseup.keyboard touchend.keyboard', function(){
if (base.checkCaret) { base.lastCaret = base.$preview.caret(); }
});
// prevent keyboard event bubbling
base.$keyboard.bind('mousedown.keyboard click.keyboard touchstart.keyboard', function(e){
e.stopPropagation();
if (!base.isCurrent()) {
base.reveal();
$(document).trigger('checkkeyboard.keyboard');
}
});
// If preventing paste, block context menu (right click)
if (o.preventPaste){
base.$preview.bind('contextmenu.keyboard', function(e){ e.preventDefault(); });
base.$el.bind('contextmenu.keyboard', function(e){ e.preventDefault(); });
}
};
base.bindKeys = function(){
var allEvents = (o.keyBinding + ' repeater mouseenter mouseleave touchstart mousewheel ' +
'mouseup click ').split(' ').join('.keyboard ') + ('mouseleave mousedown touchstart ' +
'touchend touchmove touchcancel ').split(' ').join('.kb ');
base.$allKeys = base.$keyboard.find('button.ui-keyboard-button')
.unbind(allEvents)
.bind(o.keyBinding.split(' ').join('.keyboard ') + '.keyboard repeater.keyboard', function(e){
// prevent errors when external triggers attempt to "type" - see issue #158
if (!base.$keyboard.is(":visible")){ return false; }
// 'key', { action: doAction, original: n, curTxt : n, curNum: 0 }
var txt, key = $.data(this, 'key'), action = key.action.split(':')[0],
// prevent mousedown & touchstart from both firing events at the same time - see #184
timer = new Date().getTime();
if (timer - (base.lastEventTime || 0) < o.preventDoubleEventTime) { return; }
base.lastEventTime = timer;
base.$preview.focus();
base.$lastKey = $(this);
base.lastKey = key.curTxt;
// Start caret in IE when not focused (happens with each virtual keyboard button click
if (base.checkCaret) { base.$preview.caret( base.lastCaret.start, base.lastCaret.end ); }
if (action.match('meta')) { action = 'meta'; }
if ($.keyboard.keyaction.hasOwnProperty(action) && $(this).hasClass('ui-keyboard-actionkey')) {
// stop processing if action returns false (close & cancel)
if ($.keyboard.keyaction[action](base,this,e) === false) { return false; }
} else if (typeof key.action !== 'undefined') {
txt = base.lastKey = (base.wheel && !$(this).hasClass('ui-keyboard-actionkey')) ?
key.curTxt : key.action;
base.insertText(txt);
if (!base.capsLock && !o.stickyShift && !e.shiftKey) {
base.shiftActive = false;
base.showKeySet(this);
}
}
// set caret if caret moved by action function; also, attempt to fix issue #131
base.$preview.focus().caret( base.lastCaret.start, base.lastCaret.end );
base.checkCombos();
base.checkMaxLength();
if ($.isFunction(o.change)){ o.change( $.Event("change"), base, base.el ); }
base.$el.trigger( 'change.keyboard', [ base, base.el ] );
e.preventDefault();
})
// Change hover class and tooltip
.bind('mouseenter.keyboard mouseleave.keyboard touchstart.keyboard', function(e){
if (!base.isCurrent()) { return; }
var el = this, $this = $(this),
// 'key' = { action: doAction, original: n, curTxt : n, curNum: 0 }
key = $.data(el, 'key'),
txt = key.layers || base.getLayers( $this );
// remove duplicates
key.layers = txt = $.grep(txt, function(v, k){
return $.inArray(v, txt) === k;
});
if ((e.type === 'mouseenter' || e.type === 'touchstart') && base.el.type !== 'password' &&
!$this.hasClass(o.css.buttonDisabled) ){
$this
.addClass(o.css.buttonHover)
.attr('title', function(i,t){
// show mouse wheel message
return (base.wheel && t === '' && base.sets && txt.length > 1 && e.type !== 'touchstart') ?
o.wheelMessage : t;
});
}
if (e.type === 'mouseleave'){
key.curTxt = key.original;
key.curNum = 0;
$.data(el, 'key', key);
$this
// needed or IE flickers really bad
.removeClass( (base.el.type === 'password') ? '' : o.css.buttonHover)
.attr('title', function(i,t){ return (t === o.wheelMessage) ? '' : t; })
.find('span').text( key.original ); // restore original button text
}
})
// Allow mousewheel to scroll through other key sets of the same key
.bind('mousewheel.keyboard', function(e, delta){
if (base.wheel) {
var txt, $this = $(this), key = $.data(this, 'key');
txt = key.layers || base.getLayers( $this );
if (txt.length > 1) {
key.curNum += (delta > 0) ? -1 : 1;
if (key.curNum > txt.length-1) { key.curNum = 0; }
if (key.curNum < 0) { key.curNum = txt.length-1; }
} else {
key.curNum = 0;
}
key.layers = txt;
key.curTxt = txt[key.curNum];
$.data(this, 'key', key);
$this.find('span').text( txt[key.curNum] );
return false;
}
})
// using "kb" namespace for mouse repeat functionality to keep it separate
// I need to trigger a "repeater.keyboard" to make it work
.bind('mouseup.keyboard mouseleave.kb touchend.kb touchmove.kb touchcancel.kb', function(e){
if (/(mouseleave|touchend|touchcancel)/.test(e.type)) {
$(this).removeClass(o.css.buttonHover); // needed for touch devices
} else {
if (base.isVisible() && base.isCurrent()) { base.$preview.focus(); }
if (base.checkCaret) { base.$preview.caret( base.lastCaret.start, base.lastCaret.end ); }
}
base.mouseRepeat = [false,''];
clearTimeout(base.repeater); // make sure key repeat stops!
return false;
})
// prevent form submits when keyboard is bound locally - issue #64
.bind('click.keyboard', function(){
return false;
})
// no mouse repeat for action keys (shift, ctrl, alt, meta, etc)
.not('.ui-keyboard-actionkey')
// mouse repeated action key exceptions
.add('.ui-keyboard-tab, .ui-keyboard-bksp, .ui-keyboard-space, .ui-keyboard-enter', base.$keyboard)
.bind('mousedown.kb touchstart.kb', function(){
if (o.repeatRate !== 0) {
var key = $(this);
base.mouseRepeat = [true, key]; // save the key, make sure we are repeating the right one (fast typers)
setTimeout(function() {
if (base.mouseRepeat[0] && base.mouseRepeat[1] === key) { base.repeatKey(key); }
}, o.repeatDelay);
}
return false;
});
};
// Insert text at caret/selection - thanks to Derek Wickwire for fixing this up!
base.insertText = function(txt){
var bksp, t, h,
// use base.$preview.val() instead of base.preview.value (val.length includes carriage returns in IE).
val = base.$preview.val(),
pos = base.$preview.caret(),
scrL = base.$preview.scrollLeft(),
scrT = base.$preview.scrollTop(),
len = val.length; // save original content length
// silly IE caret hacks... it should work correctly, but navigating using arrow keys in a textarea
// is still difficult
// in IE, pos.end can be zero after input loses focus
if (pos.end < pos.start) { pos.end = pos.start; }
if (pos.start > len) { pos.end = pos.start = len; }
if (base.preview.tagName === 'TEXTAREA') {
// This makes sure the caret moves to the next line after clicking on enter (manual typing works fine)
if (base.msie && val.substr(pos.start, 1) === '\n') { pos.start += 1; pos.end += 1; }
// Set scroll top so current text is in view - needed for virtual keyboard typing, not manual typing
// this doesn't appear to work correctly in Opera
h = (val.split('\n').length - 1);
base.preview.scrollTop = (h>0) ? base.lineHeight * h : scrT;
}
bksp = (txt === 'bksp' && pos.start === pos.end) ? true : false;
txt = (txt === 'bksp') ? '' : txt;
t = pos.start + (bksp ? -1 : txt.length);
scrL += parseInt(base.$preview.css('fontSize'),10) * (txt === 'bksp' ? -1 : 1);
base.$preview
.val( base.$preview.val().substr(0, pos.start - (bksp ? 1 : 0)) + txt +
base.$preview.val().substr(pos.end) )
.caret(t, t)
.scrollLeft(scrL);
base.lastCaret = { start: t, end: t }; // save caret in case of bksp
};
// check max length
base.checkMaxLength = function(){
var t, p = base.$preview.val();
if (o.maxLength !== false && p.length > o.maxLength) {
t = Math.min(base.$preview.caret().start, o.maxLength);
base.$preview.val( p.substring(0, o.maxLength) );
// restore caret on change, otherwise it ends up at the end.
base.$preview.caret( t, t );
base.lastCaret = { start: t, end: t };
}
if (base.$decBtn.length) {
base.checkDecimal();
}
};
// mousedown repeater
base.repeatKey = function(key){
key.trigger('repeater.keyboard');
if (base.mouseRepeat[0]) {
base.repeater = setTimeout(function() {
base.repeatKey(key);
}, base.repeatTime);
}
};
base.showKeySet = function(el){
var key = '',
toShow = (base.shiftActive ? 1 : 0) + (base.altActive ? 2 : 0);
if (!base.shiftActive) { base.capsLock = false; }
// check meta key set
if (base.metaActive) {
// the name attribute contains the meta set # "meta99"
key = (el && el.name && /meta/.test(el.name)) ? el.name : '';
// save active meta keyset name
if (key === '') {
key = (base.metaActive === true) ? '' : base.metaActive;
} else {
base.metaActive = key;
}
// if meta keyset doesn't have a shift or alt keyset, then show just the meta key set
if ( (!o.stickyShift && base.lastKeyset[2] !== base.metaActive) ||
( (base.shiftActive || base.altActive) && !base.$keyboard.find('.ui-keyboard-keyset-' + key +
base.rows[toShow]).length) ) {
base.shiftActive = base.altActive = false;
}
} else if (!o.stickyShift && base.lastKeyset[2] !== base.metaActive && base.shiftActive) {
// switching from meta key set back to default, reset shift & alt if using stickyShift
base.shiftActive = base.altActive = false;
}
toShow = (base.shiftActive ? 1 : 0) + (base.altActive ? 2 : 0);
key = (toShow === 0 && !base.metaActive) ? '-default' : (key === '') ? '' : '-' + key;
if (!base.$keyboard.find('.ui-keyboard-keyset' + key + base.rows[toShow]).length) {
// keyset doesn't exist, so restore last keyset settings
base.shiftActive = base.lastKeyset[0];
base.altActive = base.lastKeyset[1];
base.metaActive = base.lastKeyset[2];
return;
}
base.$keyboard
.find('.ui-keyboard-alt, .ui-keyboard-shift, .ui-keyboard-actionkey[class*=meta]')
.removeClass(o.css.buttonAction).end()
.find('.ui-keyboard-alt')[(base.altActive) ? 'addClass' : 'removeClass'](o.css.buttonAction).end()
.find('.ui-keyboard-shift')[(base.shiftActive) ? 'addClass' : 'removeClass'](o.css.buttonAction).end()
.find('.ui-keyboard-lock')[(base.capsLock) ? 'addClass' : 'removeClass'](o.css.buttonAction).end()
.find('.ui-keyboard-keyset').hide().end()
.find('.ui-keyboard-keyset' + key + base.rows[toShow]).show().end()
.find('.ui-keyboard-actionkey.ui-keyboard' + key).addClass(o.css.buttonAction);
base.lastKeyset = [ base.shiftActive, base.altActive, base.metaActive ];
};
// check for key combos (dead keys)
base.checkCombos = function(){
if (!base.isVisible()) { return base.$preview.val(); }
var i, r, t, t2,
// use base.$preview.val() instead of base.preview.value (val.length includes carriage returns in IE).
val = base.$preview.val(),
pos = base.$preview.caret(),
len = val.length; // save original content length
// silly IE caret hacks... it should work correctly, but navigating using arrow keys in a textarea
// is still difficult
// in IE, pos.end can be zero after input loses focus
if (pos.end < pos.start) { pos.end = pos.start; }
if (pos.start > len) { pos.end = pos.start = len; }
// This makes sure the caret moves to the next line after clicking on enter (manual typing works fine)
if (base.msie && val.substr(pos.start, 1) === '\n') { pos.start += 1; pos.end += 1; }
if (o.useCombos) {
// keep 'a' and 'o' in the regex for ae and oe ligature (æ,œ)
// thanks to KennyTM: http://stackoverflow.com/q/4275077
// original regex /([`\'~\^\"ao])([a-z])/mig moved to $.keyboard.comboRegex
if (base.msie) {
// old IE may not have the caret positioned correctly, so just check the whole thing
val = val.replace(base.regex, function(s, accent, letter){
return (o.combos.hasOwnProperty(accent)) ? o.combos[accent][letter] || s : s;
});
// prevent combo replace error, in case the keyboard closes - see issue #116
} else if (base.$preview.length) {
// Modern browsers - check for combos from last two characters left of the caret
t = pos.start - (pos.start - 2 >= 0 ? 2 : 0);
// target last two characters
base.$preview.caret(t, pos.end);
// do combo replace
t2 = (base.$preview.caret().text || '').replace(base.regex, function(s, accent, letter){
return (o.combos.hasOwnProperty(accent)) ? o.combos[accent][letter] || s : s;
});
// add combo back
base.$preview.val( base.$preview.caret().replace(t2) );
val = base.$preview.val();
}
}
// check input restrictions - in case content was pasted
if (o.restrictInput && val !== '') {
t = val;
r = base.acceptedKeys.length;
for (i=0; i < r; i++){
if (t === '') { continue; }
t2 = base.acceptedKeys[i];
if (val.indexOf(t2) >= 0) {
// escape out all special characters
if (/[\[|\]|\\|\^|\$|\.|\||\?|\*|\+|\(|\)|\{|\}]/g.test(t2)) { t2 = '\\' + t2; }
t = t.replace( (new RegExp(t2, "g")), '');
}
}
// what's left over are keys that aren't in the acceptedKeys array
if (t !== '') { val = val.replace(t, ''); }
}
// save changes, then reposition caret
pos.start += val.length - len;
pos.end += val.length - len;
base.$preview.val(val);
base.$preview.caret(pos.start, pos.end);
// calculate current cursor scroll location and set scrolltop to keep it in view
// find row, multiply by font-size
base.preview.scrollTop = base.lineHeight * (val.substring(0, pos.start).split('\n').length - 1);
base.lastCaret = { start: pos.start, end: pos.end };
if (o.acceptValid) { base.checkValid(); }
return val; // return text, used for keyboard closing section
};
// Toggle accept button classes, if validating
base.checkValid = function(){
var valid = true;
if (o.validate && typeof o.validate === "function") {
valid = o.validate(base, base.$preview.val(), false);
}
// toggle accept button classes; defined in the css
base.$keyboard.find('.ui-keyboard-accept')
[valid ? 'removeClass' : 'addClass']('ui-keyboard-invalid-input')
[valid ? 'addClass' : 'removeClass']('ui-keyboard-valid-input');
};
// Decimal button for num pad - only allow one (not used by default)
base.checkDecimal = function(){
// Check US "." or European "," format
if ( ( base.decimal && /\./g.test(base.preview.value) ) ||
( !base.decimal && /\,/g.test(base.preview.value) ) ) {
base.$decBtn
.attr({ 'disabled': 'disabled', 'aria-disabled': 'true' })
.removeClass(o.css.buttonDefault + ' ' + o.css.buttonHover)
.addClass(o.css.buttonDisabled);
} else {
base.$decBtn
.removeAttr('disabled')
.attr({ 'aria-disabled': 'false' })
.addClass(o.css.buttonDefault)
.removeClass(o.css.buttonDisabled);
}
};
// get other layer values for a specific key
base.getLayers = function(el){
var key, keys;
key = el.attr('data-pos');
keys = el.closest('.ui-keyboard').find('button[data-pos="' + key + '"]').map(function(){
// added '> span' because jQuery mobile adds multiple spans inside the button
return $(this).find('> span').text();
}).get();
return keys;
};
// Go to next or prev inputs
// goToNext = true, then go to next input; if false go to prev
// isAccepted is from autoAccept option or true if user presses shift-enter
base.switchInput = function(goToNext, isAccepted){
if (typeof o.switchInput === "function") {
o.switchInput(base, goToNext, isAccepted);
} else {
base.$keyboard.hide();
var kb, stopped = false,
all = $('button, input, textarea, a').filter(':visible'),
indx = all.index(base.$el) + (goToNext ? 1 : -1);
base.$keyboard.show();
if (indx > all.length - 1) {
stopped = o.stopAtEnd;
indx = 0; // go to first input
}
if (indx < 0) {
stopped = o.stopAtEnd;
indx = all.length - 1; // stop or go to last
}
if (!stopped) {
base.close(isAccepted);
kb = all.eq(indx).data('keyboard');
if (kb && kb.options.openOn.length) {
kb.focusOn();
} else {
all.eq(indx).focus();
}
}
}
return false;
};
// Close the keyboard, if visible. Pass a status of true, if the content was accepted
// (for the event trigger).
base.close = function(accepted){
if (base.isOpen) {
clearTimeout(base.throttled);
var val = (accepted) ? base.checkCombos() : base.originalContent;
// validate input if accepted
if (accepted && o.validate && typeof(o.validate) === "function" && !o.validate(base, val, true)) {
val = base.originalContent;
accepted = false;
if (o.cancelClose) { return; }
}
base.isCurrent(false);
base.isOpen = false;
base.$el
.removeClass('ui-keyboard-input-current ui-keyboard-autoaccepted')
// add "ui-keyboard-autoaccepted" to inputs - see issue #66
.addClass( (accepted || false) ? accepted === true ? '' : 'ui-keyboard-autoaccepted' : '' )
.trigger( (o.alwaysOpen) ? '' : 'beforeClose.keyboard', [ base, base.el, (accepted || false) ] )
.val( val )
.scrollTop( base.el.scrollHeight )
.trigger( ((accepted || false) ? 'accepted.keyboard' : 'canceled.keyboard'), [ base, base.el ] )
.trigger( (o.alwaysOpen) ? 'inactive.keyboard' : 'hidden.keyboard', [ base, base.el ] )
.blur();
// update value for always open keyboards
base.$preview.val(val);
if (o.openOn) {
// rebind input focus - delayed to fix IE issue #72
base.timer = setTimeout(function(){
base.$el.bind( o.openOn + '.keyboard', function(){ base.focusOn(); });
// remove focus from element (needed for IE since blur doesn't seem to work)
if ($(':focus')[0] === base.el) { base.$el.blur(); }
}, 500);
}
if (!o.alwaysOpen) {
base.$keyboard.hide();
}
if (!base.watermark && base.el.value === '' && base.inPlaceholder !== '') {
base.$el
.addClass('ui-keyboard-placeholder')
.val(base.inPlaceholder);
}
// trigger default change event - see issue #146
base.$el.trigger('change');
}
return !!accepted;
};
base.accept = function(){
return base.close(true);
};
base.escClose = function(e){
if ( e && e.type === 'keyup' ) {
return ( e.which === 27 ) ? base.close() : '';
}
// keep keyboard open if alwaysOpen or stayOpen is true - fixes mutliple always open keyboards or
// single stay open keyboard
if ( !base.isOpen ) { return; }
// ignore autoaccept if using escape - good idea?
if ( !base.isCurrent() && base.isOpen || base.isOpen && e.target !== base.el && !o.stayOpen) {
// stop propogation in IE - an input getting focus doesn't open a keyboard if one is already open
if ( base.allie ) {
e.preventDefault();
}
// send "true" instead of a true (boolean), the input won't get a "ui-keyboard-autoaccepted"
// class name - see issue #66
base.close( o.autoAccept ? 'true' : false );
}
};
// Build default button
base.keyBtn = $('<button />')
.attr({ 'role': 'button', 'aria-disabled': 'false', 'tabindex' : '-1' })
.addClass('ui-keyboard-button');
// Add key function
// keyName = the name of the function called in $.keyboard.keyaction when the button is clicked
// name = name added to key, or cross-referenced in the display options
// newSet = keyset to attach the new button
// regKey = true when it is not an action key
base.addKey = function(keyName, name, regKey){
var t, keyType, m, map, nm,
n = (regKey === true) ? keyName : o.display[name] || keyName,
kn = (regKey === true) ? keyName.charCodeAt(0) : keyName;
// map defined keys - format "key(A):Label_for_key"
// "key" = key that is seen (can any character; but it might need to be escaped using "\"
// or entered as unicode "\u####"
// "(A)" = the actual key on the real keyboard to remap, ":Label_for_key" ends up in the title/tooltip
if (/\(.+\)/.test(n)) { // n = "\u0391(A):alpha"
map = n.replace(/\(([^()]+)\)/, ''); // remove "(A)", left with "\u0391:alpha"
m = n.match(/\(([^()]+)\)/)[1]; // extract "A" from "(A)"
n = map;
nm = map.split(':');
map = (nm[0] !== '' && nm.length > 1) ? nm[0] : map; // get "\u0391" from "\u0391:alpha"
base.mappedKeys[m] = map;
}
// find key label
nm = n.split(':');
// corner case of ":(:):;" reduced to "::;", split as ["", "", ";"]
if (nm[0] === '' && nm[1] === '') { n = ':'; }
n = (nm[0] !== '' && nm.length > 1) ? $.trim(nm[0]) : n;
// added to title
t = (nm.length > 1) ? $.trim(nm[1]).replace(/_/g, " ") || '' : '';
// Action keys will have the 'ui-keyboard-actionkey' class
// '\u2190'.length = 1 because the unicode is converted, so if more than one character,
// add the wide class
keyType = (n.length > 1) ? ' ui-keyboard-widekey' : '';
keyType += (regKey) ? '' : ' ui-keyboard-actionkey';
return base.keyBtn
.clone()
.attr({ 'data-value' : n, 'name': kn, 'data-pos': base.temp[1] + ',' + base.temp[2], 'title' : t })
.data('key', { action: keyName, original: n, curTxt : n, curNum: 0 })
// add "ui-keyboard-" + keyName, if this is an action key
// (e.g. "Bksp" will have 'ui-keyboard-bskp' class)
// add "ui-keyboard-" + unicode of 1st character
// (e.g. "~" is a regular key, class = 'ui-keyboard-126'
// (126 is the unicode value - same as typing ~)
.addClass('ui-keyboard-' + kn + keyType + ' ' + o.css.buttonDefault)
.html('<span>' + n + '</span>')
.appendTo(base.temp[0]);
};
base.buildKeyboard = function(){
var t, action, row, newSet, isAction,
currentSet, key, keys, margin,
sets = 0,
container = $('<div />')
.addClass('ui-keyboard ' + o.css.container + (o.alwaysOpen ? ' ui-keyboard-always-open' : '') )
.attr({ 'role': 'textbox' })
.hide();
// build preview display
if (o.usePreview) {
base.$preview = base.$el.clone(false)
.removeAttr('id')
.removeClass('ui-keyboard-placeholder ui-keyboard-input')
.addClass('ui-keyboard-preview ' + o.css.input)
.attr('tabindex', '-1')
.show(); // for hidden inputs
// build preview container and append preview display
$('<div />')
.addClass('ui-keyboard-preview-wrapper')
.append(base.$preview)
.appendTo(container);
} else {