This repository has been archived by the owner on Nov 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 50
/
ZSSRichTextEditor.js
executable file
·3269 lines (2638 loc) · 109 KB
/
ZSSRichTextEditor.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
/*!
*
* ZSSRichTextEditor v1.0
* http://www.zedsaid.com
*
* Copyright 2013 Zed Said Studio
*
*/
// If we are using iOS or desktop
var isUsingiOS = false;
var isUsingAndroid = true;
// THe default callback parameter separator
var defaultCallbackSeparator = '~';
const NodeName = {
BLOCKQUOTE: "BLOCKQUOTE",
PARAGRAPH: "P",
STRONG: "STRONG",
DEL: "DEL",
EM: "EM",
A: "A",
OL: "OL",
UL: "UL",
LI: "LI",
CODE: "CODE",
SPAN: "SPAN",
BR: "BR"
};
// The editor object
var ZSSEditor = {};
// These variables exist to reduce garbage (as in memory garbage) generation when typing real fast
// in the editor.
//
ZSSEditor.caretArguments = ['yOffset=' + 0, 'height=' + 0];
ZSSEditor.caretInfo = { y: 0, height: 0 };
// Is this device an iPad
ZSSEditor.isiPad;
// The current selection
ZSSEditor.currentSelection;
// The current editing image
ZSSEditor.currentEditingImage;
// The current editing video
ZSSEditor.currentEditingVideo;
// The current editing link
ZSSEditor.currentEditingLink;
ZSSEditor.focusedField = null;
// The objects that are enabled
ZSSEditor.enabledItems = {};
ZSSEditor.editableFields = {};
ZSSEditor.lastTappedNode = null;
// The default paragraph separator
ZSSEditor.defaultParagraphSeparator = 'p';
// Video format tags supported by the [video] shortcode: https://codex.wordpress.org/Video_Shortcode
// mp4, m4v and webm prioritized since they're supported by the stock player as of Android API 23
ZSSEditor.videoShortcodeFormats = ["mp4", "m4v", "webm", "ogv", "wmv", "flv"];
// We use a MutationObserver to catch user deletions of uploading or failed media
// This is only officially supported on API>18; when the WebView doesn't recognize the MutationObserver,
// we fall back to the deprecated DOMNodeRemoved event
ZSSEditor.mutationObserver;
ZSSEditor.defaultMutationObserverConfig = { attributes: false, childList: true, characterData: false };
/**
* The initializer function that must be called onLoad
*/
ZSSEditor.init = function() {
rangy.init();
// Change a few CSS values if the device is an iPad
ZSSEditor.isiPad = (navigator.userAgent.match(/iPad/i) != null);
if (ZSSEditor.isiPad) {
$(document.body).addClass('ipad_body');
$('#zss_field_title').addClass('ipad_field_title');
$('#zss_field_content').addClass('ipad_field_content');
}
document.execCommand('insertBrOnReturn', false, false);
document.execCommand('defaultParagraphSeparator', false, this.defaultParagraphSeparator);
var editor = $('div.field').each(function() {
var editableField = new ZSSField($(this));
var editableFieldId = editableField.getNodeId();
ZSSEditor.editableFields[editableFieldId] = editableField;
ZSSEditor.callback("callback-new-field", "id=" + editableFieldId);
});
document.addEventListener("selectionchange", function(e) {
ZSSEditor.currentEditingLink = null;
// DRM: only do something here if the editor has focus. The reason is that when the
// selection changes due to the editor loosing focus, the focusout event will not be
// sent if we try to load a callback here.
//
if (editor.is(":focus")) {
ZSSEditor.selectionChangedCallback();
ZSSEditor.sendEnabledStyles(e);
var clicked = $(e.target);
if (!clicked.hasClass('zs_active')) {
$('img').removeClass('zs_active');
}
}
}, false);
// Attempt to instantiate a MutationObserver. This should fail for API<19, unless the OEM of the device has
// modified the WebView. If it fails, the editor will fall back to DOMNodeRemoved events.
try {
ZSSEditor.mutationObserver = new MutationObserver(function(mutations) {
ZSSEditor.onMutationObserved(mutations);} );
} catch(e) {
// no op
}
}; //end
// MARK: - Debugging logs
ZSSEditor.logMainElementSizes = function() {
msg = 'Window [w:' + $(window).width() + '|h:' + $(window).height() + ']';
this.log(msg);
var msg = encodeURIComponent('Viewport [w:' + window.innerWidth + '|h:' + window.innerHeight + ']');
this.log(msg);
msg = encodeURIComponent('Body [w:' + $(document.body).width() + '|h:' + $(document.body).height() + ']');
this.log(msg);
msg = encodeURIComponent('HTML [w:' + $('html').width() + '|h:' + $('html').height() + ']');
this.log(msg);
msg = encodeURIComponent('Document [w:' + $(document).width() + '|h:' + $(document).height() + ']');
this.log(msg);
};
// MARK: - Viewport Refreshing
ZSSEditor.refreshVisibleViewportSize = function() {
$(document.body).css('min-height', window.innerHeight + 'px');
$('#zss_field_content').css('min-height', (window.innerHeight - $('#zss_field_content').position().top) + 'px');
};
// MARK: - Fields
ZSSEditor.focusFirstEditableField = function() {
$('div[contenteditable=true]:first').focus();
};
ZSSEditor.formatNewLine = function(e) {
var currentField = this.getFocusedField();
if (currentField.isMultiline()) {
var parentBlockQuoteNode = ZSSEditor.closerParentNodeWithName('blockquote');
if (parentBlockQuoteNode) {
this.formatNewLineInsideBlockquote(e);
} else if (!ZSSEditor.isCommandEnabled('insertOrderedList')
&& !ZSSEditor.isCommandEnabled('insertUnorderedList')) {
document.execCommand('formatBlock', false, 'p');
}
} else {
e.preventDefault();
}
};
ZSSEditor.formatNewLineInsideBlockquote = function(e) {
this.insertBreakTagAtCaretPosition();
e.preventDefault();
};
ZSSEditor.getField = function(fieldId) {
var field = this.editableFields[fieldId];
return field;
};
ZSSEditor.getFocusedField = function() {
var currentField = $(this.closerParentNodeWithName('div'));
var currentFieldId = currentField.attr('id');
while (currentField
&& (!currentFieldId || this.editableFields[currentFieldId] == null)) {
currentField = this.closerParentNodeStartingAtNode('div', currentField);
currentFieldId = currentField.attr('id');
}
return this.editableFields[currentFieldId];
};
ZSSEditor.execFunctionForResult = function(methodName) {
var functionArgument = "function=" + methodName;
var resultArgument = "result=" + window["ZSSEditor"][methodName].apply();
ZSSEditor.callback('callback-response-string', functionArgument + defaultCallbackSeparator + resultArgument);
};
// MARK: - Mutation observing
/**
* @brief Register a node to be tracked for modifications
*/
ZSSEditor.trackNodeForMutation = function(target) {
if (ZSSEditor.mutationObserver != undefined) {
ZSSEditor.mutationObserver.observe(target[0], ZSSEditor.defaultMutationObserverConfig);
} else {
// The WebView doesn't support MutationObservers - fall back to DOMNodeRemoved events
target.bind("DOMNodeRemoved", function(event) { ZSSEditor.onDomNodeRemoved(event); });
}
};
/**
* @brief Called when the MutationObserver registers a mutation to a node it's listening to
*/
ZSSEditor.onMutationObserved = function(mutations) {
mutations.forEach(function(mutation) {
for (var i = 0; i < mutation.removedNodes.length; i++) {
var removedNode = mutation.removedNodes[i];
if (ZSSEditor.isMediaContainerNode(removedNode)) {
// An uploading or failed container node was deleted manually - notify native
var mediaIdentifier = ZSSEditor.extractMediaIdentifier(removedNode);
ZSSEditor.sendMediaRemovedCallback(mediaIdentifier);
} else if (removedNode.attributes.getNamedItem("data-wpid")) {
// An uploading or failed image was deleted manually - remove its container and send the callback
var mediaIdentifier = removedNode.attributes.getNamedItem("data-wpid").value;
var parentRange = ZSSEditor.getParentRangeOfFocusedNode();
ZSSEditor.removeImage(mediaIdentifier);
ZSSEditor.setRange(parentRange);
ZSSEditor.sendMediaRemovedCallback(mediaIdentifier);
} else if (removedNode.attributes.getNamedItem("data-video_wpid")) {
// An uploading or failed video was deleted manually - remove its container and send the callback
var mediaIdentifier = removedNode.attributes.getNamedItem("data-video_wpid").value;
var parentRange = ZSSEditor.getParentRangeOfFocusedNode();
ZSSEditor.removeVideo(mediaIdentifier);
ZSSEditor.setRange(parentRange);
ZSSEditor.sendMediaRemovedCallback(mediaIdentifier);
}
}
});
};
/**
* @brief Called when a DOMNodeRemoved event is triggered for an element we're tracking
* (only used when MutationObserver is unsupported by the WebView)
*/
ZSSEditor.onDomNodeRemoved = function(event) {
if (event.target.id.length > 0) {
var mediaId = ZSSEditor.extractMediaIdentifier(event.target);
} else if (event.target.parentNode.id.length > 0) {
var mediaId = ZSSEditor.extractMediaIdentifier(event.target.parentNode);
} else {
return;
}
ZSSEditor.sendMediaRemovedCallback(mediaId);
};
// MARK: - Logging
ZSSEditor.log = function(msg) {
ZSSEditor.callback('callback-log', 'msg=' + msg);
};
// MARK: - Callbacks
ZSSEditor.domLoadedCallback = function() {
ZSSEditor.callback("callback-dom-loaded");
};
ZSSEditor.selectionChangedCallback = function () {
var joinedArguments = ZSSEditor.getJoinedFocusedFieldIdAndCaretArguments();
ZSSEditor.callback('callback-selection-changed', joinedArguments);
this.callback("callback-input", joinedArguments);
};
ZSSEditor.callback = function(callbackScheme, callbackPath) {
var url = callbackScheme + ":";
if (callbackPath) {
url = url + callbackPath;
}
if (isUsingiOS) {
ZSSEditor.callbackThroughIFrame(url);
} else if (isUsingAndroid) {
if (nativeState.androidApiLevel < 17) {
ZSSEditor.callbackThroughIFrame(url);
} else {
nativeCallbackHandler.executeCallback(callbackScheme, callbackPath);
}
} else {
console.log(url);
}
};
/**
* @brief Executes a callback by loading it into an IFrame.
* @details The reason why we're using this instead of window.location is that window.location
* can sometimes fail silently when called multiple times in rapid succession.
* Found here:
* http://stackoverflow.com/questions/10010342/clicking-on-a-link-inside-a-webview-that-will-trigger-a-native-ios-screen-with/10080969#10080969
*
* @param url The callback URL.
*/
ZSSEditor.callbackThroughIFrame = function(url) {
var iframe = document.createElement("IFRAME");
iframe.setAttribute('sandbox', '');
iframe.setAttribute("src", url);
// IMPORTANT: the IFrame was showing up as a black box below our text. By setting its borders
// to be 0px transparent we make sure it's not shown at all.
//
// REF BUG: https://github.com/wordpress-mobile/WordPress-iOS-Editor/issues/318
//
iframe.style.cssText = "border: 0px transparent;";
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
};
ZSSEditor.stylesCallback = function(stylesArray) {
var stylesString = '';
if (stylesArray.length > 0) {
stylesString = stylesArray.join(defaultCallbackSeparator);
}
ZSSEditor.callback("callback-selection-style", stylesString);
};
// MARK: - Selection
ZSSEditor.backupRange = function(){
var selection = window.getSelection();
var range = selection.getRangeAt(0);
ZSSEditor.currentSelection =
{
"startContainer": range.startContainer,
"startOffset": range.startOffset,
"endContainer": range.endContainer,
"endOffset": range.endOffset
};
};
ZSSEditor.restoreRange = function(){
if (this.currentSelection) {
var selection = window.getSelection();
selection.removeAllRanges();
var range = document.createRange();
range.setStart(this.currentSelection.startContainer, this.currentSelection.startOffset);
range.setEnd(this.currentSelection.endContainer, this.currentSelection.endOffset);
selection.addRange(range);
}
};
ZSSEditor.getSelectedText = function() {
var selection = window.getSelection();
return selection.toString();
};
ZSSEditor.getCaretArguments = function() {
var caretInfo = this.getYCaretInfo();
if (caretInfo == null) {
return null;
} else {
this.caretArguments[0] = 'yOffset=' + caretInfo.y;
this.caretArguments[1] = 'height=' + caretInfo.height;
return this.caretArguments;
}
};
ZSSEditor.getJoinedFocusedFieldIdAndCaretArguments = function() {
var joinedArguments = ZSSEditor.getJoinedCaretArguments();
var idArgument = "id=" + ZSSEditor.getFocusedField().getNodeId();
joinedArguments = idArgument + defaultCallbackSeparator + joinedArguments;
return joinedArguments;
};
ZSSEditor.getJoinedCaretArguments = function() {
var caretArguments = this.getCaretArguments();
var joinedArguments = this.caretArguments.join(defaultCallbackSeparator);
return joinedArguments;
};
ZSSEditor.getCaretYPosition = function() {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var span = document.createElement("span");
// Ensure span has dimensions and position by
// adding a zero-width space character
span.appendChild( document.createTextNode("\u200b") );
range.insertNode(span);
var y = span.offsetTop;
var spanParent = span.parentNode;
spanParent.removeChild(span);
// Glue any broken text nodes back together
spanParent.normalize();
return y;
}
ZSSEditor.getYCaretInfo = function() {
var selection = window.getSelection();
var noSelectionAvailable = selection.rangeCount == 0;
if (noSelectionAvailable) {
return null;
}
var y = 0;
var height = 0;
var range = selection.getRangeAt(0);
var needsToWorkAroundNewlineBug = (range.getClientRects().length == 0);
// PROBLEM: iOS seems to have problems getting the offset for some empty nodes and return
// 0 (zero) as the selection range top offset.
//
// WORKAROUND: To fix this problem we use a different method to obtain the Y position instead.
//
if (needsToWorkAroundNewlineBug) {
var closerParentNode = ZSSEditor.closerParentNode();
var closerDiv = ZSSEditor.closerParentNodeWithName('div');
var fontSize = $(closerParentNode).css('font-size');
var lineHeight = Math.floor(parseInt(fontSize.replace('px','')) * 1.5);
y = this.getCaretYPosition();
height = lineHeight;
} else {
if (range.getClientRects) {
var rects = range.getClientRects();
if (rects.length > 0) {
// PROBLEM: some iOS versions differ in what is returned by getClientRects()
// Some versions return the offset from the page's top, some other return the
// offset from the visible viewport's top.
//
// WORKAROUND: see if the offset of the body's top is ever negative. If it is
// then it means that the offset we have is relative to the body's top, and we
// should add the scroll offset.
//
var addsScrollOffset = document.body.getClientRects()[0].top < 0;
if (addsScrollOffset) {
y = document.body.scrollTop;
}
y += rects[0].top;
height = rects[0].height;
}
}
}
this.caretInfo.y = y;
this.caretInfo.height = height;
return this.caretInfo;
};
// MARK: - Default paragraph separator
ZSSEditor.defaultParagraphSeparatorTag = function() {
return '<' + this.defaultParagraphSeparator + '>';
};
// MARK: - Styles
ZSSEditor.setBold = function() {
document.execCommand('bold', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setItalic = function() {
document.execCommand('italic', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setSubscript = function() {
document.execCommand('subscript', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setSuperscript = function() {
document.execCommand('superscript', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setStrikeThrough = function() {
var commandName = 'strikeThrough';
var isDisablingStrikeThrough = ZSSEditor.isCommandEnabled(commandName);
document.execCommand(commandName, false, null);
// DRM: WebKit has a problem disabling strikeThrough when the tag <del> is used instead of
// <strike>. The code below serves as a way to fix this issue.
//
var mustHandleWebKitIssue = (isDisablingStrikeThrough
&& ZSSEditor.isCommandEnabled(commandName));
if (mustHandleWebKitIssue) {
var troublesomeNodeNames = ['del'];
var selection = window.getSelection();
var range = selection.getRangeAt(0).cloneRange();
var container = range.commonAncestorContainer;
var nodeFound = false;
var textNode = null;
while (container && !nodeFound) {
nodeFound = (container
&& container.nodeType == document.ELEMENT_NODE
&& troublesomeNodeNames.indexOf(container.nodeName.toLowerCase()) > -1);
if (!nodeFound) {
container = container.parentElement;
}
}
if (container) {
var newObject = $(container).replaceWith(container.innerHTML);
var finalSelection = window.getSelection();
var finalRange = selection.getRangeAt(0).cloneRange();
finalRange.setEnd(finalRange.startContainer, finalRange.startOffset + 1);
selection.removeAllRanges();
selection.addRange(finalRange);
}
}
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setUnderline = function() {
document.execCommand('underline', false, null);
ZSSEditor.sendEnabledStyles();
};
/**
* @brief Turns blockquote ON or OFF for the current selection.
* @details This method makes sure that the contents of the blockquotes are surrounded by the
* defaultParagraphSeparatorTag (by default '<p>'). This ensures parity with the web
* editor.
*/
ZSSEditor.setBlockquote = function() {
var savedSelection = rangy.saveSelection();
var selection = document.getSelection();
var range = selection.getRangeAt(0).cloneRange();
var sendStyles = false;
var ancestorElement = this.getAncestorElementForSettingBlockquote(range);
if (ancestorElement) {
sendStyles = true;
var childNodes = this.getChildNodesIntersectingRange(ancestorElement, range);
if (childNodes && childNodes.length) {
this.toggleBlockquoteForSpecificChildNodes(ancestorElement, childNodes);
}
}
rangy.restoreSelection(savedSelection);
if (sendStyles) {
ZSSEditor.sendEnabledStyles();
}
};
ZSSEditor.removeFormating = function() {
document.execCommand('removeFormat', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setHorizontalRule = function() {
document.execCommand('insertHorizontalRule', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setHeading = function(heading) {
var formatTag = heading;
var formatBlock = document.queryCommandValue('formatBlock');
if (formatBlock.length > 0 && formatBlock.toLowerCase() == formatTag) {
document.execCommand('formatBlock', false, this.defaultParagraphSeparatorTag());
} else {
document.execCommand('formatBlock', false, '<' + formatTag + '>');
}
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setParagraph = function() {
var formatTag = "p";
var formatBlock = document.queryCommandValue('formatBlock');
if (formatBlock.length > 0 && formatBlock.toLowerCase() == formatTag) {
document.execCommand('formatBlock', false, this.defaultParagraphSeparatorTag());
} else {
document.execCommand('formatBlock', false, '<' + formatTag + '>');
}
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.undo = function() {
document.execCommand('undo', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.redo = function() {
document.execCommand('redo', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setOrderedList = function() {
document.execCommand('insertOrderedList', false, null);
// If the insertOrderedList is no longer enabled after running execCommand,
// we can assume the user is turning it off.
if (!ZSSEditor.isCommandEnabled('insertOrderedList')) {
ZSSEditor.completeListEditing();
}
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setUnorderedList = function() {
document.execCommand('insertUnorderedList', false, null);
// If the insertUnorderedList is no longer enabled after running execCommand,
// we can assume the user is turning it off.
if (!ZSSEditor.isCommandEnabled('insertUnorderedList')) {
ZSSEditor.completeListEditing();
}
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setJustifyCenter = function() {
document.execCommand('justifyCenter', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setJustifyFull = function() {
document.execCommand('justifyFull', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setJustifyLeft = function() {
document.execCommand('justifyLeft', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setJustifyRight = function() {
document.execCommand('justifyRight', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setIndent = function() {
document.execCommand('indent', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setOutdent = function() {
document.execCommand('outdent', false, null);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setTextColor = function(color) {
ZSSEditor.restoreRange();
document.execCommand("styleWithCSS", null, true);
document.execCommand('foreColor', false, color);
document.execCommand("styleWithCSS", null, false);
ZSSEditor.sendEnabledStyles();
// document.execCommand("removeFormat", false, "foreColor"); // Removes just foreColor
};
ZSSEditor.setBackgroundColor = function(color) {
ZSSEditor.restoreRange();
document.execCommand("styleWithCSS", null, true);
document.execCommand('hiliteColor', false, color);
document.execCommand("styleWithCSS", null, false);
ZSSEditor.sendEnabledStyles();
};
/**
* @brief Wraps given HTML in paragraph tags and appends a new line
* @details This method makes sure that passed HTML is wrapped in a separate paragraph.
* It also appends a new opening paragraph tag and a space. This step is necessary to keep any spans or
* divs in the HTML from being read by the WebView as a style and applied to all future paragraphs.
*/
ZSSEditor.wrapInParagraphTags = function(html) {
var space = '<br>';
var paragraphOpenTag = '<' + this.defaultParagraphSeparator + '>';
var paragraphCloseTag = '</' + this.defaultParagraphSeparator + '>';
if (this.getFocusedField().getHTML().length == 0) {
html = paragraphOpenTag + html;
}
html = html + paragraphCloseTag + paragraphOpenTag + space;
return html;
};
// Needs addClass method
ZSSEditor.insertLink = function(url, title) {
this.insertHTML('<a href="' + url + '">' + title + "</a>");
};
ZSSEditor.updateLink = function(url, title) {
ZSSEditor.restoreRange();
var currentLinkNode = ZSSEditor.lastTappedNode;
if (currentLinkNode) {
currentLinkNode.setAttribute("href", url);
currentLinkNode.innerHTML = title;
}
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.unlink = function() {
var savedSelection = rangy.saveSelection();
var currentLinkNode = ZSSEditor.closerParentNodeWithName('a');
if (currentLinkNode) {
ZSSEditor.unwrapNode(currentLinkNode);
}
rangy.restoreSelection(savedSelection);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.unwrapNode = function(node) {
$(node).contents().unwrap();
};
ZSSEditor.quickLink = function() {
var sel = document.getSelection();
var link_url = "";
var test = new String(sel);
var mailregexp = new RegExp("^(.+)(\@)(.+)$", "gi");
if (test.search(mailregexp) == -1) {
checkhttplink = new RegExp("^http\:\/\/", "gi");
if (test.search(checkhttplink) == -1) {
checkanchorlink = new RegExp("^\#", "gi");
if (test.search(checkanchorlink) == -1) {
link_url = "http://" + sel;
} else {
link_url = sel;
}
} else {
link_url = sel;
}
} else {
checkmaillink = new RegExp("^mailto\:", "gi");
if (test.search(checkmaillink) == -1) {
link_url = "mailto:" + sel;
} else {
link_url = sel;
}
}
var html_code = '<a href="' + link_url + '">' + sel + '</a>';
ZSSEditor.insertHTML(html_code);
};
// MARK: - Blockquotes
/**
* @brief This method toggles blockquote for the specified child nodes. This is useful since
* we can toggle blockquote either for some or ALL of the child nodes, depending on
* what we need to achieve.
* @details CASE 1: If the parent node is a blockquote node, the child nodes will be extracted
* from it leaving the remaining siblings untouched (by splitting the parent blockquote
* node in two if necessary).
* CASE 2: If the parent node is NOT a blockquote node, but the first child is, the
* method will make sure all child nodes that are blockquote nodes will be toggled to
* non-blockquote nodes.
* CASE 3: If both the parent node and the first node are non-blockquote nodes, this
* method will turn all child nodes into blockquote nodes.
*
* @param parentNode The parent node. Can be either a blockquote or non-blockquote node.
* Cannot be null.
* @param nodes The child nodes. Can be any combination of blockquote and
* non-blockquote nodes. Cannot be null.
*/
ZSSEditor.toggleBlockquoteForSpecificChildNodes = function(parentNode, nodes) {
if (nodes && nodes.length > 0) {
if (parentNode.nodeName == NodeName.BLOCKQUOTE) {
for (var counter = 0; counter < nodes.length; counter++) {
this.turnBlockquoteOffForNode(nodes[counter]);
}
} else {
var turnOn = (nodes[0].nodeName != NodeName.BLOCKQUOTE);
for (var counter = 0; counter < nodes.length; counter++) {
if (turnOn) {
this.turnBlockquoteOnForNode(nodes[counter]);
} else {
this.turnBlockquoteOffForNode(nodes[counter]);
}
}
}
}
};
/**
* @brief Turns blockquote off for the specified node.
*
* @param node The node to turn the blockquote off for. It can either be a blockquote
* node (in which case it will be removed and all child nodes extracted) or
* have a parent blockquote node (in which case the node will be extracted
* from its parent).
*/
ZSSEditor.turnBlockquoteOffForNode = function(node) {
if (node.nodeName == NodeName.BLOCKQUOTE) {
for (var i = 0; i < node.childNodes.length; i++) {
this.extractNodeFromAncestorNode(node.childNodes[i], node);
}
} else {
if (node.parentNode.nodeName == NodeName.BLOCKQUOTE) {
this.extractNodeFromAncestorNode(node, node.parentNode);
}
}
};
/**
* @brief Turns blockquote on for the specified node.
*
* @param node The node to turn blockquote on for. Will attempt to attach the newly
* created blockquote to sibling or uncle blockquote nodes. If the node is
* null or it's parent is null, this method will exit without affecting it
* (this can actually be caused by this method modifying the surrounding
* nodes, if those nodes are stored in an array - and thus are not notified
* of DOM hierarchy changes).
*/
ZSSEditor.turnBlockquoteOnForNode = function(node) {
if (!node || !node.parentNode) {
return;
}
var couldJoinBlockquotes = this.joinAdjacentSiblingsOrAncestorBlockquotes(node);
if (!couldJoinBlockquotes) {
var blockquote = document.createElement(NodeName.BLOCKQUOTE);
node.parentNode.insertBefore(blockquote, node);
blockquote.appendChild(node);
}
};
// MARK: - Generic media
ZSSEditor.isMediaContainerNode = function(node) {
if (node.id === undefined) {
return false;
}
return (node.id.search("img_container_") == 0) || (node.id.search("video_container_") == 0);
};
ZSSEditor.extractMediaIdentifier = function(node) {
if (node.id.search("img_container_") == 0) {
return node.id.replace("img_container_", "");
} else if (node.id.search("video_container_") == 0) {
return node.id.replace("video_container_", "");
}
return "";
};
ZSSEditor.getMediaContainerNodeWithIdentifier = function(mediaNodeIdentifier) {
var imageContainerNode = ZSSEditor.getImageContainerNodeWithIdentifier(mediaNodeIdentifier);
if (imageContainerNode.length > 0) {
return imageContainerNode;
} else {
return ZSSEditor.getVideoContainerNodeWithIdentifier(mediaNodeIdentifier);
}
};
ZSSEditor.sendMediaRemovedCallback = function(mediaNodeIdentifier) {
var arguments = ['id=' + encodeURIComponent(mediaNodeIdentifier)];
var joinedArguments = arguments.join(defaultCallbackSeparator);
this.callback("callback-media-removed", joinedArguments);
};
/**
* @brief Marks all in-progress images as failed to upload
*/
ZSSEditor.markAllUploadingMediaAsFailed = function(message) {
var html = ZSSEditor.getField("zss_field_content").getHTML();
var tmp = document.createElement( "div" );
var tmpDom = $( tmp ).html( html );
var matches = tmpDom.find("img.uploading");
for(var i = 0; i < matches.size(); i++) {
if (matches[i].hasAttribute('data-wpid')) {
var mediaId = matches[i].getAttribute('data-wpid');
ZSSEditor.markImageUploadFailed(mediaId, message);
} else if (matches[i].hasAttribute('data-video_wpid')) {
var videoId = matches[i].getAttribute('data-video_wpid');
ZSSEditor.markVideoUploadFailed(videoId, message);
}
}
};
/**
* @brief Sends a callback with a list of failed images
*/
ZSSEditor.getFailedMedia = function() {
var html = ZSSEditor.getField("zss_field_content").getHTML();
var tmp = document.createElement( "div" );
var tmpDom = $( tmp ).html( html );
var matches = tmpDom.find("img.failed");
var functionArgument = "function=getFailedMedia";
var mediaIdArray = [];
for (var i = 0; i < matches.size(); i++) {
var mediaId;
if (matches[i].hasAttribute("data-wpid")) {
mediaId = matches[i].getAttribute("data-wpid");
} else if (matches[i].hasAttribute("data-video_wpid")) {
mediaId = matches[i].getAttribute("data-video_wpid");
}
// Track pre-existing failed media nodes for manual deletion events
ZSSEditor.trackNodeForMutation(this.getMediaContainerNodeWithIdentifier(mediaId));
if (mediaId.length > 0) {
mediaIdArray.push(mediaId);
}
}
var joinedArguments = functionArgument + defaultCallbackSeparator + "ids=" + mediaIdArray.toString();
ZSSEditor.callback('callback-response-string', joinedArguments);
};
// MARK: - Images
ZSSEditor.updateImage = function(url, alt) {
ZSSEditor.restoreRange();
if (ZSSEditor.currentEditingImage) {
var c = ZSSEditor.currentEditingImage;
c.attr('src', url);
c.attr('alt', alt);
}
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.insertImage = function(url, remoteId, alt) {
var html = '<img src="' + url + '" alt="' + alt + '" class="wp-image-' + remoteId + '" />';
this.insertHTML(this.wrapInParagraphTags(html));
this.sendEnabledStyles();
};