@ckeditor/ckeditor5-engine 35.0.1 → 35.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +4 -4
  2. package/package.json +30 -24
  3. package/src/controller/datacontroller.js +467 -561
  4. package/src/controller/editingcontroller.js +168 -204
  5. package/src/conversion/conversion.js +541 -565
  6. package/src/conversion/conversionhelpers.js +24 -28
  7. package/src/conversion/downcastdispatcher.js +457 -686
  8. package/src/conversion/downcasthelpers.js +1583 -1965
  9. package/src/conversion/mapper.js +518 -707
  10. package/src/conversion/modelconsumable.js +240 -283
  11. package/src/conversion/upcastdispatcher.js +372 -718
  12. package/src/conversion/upcasthelpers.js +707 -818
  13. package/src/conversion/viewconsumable.js +524 -581
  14. package/src/dataprocessor/basichtmlwriter.js +12 -16
  15. package/src/dataprocessor/dataprocessor.js +5 -0
  16. package/src/dataprocessor/htmldataprocessor.js +100 -116
  17. package/src/dataprocessor/htmlwriter.js +1 -18
  18. package/src/dataprocessor/xmldataprocessor.js +116 -137
  19. package/src/dev-utils/model.js +260 -352
  20. package/src/dev-utils/operationreplayer.js +106 -126
  21. package/src/dev-utils/utils.js +34 -51
  22. package/src/dev-utils/view.js +632 -753
  23. package/src/index.js +0 -11
  24. package/src/model/batch.js +111 -127
  25. package/src/model/differ.js +988 -1233
  26. package/src/model/document.js +340 -449
  27. package/src/model/documentfragment.js +327 -364
  28. package/src/model/documentselection.js +996 -1189
  29. package/src/model/element.js +306 -410
  30. package/src/model/history.js +224 -262
  31. package/src/model/item.js +5 -0
  32. package/src/model/liveposition.js +84 -145
  33. package/src/model/liverange.js +108 -185
  34. package/src/model/markercollection.js +379 -480
  35. package/src/model/model.js +883 -1034
  36. package/src/model/node.js +419 -463
  37. package/src/model/nodelist.js +175 -201
  38. package/src/model/operation/attributeoperation.js +153 -182
  39. package/src/model/operation/detachoperation.js +64 -83
  40. package/src/model/operation/insertoperation.js +135 -166
  41. package/src/model/operation/markeroperation.js +114 -140
  42. package/src/model/operation/mergeoperation.js +163 -191
  43. package/src/model/operation/moveoperation.js +157 -187
  44. package/src/model/operation/nooperation.js +28 -38
  45. package/src/model/operation/operation.js +106 -125
  46. package/src/model/operation/operationfactory.js +30 -34
  47. package/src/model/operation/renameoperation.js +109 -135
  48. package/src/model/operation/rootattributeoperation.js +155 -188
  49. package/src/model/operation/splitoperation.js +196 -232
  50. package/src/model/operation/transform.js +1833 -2204
  51. package/src/model/operation/utils.js +140 -204
  52. package/src/model/position.js +899 -1053
  53. package/src/model/range.js +910 -1028
  54. package/src/model/rootelement.js +77 -97
  55. package/src/model/schema.js +1189 -1835
  56. package/src/model/selection.js +745 -862
  57. package/src/model/text.js +90 -114
  58. package/src/model/textproxy.js +204 -240
  59. package/src/model/treewalker.js +316 -397
  60. package/src/model/typecheckable.js +16 -0
  61. package/src/model/utils/autoparagraphing.js +32 -44
  62. package/src/model/utils/deletecontent.js +334 -418
  63. package/src/model/utils/findoptimalinsertionrange.js +25 -36
  64. package/src/model/utils/getselectedcontent.js +96 -118
  65. package/src/model/utils/insertcontent.js +654 -773
  66. package/src/model/utils/insertobject.js +96 -119
  67. package/src/model/utils/modifyselection.js +120 -158
  68. package/src/model/utils/selection-post-fixer.js +153 -201
  69. package/src/model/writer.js +1305 -1474
  70. package/src/view/attributeelement.js +189 -225
  71. package/src/view/containerelement.js +75 -85
  72. package/src/view/document.js +172 -215
  73. package/src/view/documentfragment.js +200 -249
  74. package/src/view/documentselection.js +338 -367
  75. package/src/view/domconverter.js +1370 -1617
  76. package/src/view/downcastwriter.js +1747 -2076
  77. package/src/view/editableelement.js +81 -97
  78. package/src/view/element.js +739 -890
  79. package/src/view/elementdefinition.js +5 -0
  80. package/src/view/emptyelement.js +82 -92
  81. package/src/view/filler.js +35 -50
  82. package/src/view/item.js +5 -0
  83. package/src/view/matcher.js +260 -559
  84. package/src/view/node.js +274 -360
  85. package/src/view/observer/arrowkeysobserver.js +19 -28
  86. package/src/view/observer/bubblingemittermixin.js +120 -263
  87. package/src/view/observer/bubblingeventinfo.js +47 -55
  88. package/src/view/observer/clickobserver.js +7 -13
  89. package/src/view/observer/compositionobserver.js +14 -24
  90. package/src/view/observer/domeventdata.js +57 -67
  91. package/src/view/observer/domeventobserver.js +40 -64
  92. package/src/view/observer/fakeselectionobserver.js +81 -96
  93. package/src/view/observer/focusobserver.js +45 -61
  94. package/src/view/observer/inputobserver.js +7 -13
  95. package/src/view/observer/keyobserver.js +17 -27
  96. package/src/view/observer/mouseobserver.js +7 -14
  97. package/src/view/observer/mutationobserver.js +220 -315
  98. package/src/view/observer/observer.js +81 -102
  99. package/src/view/observer/selectionobserver.js +191 -246
  100. package/src/view/observer/tabobserver.js +23 -36
  101. package/src/view/placeholder.js +128 -173
  102. package/src/view/position.js +350 -401
  103. package/src/view/range.js +453 -513
  104. package/src/view/rawelement.js +85 -112
  105. package/src/view/renderer.js +874 -1018
  106. package/src/view/rooteditableelement.js +80 -90
  107. package/src/view/selection.js +608 -689
  108. package/src/view/styles/background.js +43 -44
  109. package/src/view/styles/border.js +220 -276
  110. package/src/view/styles/margin.js +8 -17
  111. package/src/view/styles/padding.js +8 -16
  112. package/src/view/styles/utils.js +127 -160
  113. package/src/view/stylesmap.js +728 -905
  114. package/src/view/text.js +102 -126
  115. package/src/view/textproxy.js +144 -170
  116. package/src/view/treewalker.js +383 -479
  117. package/src/view/typecheckable.js +19 -0
  118. package/src/view/uielement.js +166 -187
  119. package/src/view/upcastwriter.js +395 -449
  120. package/src/view/view.js +569 -664
  121. package/src/dataprocessor/dataprocessor.jsdoc +0 -64
  122. package/src/model/item.jsdoc +0 -14
  123. package/src/view/elementdefinition.jsdoc +0 -59
  124. package/src/view/item.jsdoc +0 -14
@@ -2,1059 +2,908 @@
2
2
  * @license Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
3
3
  * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
4
  */
5
-
6
5
  /**
7
6
  * @module engine/model/model
8
7
  */
9
-
10
8
  import Batch from './batch';
11
- import Writer from './writer';
12
- import Schema from './schema';
13
9
  import Document from './document';
14
10
  import MarkerCollection from './markercollection';
15
- import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
16
- import mix from '@ckeditor/ckeditor5-utils/src/mix';
17
- import ModelElement from './element';
18
- import ModelRange from './range';
19
11
  import ModelPosition from './position';
12
+ import ModelRange from './range';
20
13
  import ModelSelection from './selection';
21
14
  import OperationFactory from './operation/operationfactory';
22
-
15
+ import Schema from './schema';
16
+ import Writer from './writer';
17
+ import { autoParagraphEmptyRoots } from './utils/autoparagraphing';
18
+ import { injectSelectionPostFixer } from './utils/selection-post-fixer';
19
+ import deleteContent from './utils/deletecontent';
20
+ import getSelectedContent from './utils/getselectedcontent';
23
21
  import insertContent from './utils/insertcontent';
24
22
  import insertObject from './utils/insertobject';
25
- import deleteContent from './utils/deletecontent';
26
23
  import modifySelection from './utils/modifyselection';
27
- import getSelectedContent from './utils/getselectedcontent';
28
- import { injectSelectionPostFixer } from './utils/selection-post-fixer';
29
- import { autoParagraphEmptyRoots } from './utils/autoparagraphing';
30
24
  import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
31
-
25
+ import { Observable } from '@ckeditor/ckeditor5-utils/src/observablemixin';
32
26
  // @if CK_DEBUG_ENGINE // const { dumpTrees } = require( '../dev-utils/utils' );
33
27
  // @if CK_DEBUG_ENGINE // const { OperationReplayer } = require( '../dev-utils/operationreplayer' ).default;
34
-
35
28
  /**
36
29
  * Editor's data model. Read about the model in the
37
30
  * {@glink framework/guides/architecture/editing-engine engine architecture guide}.
38
31
  *
39
32
  * @mixes module:utils/observablemixin~ObservableMixin
40
33
  */
