-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
downcastwriter.js
1914 lines (1667 loc) · 73.8 KB
/
downcastwriter.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-2020, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module module:engine/view/downcastwriter
*/
import Position from './position';
import Range from './range';
import Selection from './selection';
import ContainerElement from './containerelement';
import AttributeElement from './attributeelement';
import EmptyElement from './emptyelement';
import UIElement from './uielement';
import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
import DocumentFragment from './documentfragment';
import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
import Text from './text';
import EditableElement from './editableelement';
import { isPlainObject } from 'lodash-es';
/**
* View downcast writer.
*
* It provides a set of methods used to manipulate view nodes.
*
* Do not create an instance of this writer manually. To modify a view structure, use
* the {@link module:engine/view/view~View#change `View#change()`} block.
*
* The `DowncastWriter` is designed to work with semantic views which are the views that were/are being downcasted from the model.
* To work with ordinary views (e.g. parsed from a pasted content) use the
* {@link module:engine/view/upcastwriter~UpcastWriter upcast writer}.
*
* Read more about changing the view in the {@glink framework/guides/architecture/editing-engine#changing-the-view Changing the view}
* section of the {@glink framework/guides/architecture/editing-engine Editing engine architecture} guide.
*/
export default class DowncastWriter {
/**
* @param {module:engine/view/document~Document} document The view document instance.
*/
constructor( document ) {
/**
* The view document instance in which this writer operates.
*
* @readonly
* @type {module:engine/view/document~Document}
*/
this.document = document;
/**
* Holds references to the attribute groups that share the same {@link module:engine/view/attributeelement~AttributeElement#id id}.
* The keys are `id`s, the values are `Set`s holding {@link module:engine/view/attributeelement~AttributeElement}s.
*
* @private
* @type {Map.<String,Set>}
*/
this._cloneGroups = new Map();
}
/**
* Sets {@link module:engine/view/documentselection~DocumentSelection selection's} ranges and direction to the
* specified location based on the given {@link module:engine/view/selection~Selectable selectable}.
*
* Usage:
*
* // Sets selection to the given range.
* const range = writer.createRange( start, end );
* writer.setSelection( range );
*
* // Sets backward selection to the given range.
* const range = writer.createRange( start, end );
* writer.setSelection( range );
*
* // Sets selection to given ranges.
* const ranges = [ writer.createRange( start1, end2 ), writer.createRange( start2, end2 ) ];
* writer.setSelection( range );
*
* // Sets selection to the other selection.
* const otherSelection = writer.createSelection();
* writer.setSelection( otherSelection );
*
* // Sets collapsed selection at the given position.
* const position = writer.createPositionFromPath( root, path );
* writer.setSelection( position );
*
* // Sets collapsed selection at the position of given item and offset.
* const paragraph = writer.createContainerElement( 'p' );
* writer.setSelection( paragraph, offset );
*
* Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
* that element and ends after the last child of that element.
*
* writer.setSelection( paragraph, 'in' );
*
* Creates a range on the {@link module:engine/view/item~Item item} which starts before the item and ends just after the item.
*
* writer.setSelection( paragraph, 'on' );
*
* // Removes all ranges.
* writer.setSelection( null );
*
* `DowncastWriter#setSelection()` allow passing additional options (`backward`, `fake` and `label`) as the last argument.
*
* // Sets selection as backward.
* writer.setSelection( range, { backward: true } );
*
* // Sets selection as fake.
* // Fake selection does not render as browser native selection over selected elements and is hidden to the user.
* // This way, no native selection UI artifacts are displayed to the user and selection over elements can be
* // represented in other way, for example by applying proper CSS class.
* writer.setSelection( range, { fake: true } );
*
* // Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM
* // (and be properly handled by screen readers).
* writer.setSelection( range, { fake: true, label: 'foo' } );
*
* @param {module:engine/view/selection~Selectable} selectable
* @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
* @param {Object} [options]
* @param {Boolean} [options.backward] Sets this selection instance to be backward.
* @param {Boolean} [options.fake] Sets this selection instance to be marked as `fake`.
* @param {String} [options.label] Label for the fake selection.
*/
setSelection( selectable, placeOrOffset, options ) {
this.document.selection._setTo( selectable, placeOrOffset, options );
}
/**
* Moves {@link module:engine/view/documentselection~DocumentSelection#focus selection's focus} to the specified location.
*
* The location can be specified in the same form as {@link module:engine/view/view~View#createPositionAt view.createPositionAt()}
* parameters.
*
* @param {module:engine/view/item~Item|module:engine/view/position~Position} itemOrPosition
* @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
* first parameter is a {@link module:engine/view/item~Item view item}.
*/
setSelectionFocus( itemOrPosition, offset ) {
this.document.selection._setFocus( itemOrPosition, offset );
}
/**
* Creates a new {@link module:engine/view/text~Text text node}.
*
* writer.createText( 'foo' );
*
* @param {String} data The text's data.
* @returns {module:engine/view/text~Text} The created text node.
*/
createText( data ) {
return new Text( this.document, data );
}
/**
* Creates new {@link module:engine/view/attributeelement~AttributeElement}.
*
* writer.createAttributeElement( 'strong' );
* writer.createAttributeElement( 'a', { href: 'foo.bar' } );
*
* // Make `<a>` element contain other attributes element so the `<a>` element is not broken.
* writer.createAttributeElement( 'a', { href: 'foo.bar' }, { priority: 5 } );
*
* // Set `id` of a marker element so it is not joined or merged with "normal" elements.
* writer.createAttributeElement( 'span', { class: 'my-marker' }, { id: 'marker:my' } );
*
* @param {String} name Name of the element.
* @param {Object} [attributes] Element's attributes.
* @param {Object} [options] Element's options.
* @param {Number} [options.priority] Element's {@link module:engine/view/attributeelement~AttributeElement#priority priority}.
* @param {Number|String} [options.id] Element's {@link module:engine/view/attributeelement~AttributeElement#id id}.
* @returns {module:engine/view/attributeelement~AttributeElement} Created element.
*/
createAttributeElement( name, attributes, options = {} ) {
const attributeElement = new AttributeElement( this.document, name, attributes );
if ( options.priority ) {
attributeElement._priority = options.priority;
}
if ( options.id ) {
attributeElement._id = options.id;
}
return attributeElement;
}
/**
* Creates new {@link module:engine/view/containerelement~ContainerElement}.
*
* writer.createContainerElement( 'p' );
*
* // Create element with custom attributes.
* writer.createContainerElement( 'div', { id: 'foo-bar', 'data-baz': '123' } );
*
* // Create element with custom styles.
* writer.createContainerElement( 'p', { style: 'font-weight: bold; padding-bottom: 10px' } );
*
* // Create element with custom classes.
* writer.createContainerElement( 'p', { class: 'foo bar baz' } );
*
* @param {String} name Name of the element.
* @param {Object} [attributes] Elements attributes.
* @returns {module:engine/view/containerelement~ContainerElement} Created element.
*/
createContainerElement( name, attributes ) {
return new ContainerElement( this.document, name, attributes );
}
/**
* Creates new {@link module:engine/view/editableelement~EditableElement}.
*
* writer.createEditableElement( 'div' );
* writer.createEditableElement( 'div', { id: 'foo-1234' } );
*
* @param {String} name Name of the element.
* @param {Object} [attributes] Elements attributes.
* @returns {module:engine/view/editableelement~EditableElement} Created element.
*/
createEditableElement( name, attributes ) {
const editableElement = new EditableElement( this.document, name, attributes );
editableElement._document = this.document;
return editableElement;
}
/**
* Creates new {@link module:engine/view/emptyelement~EmptyElement}.
*
* writer.createEmptyElement( 'img' );
* writer.createEmptyElement( 'img', { id: 'foo-1234' } );
*
* @param {String} name Name of the element.
* @param {Object} [attributes] Elements attributes.
* @returns {module:engine/view/emptyelement~EmptyElement} Created element.
*/
createEmptyElement( name, attributes ) {
return new EmptyElement( this.document, name, attributes );
}
/**
* Creates new {@link module:engine/view/uielement~UIElement}.
*
* writer.createUIElement( 'span' );
* writer.createUIElement( 'span', { id: 'foo-1234' } );
*
* Custom render function can be provided as third parameter:
*
* writer.createUIElement( 'span', null, function( domDocument ) {
* const domElement = this.toDomElement( domDocument );
* domElement.innerHTML = '<b>this is ui element</b>';
*
* return domElement;
* } );
*
* @param {String} name Name of the element.
* @param {Object} [attributes] Elements attributes.
* @param {Function} [renderFunction] Custom render function.
* @returns {module:engine/view/uielement~UIElement} Created element.
*/
createUIElement( name, attributes, renderFunction ) {
const uiElement = new UIElement( this.document, name, attributes );
if ( renderFunction ) {
uiElement.render = renderFunction;
}
return uiElement;
}
/**
* Adds or overwrite element's attribute with a specified key and value.
*
* writer.setAttribute( 'href', 'http://ckeditor.com', linkElement );
*
* @param {String} key Attribute key.
* @param {String} value Attribute value.
* @param {module:engine/view/element~Element} element
*/
setAttribute( key, value, element ) {
element._setAttribute( key, value );
}
/**
* Removes attribute from the element.
*
* writer.removeAttribute( 'href', linkElement );
*
* @param {String} key Attribute key.
* @param {module:engine/view/element~Element} element
*/
removeAttribute( key, element ) {
element._removeAttribute( key );
}
/**
* Adds specified class to the element.
*
* writer.addClass( 'foo', linkElement );
* writer.addClass( [ 'foo', 'bar' ], linkElement );
*
* @param {Array.<String>|String} className
* @param {module:engine/view/element~Element} element
*/
addClass( className, element ) {
element._addClass( className );
}
/**
* Removes specified class from the element.
*
* writer.removeClass( 'foo', linkElement );
* writer.removeClass( [ 'foo', 'bar' ], linkElement );
*
* @param {Array.<String>|String} className
* @param {module:engine/view/element~Element} element
*/
removeClass( className, element ) {
element._removeClass( className );
}
/**
* Adds style to the element.
*
* writer.setStyle( 'color', 'red', element );
* writer.setStyle( {
* color: 'red',
* position: 'fixed'
* }, element );
*
* **Note**: The passed style can be normalized if
* {@link module:engine/controller/datacontroller~DataController#addStyleProcessorRules a particular style processor rule is enabled}.
* See {@link module:engine/view/stylesmap~StylesMap#set `StylesMap#set()`} for details.
*
* @param {String|Object} property Property name or object with key - value pairs.
* @param {String} [value] Value to set. This parameter is ignored if object is provided as the first parameter.
* @param {module:engine/view/element~Element} element Element to set styles on.
*/
setStyle( property, value, element ) {
if ( isPlainObject( property ) && element === undefined ) {
element = value;
}
element._setStyle( property, value );
}
/**
* Removes specified style from the element.
*
* writer.removeStyle( 'color', element ); // Removes 'color' style.
* writer.removeStyle( [ 'color', 'border-top' ], element ); // Removes both 'color' and 'border-top' styles.
*
* **Note**: This method can work with normalized style names if
* {@link module:engine/controller/datacontroller~DataController#addStyleProcessorRules a particular style processor rule is enabled}.
* See {@link module:engine/view/stylesmap~StylesMap#remove `StylesMap#remove()`} for details.
*
* @param {Array.<String>|String} property
* @param {module:engine/view/element~Element} element
*/
removeStyle( property, element ) {
element._removeStyle( property );
}
/**
* Sets a custom property on element. Unlike attributes, custom properties are not rendered to the DOM,
* so they can be used to add special data to elements.
*
* @param {String|Symbol} key
* @param {*} value
* @param {module:engine/view/element~Element} element
*/
setCustomProperty( key, value, element ) {
element._setCustomProperty( key, value );
}
/**
* Removes a custom property stored under the given key.
*
* @param {String|Symbol} key
* @param {module:engine/view/element~Element} element
* @returns {Boolean} Returns true if property was removed.
*/
removeCustomProperty( key, element ) {
return element._removeCustomProperty( key );
}
/**
* Breaks attribute nodes at provided position or at boundaries of provided range. It breaks attribute elements inside
* up to a container element.
*
* In following examples `<p>` is a container, `<b>` and `<u>` are attribute nodes:
*
* <p>foo<b><u>bar{}</u></b></p> -> <p>foo<b><u>bar</u></b>[]</p>
* <p>foo<b><u>{}bar</u></b></p> -> <p>foo{}<b><u>bar</u></b></p>
* <p>foo<b><u>b{}ar</u></b></p> -> <p>foo<b><u>b</u></b>[]<b><u>ar</u></b></p>
* <p><b>fo{o</b><u>ba}r</u></p> -> <p><b>fo</b><b>o</b><u>ba</u><u>r</u></b></p>
*
* **Note:** {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment} is treated like a container.
*
* **Note:** Difference between {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes breakAttributes} and
* {@link module:engine/view/downcastwriter~DowncastWriter#breakContainer breakContainer} is that `breakAttributes` breaks all
* {@link module:engine/view/attributeelement~AttributeElement attribute elements} that are ancestors of given `position`,
* up to the first encountered {@link module:engine/view/containerelement~ContainerElement container element}.
* `breakContainer` assumes that given `position` is directly in container element and breaks that container element.
*
* Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container`
* when {@link module:engine/view/range~Range#start start}
* and {@link module:engine/view/range~Range#end end} positions of a passed range are not placed inside same parent container.
*
* Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-empty-element`
* when trying to break attributes
* inside {@link module:engine/view/emptyelement~EmptyElement EmptyElement}.
*
* Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-ui-element`
* when trying to break attributes
* inside {@link module:engine/view/uielement~UIElement UIElement}.
*
* @see module:engine/view/attributeelement~AttributeElement
* @see module:engine/view/containerelement~ContainerElement
* @see module:engine/view/downcastwriter~DowncastWriter#breakContainer
* @param {module:engine/view/position~Position|module:engine/view/range~Range} positionOrRange Position where
* to break attribute elements.
* @returns {module:engine/view/position~Position|module:engine/view/range~Range} New position or range, after breaking the attribute
* elements.
*/
breakAttributes( positionOrRange ) {
if ( positionOrRange instanceof Position ) {
return this._breakAttributes( positionOrRange );
} else {
return this._breakAttributesRange( positionOrRange );
}
}
/**
* Breaks {@link module:engine/view/containerelement~ContainerElement container view element} into two, at the given position. Position
* has to be directly inside container element and cannot be in root. Does not break if position is at the beginning
* or at the end of it's parent element.
*
* <p>foo^bar</p> -> <p>foo</p><p>bar</p>
* <div><p>foo</p>^<p>bar</p></div> -> <div><p>foo</p></div><div><p>bar</p></div>
* <p>^foobar</p> -> ^<p>foobar</p>
* <p>foobar^</p> -> <p>foobar</p>^
*
* **Note:** Difference between {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes breakAttributes} and
* {@link module:engine/view/downcastwriter~DowncastWriter#breakContainer breakContainer} is that `breakAttributes` breaks all
* {@link module:engine/view/attributeelement~AttributeElement attribute elements} that are ancestors of given `position`,
* up to the first encountered {@link module:engine/view/containerelement~ContainerElement container element}.
* `breakContainer` assumes that given `position` is directly in container element and breaks that container element.
*
* @see module:engine/view/attributeelement~AttributeElement
* @see module:engine/view/containerelement~ContainerElement
* @see module:engine/view/downcastwriter~DowncastWriter#breakAttributes
* @param {module:engine/view/position~Position} position Position where to break element.
* @returns {module:engine/view/position~Position} Position between broken elements. If element has not been broken,
* the returned position is placed either before it or after it.
*/
breakContainer( position ) {
const element = position.parent;
if ( !( element.is( 'containerElement' ) ) ) {
/**
* Trying to break an element which is not a container element.
*
* @error view-writer-break-non-container-element
*/
throw new CKEditorError(
'view-writer-break-non-container-element: Trying to break an element which is not a container element.',
this.document
);
}
if ( !element.parent ) {
/**
* Trying to break root element.
*
* @error view-writer-break-root
*/
throw new CKEditorError( 'view-writer-break-root: Trying to break root element.', this.document );
}
if ( position.isAtStart ) {
return Position._createBefore( element );
} else if ( !position.isAtEnd ) {
const newElement = element._clone( false );
this.insert( Position._createAfter( element ), newElement );
const sourceRange = new Range( position, Position._createAt( element, 'end' ) );
const targetPosition = new Position( newElement, 0 );
this.move( sourceRange, targetPosition );
}
return Position._createAfter( element );
}
/**
* Merges {@link module:engine/view/attributeelement~AttributeElement attribute elements}. It also merges text nodes if needed.
* Only {@link module:engine/view/attributeelement~AttributeElement#isSimilar similar} attribute elements can be merged.
*
* In following examples `<p>` is a container and `<b>` is an attribute element:
*
* <p>foo[]bar</p> -> <p>foo{}bar</p>
* <p><b>foo</b>[]<b>bar</b></p> -> <p><b>foo{}bar</b></p>
* <p><b foo="bar">a</b>[]<b foo="baz">b</b></p> -> <p><b foo="bar">a</b>[]<b foo="baz">b</b></p>
*
* It will also take care about empty attributes when merging:
*
* <p><b>[]</b></p> -> <p>[]</p>
* <p><b>foo</b><i>[]</i><b>bar</b></p> -> <p><b>foo{}bar</b></p>
*
* **Note:** Difference between {@link module:engine/view/downcastwriter~DowncastWriter#mergeAttributes mergeAttributes} and
* {@link module:engine/view/downcastwriter~DowncastWriter#mergeContainers mergeContainers} is that `mergeAttributes` merges two
* {@link module:engine/view/attributeelement~AttributeElement attribute elements} or {@link module:engine/view/text~Text text nodes}
* while `mergeContainer` merges two {@link module:engine/view/containerelement~ContainerElement container elements}.
*
* @see module:engine/view/attributeelement~AttributeElement
* @see module:engine/view/containerelement~ContainerElement
* @see module:engine/view/downcastwriter~DowncastWriter#mergeContainers
* @param {module:engine/view/position~Position} position Merge position.
* @returns {module:engine/view/position~Position} Position after merge.
*/
mergeAttributes( position ) {
const positionOffset = position.offset;
const positionParent = position.parent;
// When inside text node - nothing to merge.
if ( positionParent.is( 'text' ) ) {
return position;
}
// When inside empty attribute - remove it.
if ( positionParent.is( 'attributeElement' ) && positionParent.childCount === 0 ) {
const parent = positionParent.parent;
const offset = positionParent.index;
positionParent._remove();
this._removeFromClonedElementsGroup( positionParent );
return this.mergeAttributes( new Position( parent, offset ) );
}
const nodeBefore = positionParent.getChild( positionOffset - 1 );
const nodeAfter = positionParent.getChild( positionOffset );
// Position should be placed between two nodes.
if ( !nodeBefore || !nodeAfter ) {
return position;
}
// When position is between two text nodes.
if ( nodeBefore.is( 'text' ) && nodeAfter.is( 'text' ) ) {
return mergeTextNodes( nodeBefore, nodeAfter );
}
// When position is between two same attribute elements.
else if ( nodeBefore.is( 'attributeElement' ) && nodeAfter.is( 'attributeElement' ) && nodeBefore.isSimilar( nodeAfter ) ) {
// Move all children nodes from node placed after selection and remove that node.
const count = nodeBefore.childCount;
nodeBefore._appendChild( nodeAfter.getChildren() );
nodeAfter._remove();
this._removeFromClonedElementsGroup( nodeAfter );
// New position is located inside the first node, before new nodes.
// Call this method recursively to merge again if needed.
return this.mergeAttributes( new Position( nodeBefore, count ) );
}
return position;
}
/**
* Merges two {@link module:engine/view/containerelement~ContainerElement container elements} that are before and after given position.
* Precisely, the element after the position is removed and it's contents are moved to element before the position.
*
* <p>foo</p>^<p>bar</p> -> <p>foo^bar</p>
* <div>foo</div>^<p>bar</p> -> <div>foo^bar</div>
*
* **Note:** Difference between {@link module:engine/view/downcastwriter~DowncastWriter#mergeAttributes mergeAttributes} and
* {@link module:engine/view/downcastwriter~DowncastWriter#mergeContainers mergeContainers} is that `mergeAttributes` merges two
* {@link module:engine/view/attributeelement~AttributeElement attribute elements} or {@link module:engine/view/text~Text text nodes}
* while `mergeContainer` merges two {@link module:engine/view/containerelement~ContainerElement container elements}.
*
* @see module:engine/view/attributeelement~AttributeElement
* @see module:engine/view/containerelement~ContainerElement
* @see module:engine/view/downcastwriter~DowncastWriter#mergeAttributes
* @param {module:engine/view/position~Position} position Merge position.
* @returns {module:engine/view/position~Position} Position after merge.
*/
mergeContainers( position ) {
const prev = position.nodeBefore;
const next = position.nodeAfter;
if ( !prev || !next || !prev.is( 'containerElement' ) || !next.is( 'containerElement' ) ) {
/**
* Element before and after given position cannot be merged.
*
* @error view-writer-merge-containers-invalid-position
*/
throw new CKEditorError( 'view-writer-merge-containers-invalid-position: ' +
'Element before and after given position cannot be merged.', this.document );
}
const lastChild = prev.getChild( prev.childCount - 1 );
const newPosition = lastChild instanceof Text ? Position._createAt( lastChild, 'end' ) : Position._createAt( prev, 'end' );
this.move( Range._createIn( next ), Position._createAt( prev, 'end' ) );
this.remove( Range._createOn( next ) );
return newPosition;
}
/**
* Insert node or nodes at specified position. Takes care about breaking attributes before insertion
* and merging them afterwards.
*
* Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-insert-invalid-node` when nodes to insert
* contains instances that are not {@link module:engine/view/text~Text Texts},
* {@link module:engine/view/attributeelement~AttributeElement AttributeElements},
* {@link module:engine/view/containerelement~ContainerElement ContainerElements},
* {@link module:engine/view/emptyelement~EmptyElement EmptyElements} or
* {@link module:engine/view/uielement~UIElement UIElements}.
*
* @param {module:engine/view/position~Position} position Insertion position.
* @param {module:engine/view/text~Text|module:engine/view/attributeelement~AttributeElement|
* module:engine/view/containerelement~ContainerElement|module:engine/view/emptyelement~EmptyElement|
* module:engine/view/uielement~UIElement|Iterable.<module:engine/view/text~Text|
* module:engine/view/attributeelement~AttributeElement|module:engine/view/containerelement~ContainerElement|
* module:engine/view/emptyelement~EmptyElement|module:engine/view/uielement~UIElement>} nodes Node or nodes to insert.
* @returns {module:engine/view/range~Range} Range around inserted nodes.
*/
insert( position, nodes ) {
nodes = isIterable( nodes ) ? [ ...nodes ] : [ nodes ];
// Check if nodes to insert are instances of AttributeElements, ContainerElements, EmptyElements, UIElements or Text.
validateNodesToInsert( nodes, this.document );
const container = getParentContainer( position );
if ( !container ) {
/**
* Position's parent container cannot be found.
*
* @error view-writer-invalid-position-container
*/
throw new CKEditorError( 'view-writer-invalid-position-container', this.document );
}
const insertionPosition = this._breakAttributes( position, true );
const length = container._insertChild( insertionPosition.offset, nodes );
for ( const node of nodes ) {
this._addToClonedElementsGroup( node );
}
const endPosition = insertionPosition.getShiftedBy( length );
const start = this.mergeAttributes( insertionPosition );
// When no nodes were inserted - return collapsed range.
if ( length === 0 ) {
return new Range( start, start );
} else {
// If start position was merged - move end position.
if ( !start.isEqual( insertionPosition ) ) {
endPosition.offset--;
}
const end = this.mergeAttributes( endPosition );
return new Range( start, end );
}
}
/**
* Removes provided range from the container.
*
* Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
* {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
* same parent container.
*
* @param {module:engine/view/range~Range|module:engine/view/item~Item} rangeOrItem Range to remove from container
* or an {@link module:engine/view/item~Item item} to remove. If range is provided, after removing, it will be updated
* to a collapsed range showing the new position.
* @returns {module:engine/view/documentfragment~DocumentFragment} Document fragment containing removed nodes.
*/
remove( rangeOrItem ) {
const range = rangeOrItem instanceof Range ? rangeOrItem : Range._createOn( rangeOrItem );
validateRangeContainer( range, this.document );
// If range is collapsed - nothing to remove.
if ( range.isCollapsed ) {
return new DocumentFragment( this.document );
}
// Break attributes at range start and end.
const { start: breakStart, end: breakEnd } = this._breakAttributesRange( range, true );
const parentContainer = breakStart.parent;
const count = breakEnd.offset - breakStart.offset;
// Remove nodes in range.
const removed = parentContainer._removeChildren( breakStart.offset, count );
for ( const node of removed ) {
this._removeFromClonedElementsGroup( node );
}
// Merge after removing.
const mergePosition = this.mergeAttributes( breakStart );
range.start = mergePosition;
range.end = mergePosition.clone();
// Return removed nodes.
return new DocumentFragment( this.document, removed );
}
/**
* Removes matching elements from given range.
*
* Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
* {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
* same parent container.
*
* @param {module:engine/view/range~Range} range Range to clear.
* @param {module:engine/view/element~Element} element Element to remove.
*/
clear( range, element ) {
validateRangeContainer( range, this.document );
// Create walker on given range.
// We walk backward because when we remove element during walk it modifies range end position.
const walker = range.getWalker( {
direction: 'backward',
ignoreElementEnd: true
} );
// Let's walk.
for ( const current of walker ) {
const item = current.item;
let rangeToRemove;
// When current item matches to the given element.
if ( item.is( 'element' ) && element.isSimilar( item ) ) {
// Create range on this element.
rangeToRemove = Range._createOn( item );
// When range starts inside Text or TextProxy element.
} else if ( !current.nextPosition.isAfter( range.start ) && item.is( 'textProxy' ) ) {
// We need to check if parent of this text matches to given element.
const parentElement = item.getAncestors().find( ancestor => {
return ancestor.is( 'element' ) && element.isSimilar( ancestor );
} );
// If it is then create range inside this element.
if ( parentElement ) {
rangeToRemove = Range._createIn( parentElement );
}
}
// If we have found element to remove.
if ( rangeToRemove ) {
// We need to check if element range stick out of the given range and truncate if it is.
if ( rangeToRemove.end.isAfter( range.end ) ) {
rangeToRemove.end = range.end;
}
if ( rangeToRemove.start.isBefore( range.start ) ) {
rangeToRemove.start = range.start;
}
// At the end we remove range with found element.
this.remove( rangeToRemove );
}
}
}
/**
* Moves nodes from provided range to target position.
*
* Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
* {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
* same parent container.
*
* @param {module:engine/view/range~Range} sourceRange Range containing nodes to move.
* @param {module:engine/view/position~Position} targetPosition Position to insert.
* @returns {module:engine/view/range~Range} Range in target container. Inserted nodes are placed between
* {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions.
*/
move( sourceRange, targetPosition ) {
let nodes;
if ( targetPosition.isAfter( sourceRange.end ) ) {
targetPosition = this._breakAttributes( targetPosition, true );
const parent = targetPosition.parent;
const countBefore = parent.childCount;
sourceRange = this._breakAttributesRange( sourceRange, true );
nodes = this.remove( sourceRange );
targetPosition.offset += ( parent.childCount - countBefore );
} else {
nodes = this.remove( sourceRange );
}
return this.insert( targetPosition, nodes );
}
/**
* Wraps elements within range with provided {@link module:engine/view/attributeelement~AttributeElement AttributeElement}.
* If a collapsed range is provided, it will be wrapped only if it is equal to view selection.
*
* If a collapsed range was passed and is same as selection, the selection
* will be moved to the inside of the wrapped attribute element.
*
* Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-invalid-range-container`
* when {@link module:engine/view/range~Range#start}
* and {@link module:engine/view/range~Range#end} positions are not placed inside same parent container.
*
* Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
* an instance of {@link module:engine/view/attributeelement~AttributeElement AttributeElement}.
*
* Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-nonselection-collapsed-range` when passed range
* is collapsed and different than view selection.
*
* @param {module:engine/view/range~Range} range Range to wrap.
* @param {module:engine/view/attributeelement~AttributeElement} attribute Attribute element to use as wrapper.
* @returns {module:engine/view/range~Range} range Range after wrapping, spanning over wrapping attribute element.
*/
wrap( range, attribute ) {
if ( !( attribute instanceof AttributeElement ) ) {
throw new CKEditorError( 'view-writer-wrap-invalid-attribute', this.document );
}
validateRangeContainer( range, this.document );
if ( !range.isCollapsed ) {
// Non-collapsed range. Wrap it with the attribute element.
return this._wrapRange( range, attribute );
} else {
// Collapsed range. Wrap position.
let position = range.start;
if ( position.parent.is( 'element' ) && !_hasNonUiChildren( position.parent ) ) {
position = position.getLastMatchingPosition( value => value.item.is( 'uiElement' ) );
}
position = this._wrapPosition( position, attribute );
const viewSelection = this.document.selection;
// If wrapping position is equal to view selection, move view selection inside wrapping attribute element.
if ( viewSelection.isCollapsed && viewSelection.getFirstPosition().isEqual( range.start ) ) {
this.setSelection( position );
}
return new Range( position );
}
}
/**
* Unwraps nodes within provided range from attribute element.
*
* Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
* {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
* same parent container.
*
* @param {module:engine/view/range~Range} range
* @param {module:engine/view/attributeelement~AttributeElement} attribute
*/
unwrap( range, attribute ) {
if ( !( attribute instanceof AttributeElement ) ) {
/**
* Attribute element need to be instance of attribute element.
*
* @error view-writer-unwrap-invalid-attribute
*/
throw new CKEditorError( 'view-writer-unwrap-invalid-attribute', this.document );
}
validateRangeContainer( range, this.document );
// If range is collapsed - nothing to unwrap.
if ( range.isCollapsed ) {
return range;
}
// Break attributes at range start and end.
const { start: breakStart, end: breakEnd } = this._breakAttributesRange( range, true );
const parentContainer = breakStart.parent;
// Unwrap children located between break points.
const newRange = this._unwrapChildren( parentContainer, breakStart.offset, breakEnd.offset, attribute );
// Merge attributes at the both ends and return a new range.
const start = this.mergeAttributes( newRange.start );
// If start position was merged - move end position back.
if ( !start.isEqual( newRange.start ) ) {
newRange.end.offset--;
}
const end = this.mergeAttributes( newRange.end );
return new Range( start, end );
}
/**
* Renames element by creating a copy of renamed element but with changed name and then moving contents of the
* old element to the new one. Keep in mind that this will invalidate all {@link module:engine/view/position~Position positions} which
* has renamed element as {@link module:engine/view/position~Position#parent a parent}.
*
* New element has to be created because `Element#tagName` property in DOM is readonly.
*
* Since this function creates a new element and removes the given one, the new element is returned to keep reference.
*
* @param {String} newName New name for element.
* @param {module:engine/view/containerelement~ContainerElement} viewElement Element to be renamed.
*/
rename( newName, viewElement ) {
const newElement = new ContainerElement( this.document, newName, viewElement.getAttributes() );
this.insert( Position._createAfter( viewElement ), newElement );
this.move( Range._createIn( viewElement ), Position._createAt( newElement, 0 ) );
this.remove( Range._createOn( viewElement ) );
return newElement;
}
/**
* Cleans up memory by removing obsolete cloned elements group from the writer.
*
* Should be used whenever all {@link module:engine/view/attributeelement~AttributeElement attribute elements}
* with the same {@link module:engine/view/attributeelement~AttributeElement#id id} are going to be removed from the view and
* the group will no longer be needed.
*
* Cloned elements group are not removed automatically in case if the group is still needed after all its elements
* were removed from the view.
*
* Keep in mind that group names are equal to the `id` property of the attribute element.
*
* @param {String} groupName Name of the group to clear.
*/
clearClonedElementsGroup( groupName ) {
this._cloneGroups.delete( groupName );
}
/**
* Creates position at the given location. The location can be specified as:
*
* * a {@link module:engine/view/position~Position position},
* * parent element and offset (offset defaults to `0`),
* * parent element and `'end'` (sets position at the end of that element),
* * {@link module:engine/view/item~Item view item} and `'before'` or `'after'` (sets position before or after given view item).
*
* This method is a shortcut to other constructors such as:
*
* * {@link #createPositionBefore},
* * {@link #createPositionAfter},
*
* @param {module:engine/view/item~Item|module:engine/model/position~Position} itemOrPosition
* @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
* first parameter is a {@link module:engine/view/item~Item view item}.
*/
createPositionAt( itemOrPosition, offset ) {
return Position._createAt( itemOrPosition, offset );
}
/**
* Creates a new position after given view item.
*
* @param {module:engine/view/item~Item} item View item after which the position should be located.
* @returns {module:engine/view/position~Position}
*/
createPositionAfter( item ) {
return Position._createAfter( item );
}
/**
* Creates a new position before given view item.
*
* @param {module:engine/view/item~Item} item View item before which the position should be located.
* @returns {module:engine/view/position~Position}
*/
createPositionBefore( item ) {
return Position._createBefore( item );
}
/**
* Creates a range spanning from `start` position to `end` position.
*
* **Note:** This factory method creates its own {@link module:engine/view/position~Position} instances basing on passed values.
*
* @param {module:engine/view/position~Position} start Start position.
* @param {module:engine/view/position~Position} [end] End position. If not set, range will be collapsed at `start` position.
* @returns {module:engine/view/range~Range}
*/
createRange( start, end ) {
return new Range( start, end );