-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextSelection.js
More file actions
2237 lines (1846 loc) · 77.8 KB
/
TextSelection.js
File metadata and controls
2237 lines (1846 loc) · 77.8 KB
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
/*
* Copyright (c) 2025 Bloxtor (http://bloxtor.com) and Joao Pinto (http://jplpinto.com)
*
* Multi-licensed: BSD 3-Clause | Apache 2.0 | GNU LGPL v3 | HLNC License (http://bloxtor.com/LICENSE_HLNC.md)
* Choose one license that best fits your needs.
*
* Original Layout UI Editor Repo: https://github.com/a19836/layout-ui-editor/
* Original Bloxtor Repo: https://github.com/a19836/bloxtor
*
* YOU ARE NOT AUTHORIZED TO MODIFY OR REMOVE ANY PART OF THIS NOTICE!
*/
//TODO: resize of tables and images
function TextSelection() {
/* #ADD_SECURITY_CODE_HERE# */ //Important: do not remove this comment because it will be used by the other/scripts/obfuscate_js_files.php to only allow this code in the allowed domains.
//Note: more info about the document.execCommand in: http://help.dottoro.com/larpvnhw.php
var me = this;
//top and left should be the position for the text selection in the layoutUIEditor. Don't forget that the TextSelection will be for elements inside of an iframe: template_widgets_iframe
me.options = {
top: 0,
left: 0,
width: null,
height: null,
sticky_menu: false,
on_before_show_menu: null,
on_after_show_menu: null,
on_before_hide_menu: null,
on_after_hide_menu: null,
on_before_click_menu_item: null,
on_after_click_menu_item: null,
on_create_node: null,
on_create_node_attributes: null,
on_parse_node_attributes: null,
on_paste_widget: null,
};
me.is_active = false;
me.selection_elm = null;
me.selection_opts = null;
me.menu_elm = null;
me.messages_elm = null;
me.editor_elm = null;
me.elm_to_append_menu = null;
me.saved_range = null;
me.available_menu_items_props = getAvailableMenuItemsProps();
me.getAvailableMenuItemProps = function(id) {
return me.available_menu_items_props[id];
};
me.menu_items_props = [
me.getAvailableMenuItemProps("undo"),
me.getAvailableMenuItemProps("redo"),
me.getAvailableMenuItemProps("paste"),
me.getAvailableMenuItemProps("format-block"),
me.getAvailableMenuItemProps("font-family"),
me.getAvailableMenuItemProps("font-size"),
me.getAvailableMenuItemProps("bold"),
me.getAvailableMenuItemProps("italic"),
me.getAvailableMenuItemProps("underline"),
me.getAvailableMenuItemProps("strikethrough"),
me.getAvailableMenuItemProps("text-color"),
me.getAvailableMenuItemProps("text-color-caret"),
me.getAvailableMenuItemProps("back-color"),
me.getAvailableMenuItemProps("back-color-caret"),
me.getAvailableMenuItemProps("reset-color"),
me.getAvailableMenuItemProps("remove-format"),
'<i class="separator">|</i>',
me.getAvailableMenuItemProps("subscript"),
me.getAvailableMenuItemProps("superscript"),
'<br/>',
me.getAvailableMenuItemProps("align-left"),
me.getAvailableMenuItemProps("align-center"),
me.getAvailableMenuItemProps("align-right"),
me.getAvailableMenuItemProps("align-justify"),
me.getAvailableMenuItemProps("indent"),
me.getAvailableMenuItemProps("outdent"),
me.getAvailableMenuItemProps("insert-ul"),
me.getAvailableMenuItemProps("insert-ol"),
'<i class="separator">|</i>',
me.getAvailableMenuItemProps("link"),
me.getAvailableMenuItemProps("unlink"),
'<i class="separator">|</i>',
me.getAvailableMenuItemProps("image"),
me.getAvailableMenuItemProps("insert-hr"),
me.getAvailableMenuItemProps("insert-table"),
me.getAvailableMenuItemProps("insert-p"),
me.getAvailableMenuItemProps("insert-html"),
'<i class="separator">|</i>',
me.getAvailableMenuItemProps("html-element-props"),
me.getAvailableMenuItemProps("delete"),
me.getAvailableMenuItemProps("spellcheck"),
me.getAvailableMenuItemProps("select-all"),
me.getAvailableMenuItemProps("unselect"),
me.getAvailableMenuItemProps("close-menu"),
me.getAvailableMenuItemProps("toggle-menu"),
];
me.init = function(elm_to_append_menu, editor_elm) {
me.elm_to_append_menu = elm_to_append_menu instanceof jQuery ? elm_to_append_menu : $(elm_to_append_menu);
me.editor_elm = editor_elm instanceof jQuery ? editor_elm : $(editor_elm);
var editor_doc = me.editor_elm[0].ownerDocument;
var doc_to_append_menu = elm_to_append_menu[0].ownerDocument;
var o = me.elm_to_append_menu.offset();
me.options.top = o.top;
me.options.left = o.left;
me.menu_elm = me.elm_to_append_menu.children(".text-selection-menu");
if (!me.menu_elm[0])
me.createMenu(me.elm_to_append_menu);
me.messages_elm = me.menu_elm.children(".messages");
if (!me.messages_elm[0]) {
me.messages_elm = $('<div class="messages"></div>');
me.messages_elm.hide();
me.menu_elm.append(me.messages_elm);
}
initMessages();
me.menu_elm.hide(); //do not use me.hideMenu(). we only want to change the display style to none
me.menu_elm.disableSelection(); //set disableSelection for options
if (me.options.sticky_menu)
me.menu_elm.addClass("sticky-text-selection-menu");
else
me.menu_elm.removeClass("sticky-text-selection-menu");
//Save previous getRangeAt, because of the error explained in: https://stackoverflow.com/questions/22935320/uncaught-indexsizeerror-failed-to-execute-getrangeat-on-selection-0-is-not
editor_doc.addEventListener("selectionchange", function() {
var selection = me.getSelection();
if (selection && selection.rangeCount > 0)
me.saved_range = selection.getRangeAt(0);
}, false);
me.initEditorElm();
//on scroll handler update menu position
if (!me.options.sticky_menu) {
$(doc_to_append_menu).scroll(function(e) {
if (me.selection_opts && me.selection_opts.has_range)
me.refreshMenu(e);
});
$(editor_doc).scroll(function(e) {
if (me.selection_opts && me.selection_opts.has_range)
me.refreshMenu(e);
});
}
me.is_active = true;
};
me.initEditorElm = function() {
for (var i = 0; i < me.editor_elm.length; i++) {
var item = me.editor_elm[i];
//turn off spellcheck
if ('spellcheck' in item) // Firefox
item.spellcheck = false;
if ('contentEditable' in item) // allow contentEditable
item.contentEditable = true;
else { // Firefox before version 3
if ('designMode' in editor_doc) // turn on designMode
editor_doc.designMode = "on";
}
}
var ctrl_key_down = false;
me.editor_elm.mouseup(function(e) {
e.preventDefault();
e.stopPropagation();
me.setSelectionElm(e.target);
if (me.selection_opts) {
//console.log(e);
//console.log(me.options);
//console.log(me.editor_elm.offset());
var selection = me.getSelection();
//console.log(selection);
if (!selection)
me.hideMenu(); //Note: DO NOT clear the document.range, otherwise the contenteditable element will stop working
else {
me.showMenu(e);
me.loadMenu();
}
}
else
me.hideMenu(); //Note: DO NOT clear the docuemnt.range, otherwise the contenteditable element will stop working
return true;
})
.keydown(function(e) { //change enter key in template_widgets_droppable to be the same than the switch key, otherwise it will clone the target element
var enter_key_with_only_non_editable_children = false;
//Fix issue when the main-droppable have some elements inside with contenteditable=false, and then we want to write something below that items. By default the main-droppable doesn't get focus because the focus goes to the non-editable objects inside of the main-droppable. So we must place the caret inside of the main-droppable and after the non-editable elements.
//This issue only happends if there are any children, otherwise the problem will not happen.
if (this.childNodes.length > 0 && me.selection_opts) {
var contains_char = me.isPressedKeyPrintable(e); //checks if pressed key contains any char
//if contains a char (this already includes the enter key)
if (contains_char) {
//checks if there are only non editable children
var only_non_editable_children = true;
for (var j = 0; j < this.childNodes.length; j++) {
var child = this.childNodes[j];
if ((child.nodeType == Node.TEXT_NODE && child.nodeValue != "") || child.contentEditable === true) {
only_non_editable_children = false;
break;
}
}
//if only .item children or if enter/return key
if (only_non_editable_children || e.keyCode === 13) {
var selection = me.selection_opts.selection;
var node = me.selection_opts.first_node;
//only if the caret is a main-droppable
if (node == null || node == this) {
//set cursor at the end of main-droppable
var range = new Range();
var offset = this.childNodes.length;
range.setStart(this, offset);
range.setEnd(this, offset);
//add zero with space char
var doc = this.ownerDocument; //please do not use "document" here, bc the selection_elm can be inside of an iframe
var ze = doc.createTextNode("\u200B"); //\u200B: &Zero with Space invisble char. in alternative, we can replace this by
range.insertNode(ze);
range.setStartBefore(ze);
range.setEndBefore(ze);
// apply the selection, explained later below
selection.removeAllRanges();
selection.addRange(range);
if (e.keyCode === 13) //enter/return key
enter_key_with_only_non_editable_children = only_non_editable_children;
}
}
}
}
if (e.keyCode === 13) { //enter/return key
var is_shift = window.event ? window.event.shiftKey : e.shiftKey;
if (!is_shift) {
//prevents event to continue with the default.
e.preventDefault();
e.stopPropagation();
//avoids add a another br, when this was already taken care from the above code.
if (enter_key_with_only_non_editable_children) //this must be here, after the preventDefault and stopPropagation
return false;
var selection = me.selection_opts ? me.selection_opts.selection : null;
if (selection) {
//restore saved_range in case doesn't exists. This is because of the error explained in: https://stackoverflow.com/questions/22935320/uncaught-indexsizeerror-failed-to-execute-getrangeat-on-selection-0-is-not
if (selection.rangeCount == 0 && me.saved_range != null)
selection.addRange(me.saved_range);
if (selection.rangeCount > 0) {
var range = selection.getRangeAt(0);
var node = me.selection_opts.first_node == null ? this : me.selection_opts.first_node;
//if node is not editable, returns false. This wil be usefull in the edit_entity_simple when trying to insert an enter char when other "region blocks .item" elements already exists.
if (node.nodeType == Node.ELEMENT_NODE && (node.contentEditable === false || node.getAttribute("contentEditable") == "false"))
return false;
var pNode = node.parentNode;
var doc = node.ownerDocument;
range.deleteContents();
var br = doc.createElement('br');
range.insertNode(br);
range.setStartAfter(br);
range.setEndAfter(br);
var char_exists = false;
var aux = br.nextSibling;
while (aux) {
if (aux.nodeType == Node.ELEMENT_NODE || (aux.nodeType == Node.TEXT_NODE && aux.nodeValue != "")) {
char_exists = true;
break;
}
else
aux = aux.nextSibling;
};
if (!char_exists) {
var ze = doc.createTextNode("\u200B"); //\u200B: &Zero with Space invisble char. in alternative, we can replace this by
range.insertNode(ze);
range.setStartBefore(ze);
range.setEndBefore(ze);
}
selection.removeAllRanges();
selection.addRange(range);
}
}
return false; //prevents event to continue with the default.
}
}
else if (e.keyCode === 17 || e.keyCode == 91) { //Key codes: ctrlKey = 17, cmdKey = 91
ctrl_key_down = true;
}
else if (ctrl_key_down && e.keyCode == 86) { //paste key. Key codes: vKey = 86
setTimeout(function() { //must be with setTimeout bc the paste will only happen after this code gets executed.
var opts = me.selection_opts;
if (opts) {
var node = opts.common_parent;
if (typeof me.options.on_create_node == "function")
me.options.on_create_node(e, null, $(node), {paste_action: true, common_parents: opts.common_parents});
}
}, 100);
return true; //so the system can paste what was copied.
}
})
.keyup(function(e) {
if (e.keyCode === 17 || e.keyCode == 91) { //Key codes: ctrlKey = 17, cmdKey = 91
ctrl_key_down = false;
}
});
};
me.isPressedKeyPrintable = function(e) {
//checks if pressed key contains any char
var contains_char = false;
if (typeof e.which == "undefined") //This is IE, which only fires keypress events for printable keys
contains_char = true;
else if (typeof e.which == "number" && e.which > 0) {
//In other browsers except old versions of WebKit, e.which is only greater than zero if the keypress is a printable key.
//We need to filter out backspace and ctrl/alt/meta key combinations
contains_char = !e.ctrlKey && !e.metaKey && !e.altKey && e.which != 8;
}
return contains_char;
};
me.isPressedKeyCharPrintable = function(e) {
var contains_char = me.isPressedKeyPrintable(e);
if (e.key.length !== 1) //means that only char keys are allowed: Arrows will not be allowed
contains_char = false;
return contains_char;
};
me.isActiveElement = function(elm) {
var doc = elm.ownerDocument || elm.document;
return doc.activeElement === elm;
};
me.getLastCaretCharacterOffset = function(elm) {
var doc = elm.ownerDocument || elm.document;
var win = doc.defaultView || doc.parentWindow;
var selection = null;
var l = null;
if (doc.selection && doc.selection.createRange)
selection = typeof doc.selection == "function" ? doc.selection() : doc.selection;
else if (win.getSelection)
selection = win.getSelection();
if (typeof selection && typeof doc.createRange != "undefined") {
var range = doc.createRange();
range.selectNodeContents(elm);
l = range.toString().length;
}
else if (typeof doc.body.createTextRange != "undefined") {
var textRange = doc.body.createTextRange();
textRange.moveToElementText(elm);
l = textRange.toString().length;
}
return l;
};
me.getCaretCharacterOffsetWithin = function(elm) {
var caret_offset = null; //must be null so we can detect if the cursor caret was place inside of element or not. However sometimes the caret is not placed but the caret_offset is 0. So this is not very realiable.
var doc = elm.ownerDocument || elm.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = sel.getRangeAt(0);
var pre_caret_range = range.cloneRange();
pre_caret_range.selectNodeContents(elm);
pre_caret_range.setEnd(range.endContainer, range.endOffset);
caret_offset = pre_caret_range.toString().length;
}
}
else if ( (sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var pre_caret_text_range = doc.body.createTextRange();
pre_caret_text_range.moveToElementText(elm);
pre_caret_text_range.setEndPoint("EndToEnd", textRange);
caret_offset = pre_caret_text_range.text.length;
}
return caret_offset;
};
me.isCaretAtStartOfElement = function(elm) {
var doc = elm.ownerDocument || elm.document;
var win = doc.defaultView || doc.parentWindow;
//Bail if there is text selected
if (typeof win.getSelection != "undefined") {
var sel = win.getSelection();
if (sel.rangeCount > 0 && sel.getRangeAt(0).toString().length > 0)
return false;
}
return me.getCaretCharacterOffsetWithin(elm) === 0;
};
me.isCaretAtEndOfElement = function(elm) {
var doc = elm.ownerDocument || elm.document;
var win = doc.defaultView || doc.parentWindow;
//Bail if there is text selected
if (typeof win.getSelection != "undefined") {
var sel = win.getSelection();
if (sel.rangeCount > 0 && sel.getRangeAt(0).toString().length > 0)
return false;
}
var offset = me.getCaretCharacterOffsetWithin(elm);
return offset !== null && offset === me.getLastCaretCharacterOffset(elm);
};
me.isCaretOnFirstLine = function(elm) {
var doc = elm.ownerDocument || elm.document;
var win = doc.defaultView || doc.parentWindow;
var selection = null;
if (doc.selection && doc.selection.createRange)
selection = typeof doc.selection == "function" ? doc.selection() : doc.selection;
else if (win.getSelection)
selection = win.getSelection();
if (selection.rangeCount === 0)
return false;
//Get the client rect of the current selection
var start_range = selection.getRangeAt(0);
//Bail if there is text selected
if (start_range.toString().length > 0)
return false;
var start_rect = start_range.getBoundingClientRect();
//Create a range at the end of the last text node
var end_range = doc.createRange();
end_range.selectNodeContents(elm);
//The endContainer might not be an actual text node, try to find the last text node inside
var start_container = end_range.endContainer;
var start_offset = 0;
while (start_container.hasChildNodes() && !(start_container instanceof Text))
start_container = start_container.firstChild;
end_range.setStart(start_container, start_offset);
end_range.setEnd(start_container, start_offset);
var end_rect = end_range.getBoundingClientRect();
return start_rect.top === end_rect.top;
};
me.isCaretOnLastLine = function(elm) {
var doc = elm.ownerDocument || elm.document;
var win = doc.defaultView || doc.parentWindow;
var selection = null;
if (doc.selection && doc.selection.createRange)
selection = typeof doc.selection == "function" ? doc.selection() : doc.selection;
else if (win.getSelection)
selection = win.getSelection();
if (selection.rangeCount === 0)
return false;
//Get the client rect of the current selection
var start_range = selection.getRangeAt(0);
//Bail if there is text selected
if (start_range.toString().length > 0)
return false;
var start_rect = start_range.getBoundingClientRect();
//Create a range at the end of the last text node
var end_range = document.createRange();
end_range.selectNodeContents(elm);
//The endContainer might not be an actual text node, try to find the last text node inside
var end_container = end_range.endContainer;
var end_offset = 0;
while (end_container.hasChildNodes() && !(end_container instanceof Text)) {
end_container = end_container.lastChild;
end_offset = end_container.length ?? 0;
}
end_range.setEnd(end_container, end_offset);
end_range.setStart(end_container, end_offset);
var end_rect = end_range.getBoundingClientRect();
return start_rect.bottom === end_rect.bottom;
};
me.placeCaretAtStartOfElement = function(elm) {
if (elm.nodeType == Node.ELEMENT_NODE)
elm.focus();
var doc = elm.ownerDocument; //please do not use "document" here, bc the selection_elm can be inside of an iframe
var win = doc.defaultView || doc.parentWindow; //please do not use "window" here, bc the selection_elm can be inside of an iframe
var selection = null;
if (doc.selection && doc.selection.createRange)
selection = typeof doc.selection == "function" ? doc.selection() : doc.selection;
else if (win.getSelection)
selection = win.getSelection();
if (typeof selection && typeof doc.createRange != "undefined") {
var range = doc.createRange();
range.setStart(elm, 0);
range.setEnd(elm, 0);
range.collapse(false);
var sel = selection;
sel.removeAllRanges();
sel.addRange(range);
}
else if (typeof doc.body.createTextRange != "undefined") {
var textRange = doc.body.createTextRange();
textRange.moveStart(elm, 0);
textRange.moveEnd(elm, 0);
textRange.collapse(false);
textRange.select();
}
};
me.placeCaretAtEndOfElement = function(elm) {
if (elm.nodeType == Node.ELEMENT_NODE)
elm.focus();
var doc = elm.ownerDocument; //please do not use "document" here, bc the selection_elm can be inside of an iframe
var win = doc.defaultView || doc.parentWindow; //please do not use "window" here, bc the selection_elm can be inside of an iframe
var selection = null;
if (doc.selection && doc.selection.createRange)
selection = typeof doc.selection == "function" ? doc.selection() : doc.selection;
else if (win.getSelection)
selection = win.getSelection();
if (typeof selection && typeof doc.createRange != "undefined") {
var range = doc.createRange();
range.selectNodeContents(elm);
range.collapse(false);
var sel = selection;
sel.removeAllRanges();
sel.addRange(range);
}
else if (typeof doc.body.createTextRange != "undefined") {
var textRange = doc.body.createTextRange();
textRange.moveToElementText(elm);
textRange.collapse(false);
textRange.select();
}
};
me.removeCaretFromElement = function(elm) {
if (elm.nodeType == Node.ELEMENT_NODE)
elm.blur();
var doc = elm.ownerDocument; //please do not use "document" here, bc the selection_elm can be inside of an iframe
var win = doc.defaultView || doc.parentWindow; //please do not use "window" here, bc the selection_elm can be inside of an iframe
var selection = null;
if (doc.selection && doc.selection.createRange)
selection = typeof doc.selection == "function" ? doc.selection() : doc.selection;
else if (win.getSelection)
selection = win.getSelection();
if (typeof selection && typeof selection.removeAllRanges != "undefined") {
selection.removeAllRanges();
}
};
me.setEditorElm = function(editor_elm) {
if (me.is_active) {
me.editor_elm = editor_elm instanceof jQuery ? editor_elm : $(editor_elm);
me.initEditorElm();
}
};
/* selection functions */
me.prepareSelection = function() {
var selection = me.getSelection();
if (selection) {
//console.log(selection);
//get nodes
var first_node = selection.anchorNode;
var last_node = selection.focusNode;
var is_same_node = first_node == last_node;
//get nodes offsets
var first_offset = selection.anchorOffset;
var last_offset = selection.focusOffset;
//get range
var has_range = true;
if (selection.createRange) {
var range = selection.createRange();
if (range.htmlText == "")
has_range = false;
}
else if (selection.rangeCount == 0)
has_range = false;
if (is_same_node && first_offset == last_offset)
has_range = false;
//get nodes parents
var first_node_parents = $(first_node).parentsUntil("body").toArray();
var last_node_parents = $(last_node).parentsUntil("body").toArray();
//if the first parents are text nodes, remove them. Only ELEMENT_NODEs allowed
if (first_node_parents.length)
while (first_node_parents[0].nodeType == Node.TEXT_NODE)
first_node_parents.shift();
if (last_node_parents.length)
while (last_node_parents[0].nodeType == Node.TEXT_NODE)
last_node_parents.shift();
//find common parent
var common_parents = $(first_node_parents).filter(last_node_parents).toArray();
var common_parent = common_parents[0];
//if selection is selected from right to left
var is_inversed_selection = false;
if (is_same_node && first_offset > last_offset) //if same node, check if selection is inverse
is_inversed_selection = true;
else if (!is_same_node) { //if not the same node
//get the parents that are not common for both nodes
var first_ps = first_node_parents.slice(0, first_node_parents.length - common_parents.length);
var last_ps = last_node_parents.slice(0, last_node_parents.length - common_parents.length);
//from the common parent, get the first child for both parents of each nodes
var first_common_parent_child = first_ps.length > 0 ? first_ps[first_ps.length - 1] : null;
var last_common_parent_child = last_ps.length > 0 ? last_ps[last_ps.length - 1] : null;
first_common_parent_child = first_common_parent_child ? first_common_parent_child : first_node;
last_common_parent_child = last_common_parent_child ? last_common_parent_child : last_node;
//get the index of the parent nodes and check if the selection is inverse
var first_node_index = 0;
var last_node_index = 0;
var doc = me.selection_elm.ownerDocument;
var children = common_parent ? common_parent.childNodes : doc.body.childNodes;
if (children)
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child == first_common_parent_child)
first_node_index = i;
else if (child == last_common_parent_child)
last_node_index = i;
}
if (first_node_index > last_node_index)
is_inversed_selection = true;
}
//flip nodes bc the selection is inverse
if (is_inversed_selection) {
var aux = first_offset;
first_offset = last_offset;
last_offset = aux;
aux = first_node;
first_node = last_node;
last_node = aux;
}
//prepare response
var response = {
selection: selection,
first_node: first_node,
last_node: last_node,
first_offset: first_offset,
last_offset: last_offset,
first_node_parents: first_node_parents,
last_node_parents: last_node_parents,
common_parents: common_parents,
common_parent: common_parent,
has_range: has_range,
is_same_node: is_same_node,
};
return response;
}
};
me.getSelection = function() {
var selection = null;
if (me.selection_elm) {
var doc = me.selection_elm.ownerDocument; //please do not use "document" here, bc the selection_elm can be inside of an iframe
var win = doc.defaultView || doc.parentWindow; //please do not use "window" here, bc the selection_elm can be inside of an iframe
if (doc.selection && doc.selection.createRange)
selection = typeof doc.selection == "function" ? doc.selection() : doc.selection;
else if (win.getSelection)
selection = win.getSelection();
return selection;
}
return null;
};
me.setSelectionElm = function(selection_elm) {
me.selection_elm = $(selection_elm)[0];//This is very important, bc if the selection_elm object comes from a "event.target", it doesn't contain the ownerDocument property and other important properties. So we must convert it to a jquery object and then get the raw object again. This avoids a lot of erros in this code when tryin gto access the me.selection_elm.ownerDocument
me.selection_opts = me.prepareSelection();
};
/* Menu Items functions */
me.createMenu = function(elm_to_append_menu) {
me.menu_elm = $('<div class="text-selection-menu"></div>');
for (var i = 0; i < me.menu_items_props.length; i++) {
var menu_item_props = me.menu_items_props[i];
if ($.isPlainObject(menu_item_props))
me.createMenuItem(menu_item_props);
else
me.menu_elm.append(menu_item_props);
}
elm_to_append_menu.append(me.menu_elm);
};
me.createMenuItem = function(menu_item_props) {
var allowed_attrs = ["title", "command", "command-value", "command-show-ui", "hide-menu", "dependencies", "button-behaviour", "style"];
var menu_item_elm = $('<i class="text-selection-item"></i>');
if (menu_item_props["class"])
menu_item_elm.addClass(menu_item_props["class"]);
for (var j = 0; j < allowed_attrs.length; j++) {
var attr = allowed_attrs[j];
if (menu_item_props[attr])
menu_item_elm.attr(attr, menu_item_props[attr]);
}
if (menu_item_props["icon"])
menu_item_elm.append('<i class="' + menu_item_props["icon"] + '"></i>');
if (menu_item_props["html"])
menu_item_elm.append(menu_item_props["html"]);
if (typeof menu_item_props["init"] == "function")
menu_item_props["init"](menu_item_elm[0]);
if (typeof menu_item_props["click"] == "function") {
menu_item_elm.click(function(e) {
me.executeMenuItemClick(menu_item_props["click"], e, menu_item_elm[0], menu_item_props);
});
}
else if (menu_item_elm.hasClass("text-selection-command-item"))
menu_item_elm.click(function(e) {
me.executeMenuItemClick( me.executeMenuItemSimpleCommand, e, menu_item_elm[0], menu_item_props);
});
me.menu_elm.append(menu_item_elm);
};
me.getMenuItemElmById = function(menu_item_class) {
return me.menu_elm.find(".menu_item_class");
};
me.executeMenuItemClick = function(func, e, menu_item_elm, menu_item_props) {
if (me.is_active) {
me.menu_elm.children(".menu-item-popup").hide(); //it's very important otherwise the menu height will be bigger than the expected. Do not pass any argument in the hide(..) function otherwise it will become assynchronous and when we get the menu height, we will get the wrong height. Wihtout any argument the hide function is synchronous.
if (typeof me.options.on_before_click_menu_item == "function")
me.options.on_before_click_menu_item(e, menu_item_elm, menu_item_props);
func(e, menu_item_elm);
if (typeof me.options.on_after_click_menu_item == "function")
me.options.on_after_click_menu_item(e, menu_item_elm, menu_item_props);
}
};
me.executeMenuItemSimpleCommand = function(e, elm) {
if (me.is_active && me.selection_elm) {
elm = $(elm);
var command = elm.attr("command");
var command_value = elm[0].hasAttribute("command-value") ? elm.attr("command-value") : null;
me.executeMenuItemCommand(e, elm[0], command, command_value);
}
};
me.executeMenuItemCommandWithHandlers = function(e, menu_item_elm, command, command_value) {
if (me.is_active) {
var menu_item_props = me.getMenuItemPropsByMenuItemElement(menu_item_elm);
if (typeof me.options.on_before_click_menu_item == "function")
me.options.on_before_click_menu_item(e, menu_item_elm, menu_item_props);
me.executeMenuItemCommand(e, menu_item_elm, command, command_value);
if (typeof me.options.on_after_click_menu_item == "function")
me.options.on_after_click_menu_item(e, menu_item_elm, menu_item_props);
}
};
me.executeMenuItemCommand = function(e, menu_item_elm, command, command_value) {
if (me.is_active && me.selection_elm && command) {
menu_item_elm = $(menu_item_elm);
var hide_menu = menu_item_elm.attr("hide-menu");
var show_ui = menu_item_elm.attr("command-show-ui");
var dependencies = menu_item_elm.attr("dependencies");
var button_behaviour = menu_item_elm.attr("button-behaviour");
show_ui = show_ui ? show_ui : false;
hide_menu = hide_menu ? hide_menu : false;
me.executeMenuItemCommandInSelection(command, show_ui, command_value);
if (button_behaviour) {
menu_item_elm.addClass("active");
setTimeout(function() {
menu_item_elm.removeClass("active");
}, 300);
}
else
menu_item_elm.toggleClass("active");
if (hide_menu)
me.hideMenu();
if (dependencies) //dependencies is a selector
me.menu_elm.find(dependencies).each(function(idx, item) {
me.loadMenuItemByMenuItemElement(item);
});
}
};
me.executeMenuItemCommandInSelection = function(command, show_ui, command_value) {
if (me.is_active)
me.selection_elm.ownerDocument.execCommand(command, show_ui, command_value);
};
me.getMenuItemCommandValue = function(command) {
var value = me.editor_elm[0].ownerDocument.queryCommandValue(command);
value = value == "false" ? false : value;
//console.log(command+":"+value);
return value;
};
/* OLd version - DEPRECATED
me.loadMenu = function() {
if (me.selection_opts) {
me.menu_elm.find(".text-selection-item").removeClass("active");
var common_parents = me.selection_opts.common_parents;
var tags = [];
for (var i = 0; i < opts.common_parents.length; i++)
if (common_parents[i].nodeType == 1)
tags.push(common_parents[i].nodeName.toLowerCase());
if (tags)
for (var i = 0; i < tags.length; i++)
switch(tags[i]) {
case "strong":
case "b":
me.menu_elm.find(".bold").addClass("active");
break;
case "i":
me.menu_elm.find(".italic").addClass("active");
break;
case "u":
me.menu_elm.find(".underline").addClass("active");
break;
case "s":
case "strike":
me.menu_elm.find(".strikethrough").addClass("active");
break;
}
}
};*/
me.loadMenu = function() {
if (me.selection_opts) {
me.menu_elm.find(".text-selection-item").removeClass("active");
for (var i = 0; i < me.menu_items_props.length; i++)
if ($.isPlainObject(me.menu_items_props[i]))
me.loadMenuItem(me.menu_items_props[i]);
}
};
me.loadMenuItem = function(menu_item_props) {
if (menu_item_props) {
var menu_item_class = menu_item_props["class"];
if (menu_item_class) {
menu_item_class = "." + menu_item_class.replace(/^\s+/g, "").replace(/\s+$/g, "").replace(/\s\s+/g, " ").replace(/ /g, ".");
var menu_item_elm = me.menu_elm.find(menu_item_class);
if (menu_item_elm[0]) {
if (typeof menu_item_props["load"] == "function")
menu_item_props["load"](menu_item_elm[0]);
else if (menu_item_elm.hasClass("text-selection-command-item"))
me.loadSimpleMenuItem(menu_item_elm[0], menu_item_props["command"]);
}
}
}
};
me.loadMenuItemByClass = function(classes_selector) {
var menu_item_props = me.getMenuItemPropsByClass(classes_selector);
me.loadMenuItem(menu_item_props);
};
me.loadMenuItemByMenuItemElement = function(menu_item_elm) {
var menu_item_props = me.getMenuItemPropsByMenuItemElement(menu_item_elm);
me.loadMenuItem(menu_item_props);
};
me.loadSimpleMenuItem = function(menu_item_elm, command) {
if (command) {
var value = me.getMenuItemCommandValue(command);
if (value)
$(menu_item_elm).addClass("active");
else
$(menu_item_elm).removeClass("active");
}
};
me.getMenuItemPropsByClass = function(classes_selector) {
if (classes_selector) {
classes_selector = classes_selector.replace(/[.]+/g, " ").replace(/^\s+/g, "").replace(/\s+$/g, "").replace(/\s\s+/g, " ").toLowerCase();
var classes = classes_selector.split(" ");
if (classes.length)
for (var i = 0; i < me.menu_items_props.length; i++) {
var menu_item_props = me.menu_items_props[i];