This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 118
/
MooEditable.js
2170 lines (1767 loc) · 69.5 KB
/
MooEditable.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
/*
---
name: MooEditable
description: Class for creating a WYSIWYG editor, for contentEditable-capable browsers.
license: MIT-style license
authors:
- Lim Chee Aun
- Radovan Lozej
- Ryan Mitchell
- Olivier Refalo
- T.J. Leahy
- MArc Schmidt <marc@kryn.org>
requires:
- Core/Class.Extras
- Core/Element.Event
- Core/Element.Dimensions
inspiration:
- Code inspired by Stefan's work [Safari Supports Content Editing!](http://www.xs4all.nl/~hhijdra/stefan/ContentEditable.html) from [safari gets contentEditable](http://walkah.net/blog/walkah/safari-gets-contenteditable)
- Main reference from Peter-Paul Koch's [execCommand compatibility](http://www.quirksmode.org/dom/execCommand.html)
- Some ideas and code inspired by [TinyMCE](http://tinymce.moxiecode.com/)
- Some functions inspired by Inviz's [Most tiny wysiwyg you ever seen](http://forum.mootools.net/viewtopic.php?id=746), [mooWyg (Most tiny WYSIWYG 2.0)](http://forum.mootools.net/viewtopic.php?id=5740)
- Some regex from Cameron Adams's [widgEditor](http://widgeditor.googlecode.com/)
- Some code from Juan M Martinez's [jwysiwyg](http://jwysiwyg.googlecode.com/)
- Some reference from MoxieForge's [PunyMCE](http://punymce.googlecode.com/)
- IE support referring Robert Bredlau's [Rich Text Editing](http://www.rbredlau.com/drupal/node/6)
provides: [MooEditable, MooEditable.Selection, MooEditable.UI, MooEditable.Actions]
...
*/
(function(){
var blockEls = /^(H[1-6]|HR|P|DIV|ADDRESS|PRE|FORM|TABLE|LI|OL|UL|TD|CAPTION|BLOCKQUOTE|CENTER|DL|DT|DD|SCRIPT|NOSCRIPT|STYLE)$/i;
var urlRegex = /^(https?|ftp|rmtp|mms):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i;
var protectRegex = /<(script|noscript|style)[\u0000-\uFFFF]*?<\/(script|noscript|style)>/g;
var dummy = new Element('p');
var supportsContentEditable = false;
if( dummy.contentEditable !== undefined )
supportsContentEditable = true;
dummy.destroy();
delete dummy;
this.MooEditable = new Class({
Implements: [Events, Options],
options: {
toolbar: true,
cleanup: true,
paragraphise: true,
xhtml : true,
semantics : true,
actions: 'bold italic underline strikethrough | insertunorderedlist insertorderedlist indent outdent | undo redo | createlink unlink | urlimage | toggleview',
handleSubmit: true,
handleLabel: true,
disabled: false,
baseCSS: 'html{ height: 100%; cursor: text; } body{ font-family: sans-serif; }',
extraCSS: '',
externalCSS: '',
html: '<!DOCTYPE html><html><head><meta charset="UTF-8">{BASEHREF}<style>{BASECSS} {EXTRACSS}</style>{EXTERNALCSS}</head><body class="mooeditable-iframe"></body></html>',
rootElement: 'p',
baseURL: '',
dimensions: null,
autoheight: true,
minHeight: 60,
extraClass: '',
flyingToolbar: false,
dialogContainer: false,
toolbarContainer: false
},
initialize: function(el, options){
// check for content editable and design mode support
if (!("contentEditable" in document.body) && !("designMode" in document)){
return;
}
this.setOptions(options);
this.textarea = document.id(el);
this.textarea.store('MooEditable', this);
this.actions = this.options.actions.clean().split(' ');
this.keys = {};
this.dialogs = {};
this.protectedElements = [];
this.plugins = {};
Object.each(MooEditable.Plugins, function(plugin,id){
this.plugins[ id ] = new plugin(this);
}.bind(this));
Object.each(MooEditable.Actions,function(def,action){
if( !this.actions.contains(action) && !def.modify ) return;
var act = MooEditable.Actions[action];
if (!act) return;
if (act.options){
var key = act.options.shortcut;
if (key) this.keys[key] = action;
}
if (act.dialogs){
Object.each(act.dialogs, function(dialog, name){
dialog = dialog.call(this, this);
dialog.name = action + ':' + name;
if (typeOf(this.dialogs[action]) != 'object') this.dialogs[action] = {};
this.dialogs[action][name] = dialog;
}, this);
}
if (act.events){
Object.each(act.events, function(fn, event){
this.addEvent(event, fn);
}, this);
}
}.bind(this));
this.render();
},
toElement: function(){
return this.textarea;
},
render: function(){
var self = this;
// Dimensions
var dimensions = this.options.dimensions || this.textarea.getSize();
// Build the container
this.container = new Element('div', {
id: (this.textarea.id) ? this.textarea.id + '-mooeditable-container' : null,
'class': 'mooeditable-container'+((this.options.extraClass)?' '+this.options.extraClass:''),
styles: {
width: dimensions.x
}
});
this.container.store('instance', this);
// Override all textarea styles
this.textarea.addClass('mooeditable-textarea').setStyle('height', dimensions.y);
// Build the "iframe"
if( supportsContentEditable ){
this.iframe = new Element('div', {
'class': 'mooeditable-iframe',
styles: {
height: (this.options.autoheight==false)?dimensions.y:null,
'min-height': (this.options.minHeight)?this.options.minHeight+'px':null
},
contentEditable: true
});
} else {
this.iframe = new IFrame({
'class': 'mooeditable-iframe',
frameBorder: 0,
src: 'javascript:""', // Workaround for HTTPs warning in IE6/7
styles: {
height: dimensions.y
}
});
}
this.toolbar = new MooEditable.UI.Toolbar(this, {
onItemAction: function(){
var args = Array.from(arguments);
var item = args[0];
self.action(item.name, args);
}
});
this.attach.delay(1, this);
// Update the event for textarea's corresponding labels
if (this.options.handleLabel && this.textarea.id) $$('label[for="'+this.textarea.id+'"]').addEvent('click', function(e){
if (self.mode != 'iframe') return;
e.preventDefault();
self.focus();
});
// Update & cleanup content before submit
if (this.options.handleSubmit){
this.form = this.textarea.getParent('form');
if (!this.form) return;
this.form.addEvent('submit', function(){
if (self.mode == 'iframe') self.saveContent();
});
}
this.fireEvent('render', this);
},
attach: function(){
var self = this;
// Assign view mode
this.mode = 'iframe';
// Editor iframe state
this.editorDisabled = false;
// Put textarea inside container
this.container.wraps(this.textarea);
this.textarea.setStyle('display', 'none');
this.iframe.setStyle('display', '').inject(this.textarea, 'before');
var dialogContainer = this.iframe.getParent('.mooeditable-dialog-container');
if( !dialogContainer )
dialogContainer = document.body;
if( this.options.dialogContainer )
dialogContainer = this.options.dialogContainer;
Object.each(this.dialogs, function(action, name){
Object.each(action, function(dialog){
dialog.setContainer( dialogContainer );
var range;
dialog.addEvents({
open: function(){
range = self.selection.getRange();
self.editorDisabled = true;
self.toolbar.disable(name);
self.fireEvent('dialogOpen', this);
},
close: function(){
self.toolbar.enable();
self.editorDisabled = false;
self.focus();
if (range) self.selection.setRange(range);
self.fireEvent('dialogClose', this);
}
});
});
});
// contentWindow and document references
if( this.iframe.get('tag') != 'iframe' ){
this.win = this.iframe.getWindow();
this.doc = this.iframe;
this.doc.body = this.doc;
} else {
this.win = this.iframe.contentWindow;
this.doc = this.win.document;
// Deal with weird quirks on Gecko
if( Browser.firefox ) this.doc.designMode = 'On';
// Build the content of iframe
var docHTML = this.options.html.substitute({
BASECSS: this.options.baseCSS,
EXTRACSS: this.options.extraCSS,
EXTERNALCSS: (this.options.externalCSS) ? '<link rel="stylesheet" href="' + this.options.externalCSS + '">': '',
BASEHREF: (this.options.baseURL) ? '<base href="' + this.options.baseURL + '" />': ''
});
this.doc.open();
this.doc.write(docHTML);
this.doc.close();
// Turn on Design Mode
// IE fired load event twice if designMode is set
(Browser.ie) ? this.doc.body.contentEditable = true : this.doc.designMode = 'On';
// Mootoolize window, document and body
Object.append(this.win, new Window);
Object.append(this.doc, new Document);
if (Browser.Element){
var winElement = this.win.Element.prototype;
for (var method in Element){ // methods from Element generics
if (!method.test(/^[A-Z]|\$|prototype|mooEditable/)){
winElement[method] = Element.prototype[method];
}
}
} else {
document.id(this.doc.body);
}
this.win.addEvents({
focus: this.editorFocus.bind(this),
blur: this.editorBlur.bind(this)
});
}
this.setContent(this.textarea.get('value'));
// Bind all events
this.doc.addEvents({
mouseup: this.editorMouseUp.bind(this),
mousedown: this.editorMouseDown.bind(this),
mouseover: this.editorMouseOver.bind(this),
mouseout: this.editorMouseOut.bind(this),
mouseenter: this.editorMouseEnter.bind(this),
mouseleave: this.editorMouseLeave.bind(this),
contextmenu: this.editorContextMenu.bind(this),
click: this.editorClick.bind(this),
dblclick: this.editorDoubleClick.bind(this),
keypress: this.editorKeyPress.bind(this),
keyup: this.editorKeyUp.bind(this),
keydown: this.editorKeyDown.bind(this),
focus: this.editorFocus.bind(this),
blur: this.editorBlur.bind(this)
});
['cut', 'copy', 'paste'].each(function(event){
self.doc.body.addListener(event, self['editor' + event.capitalize()].bind(self));
});
this.textarea.addEvent('keypress', this.textarea.retrieve('mooeditable:textareaKeyListener', this.keyListener.bind(this)));
// Fix window focus event not firing on Firefox 2
if (Browser.firefox2) this.doc.addEvent('focus', function(){
self.win.fireEvent('focus').focus();
});
// IE9 is also not firing focus event
if (this.doc.addEventListener) this.doc.addEventListener('focus', function(){
self.win.fireEvent('focus');
}, true);
// styleWithCSS, not supported in IE and Opera
if (!Browser.ie && !Browser.opera){
var styleCSS = function(){
self.execute('styleWithCSS', false, false);
self.doc.removeEvent('focus', styleCSS);
};
this.win.addEvent('focus', styleCSS);
}
if( this.options.toolbar ){
if( this.options.flyingToolbar && !this.options.toolbarContainer )
document.id(this.toolbar).inject(this.container);
else if( this.options.toolbarContainer )
document.id(this.toolbar).inject(this.options.toolbarContainer);
else
document.id(this.toolbar).inject(this.container, 'top');
this.toolbar.render(this.actions);
}
if (this.options.disabled) this.disable();
this.selection = new MooEditable.Selection(this.win);
this.oldContent = this.getContent();
this.fireEvent('attach', this);
return this;
},
detach: function(){
this.saveContent();
this.textarea.setStyle('display', '').removeClass('mooeditable-textarea').inject(this.container, 'before');
this.textarea.removeEvent('keypress', this.textarea.retrieve('mooeditable:textareaKeyListener'));
this.container.dispose();
this.fireEvent('detach', this);
return this;
},
enable: function(){
this.editorDisabled = false;
this.toolbar.enable();
return this;
},
disable: function(){
this.editorDisabled = true;
this.toolbar.disable();
return this;
},
editorFocus: function(e){
this.oldContent = '';
this.cursorInEditor = true;
this.checkStates();
this.fireEvent('editorFocus', [e, this]);
},
editorBlur: function(e){
this.cursorInEditor = false;
this.oldContent = this.saveContent().getContent();
this.checkStates();
this.fireEvent('editorBlur', [e, this]);
},
editorMouseUp: function(e){
if (this.editorDisabled){
e.stop();
return;
}
if (this.options.toolbar) this.checkStates();
this.fireEvent('editorMouseUp', [e, this]);
},
editorMouseDown: function(e){
if (this.editorDisabled){
e.stop();
return;
}
this.fireEvent('editorMouseDown', [e, this]);
},
editorMouseOver: function(e){
if (this.editorDisabled){
e.stop();
return;
}
this.fireEvent('editorMouseOver', [e, this]);
},
editorMouseOut: function(e){
if (this.editorDisabled){
e.stop();
return;
}
this.fireEvent('editorMouseOut', [e, this]);
},
editorMouseEnter: function(e){
if (this.editorDisabled){
e.stop();
return;
}
if (this.oldContent && this.getContent() != this.oldContent){
this.focus();
this.fireEvent('editorPaste', [e, this]);
}
this.fireEvent('editorMouseEnter', [e, this]);
},
editorMouseLeave: function(e){
if (this.editorDisabled){
e.stop();
return;
}
this.fireEvent('editorMouseLeave', [e, this]);
},
editorContextMenu: function(e){
if (this.editorDisabled){
e.stop();
return;
}
this.fireEvent('editorContextMenu', [e, this]);
},
editorClick: function(e){
// make images selectable and draggable in Safari
if (Browser.safari || Browser.chrome){
var el = e.target;
if (Element.get(el, 'tag') == 'img'){
// safari doesnt like dragging locally linked images
if (this.options.baseURL){
if (el.getProperty('src').indexOf('http://') == -1){
el.setProperty('src', this.options.baseURL + el.getProperty('src'));
}
}
this.selection.selectNode(el);
this.checkStates();
}
}
this.fireEvent('editorClick', [e, this]);
},
editorDoubleClick: function(e){
this.fireEvent('editorDoubleClick', [e, this]);
},
editorKeyPress: function(e){
if (this.editorDisabled){
e.stop();
return;
}
this.keyListener(e);
this.fireEvent('editorKeyPress', [e, this]);
},
editorKeyUp: function(e){
if (this.editorDisabled){
e.stop();
return;
}
var c = e.code;
var delay = (Browser.ie6)?500:200;
clearTimeout(this.checkStatesDelay);
this.checkStatesDelay = this.checkStates.delay(delay, this);
this.fireEvent('editorKeyUp', [e, this]);
},
editorKeyDown: function(e){
if (this.editorDisabled){
e.stop();
return;
}
if (e.key == 'enter'){
if (this.options.paragraphise){
if (e.shift && (Browser.safari || Browser.chrome)){
var s = this.selection;
var r = s.getRange();
// Insert BR element
var br = this.doc.createElement('br');
r.insertNode(br);
// Place caret after BR
r.setStartAfter(br);
r.setEndAfter(br);
s.setRange(r);
// Could not place caret after BR then insert an nbsp entity and move the caret
if (s.getSelection().focusNode == br.previousSibling){
var nbsp = this.doc.createTextNode('\u00a0');
var p = br.parentNode;
var ns = br.nextSibling;
(ns) ? p.insertBefore(nbsp, ns) : p.appendChild(nbsp);
s.selectNode(nbsp);
s.collapse(1);
}
// Scroll to new position, scrollIntoView can't be used due to bug: http://bugs.webkit.org/show_bug.cgi?id=16117
this.win.scrollTo(0, Element.getOffsets(s.getRange().startContainer).y);
e.preventDefault();
} else if (Browser.firefox || Browser.safari || Browser.chrome){
var node = this.selection.getNode();
var isBlock = Element.getParents(node).include(node).some(function(el){
return el.nodeName.test(blockEls);
});
if (!isBlock) this.execute('insertparagraph');
}
} else {
if (Browser.ie){
var r = this.selection.getRange();
var node = this.selection.getNode();
if (r && node.get('tag') != 'li'){
this.selection.insertContent('<br>');
this.selection.collapse(false);
}
e.preventDefault();
}
}
}
if (Browser.opera){
var ctrlmeta = e.control || e.meta;
if (ctrlmeta && e.key == 'x'){
this.fireEvent('editorCut', [e, this]);
} else if (ctrlmeta && e.key == 'c'){
this.fireEvent('editorCopy', [e, this]);
} else if ((ctrlmeta && e.key == 'v') || (e.shift && e.code == 45)){
this.fireEvent('editorPaste', [e, this]);
}
}
this.fireEvent('editorKeyDown', [e, this]);
},
editorCut: function(e){
if (this.editorDisabled){
e.stop();
return;
}
this.fireEvent('editorCut', [e, this]);
},
editorCopy: function(e){
if (this.editorDisabled){
e.stop();
return;
}
this.fireEvent('editorCopy', [e, this]);
},
editorPaste: function(e){
if (this.editorDisabled){
e.stop();
return;
}
this.fireEvent('editorPaste', [e, this]);
},
keyListener: function(e){
var key = (Browser.Platform.mac) ? e.meta : e.control;
if (!key || !this.keys[e.key]) return;
e.preventDefault();
var item = this.toolbar.getItem(this.keys[e.key]);
item.action(e);
},
focus: function(){
(this.mode == 'iframe' ? this.win : this.textarea).focus();
this.fireEvent('focus', this);
return this;
},
action: function(command, args){
var action = MooEditable.Actions[command];
if (action.command && typeOf(action.command) == 'function'){
action.command.apply(this, args);
} else {
this.focus();
this.execute(command, false, args);
if (this.mode == 'iframe') this.checkStates();
var map = {'bold':'b', 'italic':'i', 'underline':'u', 'strikethrough':'strike'};
if( ['bold', 'italic', 'underline', 'strikethrough'].contains( command ) ){
var node = this.selection.getNode();
if( node && node.get('tag') == map[command] )
this.toolbar.items[command].deactivate()
else
this.toolbar.items[command].activate()
}
}
},
execute: function(command, param1, param2){
if (this.busy) return;
this.busy = true;
if( this.iframe.get('tag') == 'iframe' )
this.doc.execCommand(command, param1, param2);
else
this.iframe.getDocument().execCommand(command, param1, param2);
this.saveContent();
this.busy = false;
return false;
},
toggleView: function(){
this.fireEvent('beforeToggleView', this);
if (this.mode == 'textarea'){
this.mode = 'iframe';
this.iframe.setStyle('display', '');
this.setContent( this.textarea.value );
this.textarea.setStyle('display', 'none');
} else {
this.saveContent();
this.mode = 'textarea';
this.textarea.setStyle('display', '');
this.iframe.setStyle('display', 'none');
}
this.fireEvent('toggleView', this);
this.focus.delay(10, this);
return this;
},
getContent: function(){
var protect = this.protectedElements;
var html = this.doc.body.get('html').replace(/<!-- mooeditable:protect:([0-9]+) -->/g, function(a, b){
return protect[b.toInt()];
});
//workaround for firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=630524
if( Browser.firefox && this.iframe.get('tag') == 'div' )
html = html.substr(11);
var root = new Element('div', {
html: html
});
Object.each(this.plugins, function(plugin,id){
if( plugin && plugin.removeControls )
plugin.removeControls( root );
});
return this.cleanup(this.ensureRootElement(root.get('html')));
},
setContent: function(content){
var protect = this.protectedElements;
//workaround for firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=630524
if( Browser.firefox && this.iframe.get('tag') == 'div' )
content = '<div></div>'+content;
content = content.replace(protectRegex, function(a){
protect.push(a);
return '<!-- mooeditable:protect:' + (protect.length-1) + ' -->';
});
this.doc.body.set('html', this.ensureRootElement(content));
this.fireEvent('change');
return this;
},
saveContent: function(){
if (this.mode == 'iframe'){
this.textarea.set('value', this.getContent());
}
return this;
},
ensureRootElement: function(val){
if (this.options.rootElement){
var el = new Element('div', {html: val.trim()});
var start = -1;
var create = false;
var html = '';
var length = el.childNodes.length;
for (var i=0; i<length; i++){
var childNode = el.childNodes[i];
var nodeName = childNode.nodeName;
if (!nodeName.test(blockEls) && nodeName !== '#comment'){
if (nodeName === '#text'){
if (childNode.nodeValue.trim()){
if (start < 0) start = i;
html += childNode.nodeValue;
}
} else {
if (start < 0) start = i;
html += new Element('div').adopt($(childNode).clone()).get('html');
}
} else {
create = true;
}
if (i == (length-1)) create = true;
if (start >= 0 && create){
var newel = new Element(this.options.rootElement, {html: html});
el.replaceChild(newel, el.childNodes[start]);
for (var k=start+1; k<i; k++){
el.removeChild(el.childNodes[k]);
length--;
i--;
k--;
}
start = -1;
create = false;
html = '';
}
}
val = el.get('html').replace(/\n\n/g, '');
}
return val;
},
checkStates: function( element ){
if( !element )
element = this.selection.getNode();
this.fireEvent('checkStates');
if (!element) return;
if (typeOf(element) != 'element') return;
if (element.get('tag') == 'tr') return;
this.toolbar.position( element );
this.toolbar.clearModify();
if( !this.lastElement || this.lastElement.get('tag') != element.get('tag') ){
this.toolbar.selectTab(1);
}
if( this.lastElement != element ){
this.fireEvent('element', element);
}
var noModifier = true;
Object.each(MooEditable.Actions, function(def,action){
var modify = MooEditable.Actions[action]['modify'];
if( modify ) {
if( typeOf(modify) == 'function' ){
if( modify.attempt([document.id(element), item], this) ){
this.toolbar.addModifier( action, tag );
noModifier = false;
}
} else if( typeOf(modify) == 'object' && modify.tags ){
var el = element;
do {
var tag = el.tagName.toLowerCase();
if(
(!modify.tags || modify.tags.contains(tag) ) &&
(!modify.withClass || el.hasClass(modify.withClass) ) &&
(
!modify.noClass ||
( typeOf(modify.noClass) == 'string' && !el.hasClass(modify.noClass)) ||
( typeOf(modify.noClass) == 'array' && !modify.noClass.contains(el.get('class')) )
)
){
this.toolbar.addModifier( action, tag );
noModifier = false;
}
}
while ((el = Element.getParent(el)) != null);
}
}
var item = this.toolbar.getItem(action);
if (!item) return;
item.deactivate();
var states = MooEditable.Actions[action]['states'];
if (!states) return;
// custom checkState
if (typeOf(states) == 'function'){
var res = states.attempt([document.id(element), item], this);
if( res != null && res == true ){
item.activate();
}
return;
}
try {
if (this.doc.queryCommandState(action)){
item.activate();
return;
}
} catch(e){}
if (states.tags){
var el = element;
do {
var tag = el.tagName.toLowerCase();
if (states.tags.contains(tag)){
item.activate(tag);
break;
}
}
while ((el = Element.getParent(el)) != null);
}
if (states.css){
var el = element;
do {
var found = false;
for (var prop in states.css){
var css = states.css[prop];
if (el.style[prop.camelCase()].contains(css)){
item.activate(css);
found = true;
}
}
if (found || el.tagName.test(blockEls)) break;
}
while ((el = Element.getParent(el)) != null);
}
}.bind(this));
if( noModifier )
this.toolbar.selectTab(1);
else if( !this.lastElement ||
(this.lastElement.get('tag') != element.get('tag') || this.lastElement.get('class') != element.get('class') ) )
this.toolbar.selectTab(2);
this.lastElement = element;
},
cleanup: function(source){
if (!this.options.cleanup) return source.trim();
do {
var oSource = source;
// replace base URL references: ie localize links
if (this.options.baseURL){
source = source.replace('="' + this.options.baseURL, '="');
}
// Webkit cleanup
source = source.replace(/<br class\="webkit-block-placeholder">/gi, "<br />");
source = source.replace(/<span class="Apple-style-span">(.*)<\/span>/gi, '$1');
source = source.replace(/ class="Apple-style-span"/gi, '');
source = source.replace(/<span style="">/gi, '');
// Remove padded paragraphs
source = source.replace(/<p>\s*<br ?\/?>\s*<\/p>/gi, '<p>\u00a0</p>');
source = source.replace(/<p>( |\s)*<\/p>/gi, '<p>\u00a0</p>');
if (!this.options.semantics){
source = source.replace(/\s*<br ?\/?>\s*<\/p>/gi, '</p>');
}
// Replace improper BRs (only if XHTML : true)
if (this.options.xhtml){
source = source.replace(/<br>/gi, "<br />");
}
if (this.options.semantics){
//remove divs from <li>
if (Browser.ie){
source = source.replace(/<li>\s*<div>(.+?)<\/div><\/li>/g, '<li>$1</li>');
}
//remove stupid apple divs
if (Browser.safari || Browser.chrome){
source = source.replace(/^([\w\s]+.*?)<div>/i, '<p>$1</p><div>');
source = source.replace(/<div>(.+?)<\/div>/ig, '<p>$1</p>');
}
//<p> tags around a list will get moved to after the list
if (!Browser.ie){
//not working properly in safari?
source = source.replace(/<p>[\s\n]*(<(?:ul|ol)>.*?<\/(?:ul|ol)>)(.*?)<\/p>/ig, '$1<p>$2</p>');
source = source.replace(/<\/(ol|ul)>\s*(?!<(?:p|ol|ul|img).*?>)((?:<[^>]*>)?\w.*)$/g, '</$1><p>$2</p>');
}
source = source.replace(/<br[^>]*><\/p>/g, '</p>'); // remove <br>'s that end a paragraph here.
source = source.replace(/<p>\s*(<img[^>]+>)\s*<\/p>/ig, '$1\n'); // if a <p> only contains <img>, remove the <p> tags
//format the source
source = source.replace(/<p([^>]*)>(.*?)<\/p>(?!\n)/g, '<p$1>$2</p>\n'); // break after paragraphs
source = source.replace(/<\/(ul|ol|p)>(?!\n)/g, '</$1>\n'); // break after </p></ol></ul> tags
source = source.replace(/><li>/g, '>\n\t<li>'); // break and indent <li>
source = source.replace(/([^\n])<\/(ol|ul)>/g, '$1\n</$2>'); //break before </ol></ul> tags
source = source.replace(/([^\n])<img/ig, '$1\n<img'); // move images to their own line
source = source.replace(/^\s*$/g, ''); // delete empty lines in the source code (not working in opera)
}
// Remove leading and trailing BRs
source = source.replace(/<br ?\/?>$/gi, '');
source = source.replace(/^<br ?\/?>/gi, '');
// Remove useless BRs
if (this.options.paragraphise) source = source.replace(/(h[1-6]|p|div|address|pre|li|ol|ul|blockquote|center|dl|dt|dd)><br ?\/?>/gi, '$1>');
// Remove BRs right before the end of blocks
source = source.replace(/<br ?\/?>\s*<\/(h1|h2|h3|h4|h5|h6|li|p)/gi, '</$1');
// Semantic conversion
source = source.replace(/<span style="font-weight: bold;">(.*)<\/span>/gi, '<strong>$1</strong>');
source = source.replace(/<span style="font-style: italic;">(.*)<\/span>/gi, '<em>$1</em>');
source = source.replace(/<b\b[^>]*>(.*?)<\/b[^>]*>/gi, '<strong>$1</strong>');
source = source.replace(/<i\b[^>]*>(.*?)<\/i[^>]*>/gi, '<em>$1</em>');
source = source.replace(/<u\b[^>]*>(.*?)<\/u[^>]*>/gi, '<span style="text-decoration: underline;">$1</span>');
source = source.replace(/<strong><span style="font-weight: normal;">(.*)<\/span><\/strong>/gi, '$1');
source = source.replace(/<em><span style="font-weight: normal;">(.*)<\/span><\/em>/gi, '$1');
source = source.replace(/<span style="text-decoration: underline;"><span style="font-weight: normal;">(.*)<\/span><\/span>/gi, '$1');
source = source.replace(/<strong style="font-weight: normal;">(.*)<\/strong>/gi, '$1');
source = source.replace(/<em style="font-weight: normal;">(.*)<\/em>/gi, '$1');
// Replace uppercase element names with lowercase
source = source.replace(/<[^> ]*/g, function(match){return match.toLowerCase();});
// Replace uppercase attribute names with lowercase
source = source.replace(/<[^>]*>/g, function(match){
match = match.replace(/ [^=]+=/g, function(match2){return match2.toLowerCase();});
return match;
});
// Put quotes around unquoted attributes
source = source.replace(/<[^!][^>]*>/g, function(match){
match = match.replace(/( [^=]+=)([^"][^ >]*)/g, "$1\"$2\"");
return match;
});
//make img tags xhtml compatible <img>,<img></img> -> <img/>
if (this.options.xhtml){
source = source.replace(/<img([^>]+)(\s*[^\/])>(<\/img>)*/gi, '<img$1$2 />');
}
//remove double <p> tags and empty <p> tags
source = source.replace(/<p>(?:\s*)<p>/g, '<p>');