This repository has been archived by the owner on Dec 13, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 209
/
ZSSRichTextEditor.js
executable file
·2034 lines (1601 loc) · 62.6 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 = true;
// THe default callback parameter separator
var defaultCallbackSeparator = '~';
// 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 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';
/**
* 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);
}; //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];
};
// 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 {
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("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();
};
ZSSEditor.setBlockquote = function() {
var formatTag = "blockquote";
var formatBlock = document.queryCommandValue('formatBlock');
if (formatBlock.length > 0 && formatBlock.toLowerCase() == formatTag) {
document.execCommand('formatBlock', false, this.defaultParagraphSeparatorTag());
} else {
var blockquoteNode = this.closerParentNodeWithName(formatTag);
if (blockquoteNode) {
this.unwrapNode(blockquoteNode);
} else {
document.execCommand('formatBlock', false, '<' + formatTag + '>');
}
}
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);
ZSSEditor.sendEnabledStyles();
};
ZSSEditor.setUnorderedList = function() {
document.execCommand('insertUnorderedList', false, null);
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();
};
// Needs addClass method
ZSSEditor.insertLink = function(url, title) {
ZSSEditor.restoreRange();
var sel = document.getSelection();
if (sel.rangeCount) {
var el = document.createElement("a");
el.setAttribute("href", url);
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(el);
el.innerHTML = title;
sel.removeAllRanges();
sel.addRange(range);
}
ZSSEditor.sendEnabledStyles();
};
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: - 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, alt) {
var html = '<img src="'+url+'" alt="'+alt+'" />';
this.insertHTML(html);
this.sendEnabledStyles();
};
/**
* @brief Inserts a local image URL. Useful for images that need to be uploaded.
* @details By inserting a local image URL, we can make sure the image is shown to the user
* as soon as it's selected for uploading. Once the image is successfully uploaded
* the application should call replaceLocalImageWithRemoteImage().
*
* @param imageNodeIdentifier This is a unique ID provided by the caller. It exists as
* a mechanism to update the image node with the remote URL
* when replaceLocalImageWithRemoteImage() is called.
* @param localImageUrl The URL of the local image to display. Please keep in mind
* that a remote URL can be used here too, since this method
* does not check for that. It would be a mistake.
*/
ZSSEditor.insertLocalImage = function(imageNodeIdentifier, localImageUrl) {
var space = ' ';
var progressIdentifier = this.getImageProgressIdentifier(imageNodeIdentifier);
var imageContainerIdentifier = this.getImageContainerIdentifier(imageNodeIdentifier);
var imgContainerStart = '<span id="' + imageContainerIdentifier+'" class="img_container" contenteditable="false" data-failed="Tap to try again!">';
var imgContainerEnd = '</span>';
var progress = '<progress id="' + progressIdentifier+'" value=0 class="wp_media_indicator" contenteditable="false"></progress>';
var image = '<img data-wpid="' + imageNodeIdentifier + '" src="' + localImageUrl + '" alt="" />';
var html = imgContainerStart + progress+image + imgContainerEnd;
html = space + html + space;
this.insertHTML(html);
this.sendEnabledStyles();
};
ZSSEditor.getImageNodeWithIdentifier = function(imageNodeIdentifier) {
return $('img[data-wpid="' + imageNodeIdentifier+'"]');
};
ZSSEditor.getImageProgressIdentifier = function(imageNodeIdentifier) {
return 'progress_' + imageNodeIdentifier;
};
ZSSEditor.getImageProgressNodeWithIdentifier = function(imageNodeIdentifier) {
return $('#'+this.getImageProgressIdentifier(imageNodeIdentifier));
};
ZSSEditor.getImageContainerIdentifier = function(imageNodeIdentifier) {
return 'img_container_' + imageNodeIdentifier;
};
ZSSEditor.getImageContainerNodeWithIdentifier = function(imageNodeIdentifier) {
return $('#'+this.getImageContainerIdentifier(imageNodeIdentifier));
};
/**
* @brief Replaces a local image URL with a remote image URL. Useful for images that have
* just finished uploading.
* @details The remote image can be available after a while, when uploading images. This method
* allows for the remote URL to be loaded once the upload completes.
*
* @param imageNodeIdentifier This is a unique ID provided by the caller. It exists as
* a mechanism to update the image node with the remote URL
* when replaceLocalImageWithRemoteImage() is called.
* @param remoteImageUrl The URL of the remote image to display.
*/
ZSSEditor.replaceLocalImageWithRemoteImage = function(imageNodeIdentifier, remoteImageUrl) {
var imageNode = this.getImageNodeWithIdentifier(imageNodeIdentifier);
if (imageNode.length == 0) {
// even if the image is not present anymore we must do callback
this.markImageUploadDone(imageNodeIdentifier);
return;
}
var image = new Image;
image.onload = function () {
imageNode.attr('src', image.src);
ZSSEditor.markImageUploadDone(imageNodeIdentifier);
var joinedArguments = ZSSEditor.getJoinedFocusedFieldIdAndCaretArguments();
ZSSEditor.callback("callback-input", joinedArguments);
}
image.onerror = function () {
// Even on an error, we swap the image for the time being. This is because private
// blogs are currently failing to download images due to access privilege issues.
//
imageNode.attr('src', image.src);
ZSSEditor.markImageUploadDone(imageNodeIdentifier);
var joinedArguments = ZSSEditor.getJoinedFocusedFieldIdAndCaretArguments();
ZSSEditor.callback("callback-input", joinedArguments);
}
image.src = remoteImageUrl;
};
/**
* @brief Update the progress indicator for the image identified with the value in progress.
*
* @param imageNodeIdentifier This is a unique ID provided by the caller.
* @param progress A value between 0 and 1 indicating the progress on the image.
*/
ZSSEditor.setProgressOnImage = function(imageNodeIdentifier, progress) {
var imageNode = this.getImageNodeWithIdentifier(imageNodeIdentifier);
if (imageNode.length == 0){
return;
}
if (progress < 1){
imageNode.addClass("uploading");
}
var imageProgressNode = this.getImageProgressNodeWithIdentifier(imageNodeIdentifier);
if (imageProgressNode.length == 0){
return;
}
imageProgressNode.attr("value",progress);
};
/**
* @brief Notifies that the image upload as finished
*
* @param imageNodeIdentifier The unique image ID for the uploaded image
*/
ZSSEditor.markImageUploadDone = function(imageNodeIdentifier) {
this.sendImageReplacedCallback(imageNodeIdentifier);
var imageNode = this.getImageNodeWithIdentifier(imageNodeIdentifier);
if (imageNode.length == 0){
return;
}
// remove identifier attributed from image
imageNode.removeAttr('data-wpid');
// remove uploading style
imageNode.removeClass("uploading");
imageNode.removeAttr("class");
// Remove all extra formatting nodes for progress
if (imageNode.parent().attr("id") == this.getImageContainerIdentifier(imageNodeIdentifier)) {
imageNode.parent().replaceWith(imageNode);
}
// Wrap link around image
var linkTag = '<a href="' + imageNode.attr("src") + '"></a>';
imageNode.wrap(linkTag);
};
/**
* @brief Callbacks to native that the image upload as finished and the local url was replaced by the remote url
*
* @param imageNodeIdentifier The unique image ID for the uploaded image
*/
ZSSEditor.sendImageReplacedCallback = function( imageNodeIdentifier ) {
var arguments = ['id=' + encodeURIComponent( imageNodeIdentifier )];
var joinedArguments = arguments.join( defaultCallbackSeparator );
this.callback("callback-image-replaced", joinedArguments);
};
/**
* @brief Marks the image as failed to upload
*
* @param imageNodeIdentifier This is a unique ID provided by the caller.
* @param message A message to show to the user, overlayed on the image
*/
ZSSEditor.markImageUploadFailed = function(imageNodeIdentifier, message) {
var imageNode = this.getImageNodeWithIdentifier(imageNodeIdentifier);
if (imageNode.length == 0){
return;
}
var sizeClass = '';
if ( imageNode[0].width > 480 && imageNode[0].height > 240 ) {
sizeClass = "largeFail";
} else if ( imageNode[0].width < 100 || imageNode[0].height < 100 ) {
sizeClass = "smallFail";
}
imageNode.addClass('failed');
var imageContainerNode = this.getImageContainerNodeWithIdentifier(imageNodeIdentifier);
if(imageContainerNode.length != 0){
imageContainerNode.attr("data-failed", message);
imageNode.removeClass("uploading");
imageContainerNode.addClass('failed');
imageContainerNode.addClass(sizeClass);
}
var imageProgressNode = this.getImageProgressNodeWithIdentifier(imageNodeIdentifier);
if (imageProgressNode.length != 0){
imageProgressNode.addClass('failed');
}
};
/**
* @brief Unmarks the image as failed to upload
*
* @param imageNodeIdentifier This is a unique ID provided by the caller.
*/
ZSSEditor.unmarkImageUploadFailed = function(imageNodeIdentifier, message) {
var imageNode = this.getImageNodeWithIdentifier(imageNodeIdentifier);
if (imageNode.length != 0){
imageNode.removeClass('failed');
}
var imageContainerNode = this.getImageContainerNodeWithIdentifier(imageNodeIdentifier);
if(imageContainerNode.length != 0){
imageContainerNode.removeAttr("data-failed");
imageContainerNode.removeClass('failed');
}
var imageProgressNode = this.getImageProgressNodeWithIdentifier(imageNodeIdentifier);
if (imageProgressNode.length != 0){
imageProgressNode.removeClass('failed');
}
};
/**
* @brief Remove the image from the DOM.
*
* @param imageNodeIdentifier This is a unique ID provided by the caller.
*/
ZSSEditor.removeImage = function(imageNodeIdentifier) {
var imageNode = this.getImageNodeWithIdentifier(imageNodeIdentifier);
if (imageNode.length != 0){
imageNode.remove();
}
// if image is inside options container we need to remove the container
var imageContainerNode = this.getImageContainerNodeWithIdentifier(imageNodeIdentifier);
if (imageContainerNode.length != 0){
imageContainerNode.remove();
}
};
/**
* @brief Updates the currently selected image, replacing its markup with
* new markup based on the specified meta data string.
*
* @param imageMetaString A JSON string representing the updated meta data.
*/
ZSSEditor.updateCurrentImageMeta = function( imageMetaString ) {
if ( !ZSSEditor.currentEditingImage ) {
return;
}
var imageMeta = JSON.parse( imageMetaString );
var html = ZSSEditor.createImageFromMeta( imageMeta );
// Insert the updated html and remove the outdated node.
// This approach is preferred to selecting the current node via a range,
// and then replacing it when calling insertHTML. The insertHTML call can,
// in certain cases, modify the current and inserted markup depending on what
// elements surround the targeted node. This approach is safer.
var node = ZSSEditor.findImageCaptionNode( ZSSEditor.currentEditingImage );
node.insertAdjacentHTML( 'afterend', html );
node.remove();
ZSSEditor.currentEditingImage = null;
}
ZSSEditor.applyImageSelectionFormatting = function( imageNode ) {
var node = ZSSEditor.findImageCaptionNode( imageNode );
var sizeClass = "";
if ( imageNode.width < 100 || imageNode.height < 100 ) {
sizeClass = " small";
}
var overlay = '<span class="edit-overlay"><span class="edit-content">Edit</span></span>';
var html = '<span class="edit-container' + sizeClass + '">' + overlay + '</span>';
node.insertAdjacentHTML( 'beforebegin', html );
var selectionNode = node.previousSibling;
selectionNode.appendChild( node );
}
ZSSEditor.removeImageSelectionFormatting = function( imageNode ) {
var node = ZSSEditor.findImageCaptionNode( imageNode );
if ( !node.parentNode || node.parentNode.className.indexOf( "edit-container" ) == -1 ) {
return;
}
var parentNode = node.parentNode;
var container = parentNode.parentNode;
container.insertBefore( node, parentNode );
parentNode.remove();
}
ZSSEditor.removeImageSelectionFormattingFromHTML = function( html ) {
var tmp = document.createElement( "div" );
var tmpDom = $( tmp ).html( html );
var matches = tmpDom.find( "span.edit-container img" );
if ( matches.length == 0 ) {
return html;
}
for ( var i = 0; i < matches.length; i++ ) {
ZSSEditor.removeImageSelectionFormatting( matches[i] );
}
return tmpDom.html();
}
/**
* @brief Finds all related caption nodes for the specified image node.
*
* @param imageNode An image node in the DOM to inspect.
*/
ZSSEditor.findImageCaptionNode = function( imageNode ) {
var node = imageNode;
if ( node.parentNode && node.parentNode.nodeName === 'A' ) {
node = node.parentNode;
}