-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
domManager.ts
1852 lines (1590 loc) · 71.5 KB
/
domManager.ts
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
// Includes KMW-added property declaration extensions for HTML elements.
/// <reference path="../kmwexthtml.ts" />
// References the base KMW object.
/// <reference path="../kmwbase.ts" />
// References DOM event handling interfaces and classes.
/// <reference path="domEventHandlers.ts" />
// References DOM-specific output handling.
/// <reference path="domDefaultOutput.ts" />
// References other DOM-specific web-core overrides.
/// <reference path="domOverrides.ts" />
// Defines the touch-alias element structure used for mobile devices.
/// <reference path="touchAliasElement.ts" />
// Defines per-element-type OutputTarget element wrapping.
/// <reference path="targets/wrapElement.ts" />
// Defines cookie-based variable store serialization
/// <reference path="variableStoreCookieSerializer.ts" />
namespace com.keyman.dom {
// Utility object used to handle beep (keyboard error response) operations.
class BeepData {
e: HTMLElement;
c: string;
constructor(e: HTMLElement) {
this.e = e;
this.c = e.style.backgroundColor;
}
reset(): void {
this.e.style.backgroundColor = this.c;
}
}
/**
* This class serves as the intermediary between KeymanWeb and any given web page's elements.
*/
export class DOMManager {
private keyman: KeymanBase;
/**
* Implements the AliasElementHandlers interface for touch interaction.
*/
touchHandlers?: DOMTouchHandlers;
/**
* Implements stubs for the AliasElementHandlers interface for non-touch interaction.
*/
nonTouchHandlers: DOMEventHandlers;
/**
* Tracks the attachment MutationObserver.
*/
attachmentObserver: MutationObserver;
/**
* Tracks the enablement MutationObserver.
*/
enablementObserver: MutationObserver;
/**
* Tracks a list of event-listening elements.
*
* In touch mode, this should contain touch-aliasing DIVs, but will contain other elements in non-touch mode.
*/
inputList: HTMLElement[] = []; // List of simulated input divisions for touch-devices I3363 (Build 301)
/**
* Tracks a visually-sorted list of elements that are KMW-enabled.
*/
sortedInputs: HTMLElement[] = []; // List of all INPUT and TEXTAREA elements ordered top to bottom, left to right
_BeepObjects: BeepData[] = []; // BeepObjects - maintains a list of active 'beep' visual feedback elements
_BeepTimeout: number = 0; // BeepTimeout - a flag indicating if there is an active 'beep'.
// Set to 1 if there is an active 'beep', otherwise leave as '0'.
// Used for special touch-based page interactions re: element activation on touch devices.
deactivateOnScroll: boolean = false;
deactivateOnRelease: boolean = false;
touchY: number; // For scroll-related aspects on iOS.
touchStartActivationHandler: (e: TouchEvent) => boolean;
touchMoveActivationHandler: (e: TouchEvent) => boolean;
touchEndActivationHandler: (e: TouchEvent) => boolean;
constructor(keyman: KeymanBase) {
this.keyman = keyman;
if(keyman.util.device.touchable) {
this.touchHandlers = new DOMTouchHandlers(keyman);
}
this.nonTouchHandlers = new DOMEventHandlers(keyman);
}
shutdown() {
// Catch and notify of any shutdown errors, but don't let errors fail unit tests.
try {
if(this.enablementObserver) {
this.enablementObserver.disconnect();
}
if(this.attachmentObserver) {
this.attachmentObserver.disconnect();
}
for(let input of this.inputList) {
this.disableInputElement(input);
}
// On shutdown, we remove our general focus-suppression handlers as well.
this.keyman.util.detachDOMEvent(document.body, 'focus', DOMManager.suppressFocusCheck, true);
this.keyman.util.detachDOMEvent(document.body, 'blur', DOMManager.suppressFocusCheck, true);
// Also, the base-page touch handlers for activation management.
if(this.touchStartActivationHandler) {
this.keyman.util.detachDOMEvent(document.body, 'touchstart', this.touchStartActivationHandler, false);
this.keyman.util.detachDOMEvent(document.body, 'touchmove', this.touchMoveActivationHandler, false);
this.keyman.util.detachDOMEvent(document.body, 'touchend', this.touchEndActivationHandler, false);
}
} catch (e) {
console.error("Error occurred during shutdown");
console.error(e);
}
}
/**
* Function beep KB (DOM-side implementation)
* Scope Public
* @param {Object} Pelem element to flash
* Description Flash body as substitute for audible beep; notify embedded device to vibrate
*/
doBeep(outputTarget: targets.OutputTarget) {
// Handles embedded-mode beeps.
let keyman = com.keyman.singleton;
if ('beepKeyboard' in keyman) {
keyman['beepKeyboard']();
return;
}
if(!(outputTarget instanceof targets.OutputTarget)) {
return;
}
// All code after this point is DOM-based, triggered by the beep.
var Pelem: HTMLElement = outputTarget.getElement();
if(outputTarget instanceof dom.targets.DesignIFrame) {
Pelem = outputTarget.docRoot; // I1446 - beep sometimes fails to flash when using OSK and rich control
}
if(!Pelem) {
return; // There's no way to signal a 'beep' to null, so just cut everything short.
}
if(!Pelem.style || typeof(Pelem.style.backgroundColor)=='undefined') {
return;
}
for(var Lbo=0; Lbo<this._BeepObjects.length; Lbo++) { // I1446 - beep sometimes fails to return background color to normal
// I1511 - array prototype extended
if(this._BeepObjects[Lbo].e == Pelem) {
return;
}
}
this._BeepObjects = com.keyman.singleton._push(this._BeepObjects, new BeepData(Pelem));
// TODO: This is probably a bad color choice if "dark mode" is enabled. A proper implementation
// would probably require some 'fun' CSS work, though.
Pelem.style.backgroundColor = '#000000';
if(this._BeepTimeout == 0) {
this._BeepTimeout = 1;
window.setTimeout(this.beepReset.bind(this), 50);
}
}
/**
* Function beepReset
* Scope Public
* Description Reset/terminate beep or flash (not currently used: Aug 2011)
*/
beepReset(): void {
com.keyman.singleton.core.keyboardInterface.resetContextCache();
var Lbo;
this._BeepTimeout = 0;
for(Lbo=0;Lbo<this._BeepObjects.length;Lbo++) { // I1511 - array prototype extended
this._BeepObjects[Lbo].reset();
}
this._BeepObjects = [];
}
/**
* Function getHandlers
* Scope Private
* @param {Element} Pelem An input, textarea, or touch-alias element from the page.
* @returns {Object}
*/
getHandlers(Pelem: HTMLElement): DOMEventHandlers {
var _attachObj = Pelem.base ? Pelem.base._kmwAttachment : Pelem._kmwAttachment;
if(_attachObj) {
return _attachObj.touchEnabled ? this.touchHandlers : this.nonTouchHandlers;
} else {
// Best guess solution.
return this.keyman.touchAliasing;
}
}
/**
* Function enableTouchElement
* Scope Private
* @param {Element} Pelem An input or textarea element from the page.
* @return {boolean} Returns true if it creates a simulated input element for Pelem; false if not.
* Description Creates a simulated input element for the specified INPUT or TEXTAREA, comprising:
* an outer DIV, matching the position, size and style of the base element
* a scrollable DIV within that outer element
* two SPAN elements within the scrollable DIV, to hold the text before and after the caret
*
* The left border of the second SPAN is flashed on and off as a visible caret
*
* Also ensures the element is registered on keymanweb's internal input list.
*/
enableTouchElement(Pelem: HTMLElement) {
// Touch doesn't worry about iframes.
if(Pelem.tagName.toLowerCase() == 'iframe') {
return false;
}
if(this.isKMWDisabled(Pelem)) {
this.setupNonKMWTouchElement(Pelem);
return false;
} else {
// Initialize and protect input elements for touch-screen devices (but never for apps)
// NB: now set disabled=true rather than readonly, since readonly does not always
// prevent element from getting focus, e.g. within a LABEL element.
// c.f. http://kreotekdev.wordpress.com/2007/11/08/disabled-vs-readonly-form-fields/
Pelem.kmwInput = true;
}
// Remove any handlers for "NonKMWTouch" elements, since we're enabling it here.
Pelem.removeEventListener('touchstart', this.nonKMWTouchHandler);
/*
* Does this element already have a simulated touch element established? If so,
* just reuse it - if it isn't still in the input list!
*/
if(Pelem['kmw_ip']) {
if(this.inputList.indexOf(Pelem['kmw_ip']) != -1) {
return false;
}
this.inputList.push(Pelem['kmw_ip']);
console.log("Unexpected state - this element's simulated input DIV should have been removed from the page!");
return true; // May need setup elsewhere since it's just been re-added!
}
// The simulated touch element doesn't already exist? Time to initialize it.
let x=dom.constructTouchAlias(Pelem);
if(this.isAttached(x)) {
x._kmwAttachment.interface = dom.targets.wrapElement(x);
} else {
this.setupElementAttachment(x); // The touch-alias should have its own wrapper.
}
Pelem._kmwAttachment = x._kmwAttachment; // It's an object reference we need to alias.
// Set font for base element
this.enableInputElement(x, true);
// Superimpose custom input fields for each input or textarea, unless readonly or disabled
// On touch event, reposition the text caret and prepare for OSK input
// Removed 'onfocus=' as that resulted in handling the event twice (on iOS, anyway)
// We know this to be the correct set of handlers because we're setting up a touch element.
var touchHandlers = this.touchHandlers;
x.addEventListener('touchstart', touchHandlers.setFocus);
x.onmspointerdown=function(e: MSPointerEvent) {
e.preventDefault();
e.stopPropagation();
return touchHandlers.setFocus(e);
};
x.addEventListener('touchend', function(e) {
e.stopPropagation();
});
x.onmspointerup=function(e) {
e.stopPropagation();
};
// Disable internal scroll when input element in focus
x.addEventListener('touchmove', touchHandlers.dragInput, false);
x.onmspointermove=touchHandlers.dragInput;
// Hide keyboard and caret when losing focus from simulated input field
x.onblur=touchHandlers.setBlur;
// Note that touchend event propagates and is processed by body touchend handler
// re-setting the first touch point for a drag
return true;
}
/**
* Function disableTouchElement
* Scope Private
* @param {Element} Pelem An input or textarea element from the page.
* Description Destroys the simulated input element for the specified INPUT or TEXTAREA and reverts
* back to desktop-style 'enablement' for the base control.
*/
disableTouchElement(Pelem: HTMLElement) {
// Do not check for the element being officially disabled - it's also used for detachment.
// Touch doesn't worry about iframes.
if(Pelem.tagName.toLowerCase() == 'iframe') {
return; // If/when we do support this, we'll need an iframe-level manager for it.
}
if(Pelem['kmw_ip']) {
var index = this.inputList.indexOf(Pelem['kmw_ip']);
if(index != -1) {
this.inputList.splice(index, 1);
}
Pelem.style.visibility='visible'; // hide by default: KMW-3
Pelem.disabled = false;
Pelem.removeEventListener('resize', Pelem['kmw_ip']._kmwResizeHandler);
// Disable touch-related handling code.
this.disableInputElement(Pelem['kmw_ip']);
Pelem._kmwAttachment.interface = dom.targets.wrapElement(Pelem);
// We get weird repositioning errors if we don't remove our simulated input element - and permanently.
if(Pelem.parentNode) {
Pelem.parentNode.removeChild(Pelem['kmw_ip']);
}
delete Pelem['kmw_ip'];
}
this.setupNonKMWTouchElement(Pelem);
}
/**
* Function nonKMWTouchHandler
* Scope Private
* Description A handler for KMW-touch-disabled elements when operating on touch devices.
*/
nonKMWTouchHandler = function(x) {
DOMEventHandlers.states.focusing=false;
clearTimeout(DOMEventHandlers.states.focusTimer);
this.keyman.osk.hideNow();
}.bind(this);
/**
* Function setupNonKMWTouchElement
* Scope Private
* @param {Element} x A child element of document.
* Description Performs handling for the specified disabled input element on touch-based systems.
*/
setupNonKMWTouchElement(x: HTMLElement) {
this.keyman.util.attachDOMEvent(x, 'touchstart', this.nonKMWTouchHandler, false);
// Signify that touch isn't enabled on the control.
if(this.isAttached(x)) {
x._kmwAttachment.touchEnabled = false;
}
}
/**
* Function enableInputElement
* Scope Private
* @param {Element} Pelem An element from the document to be enabled with full KMW handling.
* @param {boolean=} isAlias A flag that indicates if the element is a simulated input element for touch.
* Description Performs the basic enabling setup for one element and adds it to the inputList if it is an input element.
* Note that this method is called for both desktop and touch control routes; the touch route calls it from within
* enableTouchElement as it must first establish the simulated touch element to serve as the alias "input element" here.
* Note that the 'kmw-disabled' property is managed by the MutationObserver and by the surface API calls.
*/
enableInputElement(Pelem: HTMLElement, isAlias?: boolean) {
var baseElement = isAlias ? Pelem['base'] : Pelem;
if(!this.isKMWDisabled(baseElement)) {
if(Pelem instanceof Pelem.ownerDocument.defaultView.HTMLIFrameElement) {
this._AttachToIframe(Pelem);
} else {
if(!isAlias) {
this.setupElementAttachment(Pelem);
}
baseElement.className = baseElement.className ? baseElement.className + ' keymanweb-font' : 'keymanweb-font';
this.inputList.push(Pelem);
this.keyman.util.attachDOMEvent(baseElement,'focus', this.getHandlers(Pelem)._ControlFocus);
this.keyman.util.attachDOMEvent(baseElement,'blur', this.getHandlers(Pelem)._ControlBlur);
// These need to be on the actual input element, as otherwise the keyboard will disappear on touch.
Pelem.onkeypress = this.getHandlers(Pelem)._KeyPress;
Pelem.onkeydown = this.getHandlers(Pelem)._KeyDown;
Pelem.onkeyup = this.getHandlers(Pelem)._KeyUp;
}
}
};
/**
* Function disableInputElement
* Scope Private
* @param {Element} Pelem An element from the document to be enabled with full KMW handling.
* @param {boolean=} isAlias A flag that indicates if the element is a simulated input element for touch.
* Description Inverts the process of enableInputElement, removing all event-handling from the element.
* Note that the 'kmw-disabled' property is managed by the MutationObserver and by the surface API calls.
*/
disableInputElement(Pelem: HTMLElement, isAlias?: boolean) {
if(!Pelem) {
return;
}
var baseElement = isAlias ? Pelem['base'] : Pelem;
// Do NOT test for pre-disabledness - we also use this to fully detach without officially 'disabling' via kmw-disabled.
if((Pelem.ownerDocument.defaultView && Pelem instanceof Pelem.ownerDocument.defaultView.HTMLIFrameElement) ||
Pelem instanceof HTMLIFrameElement) {
this._DetachFromIframe(Pelem);
} else {
var cnIndex = baseElement.className.indexOf('keymanweb-font');
if(cnIndex > 0 && !isAlias) { // See note about the alias below.
baseElement.className = baseElement.className.replace('keymanweb-font', '').trim();
}
// Remove the element from our internal input tracking.
var index = this.inputList.indexOf(Pelem);
if(index > -1) {
this.inputList.splice(index, 1);
}
if(!isAlias) { // See note about the alias below.
this.keyman.util.detachDOMEvent(baseElement,'focus', this.getHandlers(Pelem)._ControlFocus);
this.keyman.util.detachDOMEvent(baseElement,'blur', this.getHandlers(Pelem)._ControlBlur);
}
// These need to be on the actual input element, as otherwise the keyboard will disappear on touch.
Pelem.onkeypress = null;
Pelem.onkeydown = null;
Pelem.onkeyup = null;
}
// If we're disabling an alias, we should fully enable the base version. (Thinking ahead to toggleable-touch mode.)
if(isAlias) {
this.inputList.push(baseElement);
baseElement.onkeypress = this.getHandlers(Pelem)._KeyPress;
baseElement.onkeydown = this.getHandlers(Pelem)._KeyDown;
baseElement.onkeyup = this.getHandlers(Pelem)._KeyUp;
}
var lastElem = this.lastActiveElement;
if(lastElem == Pelem || lastElem == Pelem['kmw_ip']) {
if(this.activeElement == lastElem) {
this.activeElement = null;
}
this.lastActiveElement = null;
this.keyman.osk._Hide(false);
}
return;
};
/**
* Function isKMWDisabled
* Scope Private
* @param {Element} x An element from the page.
* @return {boolean} true if the element's properties indicate a 'disabled' state.
* Description Examines attachable elements to determine their default enablement state.
*/
isKMWDisabled(x: HTMLElement): boolean {
var c = x.className;
// Exists for some HTMLElements.
if(x['readOnly']) {
return true;
} else if(c && c.indexOf('kmw-disabled') >= 0) {
return true;
}
return false;
}
/**
* Function attachToControl
* Scope Public
* @param {Element} Pelem Element to which KMW will be attached
* Description Attaches KMW to control (or IFrame)
*/
attachToControl(Pelem: HTMLElement) {
var touchable = this.keyman.util.device.touchable;
// Exception for IFrame elements, in case of async loading issues. (Fixes fun iframe loading bug with Chrome.)
if(this.isAttached(Pelem) && !(Pelem instanceof Pelem.ownerDocument.defaultView.HTMLIFrameElement)) {
return; // We're already attached.
}
if(this.isKMWInput(Pelem)) {
if(!this.isKMWDisabled(Pelem)) {
if(touchable && !this.keyman.isEmbedded) {
this.enableTouchElement(Pelem);
} else {
this.enableInputElement(Pelem);
}
} else {
if(touchable) {
this.setupNonKMWTouchElement(Pelem);
}
}
} else if(touchable) {
this.setupNonKMWTouchElement(Pelem);
}
}
/**
* Function detachFromControl
* Scope Public
* @param {Element} Pelem Element from which KMW will detach
* Description Detaches KMW from a control (or IFrame)
*/
detachFromControl(Pelem: HTMLElement) {
if(!(this.isAttached(Pelem) || Pelem instanceof Pelem.ownerDocument.defaultView.HTMLIFrameElement)) {
return; // We never were attached.
}
// #1 - if element is enabled, disable it. But don't manipulate the 'kmw-disabled' tag.
if(this.isKMWInput(Pelem)) {
// Is it already disabled?
if(!this.isKMWDisabled(Pelem)) {
this._DisableControl(Pelem);
}
}
// #2 - clear attachment data.
this.clearElementAttachment(Pelem);
}
/**
* Function isAttached
* Scope Private
* @param {Element} x An element from the page.
* @return {boolean} true if KMW is attached to the element, otherwise false.
*/
isAttached(x: HTMLElement) {
return x._kmwAttachment ? true : false;
}
/**
* Function isKMWInput
* Scope Private
* @param {Element} x An element from the page.
* @return {boolean} true if the element is viable for KMW attachment.
* Description Examines potential input elements to determine whether or not they are viable for KMW attachment.
* Also filters elements not supported for touch devices when device.touchable == true.
*/
isKMWInput(x: HTMLElement): boolean {
var touchable = this.keyman.util.device.touchable;
if(x instanceof x.ownerDocument.defaultView.HTMLTextAreaElement) {
return true;
} else if(x instanceof x.ownerDocument.defaultView.HTMLInputElement) {
if (x.type == 'text' || x.type == 'search') {
return true;
}
} else if(x instanceof x.ownerDocument.defaultView.HTMLIFrameElement && !touchable) { // Do not allow iframe attachment if in 'touch' mode.
try {
if(x.contentWindow) {
if(x.contentWindow.document) { // Only allow attachment if the iframe's internal document is valid.
return true;
}
} // else nothing?
}
catch(err) {
/* Do not attempt to access iframes outside this site */
console.warn("Error during attachment to / detachment from iframe: ");
console.warn(err);
}
} else if(x.isContentEditable && !touchable) { // Only allow contentEditable attachment outside of 'touch' mode.
return true;
}
return false;
}
/**
* Function setupElementAttachment
* Scope Private
* @param {Element} x An element from the page valid for KMW attachment
* Description Establishes the base KeymanWeb data for newly-attached elements.
* Does not establish input hooks, which are instead handled during enablement.
*/
setupElementAttachment(x: HTMLElement) {
// The `_kmwAttachment` property tag maintains all relevant KMW-maintained data regarding the element.
// It is disgarded upon de-attachment.
if(x._kmwAttachment) {
return;
} else {
// Problem: tries to wrap IFrames that aren't design-mode.
// The elements in the contained document get separately wrapped, so this doesn't need a proper wrapper.
//
// Its attachment process might need some work.
let eleInterface = dom.targets.wrapElement(x);
// May should filter better for IFrames.
if(!(eleInterface || dom.Utils.instanceof(x, "HTMLIFrameElement"))) {
console.warn("Could not create processing interface for newly-attached element!");
}
x._kmwAttachment = new AttachmentInfo(eleInterface, null, this.keyman.util.device.touchable);
}
}
/**
* Function clearElementAttachment
* Scope Private
* @param {Element} x An element from the page valid for KMW attachment
* Description Establishes the base KeymanWeb data for newly-attached elements.
* Does not establish input hooks, which are instead handled during enablement.
*/
clearElementAttachment(x: HTMLElement) {
// We need to clear the object when de-attaching; helps prevent memory leaks.
x._kmwAttachment = null;
}
/**
* Function _AttachToIframe
* Scope Private
* @param {Element} Pelem IFrame to which KMW will be attached
* Description Attaches KeymanWeb to IFrame
*/
_AttachToIframe(Pelem: HTMLIFrameElement) {
var util = this.keyman.util;
try {
var Lelem=Pelem.contentWindow.document;
/* editable Iframe */
if(Lelem) {
if(Lelem.designMode.toLowerCase() == 'on') {
// I2404 - Attach to IFRAMEs child objects, only editable IFRAMEs here
if(util.device.browser == 'firefox') {
util.attachDOMEvent(Lelem,'focus', this.getHandlers(Pelem)._ControlFocus);
util.attachDOMEvent(Lelem,'blur', this.getHandlers(Pelem)._ControlBlur);
} else { // Chrome, Safari
util.attachDOMEvent(Lelem.body,'focus', this.getHandlers(Pelem)._ControlFocus);
util.attachDOMEvent(Lelem.body,'blur', this.getHandlers(Pelem)._ControlBlur);
}
util.attachDOMEvent(Lelem.body,'keydown', this.getHandlers(Pelem)._KeyDown);
util.attachDOMEvent(Lelem.body,'keypress', this.getHandlers(Pelem)._KeyPress);
util.attachDOMEvent(Lelem.body,'keyup', this.getHandlers(Pelem)._KeyUp);
// Set up a reference alias; the internal document will need the same attachment info!
this.setupElementAttachment(Pelem);
Lelem.body._kmwAttachment = Pelem._kmwAttachment;
} else {
// Lelem is the IFrame's internal document; set 'er up!
this._SetupDocument(Lelem.body); // I2404 - Manage IE events in IFRAMEs
}
}
}
catch(err)
{
// do not attempt to attach to the iframe as it is from another domain - XSS denied!
}
}
/**
* Function _DetachFromIframe
* Scope Private
* @param {Element} Pelem IFrame to which KMW will be attached
* Description Detaches KeymanWeb from an IFrame
*/
_DetachFromIframe(Pelem: HTMLIFrameElement) {
var util = this.keyman.util;
try {
var Lelem=Pelem.contentWindow.document;
/* editable Iframe */
if(Lelem) {
if(Lelem.designMode.toLowerCase() == 'on') {
// Mozilla // I2404 - Attach to IFRAMEs child objects, only editable IFRAMEs here
if(util.device.browser == 'firefox') {
// Firefox won't handle these events on Lelem.body - only directly on Lelem (the doc) instead.
util.detachDOMEvent(Lelem,'focus', this.getHandlers(Pelem)._ControlFocus);
util.detachDOMEvent(Lelem,'blur', this.getHandlers(Pelem)._ControlBlur);
} else { // Chrome, Safari
util.detachDOMEvent(Lelem.body,'focus', this.getHandlers(Pelem)._ControlFocus);
util.detachDOMEvent(Lelem.body,'blur', this.getHandlers(Pelem)._ControlBlur);
}
util.detachDOMEvent(Lelem.body,'keydown', this.getHandlers(Pelem)._KeyDown);
util.detachDOMEvent(Lelem.body,'keypress', this.getHandlers(Pelem)._KeyPress);
util.detachDOMEvent(Lelem.body,'keyup', this.getHandlers(Pelem)._KeyUp);
// Remove the reference to our prior attachment data!
Lelem.body._kmwAttachment = null;
} else {
// Lelem is the IFrame's internal document; set 'er up!
this._ClearDocument(Lelem.body); // I2404 - Manage IE events in IFRAMEs
}
}
}
catch(err)
{
// do not attempt to attach to the iframe as it is from another domain - XSS denied!
}
}
/**
* Function _GetDocumentEditables
* Scope Private
* @param {Element} Pelem HTML element
* @return {Array<Element>} A list of potentially-editable controls. Further filtering [as with isKMWInput() and
* isKMWDisabled()] is required.
*/
_GetDocumentEditables(Pelem: HTMLElement): (HTMLElement)[] {
var util = this.keyman.util;
var possibleInputs: (HTMLElement)[] = [];
// Document.ownerDocument === null, so we better check that it's not null before proceeding.
if(Pelem.ownerDocument && Pelem instanceof Pelem.ownerDocument.defaultView.HTMLElement) {
var dv = Pelem.ownerDocument.defaultView;
if(Pelem instanceof dv.HTMLInputElement || Pelem instanceof dv.HTMLTextAreaElement) {
possibleInputs.push(Pelem);
} else if(Pelem instanceof dv.HTMLIFrameElement) {
possibleInputs.push(Pelem);
}
}
// Constructing it like this also allows for individual element filtering for the auto-attach MutationObserver without errors.
if(Pelem.getElementsByTagName) {
/**
* Function LiTmp
* Scope Private
* @param {string} _colon type of element
* @return {Array<Element>} array of elements of specified type
* Description Local function to get list of editable controls
*/
var LiTmp = function(_colon: string): HTMLElement[] {
return util.arrayFromNodeList(Pelem.getElementsByTagName(_colon));
};
// Note that isKMWInput() will block IFRAME elements as necessary for touch-based devices.
possibleInputs = possibleInputs.concat(LiTmp('INPUT'), LiTmp('TEXTAREA'), LiTmp('IFRAME'));
}
// Not all active browsers may support the method, but only those that do would work with contenteditables anyway.
if(Pelem.querySelectorAll) {
possibleInputs = possibleInputs.concat(util.arrayFromNodeList(Pelem.querySelectorAll('[contenteditable]')));
}
if(Pelem.ownerDocument && Pelem instanceof Pelem.ownerDocument.defaultView.HTMLElement && Pelem.isContentEditable) {
possibleInputs.push(Pelem);
}
return possibleInputs;
}
/**
* Function _SetupDocument
* Scope Private
* @param {Element} Pelem - the root element of a document, including IFrame documents.
* Description Used to automatically attach KMW to editable controls, regardless of control path.
*/
_SetupDocument(Pelem: HTMLElement) { // I1961
var possibleInputs = this._GetDocumentEditables(Pelem);
for(var Li = 0; Li < possibleInputs.length; Li++) {
var input = possibleInputs[Li];
// It knows how to handle pre-loaded iframes appropriately.
this.attachToControl(possibleInputs[Li] as HTMLElement);
}
}
/**
* Function _ClearDocument
* Scope Private
* @param {Element} Pelem - the root element of a document, including IFrame documents.
* Description Used to automatically detach KMW from editable controls, regardless of control path.
* Mostly used to clear out all controls of a detached IFrame.
*/
_ClearDocument(Pelem: HTMLElement) { // I1961
var possibleInputs = this._GetDocumentEditables(Pelem);
for(var Li = 0; Li < possibleInputs.length; Li++) {
var input = possibleInputs[Li];
// It knows how to handle pre-loaded iframes appropriately.
this.detachFromControl(possibleInputs[Li] as HTMLElement);
}
}
/**
* Set target element text direction (LTR or RTL), but only if the element is empty
*
* If the element base directionality is changed after it contains content, unless all the text
* has the same directionality, text runs will be re-ordered which is confusing and causes
* incorrect caret positioning
*
* @param {Object} Ptarg Target element
*/
_SetTargDir(Ptarg: HTMLElement) {
let activeKeyboard = com.keyman.singleton.core.activeKeyboard;
var elDir=(activeKeyboard && activeKeyboard.isRTL) ? 'rtl' : 'ltr';
if(Ptarg) {
if(this.keyman.util.device.touchable) {
let alias = <dom.TouchAliasElement> Ptarg;
if(Ptarg.textContent.length == 0) {
alias.base.dir=alias.dir=elDir;
alias.setTextCaret(10000);
}
} else {
if(Ptarg instanceof Ptarg.ownerDocument.defaultView.HTMLInputElement
|| Ptarg instanceof Ptarg.ownerDocument.defaultView.HTMLTextAreaElement) {
if((Ptarg as HTMLInputElement|HTMLTextAreaElement).value.length == 0) {
Ptarg.dir=elDir;
}
} else if(typeof Ptarg.textContent == "string" && Ptarg.textContent.length == 0) { // As with contenteditable DIVs, for example.
Ptarg.dir=elDir;
}
}
}
}
/**
* Function _DisableControl
* Scope Private
* @param {Element} Pelem Element to be disabled
* Description Disable KMW control element
*/
_DisableControl(Pelem: HTMLElement) {
// Only operate on attached elements! Non-design-mode IFrames don't get attachment markers, so we check them specifically instead.
if(this.isAttached(Pelem) || Pelem instanceof Pelem.ownerDocument.defaultView.HTMLIFrameElement) {
if(this.keyman.util.device.touchable) {
this.disableTouchElement(Pelem);
this.setupNonKMWTouchElement(Pelem);
var keyman = this.keyman;
// If a touch alias was removed, chances are it's gonna mess up our touch-based layout scheme, so let's update the touch elements.
window.setTimeout(function() {
this.listInputs();
for(var k = 0; k < this.sortedInputs.length; k++) {
if(this.sortedInputs[k]['kmw_ip']) {
this.sortedInputs[k]['kmw_ip'].updateInput(this.sortedInputs[k]['kmw_ip']);
}
}
}.bind(this), 1);
} else {
this.listInputs(); // Fix up our internal input ordering scheme.
}
this.disableInputElement(Pelem);
}
}
/**
* Function _EnableControl
* Scope Private
* @param {Element} Pelem Element to be enabled
* Description Enable KMW control element
*/
_EnableControl(Pelem: HTMLElement) {
if(this.isAttached(Pelem)) { // Only operate on attached elements!
if(this.keyman.util.device.touchable) {
this.enableTouchElement(Pelem);
var keyman = this.keyman;
// If we just added a new input alias, some languages will mess up our touch-based layout scheme
// if we don't update the touch elements.
window.setTimeout(function() {
keyman.domManager.listInputs();
for(var k = 0; k < this.sortedInputs.length; k++) {
if(this.sortedInputs[k]['kmw_ip']) {
this.sortedInputs[k]['kmw_ip'].updateInput(this.sortedInputs[k]['kmw_ip']);
}
}
}.bind(this), 1);
} else {
this.enableInputElement(Pelem);
}
}
}
// Create an ordered list of all text and search input elements and textarea elements
// except any tagged with class 'kmw-disabled'
// TODO: email and url types should perhaps use default keyboard only
listInputs() {
var i,eList=[],
t1=document.getElementsByTagName<'input'>('input'),
t2=document.getElementsByTagName<'textarea'>('textarea');
var util = this.keyman.util;
for(i=0; i<t1.length; i++) {
switch(t1[i].type) {
case 'text':
case 'search':
case 'email':
case 'url':
if(t1[i].className.indexOf('kmw-disabled') < 0) {
eList.push({ip:t1[i], x: dom.Utils.getAbsoluteX(t1[i]), y: dom.Utils.getAbsoluteY(t1[i])});
}
break;
}
}
for(i=0; i<t2.length; i++) {
if(t2[i].className.indexOf('kmw-disabled') < 0)
eList.push({ip:t2[i], x: dom.Utils.getAbsoluteX(t2[i]), y: dom.Utils.getAbsoluteY(t2[i])});
}
/**
* Local function to sort by screen position
*
* @param {Object} e1 first object
* @param {Object} e2 second object
* @return {number} y-difference between object positions, or x-difference if y values the same
*/
var xySort=function(e1,e2)
{
if(e1.y != e2.y) return e1.y-e2.y;
return e1.x-e2.x;
}
// Sort elements by Y then X
eList.sort(xySort);
// Create a new list of sorted elements
var tList=[];
for(i=0;i<eList.length;i++)
tList.push(eList[i].ip);
// Return the sorted element list
this.sortedInputs=tList;
}
_EnablementMutationObserverCore = function(mutations: MutationRecord[]) {
for(var i=0; i < mutations.length; i++) {
var mutation = mutations[i];
// ( ? : ) needed as a null check.
var disabledBefore = mutation.oldValue ? mutation.oldValue.indexOf('kmw-disabled') >= 0 : false;
var disabledAfter = (mutation.target as HTMLElement).className.indexOf('kmw-disabled') >= 0;
if(disabledBefore && !disabledAfter) {
this._EnableControl(mutation.target);
} else if(!disabledBefore && disabledAfter) {
this._DisableControl(mutation.target);
}
// 'readonly' triggers on whether or not the attribute exists, not its value.
if(!disabledAfter && mutation.attributeName == "readonly") {
var readonlyBefore = mutation.oldValue ? mutation.oldValue != null : false;
var elem = mutation.target;
if(elem instanceof elem.ownerDocument.defaultView.HTMLInputElement
|| elem instanceof elem.ownerDocument.defaultView.HTMLTextAreaElement) {
var readonlyAfter = elem.readOnly;
if(readonlyBefore && !readonlyAfter) {
this._EnableControl(mutation.target);
} else if(!readonlyBefore && readonlyAfter) {
this._DisableControl(mutation.target);
}
}
}
}
}.bind(this);
_AutoAttachObserverCore = function(mutations: MutationRecord[]) {
var inputElementAdditions = [];
var inputElementRemovals = [];
for(var i=0; i < mutations.length; i++) {
var mutation = mutations[i];
for(var j=0; j < mutation.addedNodes.length; j++) {
inputElementAdditions = inputElementAdditions.concat(this._GetDocumentEditables(mutation.addedNodes[j]));
}
for(j = 0; j < mutation.removedNodes.length; j++) {
inputElementRemovals = inputElementRemovals.concat(this._GetDocumentEditables(mutation.removedNodes[j]));
}
}
for(var k = 0; k < inputElementAdditions.length; k++) {
if(this.isKMWInput(inputElementAdditions[k])) { // Apply standard element filtering!
this._MutationAdditionObserved(inputElementAdditions[k]);
}
}
for(k = 0; k < inputElementRemovals.length; k++) {