-
Notifications
You must be signed in to change notification settings - Fork 824
/
Copy pathHtmlEditorField.js
1641 lines (1423 loc) · 49.6 KB
/
HtmlEditorField.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
/**
* Functions for HtmlEditorFields in the back end.
* Includes the JS for the ImageUpload forms.
*
* Relies on the jquery.form.js plugin to power the
* ajax / iframe submissions
*/
var ss = ss || {};
/**
* Wrapper for HTML WYSIWYG libraries, which abstracts library internals
* from interface concerns like inserting and editing links.
* Caution: Incomplete and unstable API.
*/
ss.editorWrappers = {};
ss.editorWrappers.tinyMCE = (function() {
var instance;
return {
init: function(config) {
if(!ss.editorWrappers.tinyMCE.initialized) {
tinyMCE.init(config);
ss.editorWrappers.tinyMCE.initialized = true;
}
},
/**
* @return Mixed Implementation specific object
*/
getInstance: function() {
return this.instance;
},
/**
* Invoked when a content-modifying UI is opened.
*/
onopen: function() {
},
/**
* Invoked when a content-modifying UI is closed.
*/
onclose: function() {
},
/**
* Write the HTML back to the original text area field.
*/
save: function() {
tinyMCE.triggerSave();
},
/**
* Create a new instance based on a textarea field.
*
* Please proxy the events from your editor implementation into JS events
* on the textarea field. For events that do not map directly, use the
* following naming scheme: editor<event>.
*
* @param String
* @param Object Implementation specific configuration
* @param Function
*/
create: function(domID, config) {
this.instance = new tinymce.Editor(domID, config);
// Patch TinyMCE events into underlying textarea field.
this.instance.onInit.add(function(ed) {
if(!ss.editorWrappers.tinyMCE.patched) {
// Not ideal, but there's a memory leak we need to patch
var originalDestroy = tinymce.themes.AdvancedTheme.prototype.destroy;
tinymce.themes.AdvancedTheme.prototype.destroy = function() {
originalDestroy.apply(this, arguments);
if (this.statusKeyboardNavigation) {
this.statusKeyboardNavigation.destroy();
this.statusKeyboardNavigation = null;
}
};
ss.editorWrappers.tinyMCE.patched = true;
}
jQuery(ed.getElement()).trigger('editorinit');
// Periodically check for inline changes when focused,
// since TinyMCE's onChange only fires on certain actions
// like inserting a new paragraph, as opposed to any user input.
// This also works around an issue where the "save" button
// wouldn't trigger if the click is the cause of a "blur" event
// after an (undetected) inline change. This "blur" causes onChange
// to trigger, which will change the button markup to show "alternative" styles,
// effectively cancelling the original click event.
if(ed.settings.update_interval) {
var interval;
jQuery(ed.getBody()).on('focus', function() {
interval = setInterval(function() {
// Update underlying element as necessary
var element = jQuery(ed.getElement());
if(ed.isDirty()) {
// Set content without triggering editor content cleanup
element.val(ed.getContent({format : 'raw', no_events : 1}));
}
}, ed.settings.update_interval);
});
jQuery(ed.getBody()).on('blur', function() {
clearInterval(interval);
});
}
});
this.instance.onChange.add(function(ed, l) {
// Update underlying textarea on every change, so external handlers
// such as changetracker have a chance to trigger properly.
ed.save();
jQuery(ed.getElement()).trigger('change');
});
// Add more events here as needed.
this.instance.render();
},
/**
* Redraw the editor contents
*/
repaint: function() {
tinyMCE.execCommand("mceRepaint");
},
/**
* @return boolean
*/
isDirty: function() {
return this.getInstance().isDirty();
},
/**
* HTML representation of the edited content.
*
* Returns: {String}
*/
getContent: function() {
return this.getInstance().getContent();
},
/**
* DOM tree of the edited content
*
* Returns: DOMElement
*/
getDOM: function() {
return this.getInstance().dom;
},
/**
* Returns: DOMElement
*/
getContainer: function() {
return this.getInstance().getContainer();
},
/**
* Get the closest node matching the current selection.
*
* Returns: {jQuery} DOMElement
*/
getSelectedNode: function() {
return this.getInstance().selection.getNode();
},
/**
* Select the given node within the editor DOM
*
* Parameters: {DOMElement}
*/
selectNode: function(node) {
this.getInstance().selection.select(node);
},
/**
* Replace entire content
*
* @param String HTML
* @param Object opts
*/
setContent: function(html, opts) {
this.getInstance().execCommand('mceSetContent', false, html, opts);
},
/**
* Insert content at the current caret position
*
* @param String HTML
*/
insertContent: function(html, opts) {
this.getInstance().execCommand('mceInsertContent', false, html, opts);
},
/**
* Replace currently selected content
*
* @param {String} html
*/
replaceContent: function(html, opts) {
this.getInstance().execCommand('mceReplaceContent', false, html, opts);
},
/**
* Insert or update a link in the content area (based on current editor selection)
*
* Parameters: {Object} attrs
*/
insertLink: function(attrs, opts) {
this.getInstance().execCommand("mceInsertLink", false, attrs, opts);
},
/**
* Remove the link from the currently selected node (if any).
*/
removeLink: function() {
this.getInstance().execCommand('unlink', false);
},
/**
* Strip any editor-specific notation from link in order to make it presentable in the UI.
*
* Parameters:
* {Object}
* {DOMElement}
*/
cleanLink: function(href, node) {
var cb = tinyMCE.settings['urlconverter_callback'],
cu = tinyMCE.settings['convert_urls'];
if(cb) href = eval(cb + "(href, node, true);");
// Turn into relative, if set in TinyMCE config
if(cu && href.match(new RegExp('^' + tinyMCE.settings['document_base_url'] + '(.*)$'))) {
href = RegExp.$1;
}
// Get rid of TinyMCE's temporary URLs
if(href.match(/^javascript:\s*mctmp/)) href = '';
return href;
},
/**
* Creates a bookmark for the currently selected range,
* which can be used to reselect this range at a later point.
* @return {mixed}
*/
createBookmark: function() {
return this.getInstance().selection.getBookmark();
},
/**
* Selects a bookmarked range previously saved through createBookmark().
* @param {mixed} bookmark
*/
moveToBookmark: function(bookmark) {
this.getInstance().selection.moveToBookmark(bookmark);
this.getInstance().focus();
},
/**
* Removes any selection & de-focuses this editor
*/
blur: function() {
this.getInstance().selection.collapse();
},
/**
* Add new undo point with the current DOM content.
*/
addUndo: function() {
this.getInstance().undoManager.add();
}
};
});
// Override this to switch editor wrappers
ss.editorWrappers['default'] = ss.editorWrappers.tinyMCE;
(function($) {
$.entwine('ss', function($) {
/**
* Class: textarea.htmleditor
*
* Add tinymce to HtmlEditorFields within the CMS. Works in combination
* with a TinyMCE.init() call which is prepopulated with the used HTMLEditorConfig settings,
* and included in the page as an inline <script> tag.
*/
$('textarea.htmleditor').entwine({
Editor: null,
/**
* Constructor: onmatch
*/
onadd: function() {
var edClass = this.data('editor') || 'default', ed = ss.editorWrappers[edClass]();
this.setEditor(ed);
// Using a global config (generated through HTMLEditorConfig PHP logic).
// Depending on browser cache load behaviour, entwine's DOMMaybeChanged
// can be called before the bottom-most inline script tag is executed,
// which defines the global. If that's the case, wait for the window load.
if(typeof ssTinyMceConfig != 'undefined') this.redraw();
this._super();
},
onremove: function() {
var ed = tinyMCE.get(this.attr('id'));
if (ed) {
try {
ed.remove();
} catch(ex) {}
try {
ed.destroy();
} catch(ex) {}
// Remove any residual tinyMCE editor element
this.next('.mceEditor').remove();
// TinyMCE leaves behind events. We should really fix TinyMCE, but lets brute force it for now
$.each(jQuery.cache, function(){
var source = this.handle && this.handle.elem;
if (!source) return;
var parent = source;
try {
while (parent && parent.nodeType == 1) parent = parent.parentNode;
}
catch(err) {}
if (!parent) $(source).unbind().remove();
});
}
this._super();
},
getContainingForm: function(){
return this.closest('form');
},
fromWindow: {
onload: function(){
this.redraw();
}
},
redraw: function() {
// Using textarea config ID from global config object (generated through HTMLEditorConfig PHP logic)
var config = ssTinyMceConfig[this.data('config')], self = this, ed = this.getEditor();
ed.init(config);
// Create editor instance and render it.
// Similar logic to adapter/jquery/jquery.tinymce.js, but doesn't rely on monkey-patching
// jQuery methods, and avoids replicate the script lazyloading which is already in place with jQuery.ondemand.
ed.create(this.attr('id'), config);
this._super();
},
/**
* Make sure the editor has flushed all it's buffers before the form is submitted.
*/
'from .cms-edit-form': {
onbeforesubmitform: function(e) {
this.getEditor().save();
this._super();
}
},
oneditorinit: function() {
// Delayed show because TinyMCE calls hide() via setTimeout on removing an element,
// which is called in quick succession with adding a new editor after ajax loading new markup
//storing the container object before setting timeout
var redrawObj = $(this.getEditor().getInstance().getContainer());
setTimeout(function() {
redrawObj.show();
}, 10);
},
'from .cms-container': {
onbeforestatechange: function(){
this.css('visibility', 'hidden');
var ed = this.getEditor(), container = (ed && ed.getInstance()) ? ed.getContainer() : null;
if(container && container.length) container.remove();
}
},
isChanged: function() {
var ed = this.getEditor();
return (ed && ed.getInstance() && ed.isDirty());
},
resetChanged: function() {
var ed = this.getEditor();
if(typeof tinyMCE == 'undefined') return;
// TODO Abstraction layer
var inst = tinyMCE.getInstanceById(this.attr('id'));
if (inst) inst.startContent = tinymce.trim(inst.getContent({format : 'raw', no_events : 1}));
},
openLinkDialog: function() {
this.openDialog('link');
},
openMediaDialog: function() {
this.openDialog('media');
},
openDialog: function(type) {
var capitalize = function(text) {
return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
};
var self = this, url = $('#cms-editor-dialogs').data('url' + capitalize(type) + 'form'),
dialog = $('.htmleditorfield-' + type + 'dialog');
if(dialog.length) {
dialog.getForm().setElement(this);
dialog.open();
} else {
// Show a placeholder for instant feedback. Will be replaced with actual
// form dialog once its loaded.
dialog = $('<div class="htmleditorfield-dialog htmleditorfield-' + type + 'dialog loading">');
$('body').append(dialog);
$.ajax({
url: url,
complete: function() {
dialog.removeClass('loading');
},
success: function(html) {
dialog.html(html);
dialog.getForm().setElement(self);
dialog.trigger('ssdialogopen');
}
});
}
}
});
$('.htmleditorfield-dialog').entwine({
onadd: function() {
// Create jQuery dialog
if (!this.is('.ui-dialog-content')) {
this.ssdialog({autoOpen: true});
}
this._super();
},
getForm: function() {
return this.find('form');
},
open: function() {
this.ssdialog('open');
},
close: function() {
this.ssdialog('close');
},
toggle: function(bool) {
if(this.is(':visible')) this.close();
else this.open();
}
});
/**
* Base form implementation for interactions with an editor instance,
* mostly geared towards modification and insertion of content.
*/
$('form.htmleditorfield-form').entwine({
Selection: null,
// Implementation-dependent serialization of the current editor selection state
Bookmark: null,
// DOMElement pointing to the currently active textarea
Element: null,
setSelection: function(node) {
return this._super($(node));
},
onadd: function() {
// Move title from headline to (jQuery compatible) title attribute
var titleEl = this.find(':header:first');
this.getDialog().attr('title', titleEl.text());
this._super();
},
onremove: function() {
this.setSelection(null);
this.setBookmark(null);
this.setElement(null);
this._super();
},
getDialog: function() {
// TODO Refactor to listen to form events to remove two-way coupling
return this.closest('.htmleditorfield-dialog');
},
fromDialog: {
onssdialogopen: function(){
var ed = this.getEditor();
ed.onopen();
this.setSelection(ed.getSelectedNode());
this.setBookmark(ed.createBookmark());
ed.blur();
this.find(':input:not(:submit)[data-skip-autofocus!="true"]').filter(':visible:enabled').eq(0).focus();
this.redraw();
this.updateFromEditor();
},
onssdialogclose: function(){
var ed = this.getEditor();
ed.onclose();
ed.moveToBookmark(this.getBookmark());
this.setSelection(null);
this.setBookmark(null);
this.resetFields();
}
},
/**
* @return Object ss.editorWrapper instance
*/
getEditor: function(){
return this.getElement().getEditor();
},
modifySelection: function(callback) {
var ed = this.getEditor();
ed.moveToBookmark(this.getBookmark());
callback.call(this, ed);
this.setSelection(ed.getSelectedNode());
this.setBookmark(ed.createBookmark());
ed.blur();
},
updateFromEditor: function() {
/* NOP */
},
redraw: function() {
/* NOP */
},
resetFields: function() {
// Flush the tree drop down fields, as their content might get changed in other parts of the CMS, ie in Files and images
this.find('.tree-holder').empty();
}
});
/**
* Inserts and edits links in an html editor, including internal/external web links,
* links to files on the webserver, email addresses, and anchors in the existing html content.
* Every variation has its own fields (e.g. a "target" attribute doesn't make sense for an email link),
* which are toggled through a type dropdown. Variations share fields, so there's only one "title" field in the form.
*/
$('form.htmleditorfield-linkform').entwine({
// TODO Entwine doesn't respect submits triggered by ENTER key
onsubmit: function(e) {
this.insertLink();
this.getDialog().close();
return false;
},
resetFields: function() {
this._super();
// Reset the form using a native call. This will also correctly reset checkboxes and radio buttons.
this[0].reset();
},
redraw: function() {
this._super();
var linkType = this.find(':input[name=LinkType]:checked').val();
this.addAnchorSelector();
this.resetFileField();
// Toggle field visibility depending on the link type.
this.find('div.content .field').hide();
this.find('.field[id$="LinkType"]').show();
this.find('.field[id$="' + linkType +'_Holder"]').show();
if(linkType == 'internal' || linkType == 'anchor') {
this.find('.field[id$="Anchor_Holder"]').show();
}
if(linkType == 'email') {
this.find('.field[id$="Subject_Holder"]').show();
} else {
this.find('.field[id$="TargetBlank_Holder"]').show();
}
if(linkType == 'anchor') {
this.find('.field[id$="AnchorSelector_Holder"]').show();
}
this.find('.field[id$="Description_Holder"]').show();
},
/**
* @return Object Keys: 'href', 'target', 'title'
*/
getLinkAttributes: function() {
var href,
target = null,
subject = this.find(':input[name=Subject]').val(),
anchor = this.find(':input[name=Anchor]').val();
// Determine target
if(this.find(':input[name=TargetBlank]').is(':checked')) {
target = '_blank';
}
// All other attributes
switch(this.find(':input[name=LinkType]:checked').val()) {
case 'internal':
href = '[sitetree_link,id=' + this.find(':input[name=internal]').val() + ']';
if(anchor) {
href += '#' + anchor;
}
break;
case 'anchor':
href = '#' + anchor;
break;
case 'file':
href = '[file_link,id=' + this.find('.ss-uploadfield .ss-uploadfield-item').attr('data-fileid') + ']';
break;
case 'email':
href = 'mailto:' + this.find(':input[name=email]').val();
if(subject) {
href += '?subject=' + encodeURIComponent(subject);
}
target = null;
break;
// case 'external':
default:
href = this.find(':input[name=external]').val();
// Prefix the URL with "http://" if no prefix is found
if(href.indexOf('://') == -1) href = 'http://' + href;
break;
}
return {
href : href,
target : target,
title : this.find(':input[name=Description]').val()
};
},
insertLink: function() {
this.modifySelection(function(ed){
ed.insertLink(this.getLinkAttributes());
});
},
removeLink: function() {
this.modifySelection(function(ed){
ed.removeLink();
});
this.resetFileField();
this.close();
},
resetFileField: function() {
// If there's an attached item, remove it
var fileField = this.find('.ss-uploadfield[id$="file_Holder"]'),
fileUpload = fileField.data('fileupload'),
currentItem = fileField.find('.ss-uploadfield-item[data-fileid]');
if(currentItem.length) {
fileUpload._trigger('destroy', null, {context: currentItem});
fileField.find('.ss-uploadfield-addfile').removeClass('borderTop');
}
},
/**
* Builds an anchor selector element and injects it into the DOM next to the anchor field.
*/
addAnchorSelector: function() {
// Avoid adding twice
if(this.find(':input[name=AnchorSelector]').length) return;
var self = this;
var anchorSelector = $(
'<select id="Form_EditorToolbarLinkForm_AnchorSelector" name="AnchorSelector"></select>'
);
this.find(':input[name=Anchor]').parent().append(anchorSelector);
// Initialise the anchor dropdown.
this.updateAnchorSelector();
// copy the value from dropdown to the text field
anchorSelector.change(function(e) {
self.find(':input[name="Anchor"]').val($(this).val());
});
},
/**
* Fetch relevant anchors, depending on the link type.
*
* @return $.Deferred A promise of an anchor array, or an error message.
*/
getAnchors: function() {
var linkType = this.find(':input[name=LinkType]:checked').val();
var dfdAnchors = $.Deferred();
switch (linkType) {
case 'anchor':
// Fetch from the local editor.
var collectedAnchors = [];
var ed = this.getEditor();
// name attribute is defined as CDATA, should accept all characters and entities
// http://www.w3.org/TR/1999/REC-html401-19991224/struct/links.html#h-12.2
if(ed) {
var raw = ed.getContent()
.match(/\s+(name|id)\s*=\s*(["'])([^\2\s>]*?)\2|\s+(name|id)\s*=\s*([^"']+)[\s +>]/gim);
if (raw && raw.length) {
for(var i = 0; i < raw.length; i++) {
var indexStart = (raw[i].indexOf('id=') == -1) ? 7 : 5;
collectedAnchors.push(raw[i].substr(indexStart).replace(/"$/, ''));
}
}
}
dfdAnchors.resolve(collectedAnchors);
break;
case 'internal':
// Fetch available anchors from the target internal page.
var pageId = this.find(':input[name=internal]').val();
if (pageId) {
$.ajax({
url: $.path.addSearchParams(
this.attr('action').replace('LinkForm', 'getanchors'),
{'PageID': parseInt(pageId)}
),
success: function(body, status, xhr) {
dfdAnchors.resolve($.parseJSON(body));
},
error: function(xhr, status) {
dfdAnchors.reject(xhr.responseText);
}
});
} else {
dfdAnchors.resolve([]);
}
break;
default:
// This type does not support anchors at all.
dfdAnchors.reject(ss.i18n._t(
'HtmlEditorField.ANCHORSNOTSUPPORTED',
'Anchors are not supported for this link type.'
));
break;
}
return dfdAnchors.promise();
},
/**
* Update the anchor list in the dropdown.
*/
updateAnchorSelector: function() {
var self = this;
var selector = this.find(':input[name=AnchorSelector]');
var dfdAnchors = this.getAnchors();
// Inform the user we are loading.
selector.empty();
selector.append($(
'<option value="" selected="1">' +
ss.i18n._t('HtmlEditorField.LOOKINGFORANCHORS', 'Looking for anchors...') +
'</option>'
));
dfdAnchors.done(function(anchors) {
selector.empty();
selector.append($(
'<option value="" selected="1">' +
ss.i18n._t('HtmlEditorField.SelectAnchor') +
'</option>'
));
if (anchors) {
for (var j = 0; j < anchors.length; j++) {
selector.append($('<option value="'+anchors[j]+'">'+anchors[j]+'</option>'));
}
}
}).fail(function(message) {
selector.empty();
selector.append($(
'<option value="" selected="1">' +
message +
'</option>'
));
});
// Poke the selector for IE8, otherwise the changes won't be noticed.
if ($.browser.msie) selector.hide().show();
},
/**
* Updates the state of the dialog inputs to match the editor selection.
* If selection does not contain a link, resets the fields.
*/
updateFromEditor: function() {
var htmlTagPattern = /<\S[^><]*>/g, fieldName, data = this.getCurrentLink();
if(data) {
for(fieldName in data) {
var el = this.find(':input[name=' + fieldName + ']'), selected = data[fieldName];
// Remove html tags in the selected text that occurs on IE browsers
if(typeof(selected) == 'string') selected = selected.replace(htmlTagPattern, '');
// Set values and invoke the triggers (e.g. for TreeDropdownField).
if(el.is(':checkbox')) {
el.prop('checked', selected).change();
} else if(el.is(':radio')) {
el.val([selected]).change();
} else if(fieldName == 'file') {
// UploadField inputs have a slightly different naming convention
el = this.find(':input[name="' + fieldName + '[Uploads][]"]');
// We need the UploadField "field", not just the input
el = el.parents('.ss-uploadfield');
// We have to wait for the UploadField to initialise
(function attach(el, selected) {
if( ! el.getConfig()) {
setTimeout(function(){ attach(el, selected); }, 50);
} else {
el.attachFiles([selected]);
}
})(el, selected);
} else {
el.val(selected).change();
}
}
}
},
/**
* Return information about the currently selected link, suitable for population of the link form.
*
* Returns null if no link was currently selected.
*/
getCurrentLink: function() {
var selectedEl = this.getSelection(),
href = "", target = "", title = "", action = "insert", style_class = "";
// We use a separate field for linkDataSource from tinyMCE.linkElement.
// If we have selected beyond the range of an <a> element, then use use that <a> element to get the link data source,
// but we don't use it as the destination for the link insertion
var linkDataSource = null;
if(selectedEl.length) {
if(selectedEl.is('a')) {
// Element is a link
linkDataSource = selectedEl;
// TODO Limit to inline elements, otherwise will also apply to e.g. paragraphs which already contain one or more links
// } else if((selectedEl.find('a').length)) {
// // Element contains a link
// var firstLinkEl = selectedEl.find('a:first');
// if(firstLinkEl.length) linkDataSource = firstLinkEl;
// if(linkDataSource && linkDataSource.length) this.modifySelection(function(ed){
// ed.selectNode(linkDataSource[0]);
// });
} else {
// Element is a child of a link
linkDataSource = selectedEl = selectedEl.parents('a:first');
}
}
// Is anchor not a link
if (!linkDataSource.attr('href')) linkDataSource = null;
if (linkDataSource) {
href = linkDataSource.attr('href');
target = linkDataSource.attr('target');
title = linkDataSource.attr('title');
style_class = linkDataSource.attr('class');
href = this.getEditor().cleanLink(href, linkDataSource);
action = "update";
}
if(href.match(/^mailto:([^?]*)(\?subject=(.*))?$/)) {
return {
LinkType: 'email',
email: RegExp.$1,
Subject: decodeURIComponent(RegExp.$3),
Description: title
};
} else if(href.match(/^(assets\/.*)$/) || href.match(/^\[file_link\s*(?:\s*|%20|,)?id=([0-9]+)\]?(#.*)?$/)) {
return {
LinkType: 'file',
file: RegExp.$1,
Description: title,
TargetBlank: target ? true : false
};
} else if(href.match(/^#(.*)$/)) {
return {
LinkType: 'anchor',
Anchor: RegExp.$1,
Description: title,
TargetBlank: target ? true : false
};
} else if(href.match(/^\[sitetree_link(?:\s*|%20|,)?id=([0-9]+)\]?(#.*)?$/i)) {
return {
LinkType: 'internal',
internal: RegExp.$1,
Anchor: RegExp.$2 ? RegExp.$2.substr(1) : '',
Description: title,
TargetBlank: target ? true : false
};
} else if(href) {
return {
LinkType: 'external',
external: href,
Description: title,
TargetBlank: target ? true : false
};
} else {
// No link/invalid link selected.
return null;
}
}
});
$('form.htmleditorfield-linkform input[name=LinkType]').entwine({
onclick: function(e) {
this.parents('form:first').redraw();
this._super();
},
onchange: function() {
this.parents('form:first').redraw();
// Update if a anchor-supporting link type is selected.
var linkType = this.parent().find(':checked').val();
if (linkType==='anchor' || linkType==='internal') {
this.parents('form.htmleditorfield-linkform').updateAnchorSelector();
}
this._super();
}
});
$('form.htmleditorfield-linkform input[name=internal]').entwine({
/**
* Update the anchor dropdown if a different page is selected in the "internal" dropdown.
*/
onvalueupdated: function() {
this.parents('form.htmleditorfield-linkform').updateAnchorSelector();
this._super();
}
});
$('form.htmleditorfield-linkform :submit[name=action_remove]').entwine({
onclick: function(e) {
this.parents('form:first').removeLink();
this._super();
return false;
}
});
/**
* Responsible for inserting media files, although only images are supported so far.
* Allows to select one or more files, and load form fields for each file via ajax.
* This allows us to tailor the form fields to the file type (e.g. different ones for images and flash),
* as well as add new form fields via framework extensions.
* The inputs on each of those files are used for constructing the HTML to insert into
* the rich text editor. Also allows editing the properties of existing files if any are selected in the editor.
* Note: Not each file has a representation on the webserver filesystem, supports insertion and editing
* of remove files as well.
*/
$('form.htmleditorfield-mediaform').entwine({
toggleCloseButton: function(){
var updateExisting = Boolean(this.find('.ss-htmleditorfield-file').length);
this.find('.overview .action-delete')[updateExisting ? 'hide' : 'show']();
},
onsubmit: function() {
this.modifySelection(function(ed){
this.find('.ss-htmleditorfield-file').each(function() {
$(this).insertHTML(ed);
});
ed.repaint();
});
this.getDialog().close();
return false;
},
updateFromEditor: function() {
var self = this, node = this.getSelection();