forked from sparshag21/desktopography
-
Notifications
You must be signed in to change notification settings - Fork 0
/
onscreen.js
2972 lines (2725 loc) · 96.5 KB
/
onscreen.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 v1.26.3 *//*
Author: Jeremy Satterfield
Maintained: Rob Garrison (Mottie on github)
Licensed under the MIT License
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.
This plugin adds default class names to match jQuery UI theme styling.
Bootstrap & custom themes may also be applied - See
https://github.com/Mottie/Keyboard#themes
Requires:
jQuery v1.4.3+
Caret plugin (included)
Optional:
jQuery UI (position utility only) & CSS theme
jQuery mousewheel
Setup/Usage:
Please refer to https://github.com/Mottie/Keyboard/wiki
-----------------------------------------
Caret code modified from jquery.caret.1.02.js
Licensed under the MIT License:
http://www.opensource.org/licenses/mit-license.php
-----------------------------------------
*/
/*jshint browser:true, jquery:true, unused:false */
/*global require:false, define:false, module:false */
;(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
}(function ($) {
'use strict';
var $keyboard = $.keyboard = function (el, options) {
var o, base = this;
base.version = '1.26.3';
// 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 () {
var k, position, tmp,
kbcss = $keyboard.css,
kbevents = $keyboard.events;
base.settings = options || {};
// shallow copy position to prevent performance issues; see #357
if (options && options.position) {
position = $.extend({}, options.position);
options.position = null;
}
base.options = o = $.extend(true, {}, $keyboard.defaultOptions, options);
if (position) {
o.position = position;
options.position = position;
}
// keyboard is active (not destroyed);
base.el.active = true;
// unique keyboard namespace
base.namespace = '.keyboard' + Math.random().toString(16).slice(2);
// extension namespaces added here (to unbind listeners on base.$el upon destroy)
base.extensionNamespace = [];
// 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;
// Class names of the basic key set - meta keysets are handled by the keyname
base.rows = ['', '-shift', '-alt', '-alt-shift'];
base.inPlaceholder = base.$el.attr('placeholder') || '';
// html 5 placeholder/watermark
base.watermark = $keyboard.watermark && base.inPlaceholder !== '';
// 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;
// is mousewheel plugin loaded?
base.wheel = $.isFunction($.fn.mousewheel);
// special character in regex that need to be escaped
base.escapeRegex = /[-\/\\^$*+?.()|[\]{}]/g;
// keyCode of keys always allowed to be typed
k = $keyboard.keyCodes;
// base.alwaysAllowed = [20,33,34,35,36,37,38,39,40,45,46];
base.alwaysAllowed = [
k.capsLock,
k.pageUp,
k.pageDown,
k.end,
k.home,
k.left,
k.up,
k.right,
k.down,
k.insert,
k.delete
];
base.$keyboard = [];
// keyboard enabled; set to false on destroy
base.enabled = true;
// make a copy of the original keyboard position
if (!$.isEmptyObject(o.position)) {
o.position.orig_at = o.position.at;
}
base.checkCaret = (o.lockInput || $keyboard.checkCaretSupport());
base.last = {
start: 0,
end: 0,
key: '',
val: '',
preVal: '',
layout: '',
virtual: true,
keyset: [false, false, false], // [shift, alt, meta]
wheel_$Keys: null,
wheelIndex: 0,
wheelLayers: []
};
// used when building the keyboard - [keyset element, row, index]
base.temp = ['', 0, 0];
// Callbacks
$.each([
kbevents.kbInit,
kbevents.kbBeforeVisible,
kbevents.kbVisible,
kbevents.kbHidden,
kbevents.inputCanceled,
kbevents.inputAccepted,
kbevents.kbBeforeClose,
kbevents.inputRestricted
], function (i, callback) {
if ($.isFunction(o[callback])) {
// bind callback functions within options to triggered events
base.$el.bind(callback + base.namespace + 'callbacks', o[callback]);
}
});
// Close with esc key & clicking outside
if (o.alwaysOpen) {
o.stayOpen = true;
}
tmp = $(document);
if (base.el.ownerDocument !== document) {
tmp = tmp.add(base.el.ownerDocument);
}
var bindings = 'keyup checkkeyboard mousedown touchstart ';
if (o.closeByClickEvent) {
bindings += 'click ';
}
tmp.bind(bindings.split(' ').join(base.namespace + ' '), base.checkClose);
// Display keyboard on focus
base.$el
.addClass(kbcss.input + ' ' + o.css.input)
.attr({
'aria-haspopup': 'true',
'role': 'textbox'
});
// set lockInput if the element is readonly; or make the element readonly if lockInput is set
if (o.lockInput || base.el.readOnly) {
o.lockInput = true;
base.$el
.addClass(kbcss.locked)
.attr({
'readonly': 'readonly'
});
}
// add disabled/readonly class - dynamically updated on reveal
if (base.$el.is(':disabled') || (base.$el.attr('readonly') &&
!base.$el.hasClass(kbcss.locked))) {
base.$el.addClass(kbcss.noKeyboard);
}
if (o.openOn) {
base.bindFocus();
}
// Add placeholder if not supported by the browser
if (!base.watermark && base.$el.val() === '' && base.inPlaceholder !== '' &&
base.$el.attr('placeholder') !== '') {
base.$el
.addClass(kbcss.placeholder) // css watermark style (darker text)
.val(base.inPlaceholder);
}
base.$el.trigger(kbevents.kbInit, [base, base.el]);
// initialized with keyboard open
if (o.alwaysOpen) {
base.reveal();
}
};
base.toggle = function () {
var $toggle = base.$keyboard.find('.' + $keyboard.css.keyToggle),
locked = !base.enabled;
// prevent physical keyboard from working
base.$preview.prop('readonly', locked || base.options.lockInput);
// disable all buttons
base.$keyboard
.toggleClass($keyboard.css.keyDisabled, locked)
.find('.' + $keyboard.css.keyButton)
.not($toggle)
.prop('disabled', locked)
.attr('aria-disabled', locked);
$toggle.toggleClass($keyboard.css.keyDisabled, locked);
// stop auto typing
if (locked && base.typing_options) {
base.typing_options.text = '';
}
};
base.setCurrent = function () {
var kbcss = $keyboard.css,
// close any "isCurrent" keyboard (just in case they are always open)
$current = $('.' + kbcss.isCurrent),
kb = $current.data('keyboard');
// close keyboard, if not self
if (!$.isEmptyObject(kb) && kb.el !== base.el) {
kb.close(kb.options.autoAccept ? 'true' : false);
}
$current.removeClass(kbcss.isCurrent);
// ui-keyboard-has-focus is applied in case multiple keyboards have
// alwaysOpen = true and are stacked
$('.' + kbcss.hasFocus).removeClass(kbcss.hasFocus);
base.$el.addClass(kbcss.isCurrent);
base.$keyboard.addClass(kbcss.hasFocus);
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 () {
return base.$keyboard && base.$keyboard.length ? base.$keyboard.is(':visible') : false;
};
base.focusOn = function () {
if (!base && base.el.active) {
// keyboard was destroyed
return;
}
if (!base.isVisible()) {
clearTimeout(base.timer);
base.reveal();
}
};
// add redraw method to make API more clear
base.redraw = function () {
// update keyboard after a layout change
if (base.$keyboard.length) {
base.last.preVal = '' + base.last.val;
base.last.val = base.$preview && base.$preview.val() || base.$el.val();
base.$el.val( base.last.val );
base.removeKeyboard();
base.shiftActive = base.altActive = base.metaActive = false;
}
base.isOpen = o.alwaysOpen;
base.reveal(true);
};
base.reveal = function (redraw) {
var alreadyOpen = base.isOpen,
kbcss = $keyboard.css;
base.opening = !alreadyOpen;
// remove all 'extra' keyboards by calling close function
$('.' + kbcss.keyboard).not('.' + kbcss.alwaysOpen).each(function(){
var kb = $(this).data('keyboard');
if (!$.isEmptyObject(kb)) {
kb.close(kb.options.autoAccept && kb.options.autoAcceptOnEsc ? 'true' : false);
}
});
// Don't open if disabled
if (base.$el.is(':disabled') || (base.$el.attr('readonly') && !base.$el.hasClass(kbcss.locked))) {
base.$el.addClass(kbcss.noKeyboard);
return;
} else {
base.$el.removeClass(kbcss.noKeyboard);
}
// Unbind focus to prevent recursion - openOn may be empty if keyboard is opened externally
if (o.openOn) {
base.$el.unbind($.trim((o.openOn + ' ').split(/\s+/).join(base.namespace + ' ')));
}
// build keyboard if it doesn't exist; or attach keyboard if it was removed, but not cleared
if (!base.$keyboard || base.$keyboard &&
(!base.$keyboard.length || $.contains(document.body, base.$keyboard[0]))) {
base.startup();
}
// clear watermark
if (!base.watermark && base.el.value === base.inPlaceholder) {
base.$el
.removeClass(kbcss.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();
}
if (o.resetDefault) {
base.shiftActive = base.altActive = base.metaActive = false;
}
base.showSet();
// beforeVisible event
if (!base.isVisible()) {
base.$el.trigger($keyboard.events.kbBeforeVisible, [base, base.el]);
}
base.setCurrent();
// update keyboard - enabled or disabled?
base.toggle();
// show keyboard
base.$keyboard.show();
// adjust keyboard preview window width - save width so IE won't keep expanding (fix issue #6)
if (o.usePreview && $keyboard.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);
}
base.position = $.isEmptyObject(o.position) ? false : o.position;
// position after keyboard is visible (required for UI position utility) and appropriately sized
if ($.ui && $.ui.position && base.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 || 'flipfit flipfit';
o.position.at = o.usePreview ? o.position.orig_at : o.position.at2;
base.$keyboard.position(base.position);
}
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) {
base.saveCaret(base.originalContent.length, base.originalContent.length);
}
// IE caret haxx0rs
if ($keyboard.allie) {
// sometimes end = 0 while start is > 0
if (base.last.end === 0 && base.last.start > 0) {
base.last.end = base.last.start;
}
// IE will have start -1, end of 0 when not focused (see demo: https://jsfiddle.net/Mottie/fgryQ/3/)
if (base.last.start < 0) {
// ensure caret is at the end of the text (needed for IE)
base.last.start = base.last.end = base.originalContent.length;
}
}
if (alreadyOpen || redraw) {
// restore caret position (userClosed)
$keyboard.caret(base.$preview, base.last);
return base;
}
// opening keyboard flag; delay allows switching between keyboards without immediately closing
// the keyboard
base.timer2 = setTimeout(function () {
var undef;
base.opening = false;
// Number inputs don't support selectionStart and selectionEnd
// Number/email inputs don't support selectionStart and selectionEnd
if (!/(number|email)/i.test(base.el.type) && !o.caretToEnd) {
// 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
// inside delay to get correct caret position
base.saveCaret(undef, undef, base.$el);
}
if (o.initialFocus) {
$keyboard.caret(base.$preview, base.last);
}
// save event time for keyboards with stayOpen: true
base.last.eventTime = new Date().getTime();
base.$el.trigger($keyboard.events.kbVisible, [base, base.el]);
base.timer = setTimeout(function () {
// get updated caret information after visible event - fixes #331
if (base) { // Check if base exists, this is a case when destroy is called, before timers fire
base.saveCaret();
}
}, 200);
}, 10);
// return base to allow chaining in typing extension
return base;
};
base.updateLanguage = function () {
// change language if layout is named something like 'french-azerty-1'
var layouts = $keyboard.layouts,
lang = o.language || layouts[o.layout] && layouts[o.layout].lang &&
layouts[o.layout].lang || [o.language || 'en'],
kblang = $keyboard.language;
// some languages include a dash, e.g. 'en-gb' or 'fr-ca'
// allow o.language to be a string or array...
// array is for future expansion where a layout can be set for multiple languages
lang = ($.isArray(lang) ? lang[0] : lang).split('-')[0];
// set keyboard language
o.display = $.extend(true, {},
kblang.en.display,
kblang[lang] && kblang[lang].display || {},
base.settings.display
);
o.combos = $.extend(true, {},
kblang.en.combos,
kblang[lang] && kblang[lang].combos || {},
base.settings.combos
);
o.wheelMessage = kblang[lang] && kblang[lang].wheelMessage || kblang.en.wheelMessage;
// rtl can be in the layout or in the language definition; defaults to false
o.rtl = layouts[o.layout] && layouts[o.layout].rtl || kblang[lang] && kblang[lang].rtl || false;
// save default regex (in case loading another layout changes it)
base.regex = kblang[lang] && kblang[lang].comboRegex || $keyboard.comboRegex;
// determine if US '.' or European ',' system being used
base.decimal = /^\./.test(o.display.dec);
base.$el
.toggleClass('rtl', o.rtl)
.css('direction', o.rtl ? 'rtl' : '');
};
base.startup = function () {
var kbcss = $keyboard.css;
// ensure base.$preview is defined; but don't overwrite it if keyboard is always visible
if (!((o.alwaysOpen || o.userClosed) && base.$preview)) {
base.makePreview();
}
if (!(base.$keyboard && base.$keyboard.length)) {
// custom layout - create a unique layout name based on the hash
if (o.layout === 'custom') {
o.layoutHash = 'custom' + base.customHash();
}
base.layout = o.layout === 'custom' ? o.layoutHash : o.layout;
base.last.layout = base.layout;
base.updateLanguage();
if (typeof $keyboard.builtLayouts[base.layout] === 'undefined') {
if ($.isFunction(o.create)) {
// create must call buildKeyboard() function; or create it's own keyboard
base.$keyboard = o.create(base);
} else if (!base.$keyboard.length) {
base.buildKeyboard(base.layout, true);
}
}
base.$keyboard = $keyboard.builtLayouts[base.layout].$keyboard.clone();
base.$keyboard.data('keyboard', base);
if ((base.el.id || '') !== '') {
// add ID to keyboard for styling purposes
base.$keyboard.attr('id', base.el.id + $keyboard.css.idSuffix);
}
base.makePreview();
// build preview display
if (o.usePreview) {
// restore original positioning (in case usePreview option is altered)
if (!$.isEmptyObject(o.position)) {
o.position.at = o.position.orig_at;
}
} else {
// No preview display, use element and reposition the keyboard under it.
if (!$.isEmptyObject(o.position)) {
o.position.at = o.position.at2;
}
}
}
base.$decBtn = base.$keyboard.find('.' + kbcss.keyPrefix + 'dec');
// add enter to allowed keys; fixes #190
if (o.enterNavigation || base.el.nodeName === 'TEXTAREA') {
base.alwaysAllowed.push(13);
}
base.bindKeyboard();
base.$keyboard.appendTo(o.appendLocally ? base.$el.parent() : o.appendTo || 'body');
base.bindKeys();
// adjust with window resize; don't check base.position
// here in case it is changed dynamically
if (o.reposition && $.ui && $.ui.position && o.appendTo == 'body') {
$(window).bind('resize' + base.namespace, function () {
if (base.position && base.isVisible()) {
base.$keyboard.position(base.position);
}
});
}
};
base.makePreview = function () {
if (o.usePreview) {
var indx, attrs, attr, removedAttr,
kbcss = $keyboard.css;
base.$preview = base.$el.clone(false)
.data('keyboard', base)
.removeClass(kbcss.placeholder + ' ' + kbcss.input)
.addClass(kbcss.preview + ' ' + o.css.input)
.attr('tabindex', '-1')
.show(); // for hidden inputs
base.preview = base.$preview[0];
// Switch the number input field to text so the caret positioning will work again
if (base.preview.type === 'number') {
base.preview.type = 'text';
}
// remove extraneous attributes.
removedAttr = /^(data-|id|aria-haspopup)/i;
attrs = base.$preview.get(0).attributes;
for (indx = attrs.length - 1; indx >= 0; indx--) {
attr = attrs[indx] && attrs[indx].name;
if (removedAttr.test(attr)) {
// remove data-attributes - see #351
base.preview.removeAttribute(attr);
}
}
// build preview container and append preview display
$('<div />')
.addClass(kbcss.wrapper)
.append(base.$preview)
.prependTo(base.$keyboard);
} else {
base.$preview = base.$el;
base.preview = base.el;
}
};
base.saveCaret = function (start, end, $el) {
var p = $keyboard.caret($el || base.$preview, start, end);
base.last.start = typeof start === 'undefined' ? p.start : start;
base.last.end = typeof end === 'undefined' ? p.end : end;
};
base.setScroll = function () {
// Set scroll so caret & current text is in view
// needed for virtual keyboard typing, NOT manual typing - fixes #23
if (base.last.virtual) {
var scrollWidth, clientWidth, adjustment, direction,
isTextarea = base.preview.nodeName === 'TEXTAREA',
value = base.last.val.substring(0, Math.max(base.last.start, base.last.end));
if (!base.$previewCopy) {
// clone preview
base.$previewCopy = base.$preview.clone()
.removeAttr('id') // fixes #334
.css({
position: 'absolute',
left: 0,
zIndex: -10,
visibility: 'hidden'
})
.addClass($keyboard.css.inputClone);
if (!isTextarea) {
// make input zero-width because we need an accurate scrollWidth
base.$previewCopy.css({
'white-space': 'pre',
'width': 0
});
}
if (o.usePreview) {
// add clone inside of preview wrapper
base.$preview.after(base.$previewCopy);
} else {
// just slap that thing in there somewhere
base.$keyboard.prepend(base.$previewCopy);
}
}
if (isTextarea) {
// need the textarea scrollHeight, so set the clone textarea height to be the line height
base.$previewCopy
.height(base.lineHeight)
.val(value);
// set scrollTop for Textarea
base.preview.scrollTop = base.lineHeight *
(Math.floor(base.$previewCopy[0].scrollHeight / base.lineHeight) - 1);
} else {
// add non-breaking spaces
base.$previewCopy.val(value.replace(/\s/g, '\xa0'));
// if scrollAdjustment option is set to "c" or "center" then center the caret
adjustment = /c/i.test(o.scrollAdjustment) ? base.preview.clientWidth / 2 : o.scrollAdjustment;
scrollWidth = base.$previewCopy[0].scrollWidth - 1;
// set initial state as moving right
if (typeof base.last.scrollWidth === 'undefined') {
base.last.scrollWidth = scrollWidth;
base.last.direction = true;
}
// if direction = true; we're scrolling to the right
direction = base.last.scrollWidth === scrollWidth ?
base.last.direction :
base.last.scrollWidth < scrollWidth;
clientWidth = base.preview.clientWidth - adjustment;
// set scrollLeft for inputs; try to mimic the inherit caret positioning + scrolling:
// hug right while scrolling right...
if (direction) {
if (scrollWidth < clientWidth) {
base.preview.scrollLeft = 0;
} else {
base.preview.scrollLeft = scrollWidth - clientWidth;
}
} else {
// hug left while scrolling left...
if (scrollWidth >= base.preview.scrollWidth - clientWidth) {
base.preview.scrollLeft = base.preview.scrollWidth - adjustment;
} else if (scrollWidth - adjustment > 0) {
base.preview.scrollLeft = scrollWidth - adjustment;
} else {
base.preview.scrollLeft = 0;
}
}
base.last.scrollWidth = scrollWidth;
base.last.direction = direction;
}
}
};
base.bindFocus = function () {
if (o.openOn) {
// make sure keyboard isn't destroyed
// Check if base exists, this is a case when destroy is called, before timers have fired
if (base && base.el.active) {
base.$el.bind(o.openOn + base.namespace, 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();
}
}
}
};
base.bindKeyboard = function () {
var evt,
keyCodes = $keyboard.keyCodes,
layout = $keyboard.builtLayouts[base.layout];
base.$preview
.unbind(base.namespace)
.bind('click' + base.namespace + ' touchstart' + base.namespace, function () {
if (o.alwaysOpen && !base.isCurrent()) {
base.reveal();
}
// update last caret position after user click, use at least 150ms or it doesn't work in IE
base.timer2 = setTimeout(function () {
if (base){
base.saveCaret();
}
}, 150);
})
.bind('keypress' + base.namespace, function (e) {
if (o.lockInput || !base.isCurrent()) {
return false;
}
var k = e.charCode || e.which,
// capsLock can only be checked while typing a-z
k1 = k >= keyCodes.A && k <= keyCodes.Z,
k2 = k >= keyCodes.a && k <= keyCodes.z,
str = base.last.key = String.fromCharCode(k);
base.last.virtual = false;
base.last.event = e;
base.last.$key = []; // not a virtual keyboard key
if (base.checkCaret) {
base.saveCaret();
}
// update capsLock
if (k !== keyCodes.capsLock && (k1 || k2)) {
base.capsLock = (k1 && !e.shiftKey) || (k2 && e.shiftKey);
// if shifted keyset not visible, then show it
if (base.capsLock && !base.shiftActive) {
base.shiftActive = true;
base.showSet();
}
}
// 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 === keyCodes.backSpace || e.which === 0) &&
$.inArray(e.keyCode, base.alwaysAllowed)) {
return;
}
// quick key check
if ($.inArray(str, layout.acceptedKeys) === -1) {
e.preventDefault();
// copy event object in case e.preventDefault() breaks when changing the type
evt = $.extend({}, e);
evt.type = $keyboard.events.inputRestricted;
base.$el.trigger(evt, [base, base.el]);
}
} else if ((e.ctrlKey || e.metaKey) &&
(e.which === keyCodes.A || e.which === keyCodes.C || e.which === keyCodes.V ||
(e.which >= keyCodes.X && e.which <= keyCodes.Z))) {
// Allow select all (ctrl-a), copy (ctrl-c), paste (ctrl-v) & cut (ctrl-x) &
// redo (ctrl-y)& undo (ctrl-z); 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 (layout.hasMappedKeys && layout.mappedKeys.hasOwnProperty(str)) {
base.last.key = layout.mappedKeys[str];
base.insertText(base.last.key);
e.preventDefault();
}
if (typeof o.beforeInsert === 'function') {
base.insertText(base.last.key);
e.preventDefault();
}
base.checkMaxLength();
})
.bind('keyup' + base.namespace, function (e) {
if (!base.isCurrent()) { return; }
base.last.virtual = false;
switch (e.which) {
// Insert tab key
case keyCodes.tab:
// 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 keyCodes.escape:
if (!o.ignoreEsc) {
base.close(o.autoAccept && o.autoAcceptOnEsc ? 'true' : false);
}
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 && base.isVisible()) {
base.checkCombos();
}
}, 100);
base.checkMaxLength();
base.last.preVal = '' + base.last.val;
base.last.val = base.$preview.val();
e.type = $keyboard.events.kbChange;
// base.last.key may be empty string (shift, enter, tab, etc) when keyboard is first visible
// use e.key instead, if browser supports it
e.action = base.last.key;
base.$el.trigger(e, [base, base.el]);
// 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)) {
e.type = $keyboard.events.inputChange;
o.change(e, base, base.el);
return false;
}
if (o.acceptValid && o.autoAcceptOnValid) {
if ($.isFunction(o.validate) && o.validate(base, base.$preview.val())) {
base.$preview.blur();
base.accept();
}
}
})
.bind('keydown' + base.namespace, function (e) {
// ensure alwaysOpen keyboards are made active
if (o.alwaysOpen && !base.isCurrent()) {
base.reveal();
}
// prevent tab key from leaving the preview window
if (e.which === keyCodes.tab) {
// allow tab to pass through - tab to next input/shift-tab for prev
base.tab = true;
return false;
}
if (o.lockInput) {
return false;
}
base.last.virtual = false;
switch (e.which) {
case keyCodes.backSpace:
$keyboard.keyaction.bksp(base, null, e);
e.preventDefault();
break;
case keyCodes.enter:
$keyboard.keyaction.enter(base, null, e);
break;
// Show capsLock
case keyCodes.capsLock:
base.shiftActive = base.capsLock = !base.capsLock;
base.showSet();
break;
case keyCodes.V:
// prevent ctrl-v/cmd-v
if (e.ctrlKey || e.metaKey) {
if (o.preventPaste) {
e.preventDefault();
return;
}
base.checkCombos(); // check pasted content
}
break;
}
})
.bind('mouseup touchend '.split(' ').join(base.namespace + ' '), function () {
base.last.virtual = true;
base.saveCaret();
});
// prevent keyboard event bubbling
base.$keyboard.bind('mousedown click touchstart '.split(' ').join(base.namespace + ' '), function (e) {
e.stopPropagation();
if (!base.isCurrent()) {
base.reveal();
$(document).trigger('checkkeyboard' + base.namespace);
}
if (!o.noFocus && base.$preview) {
base.$preview.focus();
e.preventDefault();
}
});
// If preventing paste, block context menu (right click)
if (o.preventPaste) {
base.$preview.bind('contextmenu' + base.namespace, function (e) {
e.preventDefault();
});
base.$el.bind('contextmenu' + base.namespace, function (e) {
e.preventDefault();
});
}
};
base.bindKeys = function () {
var kbcss = $keyboard.css;
base.$allKeys = base.$keyboard.find('button.' + kbcss.keyButton)
.unbind(base.namespace + ' ' + base.namespace + 'kb')
// Change hover class and tooltip - moved this touchstart before option.keyBinding touchstart
// to prevent mousewheel lag/duplication - Fixes #379 & #411
.bind('mouseenter mouseleave touchstart '.split(' ').join(base.namespace + ' '), function (e) {
if ((o.alwaysOpen || o.userClosed) && e.type !== 'mouseleave' && !base.isCurrent()) {
base.reveal();
base.$preview.focus();
$keyboard.caret(base.$preview, base.last);
}
if (!base.isCurrent()) {
return;
}
var $keys, txt,
last = base.last,
$this = $(this),
type = e.type;
if (o.useWheel && base.wheel) {
$keys = base.getLayers($this);
txt = ($keys.length ? $keys.map(function () {
return $(this).attr('data-value') || '';
})
.get() : '') || [$this.text()];
last.wheel_$Keys = $keys;
last.wheelLayers = txt;
last.wheelIndex = $.inArray($this.attr('data-value'), txt);
}
if ((type === 'mouseenter' || type === 'touchstart') && base.el.type !== 'password' &&
!$this.hasClass(o.css.buttonDisabled)) {
$this.addClass(o.css.buttonHover);
if (o.useWheel && base.wheel) {
$this.attr('title', function (i, t) {
// show mouse wheel message
return (base.wheel && t === '' && base.sets && txt.length > 1 && type !== 'touchstart') ?
o.wheelMessage : t;
});
}
}
if (type === 'mouseleave') {
// needed or IE flickers really bad
$this.removeClass((base.el.type === 'password') ? '' : o.css.buttonHover);
if (o.useWheel && base.wheel) {
last.wheelIndex = 0;
last.wheelLayers = [];
last.wheel_$Keys = null;
$this
.attr('title', function (i, t) {
return (t === o.wheelMessage) ? '' : t;
})
.html($this.attr('data-html')); // restore original button text
}
}
})
// keyBinding = 'mousedown touchstart' by default
.bind(o.keyBinding.split(' ').join(base.namespace + ' ') + base.namespace + ' ' +
$keyboard.events.kbRepeater, function (e) {
e.preventDefault();
// prevent errors when external triggers attempt to 'type' - see issue #158
if (!base.$keyboard.is(':visible')) {
return false;
}
var action, $keys,
last = base.last,
key = this,
$key = $(key),
// prevent mousedown & touchstart from both firing events at the same time - see #184
timer = new Date().getTime();
if (o.useWheel && base.wheel) {
// get keys from other layers/keysets (shift, alt, meta, etc) that line up by data-position
$keys = last.wheel_$Keys;
// target mousewheel selected key
$key = $keys && last.wheelIndex > -1 ? $keys.eq(last.wheelIndex) : $key;
}
action = $key.attr('data-action');
if (timer - (last.eventTime || 0) < o.preventDoubleEventTime) {
return;
}
last.eventTime = timer;
last.event = e;
last.virtual = true;
if (!o.noFocus) {