forked from ckeditor/ckeditor4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheditable.js
1632 lines (1345 loc) · 52.7 KB
/
editable.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
/**
* @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function() {
/**
* Editable class which provides all editing related activities by
* the `contenteditable` element, dynamically get attached to editor instance.
*
* @class CKEDITOR.editable
* @extends CKEDITOR.dom.element
*/
CKEDITOR.editable = CKEDITOR.tools.createClass({
base: CKEDITOR.dom.element,
/**
* The constructor hold only generic editable creation logic that are commonly shared among all different editable elements.
*
* @constructor Creates an editable class instance.
* @param {CKEDITOR.editor} editor The editor instance on which the editable operates.
* @param {HTMLElement/CKEDITOR.dom.element} element Any DOM element that been used as the editor's
* editing container, e.g. it could be either an HTML element with the `contenteditable` attribute
* set to the true that handles wysiwyg editing or a `<textarea>` element that handles source editing.
*/
$: function( editor, element ) {
// Transform the element into a CKEDITOR.dom.element instance.
this.base( element.$ || element );
this.editor = editor;
/**
* Indicate whether the editable element has gained focus.
*
* @property {Boolean} hasFocus
*/
this.hasFocus = false;
// The bootstrapping logic.
this.setup();
},
proto: {
focus: function() {
// [IE] Use instead "setActive" method to focus the editable if it belongs to
// the host page document, to avoid bringing an unexpected scroll.
this.$[ CKEDITOR.env.ie && this.getDocument().equals( CKEDITOR.document ) ? 'setActive' : 'focus' ]();
// Remedy if Safari doens't applies focus properly. (#279)
if ( CKEDITOR.env.safari && !this.isInline() ) {
var active = CKEDITOR.document.getActive();
if ( !active.equals( this.getWindow().getFrame() ) ) {
this.getWindow().focus();
}
}
},
/**
* Overrides {@link CKEDITOR.dom.element#on} to have special `focus/blur` handling.
* The `focusin/focusout` events are used in IE to replace regular `focus/blur` events
* because we want to avoid the asynchronous nature of later ones.
*/
on: function( name, fn ) {
var args = Array.prototype.slice.call( arguments, 0 );
if ( CKEDITOR.env.ie && ( /^focus|blur$/ ).exec( name ) ) {
name = name == 'focus' ? 'focusin' : 'focusout';
// The "focusin/focusout" events bubbled, e.g. If there are elements with layout
// they fire this event when clicking in to edit them but it must be ignored
// to allow edit their contents. (#4682)
fn = isNotBubbling( fn, this );
args[ 0 ] = name;
args[ 1 ] = fn;
}
return CKEDITOR.dom.element.prototype.on.apply( this, args );
},
/**
* Registers an event listener that needs to be removed on detaching.
*
* @see CKEDITOR.event#on
*/
attachListener: function( obj, event, fn, scope, listenerData, priority ) {
!this._.listeners && ( this._.listeners = [] );
// Register the listener.
var args = Array.prototype.slice.call( arguments, 1 );
this._.listeners.push( obj.on.apply( obj, args ) );
},
/**
* Remove all event listeners registered from {@link #attachListener}.
*/
clearListeners: function() {
var listeners = this._.listeners;
// Don't get broken by this.
try {
while ( listeners.length )
listeners.pop().removeListener();
} catch ( e ) {}
},
/**
* Restore all attribution changes made by {@link #changeAttr }.
*/
restoreAttrs : function() {
var changes = this._.attrChanges, orgVal;
for ( var attr in changes )
{
if ( changes.hasOwnProperty( attr ) )
{
orgVal = changes[ attr ];
// Restore original attribute.
orgVal !== null ? this.setAttribute( attr, orgVal ) : this.removeAttribute( attr );
}
}
},
/**
* Adds a CSS class name to this editable that needs to be removed on detaching.
*
* @param {String} className The class name to be added.
* @see CKEDITOR.dom.element#addClass
*/
attachClass: function( cls ) {
var classes = this.getCustomData( 'classes' );
if ( !this.hasClass( cls ) ) {
!classes && ( classes = [] ), classes.push( cls );
this.setCustomData( 'classes', classes );
this.addClass( cls );
}
},
/**
* Make an attribution change that would be reverted on editable detaching.
* @param {String} attr The attribute name to be changed.
* @param {String} val The value of specified attribute.
*/
changeAttr : function( attr, val ) {
var orgVal = this.getAttribute( attr );
if ( val !== orgVal )
{
!this._.attrChanges && ( this._.attrChanges = {} );
// Saved the original attribute val.
if ( !( attr in this._.attrChanges ) )
this._.attrChanges[ attr ] = orgVal;
this.setAttribute( attr, val );
}
},
/**
* @see CKEDITOR.editor#insertHtml
*/
insertHtml: function( data, mode ) {
beforeInsert( this );
// Default mode is 'html'.
insert( this, mode == 'text' ? 'text' : 'html', data );
},
/**
* @see CKEDITOR.editor#insertText
*/
insertText: function( text ) {
beforeInsert( this );
var editor = this.editor,
mode = editor.getSelection().getStartElement().hasAscendant( 'pre', true ) ? CKEDITOR.ENTER_BR : editor.config.enterMode,
isEnterBrMode = mode == CKEDITOR.ENTER_BR,
tools = CKEDITOR.tools;
// CRLF -> LF
var html = tools.htmlEncode( text.replace( /\r\n/g, '\n' ) );
// Tab ->   x 4;
html = html.replace( /\t/g, ' ' );
var paragraphTag = mode == CKEDITOR.ENTER_P ? 'p' : 'div';
// Two line-breaks create one paragraphing block.
if ( !isEnterBrMode ) {
var duoLF = /\n{2}/g;
if ( duoLF.test( html ) )
{
var openTag = '<' + paragraphTag + '>', endTag = '</' + paragraphTag + '>';
html = openTag + html.replace( duoLF, function() { return endTag + openTag; } ) + endTag;
}
}
// One <br> per line-break.
html = html.replace( /\n/g, '<br>' );
// Compensate padding <br> at the end of block, avoid loosing them during insertion.
if ( !isEnterBrMode ) {
html = html.replace( new RegExp( '<br>(?=</' + paragraphTag + '>)' ), function( match ) {
return tools.repeat( match, 2 );
});
}
// Preserve spaces at the ends, so they won't be lost after insertion (merged with adjacent ones).
html = html.replace( /^ | $/g, ' ' );
// Finally, preserve whitespaces that are to be lost.
html = html.replace( /(>|\s) /g, function( match, before ) {
return before + ' ';
} ).replace( / (?=<)/g, ' ' );
insert( this, 'text', html );
},
/**
* @see CKEDITOR.editor#insertElement
*/
insertElement: function( element ) {
beforeInsert( this );
var editor = this.editor,
enterMode = editor.config.enterMode,
selection = editor.getSelection(),
ranges = selection.getRanges(),
elementName = element.getName(),
isBlock = CKEDITOR.dtd.$block[ elementName ];
var range, clone, lastElement;
for ( var i = ranges.length - 1; i >= 0; i-- ) {
range = ranges[ i ];
if ( !range.checkReadOnly() ) {
// Remove the original contents, merge split nodes.
range.deleteContents( 1 );
clone = !i && element || element.clone( 1 );
// If we're inserting a block at dtd-violated position, split
// the parent blocks until we reach blockLimit.
var current, dtd;
if ( isBlock ) {
while ( ( current = range.getCommonAncestor( 0, 1 ) ) &&
( dtd = CKEDITOR.dtd[ current.getName() ] ) &&
!( dtd && dtd[ elementName ] ) ) {
// Split up inline elements.
if ( current.getName() in CKEDITOR.dtd.span )
range.splitElement( current );
// If we're in an empty block which indicate a new paragraph,
// simply replace it with the inserting block.(#3664)
else if ( range.checkStartOfBlock() && range.checkEndOfBlock() ) {
range.setStartBefore( current );
range.collapse( true );
current.remove();
} else
range.splitBlock( enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p', editor.editable() );
}
}
// Insert the new node.
range.insertNode( clone );
// Save the last element reference so we can make the
// selection later.
if ( !lastElement )
lastElement = clone;
}
}
if ( lastElement ) {
range.moveToPosition( lastElement, CKEDITOR.POSITION_AFTER_END );
// If we're inserting a block element, the new cursor position must be
// optimized. (#3100,#5436,#8950)
if ( isBlock ) {
var next = lastElement.getNext( isNotEmpty );
if ( next && next.type == CKEDITOR.NODE_ELEMENT &&
next.is( CKEDITOR.dtd.$block ) ) {
// If the next one is a text block, move cursor to the start of it's content.
if ( next.getDtd()[ '#' ] )
range.moveToElementEditStart( next );
// Otherwise move cursor to the before end of the last element.
else
range.moveToElementEditEnd( lastElement );
}
// Open a new line if the block is inserted at the end of parent.
else if ( !next && enterMode != CKEDITOR.ENTER_BR ) {
next = range.fixBlock( true, enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' );
range.moveToElementEditStart( next );
}
}
}
selection.selectRanges( [ range ] );
// Do not scroll after inserting, because Opera may fail on certain element (e.g. iframe/iframe.html).
afterInsert( this, CKEDITOR.env.opera );
},
/**
* @see CKEDITOR.editor#setData
*/
setData: function( data, isSnapshot ) {
if ( !isSnapshot && this.editor.dataProcessor )
data = this.editor.dataProcessor.toHtml( data );
this.setHtml( data );
this.editor.fire( 'dataReady' );
},
/**
* @see CKEDITOR.editor#getData
*/
getData: function( isSnapshot ) {
var data = this.getHtml();
if ( !isSnapshot && this.editor.dataProcessor )
data = this.editor.dataProcessor.toDataFormat( data );
return data;
},
/**
* Change the read-only state on this editable.
*
* @param {Boolean} isReadOnly
*/
setReadOnly: function( isReadOnly ) {
this.setAttribute( 'contenteditable', !isReadOnly );
},
/**
* Detach this editable object from the DOM (remove classes, listeners, etc.)
*/
detach: function() {
// Cleanup the element.
this.removeClass( 'cke_editable' );
// Save the editor reference which will be lost after
// calling detach from super class.
var editor = this.editor;
this._.detach();
delete editor.document;
delete editor.window;
},
/**
* Check if the editable is one of the host page element, indicates the
* an inline editing environment.
*
* @returns {Boolean}
*/
isInline : function () {
return this.getDocument().equals( CKEDITOR.document );
},
/**
* Editable element bootstrapping.
*
* @private
*/
setup: function() {
var editor = this.editor;
// Handle the load/read of editor data/snapshot.
this.attachListener( editor, 'beforeGetData', function() {
var data = this.getData();
// Post processing html output of wysiwyg editable.
if ( !this.is( 'textarea' ) ) {
// Reset empty if the document contains only one empty paragraph.
if ( editor.config.ignoreEmptyParagraph !== false )
data = data.replace( emptyParagraphRegexp, function( match, lookback ) { return lookback; } );
}
editor.setData( data, null, 1 );
}, this );
this.attachListener( editor, 'getSnapshot', function( evt ) {
evt.data = this.getData( 1 );
}, this );
this.attachListener( editor, 'afterSetData', function() {
this.setData( editor.getData( 1 ) );
}, this );
this.attachListener( editor, 'loadSnapshot', function( evt ) {
this.setData( evt.data, 1 );
}, this );
// Delegate editor focus/blur to editable.
this.attachListener( editor, 'beforeFocus', function() {
var sel = editor.getSelection(),
ieSel = sel && sel.getNative();
// IE considers control-type element as separate
// focus host when selected, avoid destroying the
// selection in such case. (#5812) (#8949)
if ( ieSel && ieSel.type == 'Control' )
return;
this.focus();
}, this );
this.attachListener( editor, 'insertHtml', function( evt ) {
this.insertHtml( evt.data.dataValue, evt.data.mode );
}, this );
this.attachListener( editor, 'insertElement', function( evt ) {
this.insertElement( evt.data );
}, this );
this.attachListener( editor, 'insertText', function( evt ) {
this.insertText( evt.data );
}, this );
// Update editable state.
this.setReadOnly( editor.readOnly );
// The editable class.
this.attachClass( 'cke_editable' );
// The element mode css class.
this.attachClass( editor.elementMode == CKEDITOR.ELEMENT_MODE_INLINE ?
'cke_editable_inline' :
editor.elementMode == CKEDITOR.ELEMENT_MODE_REPLACE ||
editor.elementMode == CKEDITOR.ELEMENT_MODE_APPENDTO ?
'cke_editable_themed' : ''
);
this.attachClass( 'cke_contents_' + editor.config.contentsLangDirection );
// Setup editor keystroke handlers on this element.
var keystrokeHandler = editor.keystrokeHandler;
keystrokeHandler.blockedKeystrokes[ 8 ] = editor.readOnly;
editor.keystrokeHandler.attach( this );
// Update focus states.
this.on( 'blur', function( evt ) {
// Opera might raise undesired blur event on editable, check if it's
// really blurred, otherwise cancel the event. (#9459)
if ( CKEDITOR.env.opera ) {
var active = CKEDITOR.document.getActive();
if ( active.equals( this.isInline() ? this : this.getWindow().getFrame() ) ) {
evt.cancel();
return;
}
}
this.hasFocus = false;
}, null, null, -1 );
this.on( 'focus', function() {
this.hasFocus = true;
}, null, null, -1 );
// Register to focus manager.
editor.focusManager.add( this );
// Inherit the initial focus on editable element.
if ( this.equals( CKEDITOR.document.getActive() ) ) {
this.hasFocus = true;
// Pending until this editable has attached.
editor.once( 'contentDom', function() {
editor.focusManager.focus();
});
}
// The above is all we'll be doing for a <textarea> editable.
if ( this.is( 'textarea' ) )
return;
// The DOM document which the editing acts upon.
editor.document = this.getDocument();
editor.window = this.getWindow();
var doc = editor.document;
this.changeAttr( 'spellcheck', !editor.config.disableNativeSpellChecker );
// Apply contents direction on demand, with original direction saved.
var dir = editor.config.contentsLangDirection;
if ( this.getDirection( 1 ) != dir )
this.changeAttr( 'dir', dir );
// Apply tab index on demand, with original direction saved.
if ( editor.document.equals( CKEDITOR.document ) ) {
// tabIndex of the editable is different than editor's one.
// Update the attribute of the editable.
this.changeAttr( 'tabindex', editor.tabIndex );
}
// Create the content stylesheet for this document.
var styles = CKEDITOR.getCss();
if ( styles ) {
var head = doc.getHead();
if ( !head.getCustomData( 'stylesheet' ) ) {
var sheet = doc.appendStyleText( styles );
sheet = new CKEDITOR.dom.element( sheet.ownerNode || sheet.owningElement );
head.setCustomData( 'stylesheet', sheet );
sheet.data( 'cke-temp', 1 );
}
}
// Update the stylesheet sharing count.
var ref = doc.getCustomData( 'stylesheet_ref' ) || 0;
doc.setCustomData( 'stylesheet_ref', ref + 1 );
// Pass this configuration to styles system.
this.setCustomData( 'cke_includeReadonly', !editor.config.disableReadonlyStyling );
// Prevent the browser opening read-only links. (#6032)
this.attachListener( this, 'click', function( ev ) {
ev = ev.data;
var target = ev.getTarget();
if ( target.is( 'a' ) && ev.$.button != 2 && target.isReadOnly() )
ev.preventDefault();
});
// Override keystrokes which should have deletion behavior
// on fully selected element . (#4047) (#7645)
this.attachListener( editor, 'key', function( evt ) {
if ( editor.readOnly )
return false;
var keyCode = evt.data.keyCode, isHandled;
// Backspace OR Delete.
if ( keyCode in { 8:1,46:1 } ) {
var sel = editor.getSelection(),
selected,
range = sel.getRanges()[ 0 ],
path = range.startPath(),
block,
parent,
next,
rtl = keyCode == 8;
// Remove the entire list/table on fully selected content. (#7645)
if ( ( selected = getSelectedTableList( sel ) ) ) {
// Make undo snapshot.
editor.fire( 'saveSnapshot' );
// Delete any element that 'hasLayout' (e.g. hr,table) in IE8 will
// break up the selection, safely manage it here. (#4795)
range.moveToPosition( selected, CKEDITOR.POSITION_BEFORE_START );
// Remove the control manually.
selected.remove();
range.select();
editor.fire( 'saveSnapshot' );
isHandled = 1;
}
else if ( range.collapsed )
{
// Handle the following special cases: (#6217)
// 1. Del/Backspace key before/after table;
// 2. Backspace Key after start of table.
if ( ( block = path.block ) &&
range[ rtl ? 'checkStartOfBlock' : 'checkEndOfBlock' ]() &&
( next = block[ rtl ? 'getPrevious' : 'getNext' ]( isNotWhitespace ) ) &&
next.is( 'table' ) )
{
editor.fire( 'saveSnapshot' );
// Remove the current empty block.
if ( range[ rtl ? 'checkEndOfBlock' : 'checkStartOfBlock' ]() )
block.remove();
// Move cursor to the beginning/end of table cell.
range[ 'moveToElementEdit' + ( rtl ? 'End' : 'Start' ) ]( next );
range.select();
editor.fire( 'saveSnapshot' );
isHandled = 1;
}
else if ( path.blockLimit && path.blockLimit.is( 'td' ) &&
( parent = path.blockLimit.getAscendant( 'table' ) ) &&
range.checkBoundaryOfElement( parent, rtl ? CKEDITOR.START : CKEDITOR.END ) &&
( next = parent[ rtl ? 'getPrevious' : 'getNext' ]( isNotWhitespace ) ) )
{
editor.fire( 'saveSnapshot' );
// Move cursor to the end of previous block.
range[ 'moveToElementEdit' + ( rtl ? 'End' : 'Start' ) ]( next );
// Remove any previous empty block.
if ( range.checkStartOfBlock() && range.checkEndOfBlock() )
next.remove();
else
range.select();
editor.fire( 'saveSnapshot' );
isHandled = 1;
}
// BACKSPACE/DEL pressed at the start/end of table cell.
else if ( ( parent = path.contains( [ 'td', 'th', 'caption' ] ) ) &&
range.checkBoundaryOfElement( parent, rtl ? CKEDITOR.START : CKEDITOR.END ) ) {
next = parent[ rtl ? 'getPreviousSourceNode' : 'getNextSourceNode' ]( 1, CKEDITOR.NODE_ELEMENT );
if ( next && !next.isReadOnly() && range.root.contains( next ) ) {
range[ rtl ? 'moveToElementEditEnd' : 'moveToElementEditStart' ]( next );
range.select();
isHandled = 1;
}
}
}
}
return !isHandled;
});
// Prevent automatic submission in IE #6336
CKEDITOR.env.ie && this.attachListener( this, 'click', blockInputClick );
// Gecko/Webkit need some help when selecting control type elements. (#3448)
if ( !( CKEDITOR.env.ie || CKEDITOR.env.opera ) ) {
this.attachListener( this, 'mousedown', function( ev ) {
var control = ev.data.getTarget();
if ( control.is( 'img', 'hr', 'input', 'textarea', 'select' ) ) {
editor.getSelection().selectElement( control );
// Prevent focus from stealing from the editable. (#9515)
if ( control.is( 'input', 'textarea', 'select' ) )
ev.data.preventDefault();
}
});
}
// Prevent right click from selecting an empty block even
// when selection is anchored inside it. (#5845)
if ( CKEDITOR.env.gecko ) {
this.attachListener( this, 'mouseup', function( ev ) {
if ( ev.data.$.button == 2 ) {
var target = ev.data.getTarget();
if ( !target.getOuterHtml().replace( emptyParagraphRegexp, '' ) ) {
var range = editor.createRange();
range.moveToElementEditStart( target );
range.select( true );
}
}
});
}
// Webkit: avoid from editing form control elements content.
if ( CKEDITOR.env.webkit ) {
// Prevent from tick checkbox/radiobox/select
this.attachListener( this, 'click', function( ev ) {
if ( ev.data.getTarget().is( 'input', 'select' ) )
ev.data.preventDefault();
});
// Prevent from editig textfield/textarea value.
this.attachListener( this, 'mouseup', function( ev ) {
if ( ev.data.getTarget().is( 'input', 'textarea' ) )
ev.data.preventDefault();
});
}
}
},
_: {
detach: function() {
// Update the editor cached data with current data.
this.editor.setData( this.editor.getData(), 0, 1 );
this.clearListeners();
this.restoreAttrs();
// Cleanup our custom classes.
var classes;
if ( ( classes = this.removeCustomData( 'classes' ) ) ) {
while ( classes.length )
this.removeClass( classes.pop() );
}
// Remove contents stylesheet from document if it's the last usage.
var doc = this.getDocument(),
head = doc.getHead();
if ( head.getCustomData( 'stylesheet' ) ) {
var refs = doc.getCustomData( 'stylesheet_ref' );
if ( !( --refs ) ) {
doc.removeCustomData( 'stylesheet_ref' );
var sheet = head.removeCustomData( 'stylesheet' );
sheet.remove();
} else
doc.setCustomData( 'stylesheet_ref', refs );
}
// Free up the editor reference.
delete this.editor;
}
}
});
/**
* Create, retrieve or detach an editable element of the editor,
* this method should always be used instead of calling directly {@link CKEDITOR.editable}.
*
* @method editable
* @member CKEDITOR.editor
* @param {CKEDITOR.dom.element/CKEDITOR.editable} elementOrEditable The
* DOM element to become the editable or a {@link CKEDITOR.editable} object.
*/
CKEDITOR.editor.prototype.editable = function( element ) {
var editable = this._.editable;
// This editor has already associated with
// an editable element, silently fails.
if ( editable && element )
return 0;
if ( arguments.length ) {
editable = this._.editable = element ? ( element instanceof CKEDITOR.editable ? element : new CKEDITOR.editable( this, element ) ) :
// Detach the editable from editor.
( editable && editable.detach(), null );
}
// Just retrieve the editable.
return editable;
};
// Auto-fixing block-less content by wrapping paragraph (#3190), prevent
// non-exitable-block by padding extra br.(#3189)
// Returns truly value when dom was changed, falsy otherwise.
function fixDom( evt ) {
var editor = evt.editor,
editable = editor.editable(),
path = evt.data.path,
blockLimit = path.blockLimit,
selection = evt.data.selection,
range = selection.getRanges()[ 0 ],
enterMode = editor.config.enterMode;
if ( CKEDITOR.env.gecko ) {
// v3: check if this is needed.
// activateEditing( editor );
// Ensure bogus br could help to move cursor (out of styles) to the end of block. (#7041)
var pathBlock = path.block || path.blockLimit || path.root,
lastNode = pathBlock && pathBlock.getLast( isNotEmpty );
// Check some specialities of the current path block:
// 1. It is really displayed as block; (#7221)
// 2. It doesn't end with one inner block; (#7467)
// 3. It doesn't have bogus br yet.
if ( pathBlock && pathBlock.isBlockBoundary() &&
!( lastNode && lastNode.type == CKEDITOR.NODE_ELEMENT && lastNode.isBlockBoundary() ) &&
!pathBlock.is( 'pre' ) && !pathBlock.getBogus() ) {
pathBlock.appendBogus();
}
}
// When we're in block enter mode, a new paragraph will be established
// to encapsulate inline contents inside editable. (#3657)
if ( editor.config.autoParagraph !== false &&
enterMode != CKEDITOR.ENTER_BR && range.collapsed &&
editable.equals( blockLimit ) && !path.block ) {
var testRng = range.clone();
testRng.enlarge( CKEDITOR.ENLARGE_BLOCK_CONTENTS );
var walker = new CKEDITOR.dom.walker( testRng );
walker.guard = function( node ) {
return !isNotEmpty( node ) ||
node.type == CKEDITOR.NODE_COMMENT ||
node.isReadOnly();
};
// 1. Inline content discovered under cursor;
// 2. Empty editable.
if ( !walker.checkForward() ||
testRng.checkStartOfBlock() && testRng.checkEndOfBlock() ) {
var fixedBlock = range.fixBlock( true, editor.config.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' );
// For IE, we should remove any filler node which was introduced before.
if ( CKEDITOR.env.ie ) {
var first = fixedBlock.getFirst( isNotEmpty );
if ( first && isNbsp( first ) ) {
first.remove();
}
}
range.select();
// Cancel this selection change in favor of the next (correct). (#6811)
evt.cancel();
}
}
}
function blockInputClick( evt ) {
var element = evt.data.getTarget();
if ( element.is( 'input' ) ) {
var type = element.getAttribute( 'type' );
if ( type == 'submit' || type == 'reset' )
evt.data.preventDefault();
}
}
function isBlankParagraph( block ) {
return block.getOuterHtml().match( emptyParagraphRegexp );
}
function isNotEmpty( node ) {
return isNotWhitespace( node ) && isNotBookmark( node );
}
function isNbsp( node ) {
return node.type == CKEDITOR.NODE_TEXT && CKEDITOR.tools.trim( node.getText() ).match( /^(?: |\xa0)$/ );
}
// Elements that could blink the cursor anchoring beside it, like hr, page-break. (#6554)
function nonEditable( element ) {
return element.isBlockBoundary() && CKEDITOR.dtd.$empty[ element.getName() ];
}
function isNotBubbling( fn, src ) {
return function( evt ) {
var other = CKEDITOR.dom.element.get( evt.data.$.toElement || evt.data.$.fromElement || evt.data.$.relatedTarget );
if ( ! ( other && ( src.equals( other ) || src.contains( other ) ) ) )
fn.call( this, evt );
};
}
// Check if the entire table/list contents is selected.
function getSelectedTableList( sel ) {
var selected,
range = sel.getRanges()[ 0 ],
editable = sel.root,
path = range.startPath(),
structural = { table:1,ul:1,ol:1,dl:1 };
var isBogus = CKEDITOR.dom.walker.bogus();
if ( path.contains( structural ) ) {
// Enlarging the start boundary.
var walkerRng = range.clone();
walkerRng.collapse( 1 );
walkerRng.setStartAt( editable, CKEDITOR.POSITION_AFTER_START );
var walker = new CKEDITOR.dom.walker( walkerRng ),
// Check the range is at the inner boundary of the structural element.
guard = function( walker, isEnd ) {
return function( node, isWalkOut ) {
if ( isWalkOut && node.type == CKEDITOR.NODE_ELEMENT && node.is( structural ) )
selected = node;
if ( isNotEmpty( node ) && !isWalkOut && !( isEnd && isBogus( node ) ) )
return false;
};
};
walker.guard = guard( walker );
walker.checkBackward();
if ( selected ) {
walkerRng = range.clone();
walkerRng.collapse();
walkerRng.setEndAt( editable, CKEDITOR.POSITION_BEFORE_END );
walker = new CKEDITOR.dom.walker( walkerRng );
walker.guard = guard( walker, 1 );
selected = 0;
walker.checkForward();
return selected;
}
}
return null;
}
// Matching an empty paragraph at the end of document.
var emptyParagraphRegexp = /(^|<body\b[^>]*>)\s*<(p|div|address|h\d|center|pre)[^>]*>\s*(?:<br[^>]*>| |\u00A0| )?\s*(:?<\/\2>)?\s*(?=$|<\/body>)/gi;
var isNotWhitespace = CKEDITOR.dom.walker.whitespaces( true ),
isNotBookmark = CKEDITOR.dom.walker.bookmark( false, true );
CKEDITOR.on( 'instanceLoaded', function( evt ) {
var editor = evt.editor;
// and flag that the element was locked by our code so it'll be editable by the editor functions (#6046).
editor.on( 'insertElement', function( evt ) {
var element = evt.data;
if ( element.type == CKEDITOR.NODE_ELEMENT && ( element.is( 'input' ) || element.is( 'textarea' ) ) ) {
// // The element is still not inserted yet, force attribute-based check.
if ( element.getAttribute( 'contentEditable' ) != "false" )
element.data( 'cke-editable', element.hasAttribute( 'contenteditable' ) ? 'true' : '1' );
element.setAttribute( 'contentEditable', false );
}
});
editor.on( 'selectionChange', function( evt ) {
if ( editor.readOnly )
return;
// Auto fixing on some document structure weakness to enhance usabilities. (#3190 and #3189)
var sel = editor.getSelection();
// Do it only when selection is not locked. (#8222)
if ( sel && !sel.isLocked ) {
var isDirty = editor.checkDirty();
// Lock undoM before touching DOM to prevent
// recording these changes as separate snapshot.
editor.fire( 'lockSnapshot' );
fixDom( evt );
editor.fire( 'unlockSnapshot' );
!isDirty && editor.resetDirty();
}
});
});
// #9222: Show text cursor in Gecko.
// Show default cursor over control elements on all non-IEs.
CKEDITOR.addCss( '.cke_editable{cursor:text}.cke_editable img,.cke_editable input,.cke_editable textarea{cursor:default}' );
//
// Functions related to insertXXX methods
//
var insert = (function() {
'use strict';
var DTD = CKEDITOR.dtd;
// Inserts the given (valid) HTML into the range position (with range content deleted),
// guarantee it's result to be a valid DOM tree.
function insert( editable, type, data ) {
var editor = editable.editor,
doc = editable.getDocument(),
selection = editor.getSelection(),
// HTML insertion only considers the first range.
// Note: getRanges will be overwritten for tests since we want to test
// custom ranges and bypass native selections.
// TODO what should we do with others? Remove?
range = selection.getRanges()[ 0 ];
// Check range spans in non-editable.
if ( range.checkReadOnly() )
return;
// RANGE PREPARATIONS
var path = new CKEDITOR.dom.elementPath( range.startContainer, range.root ),
// Let root be the nearest block that's impossible to be split
// during html processing.
blockLimit = path.blockLimit || range.root,
// The "state" value.
that = {
type: type,
editable: editable,
editor: editor,
range: range,
blockLimit: blockLimit,
// During pre-processing / preparations startContainer of affectedRange should be placed
// in this element in which inserted or moved (in case when we merge blocks) content
// could create situation that will need merging inline elements.
// Examples:
// <div><b>A</b>^B</div> + <b>C</b> => <div><b>A</b><b>C</b>B</div> - affected container is <div>.
// <p><b>A[B</b></p><p><b>C]D</b></p> + E => <p><b>AE</b></p><p><b>D</b></p> =>
// <p><b>AE</b><b>D</b></p> - affected container is <p> (in text mode).
mergeCandidates: [],
zombies: []
};
prepareRangeToDataInsertion( that );
// DATA PROCESSING
// Select range and stop execution.
if ( data ) {
processDataForInsertion( that, data );
// DATA INSERTION
insertDataIntoRange( that );
}
// FINAL CLEANUP
// Set final range position and clean up.
cleanupAfterInsertion( that );
// Make the final range selection.
range.select();
afterInsert( editable );
}
// Prepare range to its data deletion.
// Delete its contents.
// Prepare it to insertion.
function prepareRangeToDataInsertion( that ) {
var range = that.range,
mergeCandidates = that.mergeCandidates,
node, marker, path, startPath, endPath, previous, bm;