41
- export default class Model {
42
- constructor() {
43
- /**
44
- * Model's marker collection.
45
- *
46
- * @readonly
47
- * @member {module:engine/model/markercollection~MarkerCollection}
48
- */
49
- this.markers = new MarkerCollection();
50
-
51
- /**
52
- * Model's document.
53
- *
54
- * @readonly
55
- * @member {module:engine/model/document~Document}
56
- */
57
- this.document = new Document( this );
58
-
59
- /**
60
- * Model's schema.
61
- *
62
- * @readonly
63
- * @member {module:engine/model/schema~Schema}
64
- */
65
- this.schema = new Schema();
66
-
67
- /**
68
- * All callbacks added by {@link module:engine/model/model~Model#change} or
69
- * {@link module:engine/model/model~Model#enqueueChange} methods waiting to be executed.
70
- *
71
- * @private
72
- * @type {Array.<Function>}
73
- */
74
- this._pendingChanges = [];
75
-
76
- /**
77
- * The last created and currently used writer instance.
78
- *
79
- * @private
80
- * @member {module:engine/model/writer~Writer}
81
- */
82
- this._currentWriter = null;
83
-
84
- [ 'insertContent', 'insertObject', 'deleteContent', 'modifySelection', 'getSelectedContent', 'applyOperation' ]
85
- .forEach( methodName => this.decorate( methodName ) );
86
-
87
- // Adding operation validation with `highest` priority, so it is called before any other feature would like
88
- // to do anything with the operation. If the operation has incorrect parameters it should throw on the earliest occasion.
89
- this.on( 'applyOperation', ( evt, args ) => {
90
- const operation = args[ 0 ];
91
-
92
- operation._validate();
93
- }, { priority: 'highest' } );
94
-
95
- // Register some default abstract entities.
96
- this.schema.register( '$root', {
97
- isLimit: true
98
- } );
99
-
100
- this.schema.register( '$container', {
101
- allowIn: [ '$root', '$container' ]
102
- } );
103
-
104
- this.schema.register( '$block', {
105
- allowIn: [ '$root', '$container' ],
106
- isBlock: true
107
- } );
108
-
109
- this.schema.register( '$blockObject', {
110
- allowWhere: '$block',
111
- isBlock: true,
112
- isObject: true
113
- } );
114
-
115
- this.schema.register( '$inlineObject', {
116
- allowWhere: '$text',
117
- allowAttributesOf: '$text',
118
- isInline: true,
119
- isObject: true
120
- } );
121
-
122
- this.schema.register( '$text', {
123
- allowIn: '$block',
124
- isInline: true,
125
- isContent: true
126
- } );
127
-
128
- this.schema.register( '$clipboardHolder', {
129
- allowContentOf: '$root',
130
- allowChildren: '$text',
131
- isLimit: true
132
- } );
133
-
134
- this.schema.register( '$documentFragment', {
135
- allowContentOf: '$root',
136
- allowChildren: '$text',
137
- isLimit: true
138
- } );
139
-
140
- // An element needed by the `upcastElementToMarker` converter.
141
- // This element temporarily represents a marker boundary during the conversion process and is removed
142
- // at the end of the conversion. `UpcastDispatcher` or at least `Conversion` class looks like a
143
- // better place for this registration but both know nothing about `Schema`.
144
- this.schema.register( '$marker' );
145
- this.schema.addChildCheck( ( context, childDefinition ) => {
146
- if ( childDefinition.name === '$marker' ) {
147
- return true;
148
- }
149
- } );
150
-
151
- injectSelectionPostFixer( this );
152
-
153
- // Post-fixer which takes care of adding empty paragraph elements to the empty roots.
154
- this.document.registerPostFixer( autoParagraphEmptyRoots );
155
-
156
- // @if CK_DEBUG_ENGINE // this.on( 'applyOperation', () => {
157
- // @if CK_DEBUG_ENGINE // dumpTrees( this.document, this.document.version );
158
- // @if CK_DEBUG_ENGINE // }, { priority: 'lowest' } );
159
- }
160
-
161
- /**
162
- * The `change()` method is the primary way of changing the model. You should use it to modify all document nodes
163
- * (including detached nodes – i.e. nodes not added to the {@link module:engine/model/model~Model#document model document}),
164
- * the {@link module:engine/model/document~Document#selection document's selection}, and
165
- * {@link module:engine/model/model~Model#markers model markers}.
166
- *
167
- * model.change( writer => {
168
- * writer.insertText( 'foo', paragraph, 'end' );
169
- * } );
170
- *
171
- * All changes inside the change block use the same {@link module:engine/model/batch~Batch} so they are combined
172
- * into a single undo step.
173
- *
174
- * model.change( writer => {
175
- * writer.insertText( 'foo', paragraph, 'end' ); // foo.
176
- *
177
- * model.change( writer => {
178
- * writer.insertText( 'bar', paragraph, 'end' ); // foobar.
179
- * } );
180
- *
181
- * writer.insertText( 'bom', paragraph, 'end' ); // foobarbom.
182
- * } );
183
- *
184
- * The callback of the `change()` block is executed synchronously.
185
- *
186
- * You can also return a value from the change block.
187
- *
188
- * const img = model.change( writer => {
189
- * return writer.createElement( 'img' );
190
- * } );
191
- *
192
- * @see #enqueueChange
193
- * @param {Function} callback Callback function which may modify the model.
194
- * @returns {*} Value returned by the callback.
195
- */
196
- change( callback ) {
197
- try {
198
- if ( this._pendingChanges.length === 0 ) {
199
- // If this is the outermost block, create a new batch and start `_runPendingChanges` execution flow.
200
- this._pendingChanges.push( { batch: new Batch(), callback } );
201
-
202
- return this._runPendingChanges()[ 0 ];
203
- } else {
204
- // If this is not the outermost block, just execute the callback.
205
- return callback( this._currentWriter );
206
- }
207
- } catch ( err ) {
208
- // @if CK_DEBUG // throw err;
209
- /* istanbul ignore next */
210
- CKEditorError.rethrowUnexpectedError( err, this );
211
- }
212
- }
213
-
214
- /**
215
- * The `enqueueChange()` method performs similar task as the {@link #change `change()` method}, with two major differences.
216
- *
217
- * First, the callback of `enqueueChange()` is executed when all other enqueued changes are done. It might be executed
218
- * immediately if it is not nested in any other change block, but if it is nested in another (enqueue)change block,
219
- * it will be delayed and executed after the outermost block.
220
- *
221
- * model.change( writer => {
222
- * console.log( 1 );
223
- *
224
- * model.enqueueChange( writer => {
225
- * console.log( 2 );
226
- * } );
227
- *
228
- * console.log( 3 );
229
- * } ); // Will log: 1, 3, 2.
230
- *
231
- * In addition to that, the changes enqueued with `enqueueChange()` will be converted separately from the changes
232
- * done in the outer `change()` block.
233
- *
234
- * Second, it lets you define the {@link module:engine/model/batch~Batch} into which you want to add your changes.
235
- * By default, a new batch with the default {@link module:engine/model/batch~Batch#constructor batch type} is created.
236
- * In the sample above, the `change` and `enqueueChange` blocks will use a different batch (and a different
237
- * {@link module:engine/model/writer~Writer} instance since each of them operates on a separate batch).
238
- *
239
- * model.enqueueChange( { isUndoable: false }, writer => {
240
- * writer.insertText( 'foo', paragraph, 'end' );
241
- * } );
242
- *
243
- * When using the `enqueueChange()` block you can also add some changes to the batch you used before.
244
- *
245
- * model.enqueueChange( batch, writer => {
246
- * writer.insertText( 'foo', paragraph, 'end' );
247
- * } );
248
- *
249
- * In order to make a nested `enqueueChange()` create a single undo step together with the changes done in the outer `change()`
250
- * block, you can obtain the batch instance from the {@link module:engine/model/writer~Writer#batch writer} of the outer block.
251
- *
252
- * @param {module:engine/model/batch~Batch|Object} [batchOrType] A batch or a
253
- * {@link module:engine/model/batch~Batch#constructor batch type} that should be used in the callback. If not defined, a new batch with
254
- * the default type will be created.
255
- * @param {Function} callback Callback function which may modify the model.
256
- */
257
- enqueueChange( batchOrType, callback ) {
258
- try {
259
- if ( !batchOrType ) {
260
- batchOrType = new Batch();
261
- } else if ( typeof batchOrType === 'function' ) {
262
- callback = batchOrType;
263
- batchOrType = new Batch();
264
- } else if ( !( batchOrType instanceof Batch ) ) {
265
- batchOrType = new Batch( batchOrType );
266
- }
267
-
268
- this._pendingChanges.push( { batch: batchOrType, callback } );
269
-
270
- if ( this._pendingChanges.length == 1 ) {
271
- this._runPendingChanges();
272
- }
273
- } catch ( err ) {
274
- // @if CK_DEBUG // throw err;
275
- /* istanbul ignore next */
276
- CKEditorError.rethrowUnexpectedError( err, this );
277
- }
278
- }
279
-
280
- /**
281
- * {@link module:utils/observablemixin~ObservableMixin#decorate Decorated} function for applying
282
- * {@link module:engine/model/operation/operation~Operation operations} to the model.
283
- *
284
- * This is a low-level way of changing the model. It is exposed for very specific use cases (like the undo feature).
285
- * Normally, to modify the model, you will want to use {@link module:engine/model/writer~Writer `Writer`}.
286
- * See also {@glink framework/guides/architecture/editing-engine#changing-the-model Changing the model} section
287
- * of the {@glink framework/guides/architecture/editing-engine Editing architecture} guide.
288
- *
289
- * @param {module:engine/model/operation/operation~Operation} operation The operation to apply.
290
- */
291
- applyOperation( operation ) {
292
- // @if CK_DEBUG_ENGINE // console.log( 'Applying ' + operation );
293
-
294
- // @if CK_DEBUG_ENGINE // if ( !this._operationLogs ) {
295
- // @if CK_DEBUG_ENGINE // this._operationLogs = [];
296
- // @if CK_DEBUG_ENGINE // }
297
-
298
- // @if CK_DEBUG_ENGINE // this._operationLogs.push( JSON.stringify( operation ) );
299
-
300
- // @if CK_DEBUG_ENGINE //if ( !this._appliedOperations ) {
301
- // @if CK_DEBUG_ENGINE // this._appliedOperations = [];
302
- // @if CK_DEBUG_ENGINE //}
303
-
304
- // @if CK_DEBUG_ENGINE //this._appliedOperations.push( operation );
305
-
306
- operation._execute();
307
- }
308
-
309
- // @if CK_DEBUG_ENGINE // getAppliedOperation() {
310
- // @if CK_DEBUG_ENGINE // if ( !this._appliedOperations ) {
311
- // @if CK_DEBUG_ENGINE // return '';
312
- // @if CK_DEBUG_ENGINE // }
313
-
314
- // @if CK_DEBUG_ENGINE // return this._appliedOperations.map( JSON.stringify ).join( '-------' );
315
- // @if CK_DEBUG_ENGINE // }
316
-
317
- // @if CK_DEBUG_ENGINE // createReplayer( stringifiedOperations ) {
318
- // @if CK_DEBUG_ENGINE // return new OperationReplayer( this, '-------', stringifiedOperations );
319
- // @if CK_DEBUG_ENGINE // }
320
-
321
- /**
322
- * Inserts content at the position in the editor specified by the selection, as one would expect the paste
323
- * functionality to work.
324
- *
325
- * **Note**: If you want to insert an {@glink framework/guides/deep-dive/schema#object-elements object element}
326
- * (e.g. a {@link module:widget/utils~toWidget widget}), see {@link #insertObject} instead.
327
- *
328
- * This is a high-level method. It takes the {@link #schema schema} into consideration when inserting
329
- * the content, clears the given selection's content before inserting nodes and moves the selection
330
- * to its target position at the end of the process.
331
- * It can split elements, merge them, wrap bare text nodes with paragraphs, etc. &mdash; just like the
332
- * pasting feature should do.
333
- *
334
- * For lower-level methods see {@link module:engine/model/writer~Writer `Writer`}.
335
- *
336
- * This method, unlike {@link module:engine/model/writer~Writer `Writer`}'s methods, does not have to be used
337
- * inside a {@link #change `change()` block}.
338
- *
339
- * # Conversion and schema
340
- *
341
- * Inserting elements and text nodes into the model is not enough to make CKEditor 5 render that content
342
- * to the user. CKEditor 5 implements a model-view-controller architecture and what `model.insertContent()` does
343
- * is only adding nodes to the model. Additionally, you need to define
344
- * {@glink framework/guides/architecture/editing-engine#conversion converters} between the model and view
345
- * and define those nodes in the {@glink framework/guides/architecture/editing-engine#schema schema}.
346
- *
347
- * So, while this method may seem similar to CKEditor 4 `editor.insertHtml()` (in fact, both methods
348
- * are used for paste-like content insertion), the CKEditor 5 method cannot be use to insert arbitrary HTML
349
- * unless converters are defined for all elements and attributes in that HTML.
350
- *
351
- * # Examples
352
- *
353
- * Using `insertContent()` with a manually created model structure:
354
- *
355
- * // Let's create a document fragment containing such content as:
356
- * //
357
- * // <paragraph>foo</paragraph>
358
- * // <blockQuote>
359
- * // <paragraph>bar</paragraph>
360
- * // </blockQuote>
361
- * const docFrag = editor.model.change( writer => {
362
- * const p1 = writer.createElement( 'paragraph' );
363
- * const p2 = writer.createElement( 'paragraph' );
364
- * const blockQuote = writer.createElement( 'blockQuote' );
365
- * const docFrag = writer.createDocumentFragment();
366
- *
367
- * writer.append( p1, docFrag );
368
- * writer.append( blockQuote, docFrag );
369
- * writer.append( p2, blockQuote );
370
- * writer.insertText( 'foo', p1 );
371
- * writer.insertText( 'bar', p2 );
372
- *
373
- * return docFrag;
374
- * } );
375
- *
376
- * // insertContent() does not have to be used in a change() block. It can, though,
377
- * // so this code could be moved to the callback defined above.
378
- * editor.model.insertContent( docFrag );
379
- *
380
- * Using `insertContent()` with an HTML string converted to a model document fragment (similar to the pasting mechanism):
381
- *
382
- * // You can create your own HtmlDataProcessor instance or use editor.data.processor
383
- * // if you have not overridden the default one (which is the HtmlDataProcessor instance).
384
- * const htmlDP = new HtmlDataProcessor( viewDocument );
385
- *
386
- * // Convert an HTML string to a view document fragment:
387
- * const viewFragment = htmlDP.toView( htmlString );
388
- *
389
- * // Convert the view document fragment to a model document fragment
390
- * // in the context of $root. This conversion takes the schema into
391
- * // account so if, for example, the view document fragment contained a bare text node,
392
- * // this text node cannot be a child of $root, so it will be automatically
393
- * // wrapped with a <paragraph>. You can define the context yourself (in the second parameter),
394
- * // and e.g. convert the content like it would happen in a <paragraph>.
395
- * // Note: The clipboard feature uses a custom context called $clipboardHolder
396
- * // which has a loosened schema.
397
- * const modelFragment = editor.data.toModel( viewFragment );
398
- *
399
- * editor.model.insertContent( modelFragment );
400
- *
401
- * By default this method will use the document selection but it can also be used with a position, range or selection instance.
402
- *
403
- * // Insert text at the current document selection position.
404
- * editor.model.change( writer => {
405
- * editor.model.insertContent( writer.createText( 'x' ) );
406
- * } );
407
- *
408
- * // Insert text at a given position - the document selection will not be modified.
409
- * editor.model.change( writer => {
410
- * editor.model.insertContent( writer.createText( 'x' ), doc.getRoot(), 2 );
411
- *
412
- * // Which is a shorthand for:
413
- * editor.model.insertContent( writer.createText( 'x' ), writer.createPositionAt( doc.getRoot(), 2 ) );
414
- * } );
415
- *
416
- * If you want the document selection to be moved to the inserted content, use the
417
- * {@link module:engine/model/writer~Writer#setSelection `setSelection()`} method of the writer after inserting
418
- * the content:
419
- *
420
- * editor.model.change( writer => {
421
- * const paragraph = writer.createElement( 'paragraph' );
422
- *
423
- * // Insert an empty paragraph at the beginning of the root.
424
- * editor.model.insertContent( paragraph, writer.createPositionAt( editor.model.document.getRoot(), 0 ) );
425
- *
426
- * // Move the document selection to the inserted paragraph.
427
- * writer.setSelection( paragraph, 'in' );
428
- * } );
429
- *
430
- * If an instance of the {@link module:engine/model/selection~Selection model selection} is passed as `selectable`,
431
- * the new content will be inserted at the passed selection (instead of document selection):
432
- *
433
- * editor.model.change( writer => {
434
- * // Create a selection in a paragraph that will be used as a place of insertion.
435
- * const selection = writer.createSelection( paragraph, 'in' );
436
- *
437
- * // Insert the new text at the created selection.
438
- * editor.model.insertContent( writer.createText( 'x' ), selection );
439
- *
440
- * // insertContent() modifies the passed selection instance so it can be used to set the document selection.
441
- * // Note: This is not necessary when you passed the document selection to insertContent().
442
- * writer.setSelection( selection );
443
- * } );
444
- *
445
- * @fires insertContent
446
- * @param {module:engine/model/documentfragment~DocumentFragment|module:engine/model/item~Item} content The content to insert.
447
- * @param {module:engine/model/selection~Selectable} [selectable=model.document.selection]
448
- * The selection into which the content should be inserted. If not provided the current model document selection will be used.
449
- * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] To be used when a model item was passed as `selectable`.
450
- * This param defines a position in relation to that item.
451
- * @returns {module:engine/model/range~Range} Range which contains all the performed changes. This is a range that, if removed,
452
- * would return the model to the state before the insertion. If no changes were preformed by `insertContent`, returns a range collapsed
453
- * at the insertion position.
454
- */
455
- insertContent( content, selectable, placeOrOffset ) {
456
- return insertContent( this, content, selectable, placeOrOffset );
457
- }
458
-
459
- /**
460
- * Inserts an {@glink framework/guides/deep-dive/schema#object-elements object element} at a specific position in the editor content.
461
- *
462
- * This is a high-level API:
463
- * * It takes the {@link #schema schema} into consideration,
464
- * * It clears the content of passed `selectable` before inserting,
465
- * * It can move the selection at the end of the process,
466
- * * It will copy the selected block's attributes to preserve them upon insertion,
467
- * * It can split elements or wrap inline objects with paragraphs if they are not allowed in target position,
468
- * * etc.
469
- *
470
- * # Notes
471
- *
472
- * * If you want to insert a non-object content, see {@link #insertContent} instead.
473
- * * For lower-level API, see {@link module:engine/model/writer~Writer `Writer`}.
474
- * * Unlike {@link module:engine/model/writer~Writer `Writer`}, this method does not have to be used inside
475
- * a {@link #change `change()` block}.
476
- * * Inserting object into the model is not enough to make CKEditor 5 render that content to the user.
477
- * CKEditor 5 implements a model-view-controller architecture and what `model.insertObject()` does
478
- * is only adding nodes to the model. Additionally, you need to define
479
- * {@glink framework/guides/architecture/editing-engine#conversion converters} between the model and view
480
- * and define those nodes in the {@glink framework/guides/architecture/editing-engine#schema schema}.
481
- *
482
- * # Examples
483
- *
484
- * Use the following code to insert an object at the current selection and keep the selection on the inserted element:
485
- *
486
- * const rawHtmlEmbedElement = writer.createElement( 'rawHtml' );
487
- *
488
- * model.insertObject( rawHtmlEmbedElement, null, null, {
489
- * setSelection: 'on'
490
- * } );
491
- *
492
- * Use the following code to insert an object at the current selection and nudge the selection after the inserted object:
493
- *
494
- * const pageBreakElement = writer.createElement( 'pageBreak' );
495
- *
496
- * model.insertObject( pageBreakElement, null, null, {
497
- * setSelection: 'after'
498
- * } );
499
- *
500
- * Use the following code to insert an object at the current selection and avoid splitting the content (non-destructive insertion):
501
- *
502
- * const tableElement = writer.createElement( 'table' );
503
- *
504
- * model.insertObject( tableElement, null, null, {
505
- * findOptimalPosition: 'auto'
506
- * } );
507
- *
508
- * Use the following code to insert an object at the specific range (also: replace the content of the range):
509
- *
510
- * const tableElement = writer.createElement( 'table' );
511
- * const range = model.createRangeOn( model.document.getRoot().getChild( 1 ) );
512
- *
513
- * model.insertObject( tableElement, range );
514
- *
515
- * @param {module:engine/model/element~Element} object An object to be inserted into the model document.
516
- * @param {module:engine/model/selection~Selectable} [selectable=model.document.selection]
517
- * A selectable where the content should be inserted. If not specified, the current
518
- * {@link module:engine/model/document~Document#selection document selection} will be used instead.
519
- * @param {Number|'before'|'end'|'after'|'on'|'in'} placeOrOffset Specifies the exact place or offset for the insertion to take place,
520
- * relative to `selectable`.
521
- * @param {Object} [options] Additional options.
522
- * @param {'auto'|'before'|'after'} [options.findOptimalPosition] An option that, when set, adjusts the insertion position (relative to
523
- * `selectable` and `placeOrOffset`) so that the content of `selectable` is not split upon insertion (a.k.a. non-destructive insertion).
524
- * * When `'auto'`, the algorithm will decide whether to insert the object before or after `selectable` to avoid content splitting.
525
- * * When `'before'`, the closest position before `selectable` will be used that will not result in content splitting.
526
- * * When `'after'`, the closest position after `selectable` will be used that will not result in content splitting.
527
- *
528
- * Note that this option only works for block objects. Inline objects are inserted into text and do not split blocks.
529
- * @param {'on'|'after'} [options.setSelection] An option that, when set, moves the
530
- * {@link module:engine/model/document~Document#selection document selection} after inserting the object.
531
- * * When `'on'`, the document selection will be set on the inserted object.
532
- * * When `'after'`, the document selection will move to the closest text node after the inserted object. If there is no
533
- * such text node, a paragraph will be created and the document selection will be moved inside it.
534
- * @returns {module:engine/model/range~Range} A range which contains all the performed changes. This is a range that, if removed,
535
- * would return the model to the state before the insertion. If no changes were preformed by `insertObject()`, returns a range collapsed
536
- * at the insertion position.
537
- */
538
- insertObject( object, selectable, placeOrOffset, options ) {
539
- return insertObject( this, object, selectable, placeOrOffset, options );
540
- }
541
-
542
- /**
543
- * Deletes content of the selection and merge siblings. The resulting selection is always collapsed.
544
- *
545
- * **Note:** For the sake of predictability, the resulting selection should always be collapsed.
546
- * In cases where a feature wants to modify deleting behavior so selection isn't collapsed
547
- * (e.g. a table feature may want to keep row selection after pressing <kbd>Backspace</kbd>),
548
- * then that behavior should be implemented in the view's listener. At the same time, the table feature
549
- * will need to modify this method's behavior too, e.g. to "delete contents and then collapse
550
- * the selection inside the last selected cell" or "delete the row and collapse selection somewhere near".
551
- * That needs to be done in order to ensure that other features which use `deleteContent()` will work well with tables.
552
- *
553
- * @fires deleteContent
554
- * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
555
- * Selection of which the content should be deleted.
556
- * @param {Object} [options]
557
- * @param {Boolean} [options.leaveUnmerged=false] Whether to merge elements after removing the content of the selection.
558
- *
559
- * For example `<heading1>x[x</heading1><paragraph>y]y</paragraph>` will become:
560
- *
561
- * * `<heading1>x^y</heading1>` with the option disabled (`leaveUnmerged == false`)
562
- * * `<heading1>x^</heading1><paragraph>y</paragraph>` with enabled (`leaveUnmerged == true`).
563
- *
564
- * Note: {@link module:engine/model/schema~Schema#isObject object} and {@link module:engine/model/schema~Schema#isLimit limit}
565
- * elements will not be merged.
566
- *
567
- * @param {Boolean} [options.doNotResetEntireContent=false] Whether to skip replacing the entire content with a
568
- * paragraph when the entire content was selected.
569
- *
570
- * For example `<heading1>[x</heading1><paragraph>y]</paragraph>` will become:
571
- *
572
- * * `<paragraph>^</paragraph>` with the option disabled (`doNotResetEntireContent == false`)
573
- * * `<heading1>^</heading1>` with enabled (`doNotResetEntireContent == true`)
574
- *
575
- * @param {Boolean} [options.doNotAutoparagraph=false] Whether to create a paragraph if after content deletion selection is moved
576
- * to a place where text cannot be inserted.
577
- *
578
- * For example `<paragraph>x</paragraph>[<imageBlock src="foo.jpg"></imageBlock>]` will become:
579
- *
580
- * * `<paragraph>x</paragraph><paragraph>[]</paragraph>` with the option disabled (`doNotAutoparagraph == false`)
581
- * * `<paragraph>x[]</paragraph>` with the option enabled (`doNotAutoparagraph == true`).
582
- *
583
- * **Note:** if there is no valid position for the selection, the paragraph will always be created:
584
- *
585
- * `[<imageBlock src="foo.jpg"></imageBlock>]` -> `<paragraph>[]</paragraph>`.
586
- *
587
- * @param {'forward'|'backward'} [options.direction='backward'] The direction in which the content is being consumed.
588
- * Deleting backward corresponds to using the <kbd>Backspace</kbd> key, while deleting content forward corresponds to
589
- * the <kbd>Shift</kbd>+<kbd>Backspace</kbd> keystroke.
590
- */
591
- deleteContent( selection, options ) {
592
- deleteContent( this, selection, options );
593
- }
594
-
595
- /**
596
- * Modifies the selection. Currently, the supported modifications are:
597
- *
598
- * * Extending. The selection focus is moved in the specified `options.direction` with a step specified in `options.unit`.
599
- * Possible values for `unit` are:
600
- * * `'character'` (default) - moves selection by one user-perceived character. In most cases this means moving by one
601
- * character in `String` sense. However, unicode also defines "combing marks". These are special symbols, that combines
602
- * with a symbol before it ("base character") to create one user-perceived character. For example, `q̣̇` is a normal
603
- * letter `q` with two "combining marks": upper dot (`Ux0307`) and lower dot (`Ux0323`). For most actions, i.e. extending
604
- * selection by one position, it is correct to include both "base character" and all of it's "combining marks". That is
605
- * why `'character'` value is most natural and common method of modifying selection.
606
- * * `'codePoint'` - moves selection by one unicode code point. In contrary to, `'character'` unit, this will insert
607
- * selection between "base character" and "combining mark", because "combining marks" have their own unicode code points.
608
- * However, for technical reasons, unicode code points with values above `UxFFFF` are represented in native `String` by
609
- * two characters, called "surrogate pairs". Halves of "surrogate pairs" have a meaning only when placed next to each other.
610
- * For example `𨭎` is represented in `String` by `\uD862\uDF4E`. Both `\uD862` and `\uDF4E` do not have any meaning
611
- * outside the pair (are rendered as ? when alone). Position between them would be incorrect. In this case, selection
612
- * extension will include whole "surrogate pair".
613
- * * `'word'` - moves selection by a whole word.
614
- *
615
- * **Note:** if you extend a forward selection in a backward direction you will in fact shrink it.
616
- *
617
- * @fires modifySelection
618
- * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
619
- * The selection to modify.
620
- * @param {Object} [options]
621
- * @param {'forward'|'backward'} [options.direction='forward'] The direction in which the selection should be modified.
622
- * @param {'character'|'codePoint'|'word'} [options.unit='character'] The unit by which selection should be modified.
623
- * @param {Boolean} [options.treatEmojiAsSingleUnit=false] Whether multi-characer emoji sequences should be handled as single unit.
624
- */
625
- modifySelection( selection, options ) {
626
- modifySelection( this, selection, options );
627
- }
628
-
629
- /**
630
- * Gets a clone of the selected content.
631
- *
632
- * For example, for the following selection:
633
- *
634
- * ```html
635
- * <paragraph>x</paragraph>
636
- * <blockQuote>
637
- * <paragraph>y</paragraph>
638
- * <heading1>fir[st</heading1>
639
- * </blockQuote>
640
- * <paragraph>se]cond</paragraph>
641
- * <paragraph>z</paragraph>
642
- * ```
643
- *
644
- * It will return a document fragment with such a content:
645
- *
646
- * ```html
647
- * <blockQuote>
648
- * <heading1>st</heading1>
649
- * </blockQuote>
650
- * <paragraph>se</paragraph>
651
- * ```
652
- *
653
- * @fires getSelectedContent
654
- * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
655
- * The selection of which content will be returned.
656
- * @returns {module:engine/model/documentfragment~DocumentFragment}
657
- */
658
- getSelectedContent( selection ) {
659
- return getSelectedContent( this, selection );
660
- }
661
-
662
- /**
663
- * Checks whether the given {@link module:engine/model/range~Range range} or
664
- * {@link module:engine/model/element~Element element} has any meaningful content.
665
- *
666
- * Meaningful content is:
667
- *
668
- * * any text node (`options.ignoreWhitespaces` allows controlling whether this text node must also contain
669
- * any non-whitespace characters),
670
- * * or any {@link module:engine/model/schema~Schema#isContent content element},
671
- * * or any {@link module:engine/model/markercollection~Marker marker} which
672
- * {@link module:engine/model/markercollection~Marker#_affectsData affects data}.
673
- *
674
- * This means that a range containing an empty `<paragraph></paragraph>` is not considered to have a meaningful content.
675
- * However, a range containing an `<imageBlock></imageBlock>` (which would normally be marked in the schema as an object element)
676
- * is considered non-empty.
677
- *
678
- * @param {module:engine/model/range~Range|module:engine/model/element~Element} rangeOrElement Range or element to check.
679
- * @param {Object} [options]
680
- * @param {Boolean} [options.ignoreWhitespaces] Whether text node with whitespaces only should be considered empty.
681
- * @param {Boolean} [options.ignoreMarkers] Whether markers should be ignored.
682
- * @returns {Boolean}
683
- */
684
- hasContent( rangeOrElement, options = {} ) {
685
- const range = rangeOrElement instanceof ModelElement ? ModelRange._createIn( rangeOrElement ) : rangeOrElement;
686
-
687
- if ( range.isCollapsed ) {
688
- return false;
689
- }
690
-
691
- const { ignoreWhitespaces = false, ignoreMarkers = false } = options;
692
-
693
- // Check if there are any markers which affects data in this given range.
694
- if ( !ignoreMarkers ) {
695
- for ( const intersectingMarker of this.markers.getMarkersIntersectingRange( range ) ) {
696
- if ( intersectingMarker.affectsData ) {
697
- return true;
698
- }
699
- }
700
- }
701
-
702
- for ( const item of range.getItems() ) {
703
- if ( this.schema.isContent( item ) ) {
704
- if ( item.is( '$textProxy' ) ) {
705
- if ( !ignoreWhitespaces ) {
706
- return true;
707
- } else if ( item.data.search( /\S/ ) !== -1 ) {
708
- return true;
709
- }
710
- } else {
711
- return true;
712
- }
713
- }
714
- }
715
-
716
- return false;
717
- }
718
-
719
- /**
720
- * Creates a position from the given root and path in that root.
721
- *
722
- * Note: This method is also available as
723
- * {@link module:engine/model/writer~Writer#createPositionFromPath `Writer#createPositionFromPath()`}.
724
- *
725
- * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} root Root of the position.
726
- * @param {Array.<Number>} path Position path. See {@link module:engine/model/position~Position#path}.
727
- * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
728
- * See {@link module:engine/model/position~PositionStickiness}.
729
- * @returns {module:engine/model/position~Position}
730
- */
731
- createPositionFromPath( root, path, stickiness ) {
732
- return new ModelPosition( root, path, stickiness );
733
- }
734
-
735
- /**
736
- * Creates position at the given location. The location can be specified as:
737
- *
738
- * * a {@link module:engine/model/position~Position position},
739
- * * a parent element and offset in that element,
740
- * * a parent element and `'end'` (the position will be set at the end of that element),
741
- * * a {@link module:engine/model/item~Item model item} and `'before'` or `'after'`
742
- * (the position will be set before or after the given model item).
743
- *
744
- * This method is a shortcut to other factory methods such as:
745
- *
746
- * * {@link module:engine/model/model~Model#createPositionBefore `createPositionBefore()`},
747
- * * {@link module:engine/model/model~Model#createPositionAfter `createPositionAfter()`}.
748
- *
749
- * Note: This method is also available as
750
- * {@link module:engine/model/writer~Writer#createPositionAt `Writer#createPositionAt()`},
751
- *
752
- * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
753
- * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
754
- * first parameter is a {@link module:engine/model/item~Item model item}.
755
- */
756
- createPositionAt( itemOrPosition, offset ) {
757
- return ModelPosition._createAt( itemOrPosition, offset );
758
- }
759
-
760
- /**
761
- * Creates a new position after the given {@link module:engine/model/item~Item model item}.
762
- *
763
- * Note: This method is also available as
764
- * {@link module:engine/model/writer~Writer#createPositionAfter `Writer#createPositionAfter()`}.
765
- *
766
- * @param {module:engine/model/item~Item} item Item after which the position should be placed.
767
- * @returns {module:engine/model/position~Position}
768
- */
769
- createPositionAfter( item ) {
770
- return ModelPosition._createAfter( item );
771
- }
772
-
773
- /**
774
- * Creates a new position before the given {@link module:engine/model/item~Item model item}.
775
- *
776
- * Note: This method is also available as
777
- * {@link module:engine/model/writer~Writer#createPositionBefore `Writer#createPositionBefore()`}.
778
- *
779
- * @param {module:engine/model/item~Item} item Item before which the position should be placed.
780
- * @returns {module:engine/model/position~Position}
781
- */
782
- createPositionBefore( item ) {
783
- return ModelPosition._createBefore( item );
784
- }
785
-
786
- /**
787
- * Creates a range spanning from the `start` position to the `end` position.
788
- *
789
- * Note: This method is also available as
790
- * {@link module:engine/model/writer~Writer#createRange `Writer#createRange()`}:
791
- *
792
- * model.change( writer => {
793
- * const range = writer.createRange( start, end );
794
- * } );
795
- *
796
- * @param {module:engine/model/position~Position} start Start position.
797
- * @param {module:engine/model/position~Position} [end] End position. If not set, the range will be collapsed
798
- * to the `start` position.
799
- * @returns {module:engine/model/range~Range}
800
- */
801
- createRange( start, end ) {
802
- return new ModelRange( start, end );
803
- }
804
-
805
- /**
806
- * Creates a range inside the given element which starts before the first child of
807
- * that element and ends after the last child of that element.
808
- *
809
- * Note: This method is also available as
810
- * {@link module:engine/model/writer~Writer#createRangeIn `Writer#createRangeIn()`}:
811
- *
812
- * model.change( writer => {
813
- * const range = writer.createRangeIn( paragraph );
814
- * } );
815
- *
816
- * @param {module:engine/model/element~Element} element Element which is a parent for the range.
817
- * @returns {module:engine/model/range~Range}
818
- */
819
- createRangeIn( element ) {
820
- return ModelRange._createIn( element );
821
- }
822
-
823
- /**
824
- * Creates a range that starts before the given {@link module:engine/model/item~Item model item} and ends after it.
825
- *
826
- * Note: This method is also available on `writer` instance as
827
- * {@link module:engine/model/writer~Writer#createRangeOn `Writer.createRangeOn()`}:
828
- *
829
- * model.change( writer => {
830
- * const range = writer.createRangeOn( paragraph );
831
- * } );
832
- *
833
- * @param {module:engine/model/item~Item} item
834
- * @returns {module:engine/model/range~Range}
835
- */
836
- createRangeOn( item ) {
837
- return ModelRange._createOn( item );
838
- }
839
-
840
- /**
841
- * Creates a new selection instance based on the given {@link module:engine/model/selection~Selectable selectable}
842
- * or creates an empty selection if no arguments were passed.
843
- *
844
- * Note: This method is also available as
845
- * {@link module:engine/model/writer~Writer#createSelection `Writer#createSelection()`}.
846
- *
847
- * // Creates empty selection without ranges.
848
- * const selection = writer.createSelection();
849
- *
850
- * // Creates selection at the given range.
851
- * const range = writer.createRange( start, end );
852
- * const selection = writer.createSelection( range );
853
- *
854
- * // Creates selection at the given ranges
855
- * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
856
- * const selection = writer.createSelection( ranges );
857
- *
858
- * // Creates selection from the other selection.
859
- * // Note: It doesn't copies selection attributes.
860
- * const otherSelection = writer.createSelection();
861
- * const selection = writer.createSelection( otherSelection );
862
- *
863
- * // Creates selection from the given document selection.
864
- * // Note: It doesn't copies selection attributes.
865
- * const documentSelection = model.document.selection;
866
- * const selection = writer.createSelection( documentSelection );
867
- *
868
- * // Creates selection at the given position.
869
- * const position = writer.createPositionFromPath( root, path );
870
- * const selection = writer.createSelection( position );
871
- *
872
- * // Creates selection at the given offset in the given element.
873
- * const paragraph = writer.createElement( 'paragraph' );
874
- * const selection = writer.createSelection( paragraph, offset );
875
- *
876
- * // Creates a range inside an {@link module:engine/model/element~Element element} which starts before the
877
- * // first child of that element and ends after the last child of that element.
878
- * const selection = writer.createSelection( paragraph, 'in' );
879
- *
880
- * // Creates a range on an {@link module:engine/model/item~Item item} which starts before the item and ends
881
- * // just after the item.
882
- * const selection = writer.createSelection( paragraph, 'on' );
883
- *
884
- * // Additional options (`'backward'`) can be specified as the last argument.
885
- *
886
- * // Creates backward selection.
887
- * const selection = writer.createSelection( range, { backward: true } );
888
- *
889
- * @param {module:engine/model/selection~Selectable} selectable
890
- * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
891
- * @param {Object} [options]
892
- * @param {Boolean} [options.backward] Sets this selection instance to be backward.
893
- * @returns {module:engine/model/selection~Selection}
894
- */
895
- createSelection( selectable, placeOrOffset, options ) {
896
- return new ModelSelection( selectable, placeOrOffset, options );
897
- }
898
-
899
- /**
900
- * Creates a {@link module:engine/model/batch~Batch} instance.
901
- *
902
- * **Note:** In most cases creating a batch instance is not necessary as they are created when using:
903
- *
904
- * * {@link #change `change()`},
905
- * * {@link #enqueueChange `enqueueChange()`}.
906
- *
907
- * @param {Object} [type] {@link module:engine/model/batch~Batch#constructor The type} of the batch.
908
- * @returns {module:engine/model/batch~Batch}
909
- */
910
- createBatch( type ) {
911
- return new Batch( type );
912
- }
913
-
914
- /**
915
- * Creates an operation instance from a JSON object (parsed JSON string).
916
- *
917
- * This is an alias for {@link module:engine/model/operation/operationfactory~OperationFactory.fromJSON `OperationFactory.fromJSON()`}.
918
- *
919
- * @param {Object} json Deserialized JSON object.
920
- * @returns {module:engine/model/operation/operation~Operation}
921
- */
922
- createOperationFromJSON( json ) {
923
- return OperationFactory.fromJSON( json, this.document );
924
- }
925
-
926
- /**
927
- * Removes all events listeners set by model instance and destroys {@link module:engine/model/document~Document}.
928
- */
929
- destroy() {
930
- this.document.destroy();
931
- this.stopListening();
932
- }
933
-
934
- /**
935
- * Common part of {@link module:engine/model/model~Model#change} and {@link module:engine/model/model~Model#enqueueChange}
936
- * which calls callbacks and returns array of values returned by these callbacks.
937
- *
938
- * @private
939
- * @returns {Array.<*>} Array of values returned by callbacks.
940
- */
941
- _runPendingChanges() {
942
- const ret = [];
943
-
944
- this.fire( '_beforeChanges' );
945
-
946
- while ( this._pendingChanges.length ) {
947
- // Create a new writer using batch instance created for this chain of changes.
948
- const currentBatch = this._pendingChanges[ 0 ].batch;
949
- this._currentWriter = new Writer( this, currentBatch );
950
-
951
- // Execute changes callback and gather the returned value.
952
- const callbackReturnValue = this._pendingChanges[ 0 ].callback( this._currentWriter );
953
- ret.push( callbackReturnValue );
954
-
955
- this.document._handleChangeBlock( this._currentWriter );
956
-
957
- this._pendingChanges.shift();
958
- this._currentWriter = null;
959
- }
960
-
961
- this.fire( '_afterChanges' );
962
-
963
- return ret;
964
- }
965
-
966
- /**
967
- * Fired when entering the outermost {@link module:engine/model/model~Model#enqueueChange} or
968
- * {@link module:engine/model/model~Model#change} block.
969
- *
970
- * @protected
971
- * @event _beforeChanges
972
- */
973
-
974
- /**
975
- * Fired when leaving the outermost {@link module:engine/model/model~Model#enqueueChange} or
976
- * {@link module:engine/model/model~Model#change} block.
977
- *
978
- * @protected
979
- * @event _afterChanges
980
- */
981
-
982
- /**
983
- * Fired every time any {@link module:engine/model/operation/operation~Operation operation} is applied on the model
984
- * using {@link #applyOperation}.
985
- *
986
- * Note that this event is suitable only for very specific use-cases. Use it if you need to listen to every single operation
987
- * applied on the document. However, in most cases {@link module:engine/model/document~Document#event:change} should
988
- * be used.
989
- *
990
- * A few callbacks are already added to this event by engine internal classes:
991
- *
992
- * * with `highest` priority operation is validated,
993
- * * with `normal` priority operation is executed,
994
- * * with `low` priority the {@link module:engine/model/document~Document} updates its version,
995
- * * with `low` priority {@link module:engine/model/liveposition~LivePosition} and {@link module:engine/model/liverange~LiveRange}
996
- * update themselves.
997
- *
998
- * @event applyOperation
999
- * @param {Array} args Arguments of the `applyOperation` which is an array with a single element - applied
1000
- * {@link module:engine/model/operation/operation~Operation operation}.
1001
- */
1002
-
1003
- /**
1004
- * Event fired when {@link #insertContent} method is called.
1005
- *
1006
- * The {@link #insertContent default action of that method} is implemented as a
1007
- * listener to this event so it can be fully customized by the features.
1008
- *
1009
- * **Note** The `selectable` parameter for the {@link #insertContent} is optional. When `undefined` value is passed the method uses
1010
- * {@link module:engine/model/document~Document#selection document selection}.
1011
- *
1012
- * @event insertContent
1013
- * @param {Array} args The arguments passed to the original method.
1014
- */
1015
-
1016
- /**
1017
- * Event fired when the {@link #insertObject} method is called.
1018
- *
1019
- * The {@link #insertObject default action of that method} is implemented as a
1020
- * listener to this event so it can be fully customized by the features.
1021
- *
1022
- * **Note** The `selectable` parameter for the {@link #insertObject} is optional. When `undefined` value is passed the method uses
1023
- * {@link module:engine/model/document~Document#selection document selection}.
1024
- *
1025
- * @event insertObject
1026
- * @param {Array} args The arguments passed to the original method.
1027
- */
1028
-
1029
- /**
1030
- * Event fired when {@link #deleteContent} method is called.
1031
- *
1032
- * The {@link #deleteContent default action of that method} is implemented as a
1033
- * listener to this event so it can be fully customized by the features.
1034
- *
1035
- * @event deleteContent
1036
- * @param {Array} args The arguments passed to the original method.
1037
- */
1038
-
1039
- /**
1040
- * Event fired when {@link #modifySelection} method is called.
1041
- *
1042
- * The {@link #modifySelection default action of that method} is implemented as a
1043
- * listener to this event so it can be fully customized by the features.
1044
- *
1045
- * @event modifySelection
1046
- * @param {Array} args The arguments passed to the original method.
1047
- */
1048
-
1049
- /**
1050
- * Event fired when {@link #getSelectedContent} method is called.
1051
- *
1052
- * The {@link #getSelectedContent default action of that method} is implemented as a
1053
- * listener to this event so it can be fully customized by the features.
1054
- *
1055
- * @event getSelectedContent
1056
- * @param {Array} args The arguments passed to the original method.
1057
- */
34
+ export default class Model extends Observable {
35
+ constructor() {
36
+ super();
37
+ /**
38
+ * Model's marker collection.
39
+ *
40
+ * @readonly
41
+ * @member {module:engine/model/markercollection~MarkerCollection}
42
+ */
43
+ this.markers = new MarkerCollection();
44
+ /**
45
+ * Model's document.
46
+ *
47
+ * @readonly
48
+ * @member {module:engine/model/document~Document}
49
+ */
50
+ this.document = new Document(this);
51
+ /**
52
+ * Model's schema.
53
+ *
54
+ * @readonly
55
+ * @member {module:engine/model/schema~Schema}
56
+ */
57
+ this.schema = new Schema();
58
+ /**
59
+ * All callbacks added by {@link module:engine/model/model~Model#change} or
60
+ * {@link module:engine/model/model~Model#enqueueChange} methods waiting to be executed.
61
+ *
62
+ * @private
63
+ * @type {Array.<Function>}
64
+ */
65
+ this._pendingChanges = [];
66
+ /**
67
+ * The last created and currently used writer instance.
68
+ *
69
+ * @private
70
+ * @member {module:engine/model/writer~Writer}
71
+ */
72
+ this._currentWriter = null;
73
+ ['insertContent', 'insertObject', 'deleteContent', 'modifySelection', 'getSelectedContent', 'applyOperation']
74
+ .forEach(methodName => this.decorate(methodName));
75
+ // Adding operation validation with `highest` priority, so it is called before any other feature would like
76
+ // to do anything with the operation. If the operation has incorrect parameters it should throw on the earliest occasion.
77
+ this.on('applyOperation', (evt, args) => {
78
+ const operation = args[0];
79
+ operation._validate();
80
+ }, { priority: 'highest' });
81
+ // Register some default abstract entities.
82
+ this.schema.register('$root', {
83
+ isLimit: true
84
+ });
85
+ this.schema.register('$container', {
86
+ allowIn: ['$root', '$container']
87
+ });
88
+ this.schema.register('$block', {
89
+ allowIn: ['$root', '$container'],
90
+ isBlock: true
91
+ });
92
+ this.schema.register('$blockObject', {
93
+ allowWhere: '$block',
94
+ isBlock: true,
95
+ isObject: true
96
+ });
97
+ this.schema.register('$inlineObject', {
98
+ allowWhere: '$text',
99
+ allowAttributesOf: '$text',
100
+ isInline: true,
101
+ isObject: true
102
+ });
103
+ this.schema.register('$text', {
104
+ allowIn: '$block',
105
+ isInline: true,
106
+ isContent: true
107
+ });
108
+ this.schema.register('$clipboardHolder', {
109
+ allowContentOf: '$root',
110
+ allowChildren: '$text',
111
+ isLimit: true
112
+ });
113
+ this.schema.register('$documentFragment', {
114
+ allowContentOf: '$root',
115
+ allowChildren: '$text',
116
+ isLimit: true
117
+ });
118
+ // An element needed by the `upcastElementToMarker` converter.
119
+ // This element temporarily represents a marker boundary during the conversion process and is removed
120
+ // at the end of the conversion. `UpcastDispatcher` or at least `Conversion` class looks like a
121
+ // better place for this registration but both know nothing about `Schema`.
122
+ this.schema.register('$marker');
123
+ this.schema.addChildCheck((context, childDefinition) => {
124
+ if (childDefinition.name === '$marker') {
125
+ return true;
126
+ }
127
+ });
128
+ injectSelectionPostFixer(this);
129
+ // Post-fixer which takes care of adding empty paragraph elements to the empty roots.
130
+ this.document.registerPostFixer(autoParagraphEmptyRoots);
131
+ // @if CK_DEBUG_ENGINE // this.on( 'applyOperation', () => {
132
+ // @if CK_DEBUG_ENGINE // dumpTrees( this.document, this.document.version );
133
+ // @if CK_DEBUG_ENGINE // }, { priority: 'lowest' } );
134
+ }
135
+ /**
136
+ * The `change()` method is the primary way of changing the model. You should use it to modify all document nodes
137
+ * (including detached nodes – i.e. nodes not added to the {@link module:engine/model/model~Model#document model document}),
138
+ * the {@link module:engine/model/document~Document#selection document's selection}, and
139
+ * {@link module:engine/model/model~Model#markers model markers}.
140
+ *
141
+ * model.change( writer => {
142
+ * writer.insertText( 'foo', paragraph, 'end' );
143
+ * } );
144
+ *
145
+ * All changes inside the change block use the same {@link module:engine/model/batch~Batch} so they are combined
146
+ * into a single undo step.
147
+ *
148
+ * model.change( writer => {
149
+ * writer.insertText( 'foo', paragraph, 'end' ); // foo.
150
+ *
151
+ * model.change( writer => {
152
+ * writer.insertText( 'bar', paragraph, 'end' ); // foobar.
153
+ * } );
154
+ *
155
+ * writer.insertText( 'bom', paragraph, 'end' ); // foobarbom.
156
+ * } );
157
+ *
158
+ * The callback of the `change()` block is executed synchronously.
159
+ *
160
+ * You can also return a value from the change block.
161
+ *
162
+ * const img = model.change( writer => {
163
+ * return writer.createElement( 'img' );
164
+ * } );
165
+ *
166
+ * @see #enqueueChange
167
+ * @param {Function} callback Callback function which may modify the model.
168
+ * @returns {*} Value returned by the callback.
169
+ */
170
+ change(callback) {
171
+ try {
172
+ if (this._pendingChanges.length === 0) {
173
+ // If this is the outermost block, create a new batch and start `_runPendingChanges` execution flow.
174
+ this._pendingChanges.push({ batch: new Batch(), callback });
175
+ return this._runPendingChanges()[0];
176
+ }
177
+ else {
178
+ // If this is not the outermost block, just execute the callback.
179
+ return callback(this._currentWriter);
180
+ }
181
+ }
182
+ catch (err) {
183
+ // @if CK_DEBUG // throw err;
184
+ /* istanbul ignore next */
185
+ CKEditorError.rethrowUnexpectedError(err, this);
186
+ }
187
+ }
188
+ /**
189
+ * The `enqueueChange()` method performs similar task as the {@link #change `change()` method}, with two major differences.
190
+ *
191
+ * First, the callback of `enqueueChange()` is executed when all other enqueued changes are done. It might be executed
192
+ * immediately if it is not nested in any other change block, but if it is nested in another (enqueue)change block,
193
+ * it will be delayed and executed after the outermost block.
194
+ *
195
+ * model.change( writer => {
196
+ * console.log( 1 );
197
+ *
198
+ * model.enqueueChange( writer => {
199
+ * console.log( 2 );
200
+ * } );
201
+ *
202
+ * console.log( 3 );
203
+ * } ); // Will log: 1, 3, 2.
204
+ *
205
+ * In addition to that, the changes enqueued with `enqueueChange()` will be converted separately from the changes
206
+ * done in the outer `change()` block.
207
+ *
208
+ * Second, it lets you define the {@link module:engine/model/batch~Batch} into which you want to add your changes.
209
+ * By default, a new batch with the default {@link module:engine/model/batch~Batch#constructor batch type} is created.
210
+ * In the sample above, the `change` and `enqueueChange` blocks will use a different batch (and a different
211
+ * {@link module:engine/model/writer~Writer} instance since each of them operates on a separate batch).
212
+ *
213
+ * model.enqueueChange( { isUndoable: false }, writer => {
214
+ * writer.insertText( 'foo', paragraph, 'end' );
215
+ * } );
216
+ *
217
+ * When using the `enqueueChange()` block you can also add some changes to the batch you used before.
218
+ *
219
+ * model.enqueueChange( batch, writer => {
220
+ * writer.insertText( 'foo', paragraph, 'end' );
221
+ * } );
222
+ *
223
+ * In order to make a nested `enqueueChange()` create a single undo step together with the changes done in the outer `change()`
224
+ * block, you can obtain the batch instance from the {@link module:engine/model/writer~Writer#batch writer} of the outer block.
225
+ *
226
+ * @param {module:engine/model/batch~Batch|Object} [batchOrType] A batch or a
227
+ * {@link module:engine/model/batch~Batch#constructor batch type} that should be used in the callback. If not defined, a new batch with
228
+ * the default type will be created.
229
+ * @param {Function} callback Callback function which may modify the model.
230
+ */
231
+ enqueueChange(batchOrType, callback) {
232
+ try {
233
+ if (!batchOrType) {
234
+ batchOrType = new Batch();
235
+ }
236
+ else if (typeof batchOrType === 'function') {
237
+ callback = batchOrType;
238
+ batchOrType = new Batch();
239
+ }
240
+ else if (!(batchOrType instanceof Batch)) {
241
+ batchOrType = new Batch(batchOrType);
242
+ }
243
+ this._pendingChanges.push({ batch: batchOrType, callback });
244
+ if (this._pendingChanges.length == 1) {
245
+ this._runPendingChanges();
246
+ }
247
+ }
248
+ catch (err) {
249
+ // @if CK_DEBUG // throw err;
250
+ /* istanbul ignore next */
251
+ CKEditorError.rethrowUnexpectedError(err, this);
252
+ }
253
+ }
254
+ /**
255
+ * {@link module:utils/observablemixin~ObservableMixin#decorate Decorated} function for applying
256
+ * {@link module:engine/model/operation/operation~Operation operations} to the model.
257
+ *
258
+ * This is a low-level way of changing the model. It is exposed for very specific use cases (like the undo feature).
259
+ * Normally, to modify the model, you will want to use {@link module:engine/model/writer~Writer `Writer`}.
260
+ * See also {@glink framework/guides/architecture/editing-engine#changing-the-model Changing the model} section
261
+ * of the {@glink framework/guides/architecture/editing-engine Editing architecture} guide.
262
+ *
263
+ * @param {module:engine/model/operation/operation~Operation} operation The operation to apply.
264
+ */
265
+ applyOperation(operation) {
266
+ // @if CK_DEBUG_ENGINE // console.log( 'Applying ' + operation );
267
+ // @if CK_DEBUG_ENGINE // if ( !this._operationLogs ) {
268
+ // @if CK_DEBUG_ENGINE // this._operationLogs = [];
269
+ // @if CK_DEBUG_ENGINE // }
270
+ // @if CK_DEBUG_ENGINE // this._operationLogs.push( JSON.stringify( operation ) );
271
+ // @if CK_DEBUG_ENGINE //if ( !this._appliedOperations ) {
272
+ // @if CK_DEBUG_ENGINE // this._appliedOperations = [];
273
+ // @if CK_DEBUG_ENGINE //}
274
+ // @if CK_DEBUG_ENGINE //this._appliedOperations.push( operation );
275
+ operation._execute();
276
+ }
277
+ // @if CK_DEBUG_ENGINE // getAppliedOperation() {
278
+ // @if CK_DEBUG_ENGINE // if ( !this._appliedOperations ) {
279
+ // @if CK_DEBUG_ENGINE // return '';
280
+ // @if CK_DEBUG_ENGINE // }
281
+ // @if CK_DEBUG_ENGINE // return this._appliedOperations.map( JSON.stringify ).join( '-------' );
282
+ // @if CK_DEBUG_ENGINE // }
283
+ // @if CK_DEBUG_ENGINE // createReplayer( stringifiedOperations ) {
284
+ // @if CK_DEBUG_ENGINE // return new OperationReplayer( this, '-------', stringifiedOperations );
285
+ // @if CK_DEBUG_ENGINE // }
286
+ /**
287
+ * Inserts content at the position in the editor specified by the selection, as one would expect the paste
288
+ * functionality to work.
289
+ *
290
+ * **Note**: If you want to insert an {@glink framework/guides/deep-dive/schema#object-elements object element}
291
+ * (e.g. a {@link module:widget/utils~toWidget widget}), see {@link #insertObject} instead.
292
+ *
293
+ * This is a high-level method. It takes the {@link #schema schema} into consideration when inserting
294
+ * the content, clears the given selection's content before inserting nodes and moves the selection
295
+ * to its target position at the end of the process.
296
+ * It can split elements, merge them, wrap bare text nodes with paragraphs, etc. &mdash; just like the
297
+ * pasting feature should do.
298
+ *
299
+ * For lower-level methods see {@link module:engine/model/writer~Writer `Writer`}.
300
+ *
301
+ * This method, unlike {@link module:engine/model/writer~Writer `Writer`}'s methods, does not have to be used
302
+ * inside a {@link #change `change()` block}.
303
+ *
304
+ * # Conversion and schema
305
+ *
306
+ * Inserting elements and text nodes into the model is not enough to make CKEditor 5 render that content
307
+ * to the user. CKEditor 5 implements a model-view-controller architecture and what `model.insertContent()` does
308
+ * is only adding nodes to the model. Additionally, you need to define
309
+ * {@glink framework/guides/architecture/editing-engine#conversion converters} between the model and view
310
+ * and define those nodes in the {@glink framework/guides/architecture/editing-engine#schema schema}.
311
+ *
312
+ * So, while this method may seem similar to CKEditor 4 `editor.insertHtml()` (in fact, both methods
313
+ * are used for paste-like content insertion), the CKEditor 5 method cannot be use to insert arbitrary HTML
314
+ * unless converters are defined for all elements and attributes in that HTML.
315
+ *
316
+ * # Examples
317
+ *
318
+ * Using `insertContent()` with a manually created model structure:
319
+ *
320
+ * // Let's create a document fragment containing such content as:
321
+ * //
322
+ * // <paragraph>foo</paragraph>
323
+ * // <blockQuote>
324
+ * // <paragraph>bar</paragraph>
325
+ * // </blockQuote>
326
+ * const docFrag = editor.model.change( writer => {
327
+ * const p1 = writer.createElement( 'paragraph' );
328
+ * const p2 = writer.createElement( 'paragraph' );
329
+ * const blockQuote = writer.createElement( 'blockQuote' );
330
+ * const docFrag = writer.createDocumentFragment();
331
+ *
332
+ * writer.append( p1, docFrag );
333
+ * writer.append( blockQuote, docFrag );
334
+ * writer.append( p2, blockQuote );
335
+ * writer.insertText( 'foo', p1 );
336
+ * writer.insertText( 'bar', p2 );
337
+ *
338
+ * return docFrag;
339
+ * } );
340
+ *
341
+ * // insertContent() does not have to be used in a change() block. It can, though,
342
+ * // so this code could be moved to the callback defined above.
343
+ * editor.model.insertContent( docFrag );
344
+ *
345
+ * Using `insertContent()` with an HTML string converted to a model document fragment (similar to the pasting mechanism):
346
+ *
347
+ * // You can create your own HtmlDataProcessor instance or use editor.data.processor
348
+ * // if you have not overridden the default one (which is the HtmlDataProcessor instance).
349
+ * const htmlDP = new HtmlDataProcessor( viewDocument );
350
+ *
351
+ * // Convert an HTML string to a view document fragment:
352
+ * const viewFragment = htmlDP.toView( htmlString );
353
+ *
354
+ * // Convert the view document fragment to a model document fragment
355
+ * // in the context of $root. This conversion takes the schema into
356
+ * // account so if, for example, the view document fragment contained a bare text node,
357
+ * // this text node cannot be a child of $root, so it will be automatically
358
+ * // wrapped with a <paragraph>. You can define the context yourself (in the second parameter),
359
+ * // and e.g. convert the content like it would happen in a <paragraph>.
360
+ * // Note: The clipboard feature uses a custom context called $clipboardHolder
361
+ * // which has a loosened schema.
362
+ * const modelFragment = editor.data.toModel( viewFragment );
363
+ *
364
+ * editor.model.insertContent( modelFragment );
365
+ *
366
+ * By default this method will use the document selection but it can also be used with a position, range or selection instance.
367
+ *
368
+ * // Insert text at the current document selection position.
369
+ * editor.model.change( writer => {
370
+ * editor.model.insertContent( writer.createText( 'x' ) );
371
+ * } );
372
+ *
373
+ * // Insert text at a given position - the document selection will not be modified.
374
+ * editor.model.change( writer => {
375
+ * editor.model.insertContent( writer.createText( 'x' ), doc.getRoot(), 2 );
376
+ *
377
+ * // Which is a shorthand for:
378
+ * editor.model.insertContent( writer.createText( 'x' ), writer.createPositionAt( doc.getRoot(), 2 ) );
379
+ * } );
380
+ *
381
+ * If you want the document selection to be moved to the inserted content, use the
382
+ * {@link module:engine/model/writer~Writer#setSelection `setSelection()`} method of the writer after inserting
383
+ * the content:
384
+ *
385
+ * editor.model.change( writer => {
386
+ * const paragraph = writer.createElement( 'paragraph' );
387
+ *
388
+ * // Insert an empty paragraph at the beginning of the root.
389
+ * editor.model.insertContent( paragraph, writer.createPositionAt( editor.model.document.getRoot(), 0 ) );
390
+ *
391
+ * // Move the document selection to the inserted paragraph.
392
+ * writer.setSelection( paragraph, 'in' );
393
+ * } );
394
+ *
395
+ * If an instance of the {@link module:engine/model/selection~Selection model selection} is passed as `selectable`,
396
+ * the new content will be inserted at the passed selection (instead of document selection):
397
+ *
398
+ * editor.model.change( writer => {
399
+ * // Create a selection in a paragraph that will be used as a place of insertion.
400
+ * const selection = writer.createSelection( paragraph, 'in' );
401
+ *
402
+ * // Insert the new text at the created selection.
403
+ * editor.model.insertContent( writer.createText( 'x' ), selection );
404
+ *
405
+ * // insertContent() modifies the passed selection instance so it can be used to set the document selection.
406
+ * // Note: This is not necessary when you passed the document selection to insertContent().
407
+ * writer.setSelection( selection );
408
+ * } );
409
+ *
410
+ * @fires insertContent
411
+ * @param {module:engine/model/documentfragment~DocumentFragment|module:engine/model/item~Item} content The content to insert.
412
+ * @param {module:engine/model/selection~Selectable} [selectable=model.document.selection]
413
+ * The selection into which the content should be inserted. If not provided the current model document selection will be used.
414
+ * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] To be used when a model item was passed as `selectable`.
415
+ * This param defines a position in relation to that item.
416
+ * @returns {module:engine/model/range~Range} Range which contains all the performed changes. This is a range that, if removed,
417
+ * would return the model to the state before the insertion. If no changes were preformed by `insertContent`, returns a range collapsed
418
+ * at the insertion position.
419
+ */
420
+ insertContent(content, selectable, placeOrOffset) {
421
+ return insertContent(this, content, selectable, placeOrOffset);
422
+ }
423
+ /**
424
+ * Inserts an {@glink framework/guides/deep-dive/schema#object-elements object element} at a specific position in the editor content.
425
+ *
426
+ * This is a high-level API:
427
+ * * It takes the {@link #schema schema} into consideration,
428
+ * * It clears the content of passed `selectable` before inserting,
429
+ * * It can move the selection at the end of the process,
430
+ * * It will copy the selected block's attributes to preserve them upon insertion,
431
+ * * It can split elements or wrap inline objects with paragraphs if they are not allowed in target position,
432
+ * * etc.
433
+ *
434
+ * # Notes
435
+ *
436
+ * * If you want to insert a non-object content, see {@link #insertContent} instead.
437
+ * * For lower-level API, see {@link module:engine/model/writer~Writer `Writer`}.
438
+ * * Unlike {@link module:engine/model/writer~Writer `Writer`}, this method does not have to be used inside
439
+ * a {@link #change `change()` block}.
440
+ * * Inserting object into the model is not enough to make CKEditor 5 render that content to the user.
441
+ * CKEditor 5 implements a model-view-controller architecture and what `model.insertObject()` does
442
+ * is only adding nodes to the model. Additionally, you need to define
443
+ * {@glink framework/guides/architecture/editing-engine#conversion converters} between the model and view
444
+ * and define those nodes in the {@glink framework/guides/architecture/editing-engine#schema schema}.
445
+ *
446
+ * # Examples
447
+ *
448
+ * Use the following code to insert an object at the current selection and keep the selection on the inserted element:
449
+ *
450
+ * const rawHtmlEmbedElement = writer.createElement( 'rawHtml' );
451
+ *
452
+ * model.insertObject( rawHtmlEmbedElement, null, null, {
453
+ * setSelection: 'on'
454
+ * } );
455
+ *
456
+ * Use the following code to insert an object at the current selection and nudge the selection after the inserted object:
457
+ *
458
+ * const pageBreakElement = writer.createElement( 'pageBreak' );
459
+ *
460
+ * model.insertObject( pageBreakElement, null, null, {
461
+ * setSelection: 'after'
462
+ * } );
463
+ *
464
+ * Use the following code to insert an object at the current selection and avoid splitting the content (non-destructive insertion):
465
+ *
466
+ * const tableElement = writer.createElement( 'table' );
467
+ *
468
+ * model.insertObject( tableElement, null, null, {
469
+ * findOptimalPosition: 'auto'
470
+ * } );
471
+ *
472
+ * Use the following code to insert an object at the specific range (also: replace the content of the range):
473
+ *
474
+ * const tableElement = writer.createElement( 'table' );
475
+ * const range = model.createRangeOn( model.document.getRoot().getChild( 1 ) );
476
+ *
477
+ * model.insertObject( tableElement, range );
478
+ *
479
+ * @param {module:engine/model/element~Element} object An object to be inserted into the model document.
480
+ * @param {module:engine/model/selection~Selectable} [selectable=model.document.selection]
481
+ * A selectable where the content should be inserted. If not specified, the current
482
+ * {@link module:engine/model/document~Document#selection document selection} will be used instead.
483
+ * @param {Number|'before'|'end'|'after'|'on'|'in'} placeOrOffset Specifies the exact place or offset for the insertion to take place,
484
+ * relative to `selectable`.
485
+ * @param {Object} [options] Additional options.
486
+ * @param {'auto'|'before'|'after'} [options.findOptimalPosition] An option that, when set, adjusts the insertion position (relative to
487
+ * `selectable` and `placeOrOffset`) so that the content of `selectable` is not split upon insertion (a.k.a. non-destructive insertion).
488
+ * * When `'auto'`, the algorithm will decide whether to insert the object before or after `selectable` to avoid content splitting.
489
+ * * When `'before'`, the closest position before `selectable` will be used that will not result in content splitting.
490
+ * * When `'after'`, the closest position after `selectable` will be used that will not result in content splitting.
491
+ *
492
+ * Note that this option only works for block objects. Inline objects are inserted into text and do not split blocks.
493
+ * @param {'on'|'after'} [options.setSelection] An option that, when set, moves the
494
+ * {@link module:engine/model/document~Document#selection document selection} after inserting the object.
495
+ * * When `'on'`, the document selection will be set on the inserted object.
496
+ * * When `'after'`, the document selection will move to the closest text node after the inserted object. If there is no
497
+ * such text node, a paragraph will be created and the document selection will be moved inside it.
498
+ * @returns {module:engine/model/range~Range} A range which contains all the performed changes. This is a range that, if removed,
499
+ * would return the model to the state before the insertion. If no changes were preformed by `insertObject()`, returns a range collapsed
500
+ * at the insertion position.
501
+ */
502
+ insertObject(object, selectable, placeOrOffset, options) {
503
+ return insertObject(this, object, selectable, placeOrOffset, options);
504
+ }
505
+ /**
506
+ * Deletes content of the selection and merge siblings. The resulting selection is always collapsed.
507
+ *
508
+ * **Note:** For the sake of predictability, the resulting selection should always be collapsed.
509
+ * In cases where a feature wants to modify deleting behavior so selection isn't collapsed
510
+ * (e.g. a table feature may want to keep row selection after pressing <kbd>Backspace</kbd>),
511
+ * then that behavior should be implemented in the view's listener. At the same time, the table feature
512
+ * will need to modify this method's behavior too, e.g. to "delete contents and then collapse
513
+ * the selection inside the last selected cell" or "delete the row and collapse selection somewhere near".
514
+ * That needs to be done in order to ensure that other features which use `deleteContent()` will work well with tables.
515
+ *
516
+ * @fires deleteContent
517
+ * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
518
+ * Selection of which the content should be deleted.
519
+ * @param {Object} [options]
520
+ * @param {Boolean} [options.leaveUnmerged=false] Whether to merge elements after removing the content of the selection.
521
+ *
522
+ * For example `<heading1>x[x</heading1><paragraph>y]y</paragraph>` will become:
523
+ *
524
+ * * `<heading1>x^y</heading1>` with the option disabled (`leaveUnmerged == false`)
525
+ * * `<heading1>x^</heading1><paragraph>y</paragraph>` with enabled (`leaveUnmerged == true`).
526
+ *
527
+ * Note: {@link module:engine/model/schema~Schema#isObject object} and {@link module:engine/model/schema~Schema#isLimit limit}
528
+ * elements will not be merged.
529
+ *
530
+ * @param {Boolean} [options.doNotResetEntireContent=false] Whether to skip replacing the entire content with a
531
+ * paragraph when the entire content was selected.
532
+ *
533
+ * For example `<heading1>[x</heading1><paragraph>y]</paragraph>` will become:
534
+ *
535
+ * * `<paragraph>^</paragraph>` with the option disabled (`doNotResetEntireContent == false`)
536
+ * * `<heading1>^</heading1>` with enabled (`doNotResetEntireContent == true`)
537
+ *
538
+ * @param {Boolean} [options.doNotAutoparagraph=false] Whether to create a paragraph if after content deletion selection is moved
539
+ * to a place where text cannot be inserted.
540
+ *
541
+ * For example `<paragraph>x</paragraph>[<imageBlock src="foo.jpg"></imageBlock>]` will become:
542
+ *
543
+ * * `<paragraph>x</paragraph><paragraph>[]</paragraph>` with the option disabled (`doNotAutoparagraph == false`)
544
+ * * `<paragraph>x[]</paragraph>` with the option enabled (`doNotAutoparagraph == true`).
545
+ *
546
+ * **Note:** if there is no valid position for the selection, the paragraph will always be created:
547
+ *
548
+ * `[<imageBlock src="foo.jpg"></imageBlock>]` -> `<paragraph>[]</paragraph>`.
549
+ *
550
+ * @param {'forward'|'backward'} [options.direction='backward'] The direction in which the content is being consumed.
551
+ * Deleting backward corresponds to using the <kbd>Backspace</kbd> key, while deleting content forward corresponds to
552
+ * the <kbd>Shift</kbd>+<kbd>Backspace</kbd> keystroke.
553
+ */
554
+ deleteContent(selection, options) {
555
+ deleteContent(this, selection, options);
556
+ }
557
+ /**
558
+ * Modifies the selection. Currently, the supported modifications are:
559
+ *
560
+ * * Extending. The selection focus is moved in the specified `options.direction` with a step specified in `options.unit`.
561
+ * Possible values for `unit` are:
562
+ * * `'character'` (default) - moves selection by one user-perceived character. In most cases this means moving by one
563
+ * character in `String` sense. However, unicode also defines "combing marks". These are special symbols, that combines
564
+ * with a symbol before it ("base character") to create one user-perceived character. For example, `q̣̇` is a normal
565
+ * letter `q` with two "combining marks": upper dot (`Ux0307`) and lower dot (`Ux0323`). For most actions, i.e. extending
566
+ * selection by one position, it is correct to include both "base character" and all of it's "combining marks". That is
567
+ * why `'character'` value is most natural and common method of modifying selection.
568
+ * * `'codePoint'` - moves selection by one unicode code point. In contrary to, `'character'` unit, this will insert
569
+ * selection between "base character" and "combining mark", because "combining marks" have their own unicode code points.
570
+ * However, for technical reasons, unicode code points with values above `UxFFFF` are represented in native `String` by
571
+ * two characters, called "surrogate pairs". Halves of "surrogate pairs" have a meaning only when placed next to each other.
572
+ * For example `𨭎` is represented in `String` by `\uD862\uDF4E`. Both `\uD862` and `\uDF4E` do not have any meaning
573
+ * outside the pair (are rendered as ? when alone). Position between them would be incorrect. In this case, selection
574
+ * extension will include whole "surrogate pair".
575
+ * * `'word'` - moves selection by a whole word.
576
+ *
577
+ * **Note:** if you extend a forward selection in a backward direction you will in fact shrink it.
578
+ *
579
+ * @fires modifySelection
580
+ * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
581
+ * The selection to modify.
582
+ * @param {Object} [options]
583
+ * @param {'forward'|'backward'} [options.direction='forward'] The direction in which the selection should be modified.
584
+ * @param {'character'|'codePoint'|'word'} [options.unit='character'] The unit by which selection should be modified.
585
+ * @param {Boolean} [options.treatEmojiAsSingleUnit=false] Whether multi-characer emoji sequences should be handled as single unit.
586
+ */
587
+ modifySelection(selection, options) {
588
+ modifySelection(this, selection, options);
589
+ }
590
+ /**
591
+ * Gets a clone of the selected content.
592
+ *
593
+ * For example, for the following selection:
594
+ *
595
+ * ```html
596
+ * <paragraph>x</paragraph>
597
+ * <blockQuote>
598
+ * <paragraph>y</paragraph>
599
+ * <heading1>fir[st</heading1>
600
+ * </blockQuote>
601
+ * <paragraph>se]cond</paragraph>
602
+ * <paragraph>z</paragraph>
603
+ * ```
604
+ *
605
+ * It will return a document fragment with such a content:
606
+ *
607
+ * ```html
608
+ * <blockQuote>
609
+ * <heading1>st</heading1>
610
+ * </blockQuote>
611
+ * <paragraph>se</paragraph>
612
+ * ```
613
+ *
614
+ * @fires getSelectedContent
615
+ * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
616
+ * The selection of which content will be returned.
617
+ * @returns {module:engine/model/documentfragment~DocumentFragment}
618
+ */
619
+ getSelectedContent(selection) {
620
+ return getSelectedContent(this, selection);
621
+ }
622
+ /**
623
+ * Checks whether the given {@link module:engine/model/range~Range range} or
624
+ * {@link module:engine/model/element~Element element} has any meaningful content.
625
+ *
626
+ * Meaningful content is:
627
+ *
628
+ * * any text node (`options.ignoreWhitespaces` allows controlling whether this text node must also contain
629
+ * any non-whitespace characters),
630
+ * * or any {@link module:engine/model/schema~Schema#isContent content element},
631
+ * * or any {@link module:engine/model/markercollection~Marker marker} which
632
+ * {@link module:engine/model/markercollection~Marker#_affectsData affects data}.
633
+ *
634
+ * This means that a range containing an empty `<paragraph></paragraph>` is not considered to have a meaningful content.
635
+ * However, a range containing an `<imageBlock></imageBlock>` (which would normally be marked in the schema as an object element)
636
+ * is considered non-empty.
637
+ *
638
+ * @param {module:engine/model/range~Range|module:engine/model/element~Element} rangeOrElement Range or element to check.
639
+ * @param {Object} [options]
640
+ * @param {Boolean} [options.ignoreWhitespaces] Whether text node with whitespaces only should be considered empty.
641
+ * @param {Boolean} [options.ignoreMarkers] Whether markers should be ignored.
642
+ * @returns {Boolean}
643
+ */
644
+ hasContent(rangeOrElement, options = {}) {
645
+ const range = rangeOrElement instanceof ModelRange ? rangeOrElement : ModelRange._createIn(rangeOrElement);
646
+ if (range.isCollapsed) {
647
+ return false;
648
+ }
649
+ const { ignoreWhitespaces = false, ignoreMarkers = false } = options;
650
+ // Check if there are any markers which affects data in this given range.
651
+ if (!ignoreMarkers) {
652
+ for (const intersectingMarker of this.markers.getMarkersIntersectingRange(range)) {
653
+ if (intersectingMarker.affectsData) {
654
+ return true;
655
+ }
656
+ }
657
+ }
658
+ for (const item of range.getItems()) {
659
+ if (this.schema.isContent(item)) {
660
+ if (item.is('$textProxy')) {
661
+ if (!ignoreWhitespaces) {
662
+ return true;
663
+ }
664
+ else if (item.data.search(/\S/) !== -1) {
665
+ return true;
666
+ }
667
+ }
668
+ else {
669
+ return true;
670
+ }
671
+ }
672
+ }
673
+ return false;
674
+ }
675
+ /**
676
+ * Creates a position from the given root and path in that root.
677
+ *
678
+ * Note: This method is also available as
679
+ * {@link module:engine/model/writer~Writer#createPositionFromPath `Writer#createPositionFromPath()`}.
680
+ *
681
+ * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} root Root of the position.
682
+ * @param {Array.<Number>} path Position path. See {@link module:engine/model/position~Position#path}.
683
+ * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
684
+ * See {@link module:engine/model/position~PositionStickiness}.
685
+ * @returns {module:engine/model/position~Position}
686
+ */
687
+ createPositionFromPath(root, path, stickiness) {
688
+ return new ModelPosition(root, path, stickiness);
689
+ }
690
+ /**
691
+ * Creates position at the given location. The location can be specified as:
692
+ *
693
+ * * a {@link module:engine/model/position~Position position},
694
+ * * a parent element and offset in that element,
695
+ * * a parent element and `'end'` (the position will be set at the end of that element),
696
+ * * a {@link module:engine/model/item~Item model item} and `'before'` or `'after'`
697
+ * (the position will be set before or after the given model item).
698
+ *
699
+ * This method is a shortcut to other factory methods such as:
700
+ *
701
+ * * {@link module:engine/model/model~Model#createPositionBefore `createPositionBefore()`},
702
+ * * {@link module:engine/model/model~Model#createPositionAfter `createPositionAfter()`}.
703
+ *
704
+ * Note: This method is also available as
705
+ * {@link module:engine/model/writer~Writer#createPositionAt `Writer#createPositionAt()`},
706
+ *
707
+ * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
708
+ * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
709
+ * first parameter is a {@link module:engine/model/item~Item model item}.
710
+ */
711
+ createPositionAt(itemOrPosition, offset) {
712
+ return ModelPosition._createAt(itemOrPosition, offset);
713
+ }
714
+ /**
715
+ * Creates a new position after the given {@link module:engine/model/item~Item model item}.
716
+ *
717
+ * Note: This method is also available as
718
+ * {@link module:engine/model/writer~Writer#createPositionAfter `Writer#createPositionAfter()`}.
719
+ *
720
+ * @param {module:engine/model/item~Item} item Item after which the position should be placed.
721
+ * @returns {module:engine/model/position~Position}
722
+ */
723
+ createPositionAfter(item) {
724
+ return ModelPosition._createAfter(item);
725
+ }
726
+ /**
727
+ * Creates a new position before the given {@link module:engine/model/item~Item model item}.
728
+ *
729
+ * Note: This method is also available as
730
+ * {@link module:engine/model/writer~Writer#createPositionBefore `Writer#createPositionBefore()`}.
731
+ *
732
+ * @param {module:engine/model/item~Item} item Item before which the position should be placed.
733
+ * @returns {module:engine/model/position~Position}
734
+ */
735
+ createPositionBefore(item) {
736
+ return ModelPosition._createBefore(item);
737
+ }
738
+ /**
739
+ * Creates a range spanning from the `start` position to the `end` position.
740
+ *
741
+ * Note: This method is also available as
742
+ * {@link module:engine/model/writer~Writer#createRange `Writer#createRange()`}:
743
+ *
744
+ * model.change( writer => {
745
+ * const range = writer.createRange( start, end );
746
+ * } );
747
+ *
748
+ * @param {module:engine/model/position~Position} start Start position.
749
+ * @param {module:engine/model/position~Position} [end] End position. If not set, the range will be collapsed
750
+ * to the `start` position.
751
+ * @returns {module:engine/model/range~Range}
752
+ */
753
+ createRange(start, end) {
754
+ return new ModelRange(start, end);
755
+ }
756
+ /**
757
+ * Creates a range inside the given element which starts before the first child of
758
+ * that element and ends after the last child of that element.
759
+ *
760
+ * Note: This method is also available as
761
+ * {@link module:engine/model/writer~Writer#createRangeIn `Writer#createRangeIn()`}:
762
+ *
763
+ * model.change( writer => {
764
+ * const range = writer.createRangeIn( paragraph );
765
+ * } );
766
+ *
767
+ * @param {module:engine/model/element~Element} element Element which is a parent for the range.
768
+ * @returns {module:engine/model/range~Range}
769
+ */
770
+ createRangeIn(element) {
771
+ return ModelRange._createIn(element);
772
+ }
773
+ /**
774
+ * Creates a range that starts before the given {@link module:engine/model/item~Item model item} and ends after it.
775
+ *
776
+ * Note: This method is also available on `writer` instance as
777
+ * {@link module:engine/model/writer~Writer#createRangeOn `Writer.createRangeOn()`}:
778
+ *
779
+ * model.change( writer => {
780
+ * const range = writer.createRangeOn( paragraph );
781
+ * } );
782
+ *
783
+ * @param {module:engine/model/item~Item} item
784
+ * @returns {module:engine/model/range~Range}
785
+ */
786
+ createRangeOn(item) {
787
+ return ModelRange._createOn(item);
788
+ }
789
+ /**
790
+ * Creates a new selection instance based on the given {@link module:engine/model/selection~Selectable selectable}
791
+ * or creates an empty selection if no arguments were passed.
792
+ *
793
+ * Note: This method is also available as
794
+ * {@link module:engine/model/writer~Writer#createSelection `Writer#createSelection()`}.
795
+ *
796
+ * // Creates empty selection without ranges.
797
+ * const selection = writer.createSelection();
798
+ *
799
+ * // Creates selection at the given range.
800
+ * const range = writer.createRange( start, end );
801
+ * const selection = writer.createSelection( range );
802
+ *
803
+ * // Creates selection at the given ranges
804
+ * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
805
+ * const selection = writer.createSelection( ranges );
806
+ *
807
+ * // Creates selection from the other selection.
808
+ * // Note: It doesn't copies selection attributes.
809
+ * const otherSelection = writer.createSelection();
810
+ * const selection = writer.createSelection( otherSelection );
811
+ *
812
+ * // Creates selection from the given document selection.
813
+ * // Note: It doesn't copies selection attributes.
814
+ * const documentSelection = model.document.selection;
815
+ * const selection = writer.createSelection( documentSelection );
816
+ *
817
+ * // Creates selection at the given position.
818
+ * const position = writer.createPositionFromPath( root, path );
819
+ * const selection = writer.createSelection( position );
820
+ *
821
+ * // Creates selection at the given offset in the given element.
822
+ * const paragraph = writer.createElement( 'paragraph' );
823
+ * const selection = writer.createSelection( paragraph, offset );
824
+ *
825
+ * // Creates a range inside an {@link module:engine/model/element~Element element} which starts before the
826
+ * // first child of that element and ends after the last child of that element.
827
+ * const selection = writer.createSelection( paragraph, 'in' );
828
+ *
829
+ * // Creates a range on an {@link module:engine/model/item~Item item} which starts before the item and ends
830
+ * // just after the item.
831
+ * const selection = writer.createSelection( paragraph, 'on' );
832
+ *
833
+ * // Additional options (`'backward'`) can be specified as the last argument.
834
+ *
835
+ * // Creates backward selection.
836
+ * const selection = writer.createSelection( range, { backward: true } );
837
+ *
838
+ * @param {module:engine/model/selection~Selectable} selectable
839
+ * @param {Number|'before'|'end'|'after'|'on'|'in'} [optionsOrPlaceOrOffset] Sets place or offset of the selection.
840
+ * @param {Object} [options]
841
+ * @param {Boolean} [options.backward] Sets this selection instance to be backward.
842
+ * @returns {module:engine/model/selection~Selection}
843
+ */
844
+ createSelection(...args) {
845
+ return new ModelSelection(...args);
846
+ }
847
+ /**
848
+ * Creates a {@link module:engine/model/batch~Batch} instance.
849
+ *
850
+ * **Note:** In most cases creating a batch instance is not necessary as they are created when using:
851
+ *
852
+ * * {@link #change `change()`},
853
+ * * {@link #enqueueChange `enqueueChange()`}.
854
+ *
855
+ * @param {Object} [type] {@link module:engine/model/batch~Batch#constructor The type} of the batch.
856
+ * @returns {module:engine/model/batch~Batch}
857
+ */
858
+ createBatch(type) {
859
+ return new Batch(type);
860
+ }
861
+ /**
862
+ * Creates an operation instance from a JSON object (parsed JSON string).
863
+ *
864
+ * This is an alias for {@link module:engine/model/operation/operationfactory~OperationFactory.fromJSON `OperationFactory.fromJSON()`}.
865
+ *
866
+ * @param {Object} json Deserialized JSON object.
867
+ * @returns {module:engine/model/operation/operation~Operation}
868
+ */
869
+ createOperationFromJSON(json) {
870
+ return OperationFactory.fromJSON(json, this.document);
871
+ }
872
+ /**
873
+ * Removes all events listeners set by model instance and destroys {@link module:engine/model/document~Document}.
874
+ */
875
+ destroy() {
876
+ this.document.destroy();
877
+ this.stopListening();
878
+ }
879
+ /**
880
+ * Common part of {@link module:engine/model/model~Model#change} and {@link module:engine/model/model~Model#enqueueChange}
881
+ * which calls callbacks and returns array of values returned by these callbacks.
882
+ *
883
+ * @private
884
+ * @returns {Array.<*>} Array of values returned by callbacks.
885
+ */
886
+ _runPendingChanges() {
887
+ const ret = [];
888
+ this.fire('_beforeChanges');
889
+ try {
890
+ while (this._pendingChanges.length) {
891
+ // Create a new writer using batch instance created for this chain of changes.
892
+ const currentBatch = this._pendingChanges[0].batch;
893
+ this._currentWriter = new Writer(this, currentBatch);
894
+ // Execute changes callback and gather the returned value.
895
+ const callbackReturnValue = this._pendingChanges[0].callback(this._currentWriter);
896
+ ret.push(callbackReturnValue);
897
+ this.document._handleChangeBlock(this._currentWriter);
898
+ this._pendingChanges.shift();
899
+ this._currentWriter = null;
900
+ }
901
+ }
902
+ finally {
903
+ this._pendingChanges.length = 0;
904
+ this._currentWriter = null;
905
+ this.fire('_afterChanges');
906
+ }
907
+ return ret;
908
+ }
1058
909
  }
1059
-
1060
- mix( Model, ObservableMixin );