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