/
editor.js
1873 lines (1628 loc) · 87.6 KB
/
editor.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
(function($) {
$.fn.setAsEditor = function() {
// If editor can be loaded, add class to body
$('body').addClass('editor-active');
/**
* Determine editor format to load, and asset path, default to Wysiwyg
*/
var editor,
editorName,
editorRules = {}, // for Wysiwyg
editorCacheBreakValue = Math.random(),
editorVersion = gdn.definition('editorVersion', editorCacheBreakValue),
formatOriginal = gdn.definition('editorInputFormat', 'Wysiwyg'),
format = formatOriginal.toLowerCase(),
assets = gdn.definition('editorPluginAssets', '/plugins/editor'),
debug = false;
/**
* Load relevant stylesheets into editor iframe. The first one loaded is
* the actual editor.css required for the plugin. The others are extra,
* grabbed from the source of parent to iframe, as different communities
* may have styles they want injected into the iframe.
*/
if (debug) {
editorVersion += '&cachebreak=' + editorCacheBreakValue;
}
var stylesheetsInclude = [assets + '/design/editor.css?v=' + editorVersion];
/*
// If you want to include other stylsheets from the main page in the iframe.
$('link').each(function(i, el) {
if (el.href.indexOf("style.css") !== -1 || el.href.indexOf("custom.css") !== -1) {
stylesheetsInclude.push(el.href);
}
});
*/
// Some communities may want to modify just the styling of the Wysiwyg
// while editing, so this file will let them.
var editorWysiwygCSS = gdn.definition('editorWysiwygCSS', '');
if (editorWysiwygCSS != '') {
stylesheetsInclude.push(editorWysiwygCSS + '?v=' + editorVersion);
}
/**
* Fullpage actions--available to all editor views on page load.
*
* TODO: add fullpage class to iframe bodybox if in wysiwyg, for easier
* style overwriting.
*/
var fullPageInit = function(wysiwygInstance) {
// Hack to push toolbar left 15px when vertical scrollbar appears, so it
// is always aligned with the textarea. This is for clearing interval.
var toolbarInterval;
var toggleFullpage = function(e) {
// either user clicks on fullpage toggler button, or escapes out with key
var toggleButton = (typeof e != 'undefined')
? e.target
: $('#editor-fullpage-candidate').find('.editor-toggle-fullpage-button');
var bodyEl = $('body');
// New wrapper classes added to form. If the first is not availble,
// fall back to second one. This was added to core, so core will
// need to be updated alongside the plugin if site owners want
// latest feature.
var formWrapper = ($(toggleButton).closest('.fullpage-wrap').length)
? $(toggleButton).closest('.fullpage-wrap')
: $(toggleButton).closest('.bodybox-wrap');
// Not all parts of the site have same surrounding markup, so if that
// fails, grab nearest parent element that might enclose it. The
// exception this was made for is the signatures plugin.
if (typeof formWrapper == 'undefined') {
formWrapper = $(toggleButton).parent().parent();
}
var fullPageCandidate = $('#editor-fullpage-candidate');
// If no fullpage, enable it
if (!bodyEl.hasClass('editor-fullpage')) {
$(formWrapper).attr('id', 'editor-fullpage-candidate');
bodyEl.addClass('editor-fullpage');
$(toggleButton).addClass('icon-resize-small');
var editorToolbar = $(fullPageCandidate).find('.editor');
// When textarea pushes beyond viewport of its container, a
// scrollbar appears, which pushes the textarea left, while the
// fixed editor toolbar does not move, so push it over.
// Opted to go this route because support for the flow events is
// limited, webkit/moz both have their own implementations, while
// IE has no support for them. See below for example, commented out.
// Only Firefox seems to have this issue (unless this is
// mac-specific. Chrome & Safari on mac do not shift content over.
/*
if (typeof InstallTrigger !== 'undefined') {
toolbarInterval = setInterval(function() {
if ($(fullPageCandidate)[0].clientHeight < $(fullPageCandidate)[0].scrollHeight) {
// console.log('scrollbar');
$(editorToolbar).css('right', '15px');
} else {
// console.log('no scrollbar');
$(editorToolbar).css('right', '0');
}
}, 10);
}
*/
} else {
clearInterval(toolbarInterval);
// wysiwhtml5 editor area sometimes overflows beyond wrapper
// when exiting fullpage, and it reflows on window resize, so
// trigger resize event to get it done.
$('.' + editorName).css('width', '100%');
// else disable fullpage
$(formWrapper).attr('id', '');
bodyEl.removeClass('editor-fullpage');
$(toggleButton).removeClass('icon-resize-small');
// If in wysiwyg fullpage mode with lights toggled off, then
// exit, the lights off remains.
// TODO move into own function
var ifr = $(fullPageCandidate).find('.wysihtml5-sandbox');
if (ifr.length) {
var iframeBodyBox = ifr.contents().find('.BodyBox');
//$(iframeBodyBox).addClass('iframe-bodybox-lightsoff');
iframeBodyBox.off('focus blur');
$(fullPageCandidate).removeClass('editor-lights-candidate');
$(iframeBodyBox).removeClass('iframe-bodybox-lightsoff');
$(iframeBodyBox).removeClass('iframe-bodybox-lightson');
}
// Auto scroll to correct location upon exiting fullpage.
var scrollto = $(toggleButton).closest('.Comment');
if (!scrollto.length) {
scrollto = $(toggleButton).closest('.CommentForm');
}
// Just in case I haven't covered all bases.
if (scrollto.length) {
$('html, body').animate({
scrollTop: $(scrollto).offset().top
}, 400);
}
}
// Toggle lights while in fullpage (lights off essentially makes
// the background black and the buttons lighter.
toggleLights();
// Set focus to composer when going fullpage and exiting.
if (typeof wysiwygInstance != 'undefined') {
wysiwygInstance.focus();
} else {
editorSetCaretFocusEnd($(formWrapper).find('.BodyBox')[0]);
}
};
/**
* Attach fullpage toggling events
*/
// click fullpage
var clickFullPage = (function() {
$(".editor-toggle-fullpage-button")
.off('click')
.on('click', toggleFullpage);
}());
// exit fullpage on esc
var closeFullPageEsc = (function() {
$(document)
.off('keyup')
.on('keyup', function(e) {
if ($('body').hasClass('editor-fullpage') && e.which == 27) {
toggleFullpage();
}
});
}());
/**
* If full page and the user saves/cancels/previews comment,
* exit out of full page.
* Not smart in the sense that a failed post will also exit out of
* full page, but the text will remain in editor, so not big issue.
*/
var postCommentCloseFullPageEvent = (function() {
$('.Button')
.off('click.closefullpage')
.on('click.closefullpage', function() {
// Prevent auto-saving drafts from exiting fullpage
if (!$(this).hasClass('DraftButton')) {
if ($('body').hasClass('editor-fullpage')) {
toggleFullpage();
}
}
});
}());
/**
* Toggle spoilers.
*/
$(document).on('mouseup', '.Spoiled', function(e) {
// Do not close if its a link or user selects some text.
if (!document.getSelection().toString().length && e.target.nodeName.toLowerCase() != 'a') {
$(this).removeClass('Spoiled').addClass('Spoiler');
}
e.stopPropagation(); // for nesting
});
$(document).on('mouseup', '.Spoiler', function(e) {
$(this).removeClass('Spoiler').addClass('Spoiled');
e.stopPropagation(); // for nesting
});
/**
* Lights on/off in fullpage
*
* Note: Wysiwyg makes styling the BodyBox more difficult as it's an
* iframe. Consequently, JavaScript has to override all the styles
* that skip the iframe, and tie into the focus and blur events to
* override the Wysihtml5 inline style events.
*/
var toggleLights = function() {
// Set initial lights settings on/off. This setting is defined
// in global scope, so that plugins can define an initial state
var initialLightState = (typeof editorLights != 'undefined')
? editorLights // should be off, typically
: 'on';
var toggleLights = $('.editor-toggle-lights-button');
var fullPageCandidate = $('#editor-fullpage-candidate');
var ifr = {};
if (fullPageCandidate.length) {
$(toggleLights).attr('style', 'display:inline-block !important');
// Due to wysiwyg styles embedded inline and states changed
// using JavaScript, all the styles have to be duplicated from
// the external stylesheet and override the iframe inlines.
ifr = $(fullPageCandidate).find('.wysihtml5-sandbox');
if (ifr.length) {
var iframeBodyBox = ifr.contents().find('.BodyBox');
iframeBodyBox.css({
"transition": "background-color 0.4s ease, color 0.4s ease"
});
// By default, black text on white background. Some themes
// prevent text from being readable, so make sure it can.
iframeBodyBox.addClass('iframe-bodybox-lightson');
}
// Set initial state.
if (initialLightState == 'off') {
$(fullPageCandidate).addClass('editor-lights-candidate');
if (ifr.length) {
// if wysiwyg, need to manipulate content in iframe
iframeBodyBox.removeClass('iframe-bodybox-lightson');
iframeBodyBox.addClass('iframe-bodybox-lightsoff');
iframeBodyBox.on('focus blur', function(e) {
$(this).addClass('iframe-bodybox-lightsoff');
});
}
}
} else {
$(toggleLights).attr('style', '');
}
$(toggleLights).off('click').on('click', function() {
if (!$(fullPageCandidate).hasClass('editor-lights-candidate')) {
$(fullPageCandidate).addClass('editor-lights-candidate');
// Again, for Wysiwyg, override styles
if (ifr.length) {
// if wysiwyg, need to manipulate content in iframe
iframeBodyBox.removeClass('iframe-bodybox-lightson');
iframeBodyBox.addClass('iframe-bodybox-lightsoff');
iframeBodyBox.on('focus blur', function(e) {
$(this).addClass('iframe-bodybox-lightsoff');
});
}
} else {
$(fullPageCandidate).removeClass('editor-lights-candidate');
// Wysiwyg override styles
if (ifr.length) {
iframeBodyBox.off('focus blur');
// if wysiwyg, need to manipulate content in iframe
iframeBodyBox.removeClass('iframe-bodybox-lightsoff');
iframeBodyBox.addClass('iframe-bodybox-lightson');
}
}
});
};
};
/**
* When rendering editor, load correct helpt text message
*/
var editorSetHelpText = function(format, editorAreaObj) {
format = format.toLowerCase();
if (format != 'wysiwyg' && format != 'text' && format != 'textex') {
// If the helpt text is already there, don't insert it again.
if (!$(editorAreaObj).parent().find('.editor-help-text').length) {
$("<div></div>")
.addClass('editor-help-text')
.html(gdn.definition(format + 'HelpText'))
.insertAfter(editorAreaObj);
}
}
};
/**
* For non-wysiwyg views. Wysiwyg focus() automatically places caret
* at the end of a string of text.
*/
var editorSetCaretFocusEnd = function(obj) {
obj.selectionStart = obj.selectionEnd = obj.value.length;
// Hack to work around jQuery's autogrow, which requires focus to init
// the feature, but setting focus immediately here prevents that.
// Considered using trigger() and triggerHandler(), but do not work.
setTimeout(function() {
obj.focus();
}, 250);
};
/**
* Helper function to select whole text of an input or textarea on focus
*/
var editorSelectAllInput = function(obj) {
// Check if can access selection, as programmatically triggering the
// dd close event throws an error here.
obj.focus();
if (obj.value.length) {
// selectionStart is implied 0
obj.selectionEnd = obj.value.length;
obj.select();
}
};
/**
* Call to quickly close all open dropdowns. Refactor this into some of
* the areas below that are performing this function.
*/
var editorDropdownsClose = function() {
$('.editor-dropdown').each(function(i, el) {
$(el).removeClass('editor-dropdown-open');
$(el).find('.wysihtml5-command-dialog-opened').removeClass('wysihtml5-command-dialog-opened');
});
}
/**
* Deal with clashing JS for opening dialogs on click, and do not let
* more than one dialog/dropdown appear at once.
*/
var editorSetupDropdowns = function(editorInstance) {
$('.editor-dropdown .editor-action')
.off('click.dd')
.on('click.dd', function(e) {
var parentEl = $(e.target).parent();
// Again, tackling with clash from multiple codebases.
$('.editor-insert-dialog').each(function(i, el) {
setTimeout(function() {
$(el).removeAttr('style');
}, 0);
});
if (parentEl.hasClass('editor-dropdown')
&& parentEl.hasClass('editor-dropdown-open')) {
parentEl.removeClass('editor-dropdown-open');
//$(parentEl).find('.wysihtml5-command-dialog-opened').removeClass('wysihtml5-command-dialog-opened');
} else {
// clear other opened dropdowns before opening this one
$(parentEl).parent('.editor').find('.editor-dropdown-open').each(function(i, el) {
$(el).removeClass('editor-dropdown-open');
$(el).find('.wysihtml5-command-dialog-opened').removeClass('wysihtml5-command-dialog-opened');
});
// If the editor action buttons have been disabled (by switching
// to HTML code view, then do not allow dropdowns. CSS pointer-
// events should have taken care of this, but JS still fires the
// event regardless, so disable them here as well.
if (!parentEl.hasClass('wysihtml5-commands-disabled')) {
parentEl.addClass('editor-dropdown-open');
// if has input, focus and move caret to end of text
var inputBox = parentEl.find('.InputBox');
if (inputBox.length) {
editorSelectAllInput(inputBox[0]);
}
}
}
});
// Handle Enter key
$('.editor-dropdown').find('.InputBox').on('keydown', function(e) {
if (e.which == 13) {
// Cancel enter key submissions on these values.
if (this.value == ''
|| this.value == 'http://'
|| this.value == 'https://') {
e.stopPropagation();
e.preventDefault();
return false;
}
// Make exception for non-wysiwyg, as wysihtml5 has custom
// key handler.
if (!$(this).closest('.editor').hasClass('editor-format-wysiwyg')) {
// Fire event programmatically to do what needs to be done in
// ButtonBar code.
$(this).parent().find('.Button').trigger('click.insertData');
e.stopPropagation();
e.preventDefault();
return false;
}
}
});
// Clicking into an editor area should close the dropdown, but keep
// it open for anything else.
$('.TextBoxWrapper').add($('.wysihtml5-sandbox').contents().find('html')).each(function(i, el) {
$(el).addClass('editor-dialog-fire-close');
});
// Target all elements in the document that fire the dropdown close
// (some are written directly as class in view), then add the matches
// from within the iframe, and attach the relevant callbacks to events.
$('.editor-dialog-fire-close').add($('.wysihtml5-sandbox').contents().find('.editor-dialog-fire-close'))
.off('mouseup.fireclose dragover.fireclose')
.on('mouseup.fireclose dragover.fireclose', function(e) {
$('.editor-dropdown').each(function(i, el) {
$(el).removeClass('editor-dropdown-open');
$(el).find('.wysihtml5-command-dialog-opened').removeClass('wysihtml5-command-dialog-opened');
});
});
};
/**
* Editor does not play well with Quotes plugin in Wysiwyg mode.
*/
var editorHandleQuotesPlugin = function(editorInstance) {
var editor = editorInstance;
/*
// handle Quotes plugin using own logic.
$('.MessageList')
.on('mouseup.QuoteReply', 'a.ReactButton.Quote', function(e) {
// For the quotes plugin to insert the quoted text, it
// requires that the textarea be pastable, which is not true
// when not displayed, so momentarily toggle to it, then,
// unavoidable, wait short interval to then allow wysihtml5
// to toggle back and render the content.
editor.fire("change_view", "textarea");
$(editor.textarea.element).css({"opacity":"0.50"});
var initialText = $(editor.textarea.element).val();
var si = setInterval(function() {
if ($(editor.textarea.element).val() !== initialText) {
clearInterval(si);
$(editor.textarea.element).css({"opacity":""});
editor.fire("change_view", "composer");
// Inserting a quote at the end prevents editor from
// breaking out of quotation, which means everything
// typed after the inserted quotation, will be wrapped
// in a blockquote.
editor.composer.selection.setAfter(editor.composer.element.lastChild);
editor.composer.commands.exec("insertHTML", "<p></p>");
// editor.composer.setValue(editor.composer.getValue() + "<p><br></p>");
// editor.fire("focus:composer");
}
}, 0);
});
*/
// Handle quotes plugin using triggered event.
$('a.ReactButton.Quote').on('click', function(e) {
// Stop animation from other plugin and let this one
// handle the scroll, otherwise the scrolling jumps
// all over, and really distracts the eyes.
$('html, body').stop().animate({
scrollTop: $(editor.textarea.element).parent().parent().offset().top
}, 800);
});
$(editor.textarea.element).on('appendHtml', function(e, data) {
// The quotes plugin tends to add line breaks to the end of the
// quoted string, which upsets wysihtml5 paragraphing, so replace
// it with proper block ending to make sure paragraphs continue.
// data = data.replace(/<br\s?\/?>$/, '<p><br></p>');
// Read nullFix function for full explanation. Essentially,
// placeholder does not get removed, so remove it manually if
// one is set.
if (editor.composer.placeholderSet) {
// Just clear it on Firefox, then insert null fix.
editor.composer.setValue('');
}
// if (window.chrome || navigator.userAgent.toLowerCase().indexOf('safari') > -1) {
// var initial_value = editor.composer.getValue();
//
// if (!initial_value.length
// || initial_value.toString() === '<p></p>') {
// editor.composer.setValue('foo: ');
// }
// }
editor.focus();
editor.composer.commands.exec("insertHTML", data);
// Reported bug: Chrome does not handle wysihtml5's insertHTML
// command properly. The downside to this workaround is that the
// caret will be placed at the beginning of the text box.
// Safari also does not handle this command properly, so check
// for that as well. Can just check for the safari or webkit
// strings, but there's no telling when Chrome will change their
// user agent string to reflect Blink and other changes.
// if (window.chrome || navigator.userAgent.toLowerCase().indexOf('safari') > -1) {
// var initial_value = editor.composer.getValue();
//
// if (!initial_value.length
// || initial_value.toString() === '<p></p>') {
// editor.composer.setValue(initial_value + data);
// } else {
// editor.composer.setValue(initial_value);
// }
// }
// editor.focus();
});
};
/**
* This is just to make sure that editor, upon choosing to edit an
* inline post, will be scrolled to the correct location on the page.
* Some sites may have plugins that interfere on edit, so take care of
* those possibilities here.
*/
var scrollToEditorContainer = function(textarea) {
var scrollto = $(textarea).closest('.Comment');
if (!scrollto.length) {
scrollto = $(textarea).closest('.CommentForm');
}
if (scrollto.length) {
$('html, body').animate({
scrollTop: $(scrollto).offset().top
}, 400);
}
};
/**
* Inserting images into the wysi editor does not automatically adjust
* the height. It tends to require a hover over, so call this function
* to auto-adjust it. This will add the extra height onto the current
* height.
*/
var wysiInsertAdjustHeight = function(editorInstance, addHeight) {
editorInstance.focus();
var iframeElement = $(editorInstance.composer.iframe);
var newHeight = parseInt($(iframeElement).css('min-height')) + addHeight + 'px';
$(iframeElement).css('min-height', newHeight);
};
/**
* Chrome wraps span around content. Firefox prepends b.
* No real need to detect browsers.
*/
var wysiPasteFix = function(editorInstance) {
var editor = editorInstance;
editor.observe("paste:composer", function(e) {
// Cancel out this function's operation for now. On the original
// 0.3.0 version, pasting google docs would wrap either a span or
// b tag around the content. Now, since moving to 0.4.0pre, the
// paragraphing messes this up severaly. Moreover, pasting
// through this function sets caret to end of composer.
// Originally found this bug through a client site mentioning paste
// issue, which opened up larger issue of pasting with new version
// of wysihtml5. For now, disable paste filtering to make sure
// pasting and the caret remain in same position.
// TODO.
//return;
// Grab paste value
////var paste = this.composer.getValue();
// Just need to remove first one, and wysihtml5 will auto
// make sure the pasted html has all tags closed, so the
// last will just be stripped automatically. sweet.
////paste = paste.replace(/^<(span|b)>/m, ''); // just match first
// Insert into composer
////this.composer.setValue(paste);
});
};
/**
* Debugging lazyloaded scripts impossible with jQuery getScript/get,
* so make sure available.
*
* http://balpha.de/2011/10/jquery-script-insertion-and-its-consequences-for-debugging/
*/
function loadScript(path) {
var result = $.Deferred(),
script = document.createElement("script");
script.async = "async";
script.type = "text/javascript";
script.src = path;
script.onload = script.onreadystatechange = function(_, isAbort) {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
if (isAbort)
result.reject();
else
result.resolve();
}
};
script.onerror = function() {
result.reject();
};
$("head")[0].appendChild(script);
return result.promise();
}
/**
* Strange bug when editing a comment, then returning
* to main editor at bottom of discussion. For now,
* just use this temp hack. I noticed that if there
* was text in the main editor before choosing to edit
* a comment further up the discussion, that the main
* one would be fine, so insert a zero-width character
* that will virtually disappear to everyone and
* everything--except wysihtml5.
* Actual console error:
* NS_ERROR_INVALID_POINTER: Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsISelection.addRange]
* this.nativeSelection.addRange(getNativeRange(range));
* LINE: 2836 in wysihtml5-0.4.0pre.js
*
* ‌
* wysihtml5.INVISIBLE_SPACE = \uFEFF
*/
var nullFix = function(editorInstance) {
return;
var editor = editorInstance;
//var text = editor.composer.getValue();
//editor.composer.setValue(text + "<p>‌<br></p>");
// Problem with this is being able to post "empty", because invisible
// space is counted as a character. However, many forums could
// implemented a character minimum, so this will
// not happen everywhere. Regardless, this is only a bandaid. A real
// fix will need to be figured out. The wysihtml5 source was pointing
// to a few things, but it largely also utilizes hacks like this, and
// in fact does insert an initial p tag in the editor to signal that
// paragraphs should follow.
var insertNull = function() {
if (!window.chrome) {
// When placeholder attribute set, Firefox does not clear it, and this
// is due to this nullfix. Chrome handles it okay, though this
// whole function (nullFix) is just a mess of flimflam.
// Paragraphing in Wysihtml5 added many exceptions.
if (editor.composer.placeholderSet) {
// Just clear it on Firefox, then insert null fix.
editor.composer.setValue('');
}
editor.composer.commands.exec("insertHTML", "<span></span>");
} else {
editor.composer.setValue(editor.composer.getValue() + "<span></span>");
}
editor.fire("blur", "composer");
editor.focus();
};
editor.on("focus", function() {
if (!editor.composer.getValue().length) {
insertNull();
}
});
// On Chrome, when loading page, first editing a post, then going to
// reply, ctrl+a all body of new reply, delete, then start typing,
// and paragraphing is gone. This is because I'm only checking and
// inserting null on backspace when empty. I could just interval
// check for emptiness, but this nullFix is already too hackish.
// OKAY no. Return to this problem in future.
// $(editor.composer.doc).on('keyup', function(e) {
// // Backspace
// if (e.which == 8) {
// if (!editor.composer.getValue().length) {
// insertNull();
// }
// }
// });
};
/**
* Generic helper to generate correct image code based on format.
*/
var buildImgTag = function(href, editorFormat) {
// Default for text and textex. If in future they require special
// handling, then add them to switch statement.
var imgTag = href;
switch (editorFormat.toLowerCase()) {
case 'wysiwyg':
case 'html':
imgTag = '<img src="' + href + '" alt="" />';
break;
case 'bbcode':
imgTag = '[img]' + href + '[/img]';
break;
case 'markdown':
imgTag = '![](' + href + ' "")';
break;
case 'text':
case 'textex':
imgTag = '';
break;
}
return imgTag;
};
/* Note, this depends heavily on blueimp's file upload, and just a bit
* on Tim Down's rangyinputs (originally loaded for buttonbarplus).
*/
var fileUploadsInit = function(dropElement, editorInstance) {
if (!jQuery.fn.fileupload) {
//console.warn('Editor missing fileupload dependency.');
return false;
}
var canUpload = (gdn.definition('canUpload', false)) ? 1 : 0;
if (canUpload != 1) {
return false;
}
// Disable default browser behaviour of file drops
$(document).on('drop dragover', function(e) {
e.preventDefault();
});
// If drag and drop unavailable, remove its cue from the attachment
// dropdown menu, so it will just have the file input and URL input.
if (!!window.FileReader) {
$('#drop-cue-dropdown').addClass('can-drop');
}
// Multi upload element. If an iframe, it will need to be checked
// in the loop far below. Redundant, but let's see.
var dropZone = dropElement;
// Pass editor instance to uploader, to access methods
var editor = (editorInstance)
? editorInstance
: dropElement;
var maxUploadSize = gdn.definition('maxUploadSize');
var editorFileInputName = gdn.definition('editorFileInputName');
var allowedFileExtensions = gdn.definition('allowedFileExtensions');
var maxFileUploads = gdn.definition('maxFileUploads');
// Add CSS class to this element to style children on dragover
var $dndCueWrapper = $(dropElement).closest('.bodybox-wrap');
// Determine if element passed is an iframe or local element.
var handleIframe = false;
var iframeElement = '';
if ($(dropElement)[0].contentWindow) {
iframeElement = dropElement;
dropElement = $(dropElement)[0].contentWindow;
handleIframe = true;
}
// Insert container for displaying all uploads. All successful
// uploads will be inserted here.
$dndCueWrapper.find('.TextBoxWrapper').after('<div class="editor-upload-previews"></div>');
$editorUploadPreviews = $dndCueWrapper.find('.editor-upload-previews');
// Handle drop effect as UX cue
$(dropElement).on('dragenter dragover', function(e) {
$dndCueWrapper.addClass('editor-drop-cue');
// Chrome cannot handle the influx of events and adding the CSS
// class, which causes the border to become very buggy, so just
// force it for now. Also, this is only on Wysiwyg format.
if (handleIframe) {
$(editor).focus();
$(this).css({
'border': '2px dashed rgba(0,0,0,0.25)',
'border-radius': '2px'
});
}
}).on('drop dragend dragleave', function(e) {
$dndCueWrapper.removeClass('editor-drop-cue');
});
// Get current comment or discussion post box
// This is the key that finds .editor-upload-saved
var editorKey = 'editor-uploads-';
var editorForm = $dndCueWrapper.closest('form');
var savedUploadsContainer = '';
var mainCommentForm = '';
if (editorForm) {
var formCommentId = $(editorForm).find('#Form_CommentID');
var formDiscussionId = $(editorForm).find('#Form_DiscussionID');
var formConversationId = $(editorForm).find('#Form_ConversationID');
// Determine if bodybox loaded is the main comment one. This one
// will never have any saved uploads, so make sure it never grabs
// saved ones when switching.
var mainCommentBox = false;
if ((formCommentId.length
&& formCommentId[0].value == ''
&& formDiscussionId.length
&& parseInt(formDiscussionId[0].value) > 0)
|| (formConversationId.length
&& parseInt(formConversationId[0].value) > 0)) {
mainCommentBox = true;
mainCommentForm = editorForm;
mainCommentPreviews = $editorUploadPreviews;
}
// Build editorKey
if (formCommentId.length
&& parseInt(formCommentId[0].value) > 0) {
editorKey += 'commentid' + formCommentId[0].value;
} else if (formDiscussionId.length
&& parseInt(formDiscussionId[0].value) > 0) {
editorKey += 'discussionid' + formDiscussionId[0].value;
} else if (formConversationId.length
&& parseInt(formConversationId[0].value) > 0) {
editorKey += 'conversationid' + formConversationId[0].value;
}
// Make saved files editable
if (!mainCommentBox && editorKey != 'editor-uploads-') {
var savedContainer = $('#' + editorKey);
if (savedContainer.length && savedContainer.html().trim() != '') {
savedUploadsContainer = savedContainer;
}
}
}
// Used in two places below
var insertImageIntoBody = function(filePreviewContainer) {
$(filePreviewContainer).removeClass('editor-file-removed');
var file = $(filePreviewContainer).find('a.filename');
var type = $(file).data('type');
var href = file.attr('href');
if (type.indexOf('image') > -1) {
if (handleIframe) {
var iframeBody = $(iframeElement).contents().find('body');
var imgTag = buildImgTag(href, format);
editor.focus();
editor.composer.commands.exec('insertHTML', '<p>' + imgTag + '</p>');
var insertedImage = $(iframeBody).find('img[src="' + href + '"]');
var newHeight = parseInt($(iframeElement).css('min-height')) + insertedImage.height() + 'px';
$(iframeElement).css('min-height', newHeight);
} else {
try {
$(editor).replaceSelectedText(buildImgTag(href, format) + '\n');
} catch (ex) {
}
}
}
};
// Used in two places below.
var removeImageFromBody = function(filePreviewContainer) {
$(filePreviewContainer).addClass('editor-file-removed');
var file = $(filePreviewContainer).find('a.filename');
var type = $(file).data('type');
var href = file.attr('href');
// If images, remove insert from body as well
if (type.indexOf('image') > -1) {
if (handleIframe) {
var iframeBody = $(iframeElement).contents().find('body');
var insertedImage = $(iframeBody).find('img[src="' + href + '"]');
var newHeight = parseInt($(iframeElement).css('min-height')) - insertedImage.height() + 'px';
$(iframeElement).css('min-height', newHeight);
$(insertedImage).remove();
} else {
var text = $(editor).val();
// A shame that JavaScript does not have this built-in.
// https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
var imgTagEscaped = buildImgTag(href, format).replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
// Make it more loose, so it doesn't matter what the user
// may have done to the markup, it will be removed.
//var imgTagEscaped = '<img(\s+|.*)src\="'+ href.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1") +'"(\s+|.*)\/?>\n?';
// On second thought, if they modify it, don't touch it. Also,
// having to deal with mutltiple formats makes the regex more
// complex.
var reg = new RegExp(imgTagEscaped + '(\s+|.*)\n?', 'gi');
$(editor).val(text.replace(reg, ''));
}
}
};
/**
* Remove and reattach files in a live upload session
*/
$editorUploadPreviews
.on('click.live-file-remove', '.editor-file-remove', function(e) {
var $editorFilePreview = $(this).closest('.editor-file-preview');
$editorFilePreview.find('input').attr('name', 'RemoveMediaIDs[]');
// Remove element from editor body
removeImageFromBody($editorFilePreview);
})
.on('click.live-file-reattach', '.editor-file-reattach', function(e) {
var $editorFilePreview = $(this).closest('.editor-file-preview');
$editorFilePreview.find('input').attr('name', 'MediaIDs[]');
// Re-attach
insertImageIntoBody($editorFilePreview);
});
/**
* Remove and reattach files in a saved upload session, typically
* through editing.
*/
if (savedUploadsContainer) {
// Turn read-only mode on. Event is fired from conversations.js
// and discussion.js.
$(editorForm).on('clearCommentForm', function(e) {
$(savedUploadsContainer).addClass('editor-upload-readonly');
});
$(editorForm).on('clearMessageForm', function(e) {
$(savedUploadsContainer).addClass('editor-upload-readonly');
});
$(savedUploadsContainer)
// Turn read-only mode off.
.removeClass('editor-upload-readonly')
// Remove saved file. This will add hidden input to form
.on('click.saved-file-remove', '.editor-file-remove', function(e) {
var $editorFilePreview = $(this).closest('.editor-file-preview');
var mediaId = $editorFilePreview.find('input').val();
// Add hidden input to form so it knows to remove files.
$('<input>').attr({
type: 'hidden',
id: 'file-remove-' + mediaId,
name: 'RemoveMediaIDs[]',
value: mediaId
}).appendTo($(editorForm));
// Remove element from body.
removeImageFromBody($editorFilePreview);
})
// This will remove the hidden input
.on('click.saved-file-reattach', '.editor-file-reattach', function(e) {
var $editorFilePreview = $(this).closest('.editor-file-preview');
var mediaId = $editorFilePreview.find('input').val();
// Remove hidden input from form
$('#file-remove-' + mediaId).remove();
// Re-attach
insertImageIntoBody($editorFilePreview);
});
}
// Clear session preview files--this for main comment box.
if (mainCommentBox) {
// When closing editor with new uploads in session, typically
// commentbox at bottom of discussion, remove the uploads
$(editorForm).on('clearCommentForm', function(e) {
// Empty out the session previews.
$(mainCommentPreviews).empty();
});
$(editorForm).on('clearMessageForm', function(e) {