@ckeditor/ckeditor5-engine 34.2.0 → 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 (125) hide show
  1. package/CHANGELOG.md +823 -0
  2. package/LICENSE.md +4 -0
  3. package/package.json +32 -25
  4. package/src/controller/datacontroller.js +467 -561
  5. package/src/controller/editingcontroller.js +168 -204
  6. package/src/conversion/conversion.js +541 -565
  7. package/src/conversion/conversionhelpers.js +24 -28
  8. package/src/conversion/downcastdispatcher.js +457 -686
  9. package/src/conversion/downcasthelpers.js +1583 -1965
  10. package/src/conversion/mapper.js +518 -707
  11. package/src/conversion/modelconsumable.js +240 -283
  12. package/src/conversion/upcastdispatcher.js +372 -718
  13. package/src/conversion/upcasthelpers.js +707 -818
  14. package/src/conversion/viewconsumable.js +524 -581
  15. package/src/dataprocessor/basichtmlwriter.js +12 -16
  16. package/src/dataprocessor/dataprocessor.js +5 -0
  17. package/src/dataprocessor/htmldataprocessor.js +101 -117
  18. package/src/dataprocessor/htmlwriter.js +1 -18
  19. package/src/dataprocessor/xmldataprocessor.js +117 -138
  20. package/src/dev-utils/model.js +260 -352
  21. package/src/dev-utils/operationreplayer.js +106 -126
  22. package/src/dev-utils/utils.js +34 -51
  23. package/src/dev-utils/view.js +632 -753
  24. package/src/index.js +0 -11
  25. package/src/model/batch.js +111 -127
  26. package/src/model/differ.js +988 -1233
  27. package/src/model/document.js +340 -449
  28. package/src/model/documentfragment.js +327 -364
  29. package/src/model/documentselection.js +996 -1189
  30. package/src/model/element.js +306 -410
  31. package/src/model/history.js +224 -262
  32. package/src/model/item.js +5 -0
  33. package/src/model/liveposition.js +84 -145
  34. package/src/model/liverange.js +108 -185
  35. package/src/model/markercollection.js +379 -480
  36. package/src/model/model.js +883 -1034
  37. package/src/model/node.js +419 -463
  38. package/src/model/nodelist.js +175 -201
  39. package/src/model/operation/attributeoperation.js +153 -182
  40. package/src/model/operation/detachoperation.js +64 -83
  41. package/src/model/operation/insertoperation.js +135 -166
  42. package/src/model/operation/markeroperation.js +114 -140
  43. package/src/model/operation/mergeoperation.js +163 -191
  44. package/src/model/operation/moveoperation.js +157 -187
  45. package/src/model/operation/nooperation.js +28 -38
  46. package/src/model/operation/operation.js +106 -125
  47. package/src/model/operation/operationfactory.js +30 -34
  48. package/src/model/operation/renameoperation.js +109 -135
  49. package/src/model/operation/rootattributeoperation.js +155 -188
  50. package/src/model/operation/splitoperation.js +196 -232
  51. package/src/model/operation/transform.js +1833 -2204
  52. package/src/model/operation/utils.js +140 -204
  53. package/src/model/position.js +899 -1053
  54. package/src/model/range.js +910 -1028
  55. package/src/model/rootelement.js +77 -97
  56. package/src/model/schema.js +1189 -1835
  57. package/src/model/selection.js +745 -862
  58. package/src/model/text.js +90 -114
  59. package/src/model/textproxy.js +204 -240
  60. package/src/model/treewalker.js +316 -397
  61. package/src/model/typecheckable.js +16 -0
  62. package/src/model/utils/autoparagraphing.js +32 -44
  63. package/src/model/utils/deletecontent.js +334 -418
  64. package/src/model/utils/findoptimalinsertionrange.js +25 -36
  65. package/src/model/utils/getselectedcontent.js +96 -118
  66. package/src/model/utils/insertcontent.js +654 -773
  67. package/src/model/utils/insertobject.js +96 -119
  68. package/src/model/utils/modifyselection.js +120 -158
  69. package/src/model/utils/selection-post-fixer.js +153 -201
  70. package/src/model/writer.js +1305 -1474
  71. package/src/view/attributeelement.js +189 -225
  72. package/src/view/containerelement.js +75 -85
  73. package/src/view/document.js +172 -215
  74. package/src/view/documentfragment.js +200 -249
  75. package/src/view/documentselection.js +338 -367
  76. package/src/view/domconverter.js +1371 -1613
  77. package/src/view/downcastwriter.js +1747 -2076
  78. package/src/view/editableelement.js +81 -97
  79. package/src/view/element.js +739 -890
  80. package/src/view/elementdefinition.js +5 -0
  81. package/src/view/emptyelement.js +82 -92
  82. package/src/view/filler.js +35 -50
  83. package/src/view/item.js +5 -0
  84. package/src/view/matcher.js +260 -559
  85. package/src/view/node.js +274 -360
  86. package/src/view/observer/arrowkeysobserver.js +19 -28
  87. package/src/view/observer/bubblingemittermixin.js +120 -263
  88. package/src/view/observer/bubblingeventinfo.js +47 -55
  89. package/src/view/observer/clickobserver.js +7 -13
  90. package/src/view/observer/compositionobserver.js +14 -24
  91. package/src/view/observer/domeventdata.js +57 -67
  92. package/src/view/observer/domeventobserver.js +40 -64
  93. package/src/view/observer/fakeselectionobserver.js +81 -96
  94. package/src/view/observer/focusobserver.js +45 -61
  95. package/src/view/observer/inputobserver.js +7 -13
  96. package/src/view/observer/keyobserver.js +17 -27
  97. package/src/view/observer/mouseobserver.js +7 -14
  98. package/src/view/observer/mutationobserver.js +220 -315
  99. package/src/view/observer/observer.js +81 -102
  100. package/src/view/observer/selectionobserver.js +191 -246
  101. package/src/view/observer/tabobserver.js +23 -36
  102. package/src/view/placeholder.js +128 -173
  103. package/src/view/position.js +350 -401
  104. package/src/view/range.js +453 -513
  105. package/src/view/rawelement.js +85 -112
  106. package/src/view/renderer.js +874 -1014
  107. package/src/view/rooteditableelement.js +80 -90
  108. package/src/view/selection.js +608 -689
  109. package/src/view/styles/background.js +43 -44
  110. package/src/view/styles/border.js +220 -276
  111. package/src/view/styles/margin.js +8 -17
  112. package/src/view/styles/padding.js +8 -16
  113. package/src/view/styles/utils.js +127 -160
  114. package/src/view/stylesmap.js +728 -905
  115. package/src/view/text.js +102 -126
  116. package/src/view/textproxy.js +144 -170
  117. package/src/view/treewalker.js +383 -479
  118. package/src/view/typecheckable.js +19 -0
  119. package/src/view/uielement.js +166 -187
  120. package/src/view/upcastwriter.js +395 -449
  121. package/src/view/view.js +569 -664
  122. package/src/dataprocessor/dataprocessor.jsdoc +0 -64
  123. package/src/model/item.jsdoc +0 -14
  124. package/src/view/elementdefinition.jsdoc +0 -59
  125. package/src/view/item.jsdoc +0 -14
@@ -2,26 +2,20 @@
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/document
8
7
  */
9
-
10
8
  import Differ from './differ';
11
- import RootElement from './rootelement';
12
- import History from './history';
13
9
  import DocumentSelection from './documentselection';
10
+ import History from './history';
11
+ import RootElement from './rootelement';
14
12
  import Collection from '@ckeditor/ckeditor5-utils/src/collection';
15
- import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
13
+ import { Emitter } from '@ckeditor/ckeditor5-utils/src/emittermixin';
16
14
  import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
17
- import mix from '@ckeditor/ckeditor5-utils/src/mix';
18
15
  import { isInsideSurrogatePair, isInsideCombinedSymbol } from '@ckeditor/ckeditor5-utils/src/unicode';
19
16
  import { clone } from 'lodash-es';
20
-
21
17
  // @if CK_DEBUG_ENGINE // const { logDocument } = require( '../dev-utils/utils' );
22
-
23
18
  const graveyardName = '$graveyard';
24
-
25
19
  /**
26
20
  * Data model's document. It contains the model's structure, its selection and the history of changes.
27
21
  *
@@ -38,447 +32,344 @@ const graveyardName = '$graveyard';
38
32
  *
39
33
  * @mixes module:utils/emittermixin~EmitterMixin
40
34
  */
41
- export default class Document {
42
- /**
43
- * Creates an empty document instance with no {@link #roots} (other than
44
- * the {@link #graveyard graveyard root}).
45
- */
46
- constructor( model ) {
47
- /**
48
- * The {@link module:engine/model/model~Model model} that the document is a part of.
49
- *
50
- * @readonly
51
- * @type {module:engine/model/model~Model}
52
- */
53
- this.model = model;
54
-
55
- /**
56
- * The document's history.
57
- *
58
- * @readonly
59
- * @type {module:engine/model/history~History}
60
- */
61
- this.history = new History();
62
-
63
- /**
64
- * The selection in this document.
65
- *
66
- * @readonly
67
- * @type {module:engine/model/documentselection~DocumentSelection}
68
- */
69
- this.selection = new DocumentSelection( this );
70
-
71
- /**
72
- * A list of roots that are owned and managed by this document. Use {@link #createRoot} and
73
- * {@link #getRoot} to manipulate it.
74
- *
75
- * @readonly
76
- * @type {module:utils/collection~Collection}
77
- */
78
- this.roots = new Collection( { idProperty: 'rootName' } );
79
-
80
- /**
81
- * The model differ object. Its role is to buffer changes done on the model document and then calculate a diff of those changes.
82
- *
83
- * @readonly
84
- * @type {module:engine/model/differ~Differ}
85
- */
86
- this.differ = new Differ( model.markers );
87
-
88
- /**
89
- * Post-fixer callbacks registered to the model document.
90
- *
91
- * @private
92
- * @type {Set.<Function>}
93
- */
94
- this._postFixers = new Set();
95
-
96
- /**
97
- * A boolean indicates whether the selection has changed until
98
- *
99
- * @private
100
- * @type {Boolean}
101
- */
102
- this._hasSelectionChangedFromTheLastChangeBlock = false;
103
-
104
- // Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
105
- this.createRoot( '$root', graveyardName );
106
-
107
- // Then, still before an operation is applied on model, buffer the change in differ.
108
- this.listenTo( model, 'applyOperation', ( evt, args ) => {
109
- const operation = args[ 0 ];
110
-
111
- if ( operation.isDocumentOperation ) {
112
- this.differ.bufferOperation( operation );
113
- }
114
- }, { priority: 'high' } );
115
-
116
- // After the operation is applied, bump document's version and add the operation to the history.
117
- this.listenTo( model, 'applyOperation', ( evt, args ) => {
118
- const operation = args[ 0 ];
119
-
120
- if ( operation.isDocumentOperation ) {
121
- this.history.addOperation( operation );
122
- }
123
- }, { priority: 'low' } );
124
-
125
- // Listen to selection changes. If selection changed, mark it.
126
- this.listenTo( this.selection, 'change', () => {
127
- this._hasSelectionChangedFromTheLastChangeBlock = true;
128
- } );
129
-
130
- // Buffer marker changes.
131
- // This is not covered in buffering operations because markers may change outside of them (when they
132
- // are modified using `model.markers` collection, not through `MarkerOperation`).
133
- this.listenTo( model.markers, 'update', ( evt, marker, oldRange, newRange, oldMarkerData ) => {
134
- // Copy the `newRange` to the new marker data as during the marker removal the range is not updated.
135
- const newMarkerData = { ...marker.getData(), range: newRange };
136
-
137
- // Whenever marker is updated, buffer that change.
138
- this.differ.bufferMarkerChange( marker.name, oldMarkerData, newMarkerData );
139
-
140
- if ( oldRange === null ) {
141
- // If this is a new marker, add a listener that will buffer change whenever marker changes.
142
- marker.on( 'change', ( evt, oldRange ) => {
143
- const markerData = marker.getData();
144
-
145
- this.differ.bufferMarkerChange(
146
- marker.name,
147
- { ...markerData, range: oldRange },
148
- markerData
149
- );
150
- } );
151
- }
152
- } );
153
- }
154
-
155
- /**
156
- * The document version. Every applied operation increases the version number. It is used to
157
- * ensure that operations are applied on a proper document version.
158
- *
159
- * This property is equal to {@link module:engine/model/history~History#version `model.Document#history#version`}.
160
- *
161
- * If the {@link module:engine/model/operation/operation~Operation#baseVersion base version} does not match the document version,
162
- * a {@link module:utils/ckeditorerror~CKEditorError model-document-applyoperation-wrong-version} error is thrown.
163
- *
164
- * @type {Number}
165
- */
166
- get version() {
167
- return this.history.version;
168
- }
169
-
170
- set version( version ) {
171
- this.history.version = version;
172
- }
173
-
174
- /**
175
- * The graveyard tree root. A document always has a graveyard root that stores removed nodes.
176
- *
177
- * @readonly
178
- * @member {module:engine/model/rootelement~RootElement}
179
- */
180
- get graveyard() {
181
- return this.getRoot( graveyardName );
182
- }
183
-
184
- /**
185
- * Creates a new root.
186
- *
187
- * @param {String} [elementName='$root'] The element name. Defaults to `'$root'` which also has some basic schema defined
188
- * (`$block`s are allowed inside the `$root`). Make sure to define a proper schema if you use a different name.
189
- * @param {String} [rootName='main'] A unique root name.
190
- * @returns {module:engine/model/rootelement~RootElement} The created root.
191
- */
192
- createRoot( elementName = '$root', rootName = 'main' ) {
193
- if ( this.roots.get( rootName ) ) {
194
- /**
195
- * A root with the specified name already exists.
196
- *
197
- * @error model-document-createroot-name-exists
198
- * @param {module:engine/model/document~Document} doc
199
- * @param {String} name
200
- */
201
- throw new CKEditorError( 'model-document-createroot-name-exists', this, { name: rootName } );
202
- }
203
-
204
- const root = new RootElement( this, elementName, rootName );
205
- this.roots.add( root );
206
-
207
- return root;
208
- }
209
-
210
- /**
211
- * Removes all event listeners set by the document instance.
212
- */
213
- destroy() {
214
- this.selection.destroy();
215
- this.stopListening();
216
- }
217
-
218
- /**
219
- * Returns a root by its name.
220
- *
221
- * @param {String} [name='main'] A unique root name.
222
- * @returns {module:engine/model/rootelement~RootElement|null} The root registered under a given name or `null` when
223
- * there is no root with the given name.
224
- */
225
- getRoot( name = 'main' ) {
226
- return this.roots.get( name );
227
- }
228
-
229
- /**
230
- * Returns an array with names of all roots (without the {@link #graveyard}) added to the document.
231
- *
232
- * @returns {Array.<String>} Roots names.
233
- */
234
- getRootNames() {
235
- return Array.from( this.roots, root => root.rootName ).filter( name => name != graveyardName );
236
- }
237
-
238
- /**
239
- * Used to register a post-fixer callback. A post-fixer mechanism guarantees that the features
240
- * will operate on a correct model state.
241
- *
242
- * An execution of a feature may lead to an incorrect document tree state. The callbacks are used to fix the document tree after
243
- * it has changed. Post-fixers are fired just after all changes from the outermost change block were applied but
244
- * before the {@link module:engine/model/document~Document#event:change change event} is fired. If a post-fixer callback made
245
- * a change, it should return `true`. When this happens, all post-fixers are fired again to check if something else should
246
- * not be fixed in the new document tree state.
247
- *
248
- * As a parameter, a post-fixer callback receives a {@link module:engine/model/writer~Writer writer} instance connected with the
249
- * executed changes block. Thanks to that, all changes done by the callback will be added to the same
250
- * {@link module:engine/model/batch~Batch batch} (and undo step) as the original changes. This makes post-fixer changes transparent
251
- * for the user.
252
- *
253
- * An example of a post-fixer is a callback that checks if all the data were removed from the editor. If so, the
254
- * callback should add an empty paragraph so that the editor is never empty:
255
- *
256
- * document.registerPostFixer( writer => {
257
- * const changes = document.differ.getChanges();
258
- *
259
- * // Check if the changes lead to an empty root in the editor.
260
- * for ( const entry of changes ) {
261
- * if ( entry.type == 'remove' && entry.position.root.isEmpty ) {
262
- * writer.insertElement( 'paragraph', entry.position.root, 0 );
263
- *
264
- * // It is fine to return early, even if multiple roots would need to be fixed.
265
- * // All post-fixers will be fired again, so if there are more empty roots, those will be fixed, too.
266
- * return true;
267
- * }
268
- * }
269
- * } );
270
- *
271
- * @param {Function} postFixer
272
- */
273
- registerPostFixer( postFixer ) {
274
- this._postFixers.add( postFixer );
275
- }
276
-
277
- /**
278
- * A custom `toJSON()` method to solve child-parent circular dependencies.
279
- *
280
- * @returns {Object} A clone of this object with the document property changed to a string.
281
- */
282
- toJSON() {
283
- const json = clone( this );
284
-
285
- // Due to circular references we need to remove parent reference.
286
- json.selection = '[engine.model.DocumentSelection]';
287
- json.model = '[engine.model.Model]';
288
-
289
- return json;
290
- }
291
-
292
- /**
293
- * Check if there were any changes done on document, and if so, call post-fixers,
294
- * fire `change` event for features and conversion and then reset the differ.
295
- * Fire `change:data` event when at least one operation or buffered marker changes the data.
296
- *
297
- * @protected
298
- * @fires change
299
- * @fires change:data
300
- * @param {module:engine/model/writer~Writer} writer The writer on which post-fixers will be called.
301
- */
302
- _handleChangeBlock( writer ) {
303
- if ( this._hasDocumentChangedFromTheLastChangeBlock() ) {
304
- this._callPostFixers( writer );
305
-
306
- // Refresh selection attributes according to the final position in the model after the change.
307
- this.selection.refresh();
308
-
309
- if ( this.differ.hasDataChanges() ) {
310
- this.fire( 'change:data', writer.batch );
311
- } else {
312
- this.fire( 'change', writer.batch );
313
- }
314
-
315
- // Theoretically, it is not necessary to refresh selection after change event because
316
- // post-fixers are the last who should change the model, but just in case...
317
- this.selection.refresh();
318
-
319
- this.differ.reset();
320
- }
321
-
322
- this._hasSelectionChangedFromTheLastChangeBlock = false;
323
- }
324
-
325
- /**
326
- * Returns whether there is a buffered change or if the selection has changed from the last
327
- * {@link module:engine/model/model~Model#enqueueChange `enqueueChange()` block}
328
- * or {@link module:engine/model/model~Model#change `change()` block}.
329
- *
330
- * @protected
331
- * @returns {Boolean} Returns `true` if document has changed from the last `change()` or `enqueueChange()` block.
332
- */
333
- _hasDocumentChangedFromTheLastChangeBlock() {
334
- return !this.differ.isEmpty || this._hasSelectionChangedFromTheLastChangeBlock;
335
- }
336
-
337
- /**
338
- * Returns the default root for this document which is either the first root that was added to the document using
339
- * {@link #createRoot} or the {@link #graveyard graveyard root} if no other roots were created.
340
- *
341
- * @protected
342
- * @returns {module:engine/model/rootelement~RootElement} The default root for this document.
343
- */
344
- _getDefaultRoot() {
345
- for ( const root of this.roots ) {
346
- if ( root !== this.graveyard ) {
347
- return root;
348
- }
349
- }
350
-
351
- return this.graveyard;
352
- }
353
-
354
- /**
355
- * Returns the default range for this selection. The default range is a collapsed range that starts and ends
356
- * at the beginning of this selection's document {@link #_getDefaultRoot default root}.
357
- *
358
- * @protected
359
- * @returns {module:engine/model/range~Range}
360
- */
361
- _getDefaultRange() {
362
- const defaultRoot = this._getDefaultRoot();
363
- const model = this.model;
364
- const schema = model.schema;
365
-
366
- // Find the first position where the selection can be put.
367
- const position = model.createPositionFromPath( defaultRoot, [ 0 ] );
368
- const nearestRange = schema.getNearestSelectionRange( position );
369
-
370
- // If valid selection range is not found - return range collapsed at the beginning of the root.
371
- return nearestRange || model.createRange( position );
372
- }
373
-
374
- /**
375
- * Checks whether a given {@link module:engine/model/range~Range range} is a valid range for
376
- * the {@link #selection document's selection}.
377
- *
378
- * @private
379
- * @param {module:engine/model/range~Range} range A range to check.
380
- * @returns {Boolean} `true` if `range` is valid, `false` otherwise.
381
- */
382
- _validateSelectionRange( range ) {
383
- return validateTextNodePosition( range.start ) && validateTextNodePosition( range.end );
384
- }
385
-
386
- /**
387
- * Performs post-fixer loops. Executes post-fixer callbacks as long as none of them has done any changes to the model.
388
- *
389
- * @private
390
- * @param {module:engine/model/writer~Writer} writer The writer on which post-fixer callbacks will be called.
391
- */
392
- _callPostFixers( writer ) {
393
- let wasFixed = false;
394
-
395
- do {
396
- for ( const callback of this._postFixers ) {
397
- // Ensure selection attributes are up to date before each post-fixer.
398
- // https://github.com/ckeditor/ckeditor5-engine/issues/1673.
399
- //
400
- // It might be good to refresh the selection after each operation but at the moment it leads
401
- // to losing attributes for composition or and spell checking
402
- // https://github.com/ckeditor/ckeditor5-typing/issues/188
403
- this.selection.refresh();
404
-
405
- wasFixed = callback( writer );
406
-
407
- if ( wasFixed ) {
408
- break;
409
- }
410
- }
411
- } while ( wasFixed );
412
- }
413
-
414
- /**
415
- * Fired after each {@link module:engine/model/model~Model#enqueueChange `enqueueChange()` block} or the outermost
416
- * {@link module:engine/model/model~Model#change `change()` block} was executed and the document was changed
417
- * during that block's execution.
418
- *
419
- * The changes which this event will cover include:
420
- *
421
- * * document structure changes,
422
- * * selection changes,
423
- * * marker changes.
424
- *
425
- * If you want to be notified about all these changes, then simply listen to this event like this:
426
- *
427
- * model.document.on( 'change', () => {
428
- * console.log( 'The document has changed!' );
429
- * } );
430
- *
431
- * If, however, you only want to be notified about the data changes, then use the
432
- * {@link module:engine/model/document~Document#event:change:data change:data} event,
433
- * which is fired for document structure changes and marker changes (which affects the data).
434
- *
435
- * model.document.on( 'change:data', () => {
436
- * console.log( 'The data has changed!' );
437
- * } );
438
- *
439
- * @event change
440
- * @param {module:engine/model/batch~Batch} batch The batch that was used in the executed changes block.
441
- */
442
-
443
- /**
444
- * It is a narrower version of the {@link #event:change} event. It is fired for changes which
445
- * affect the editor data. This is:
446
- *
447
- * * document structure changes,
448
- * * marker changes (which affects the data).
449
- *
450
- * If you want to be notified about the data changes, then listen to this event:
451
- *
452
- * model.document.on( 'change:data', () => {
453
- * console.log( 'The data has changed!' );
454
- * } );
455
- *
456
- * If you would like to listen to all document changes, then check out the
457
- * {@link module:engine/model/document~Document#event:change change} event.
458
- *
459
- * @event change:data
460
- * @param {module:engine/model/batch~Batch} batch The batch that was used in the executed changes block.
461
- */
462
-
463
- // @if CK_DEBUG_ENGINE // log( version = null ) {
464
- // @if CK_DEBUG_ENGINE // version = version === null ? this.version : version;
465
- // @if CK_DEBUG_ENGINE // logDocument( this, version );
466
- // @if CK_DEBUG_ENGINE // }
35
+ export default class Document extends Emitter {
36
+ /**
37
+ * Creates an empty document instance with no {@link #roots} (other than
38
+ * the {@link #graveyard graveyard root}).
39
+ */
40
+ constructor(model) {
41
+ super();
42
+ /**
43
+ * The {@link module:engine/model/model~Model model} that the document is a part of.
44
+ *
45
+ * @readonly
46
+ * @type {module:engine/model/model~Model}
47
+ */
48
+ this.model = model;
49
+ /**
50
+ * The document's history.
51
+ *
52
+ * @readonly
53
+ * @type {module:engine/model/history~History}
54
+ */
55
+ this.history = new History();
56
+ /**
57
+ * The selection in this document.
58
+ *
59
+ * @readonly
60
+ * @type {module:engine/model/documentselection~DocumentSelection}
61
+ */
62
+ this.selection = new DocumentSelection(this);
63
+ /**
64
+ * A list of roots that are owned and managed by this document. Use {@link #createRoot} and
65
+ * {@link #getRoot} to manipulate it.
66
+ *
67
+ * @readonly
68
+ * @type {module:utils/collection~Collection}
69
+ */
70
+ this.roots = new Collection({ idProperty: 'rootName' });
71
+ /**
72
+ * The model differ object. Its role is to buffer changes done on the model document and then calculate a diff of those changes.
73
+ *
74
+ * @readonly
75
+ * @type {module:engine/model/differ~Differ}
76
+ */
77
+ this.differ = new Differ(model.markers);
78
+ /**
79
+ * Post-fixer callbacks registered to the model document.
80
+ *
81
+ * @private
82
+ * @type {Set.<Function>}
83
+ */
84
+ this._postFixers = new Set();
85
+ /**
86
+ * A boolean indicates whether the selection has changed until
87
+ *
88
+ * @private
89
+ * @type {Boolean}
90
+ */
91
+ this._hasSelectionChangedFromTheLastChangeBlock = false;
92
+ // Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
93
+ this.createRoot('$root', graveyardName);
94
+ // Then, still before an operation is applied on model, buffer the change in differ.
95
+ this.listenTo(model, 'applyOperation', (evt, args) => {
96
+ const operation = args[0];
97
+ if (operation.isDocumentOperation) {
98
+ this.differ.bufferOperation(operation);
99
+ }
100
+ }, { priority: 'high' });
101
+ // After the operation is applied, bump document's version and add the operation to the history.
102
+ this.listenTo(model, 'applyOperation', (evt, args) => {
103
+ const operation = args[0];
104
+ if (operation.isDocumentOperation) {
105
+ this.history.addOperation(operation);
106
+ }
107
+ }, { priority: 'low' });
108
+ // Listen to selection changes. If selection changed, mark it.
109
+ this.listenTo(this.selection, 'change', () => {
110
+ this._hasSelectionChangedFromTheLastChangeBlock = true;
111
+ });
112
+ // Buffer marker changes.
113
+ // This is not covered in buffering operations because markers may change outside of them (when they
114
+ // are modified using `model.markers` collection, not through `MarkerOperation`).
115
+ this.listenTo(model.markers, 'update', (evt, marker, oldRange, newRange, oldMarkerData) => {
116
+ // Copy the `newRange` to the new marker data as during the marker removal the range is not updated.
117
+ const newMarkerData = { ...marker.getData(), range: newRange };
118
+ // Whenever marker is updated, buffer that change.
119
+ this.differ.bufferMarkerChange(marker.name, oldMarkerData, newMarkerData);
120
+ if (oldRange === null) {
121
+ // If this is a new marker, add a listener that will buffer change whenever marker changes.
122
+ marker.on('change', (evt, oldRange) => {
123
+ const markerData = marker.getData();
124
+ this.differ.bufferMarkerChange(marker.name, { ...markerData, range: oldRange }, markerData);
125
+ });
126
+ }
127
+ });
128
+ }
129
+ /**
130
+ * The document version. Every applied operation increases the version number. It is used to
131
+ * ensure that operations are applied on a proper document version.
132
+ *
133
+ * This property is equal to {@link module:engine/model/history~History#version `model.Document#history#version`}.
134
+ *
135
+ * If the {@link module:engine/model/operation/operation~Operation#baseVersion base version} does not match the document version,
136
+ * a {@link module:utils/ckeditorerror~CKEditorError model-document-applyoperation-wrong-version} error is thrown.
137
+ *
138
+ * @type {Number}
139
+ */
140
+ get version() {
141
+ return this.history.version;
142
+ }
143
+ set version(version) {
144
+ this.history.version = version;
145
+ }
146
+ /**
147
+ * The graveyard tree root. A document always has a graveyard root that stores removed nodes.
148
+ *
149
+ * @readonly
150
+ * @member {module:engine/model/rootelement~RootElement}
151
+ */
152
+ get graveyard() {
153
+ return this.getRoot(graveyardName);
154
+ }
155
+ /**
156
+ * Creates a new root.
157
+ *
158
+ * @param {String} [elementName='$root'] The element name. Defaults to `'$root'` which also has some basic schema defined
159
+ * (`$block`s are allowed inside the `$root`). Make sure to define a proper schema if you use a different name.
160
+ * @param {String} [rootName='main'] A unique root name.
161
+ * @returns {module:engine/model/rootelement~RootElement} The created root.
162
+ */
163
+ createRoot(elementName = '$root', rootName = 'main') {
164
+ if (this.roots.get(rootName)) {
165
+ /**
166
+ * A root with the specified name already exists.
167
+ *
168
+ * @error model-document-createroot-name-exists
169
+ * @param {module:engine/model/document~Document} doc
170
+ * @param {String} name
171
+ */
172
+ throw new CKEditorError('model-document-createroot-name-exists', this, { name: rootName });
173
+ }
174
+ const root = new RootElement(this, elementName, rootName);
175
+ this.roots.add(root);
176
+ return root;
177
+ }
178
+ /**
179
+ * Removes all event listeners set by the document instance.
180
+ */
181
+ destroy() {
182
+ this.selection.destroy();
183
+ this.stopListening();
184
+ }
185
+ /**
186
+ * Returns a root by its name.
187
+ *
188
+ * @param {String} [name='main'] A unique root name.
189
+ * @returns {module:engine/model/rootelement~RootElement|null} The root registered under a given name or `null` when
190
+ * there is no root with the given name.
191
+ */
192
+ getRoot(name = 'main') {
193
+ return this.roots.get(name);
194
+ }
195
+ /**
196
+ * Returns an array with names of all roots (without the {@link #graveyard}) added to the document.
197
+ *
198
+ * @returns {Array.<String>} Roots names.
199
+ */
200
+ getRootNames() {
201
+ return Array.from(this.roots, root => root.rootName).filter(name => name != graveyardName);
202
+ }
203
+ /**
204
+ * Used to register a post-fixer callback. A post-fixer mechanism guarantees that the features
205
+ * will operate on a correct model state.
206
+ *
207
+ * An execution of a feature may lead to an incorrect document tree state. The callbacks are used to fix the document tree after
208
+ * it has changed. Post-fixers are fired just after all changes from the outermost change block were applied but
209
+ * before the {@link module:engine/model/document~Document#event:change change event} is fired. If a post-fixer callback made
210
+ * a change, it should return `true`. When this happens, all post-fixers are fired again to check if something else should
211
+ * not be fixed in the new document tree state.
212
+ *
213
+ * As a parameter, a post-fixer callback receives a {@link module:engine/model/writer~Writer writer} instance connected with the
214
+ * executed changes block. Thanks to that, all changes done by the callback will be added to the same
215
+ * {@link module:engine/model/batch~Batch batch} (and undo step) as the original changes. This makes post-fixer changes transparent
216
+ * for the user.
217
+ *
218
+ * An example of a post-fixer is a callback that checks if all the data were removed from the editor. If so, the
219
+ * callback should add an empty paragraph so that the editor is never empty:
220
+ *
221
+ * document.registerPostFixer( writer => {
222
+ * const changes = document.differ.getChanges();
223
+ *
224
+ * // Check if the changes lead to an empty root in the editor.
225
+ * for ( const entry of changes ) {
226
+ * if ( entry.type == 'remove' && entry.position.root.isEmpty ) {
227
+ * writer.insertElement( 'paragraph', entry.position.root, 0 );
228
+ *
229
+ * // It is fine to return early, even if multiple roots would need to be fixed.
230
+ * // All post-fixers will be fired again, so if there are more empty roots, those will be fixed, too.
231
+ * return true;
232
+ * }
233
+ * }
234
+ *
235
+ * return false;
236
+ * } );
237
+ *
238
+ * @param {Function} postFixer
239
+ */
240
+ registerPostFixer(postFixer) {
241
+ this._postFixers.add(postFixer);
242
+ }
243
+ /**
244
+ * A custom `toJSON()` method to solve child-parent circular dependencies.
245
+ *
246
+ * @returns {Object} A clone of this object with the document property changed to a string.
247
+ */
248
+ toJSON() {
249
+ const json = clone(this);
250
+ // Due to circular references we need to remove parent reference.
251
+ json.selection = '[engine.model.DocumentSelection]';
252
+ json.model = '[engine.model.Model]';
253
+ return json;
254
+ }
255
+ /**
256
+ * Check if there were any changes done on document, and if so, call post-fixers,
257
+ * fire `change` event for features and conversion and then reset the differ.
258
+ * Fire `change:data` event when at least one operation or buffered marker changes the data.
259
+ *
260
+ * @internal
261
+ * @protected
262
+ * @fires change
263
+ * @fires change:data
264
+ * @param {module:engine/model/writer~Writer} writer The writer on which post-fixers will be called.
265
+ */
266
+ _handleChangeBlock(writer) {
267
+ if (this._hasDocumentChangedFromTheLastChangeBlock()) {
268
+ this._callPostFixers(writer);
269
+ // Refresh selection attributes according to the final position in the model after the change.
270
+ this.selection.refresh();
271
+ if (this.differ.hasDataChanges()) {
272
+ this.fire('change:data', writer.batch);
273
+ }
274
+ else {
275
+ this.fire('change', writer.batch);
276
+ }
277
+ // Theoretically, it is not necessary to refresh selection after change event because
278
+ // post-fixers are the last who should change the model, but just in case...
279
+ this.selection.refresh();
280
+ this.differ.reset();
281
+ }
282
+ this._hasSelectionChangedFromTheLastChangeBlock = false;
283
+ }
284
+ /**
285
+ * Returns whether there is a buffered change or if the selection has changed from the last
286
+ * {@link module:engine/model/model~Model#enqueueChange `enqueueChange()` block}
287
+ * or {@link module:engine/model/model~Model#change `change()` block}.
288
+ *
289
+ * @protected
290
+ * @returns {Boolean} Returns `true` if document has changed from the last `change()` or `enqueueChange()` block.
291
+ */
292
+ _hasDocumentChangedFromTheLastChangeBlock() {
293
+ return !this.differ.isEmpty || this._hasSelectionChangedFromTheLastChangeBlock;
294
+ }
295
+ /**
296
+ * Returns the default root for this document which is either the first root that was added to the document using
297
+ * {@link #createRoot} or the {@link #graveyard graveyard root} if no other roots were created.
298
+ *
299
+ * @protected
300
+ * @returns {module:engine/model/rootelement~RootElement} The default root for this document.
301
+ */
302
+ _getDefaultRoot() {
303
+ for (const root of this.roots) {
304
+ if (root !== this.graveyard) {
305
+ return root;
306
+ }
307
+ }
308
+ return this.graveyard;
309
+ }
310
+ /**
311
+ * Returns the default range for this selection. The default range is a collapsed range that starts and ends
312
+ * at the beginning of this selection's document {@link #_getDefaultRoot default root}.
313
+ *
314
+ * @internal
315
+ * @protected
316
+ * @returns {module:engine/model/range~Range}
317
+ */
318
+ _getDefaultRange() {
319
+ const defaultRoot = this._getDefaultRoot();
320
+ const model = this.model;
321
+ const schema = model.schema;
322
+ // Find the first position where the selection can be put.
323
+ const position = model.createPositionFromPath(defaultRoot, [0]);
324
+ const nearestRange = schema.getNearestSelectionRange(position);
325
+ // If valid selection range is not found - return range collapsed at the beginning of the root.
326
+ return nearestRange || model.createRange(position);
327
+ }
328
+ /**
329
+ * Checks whether a given {@link module:engine/model/range~Range range} is a valid range for
330
+ * the {@link #selection document's selection}.
331
+ *
332
+ * @internal
333
+ * @protected
334
+ * @param {module:engine/model/range~Range} range A range to check.
335
+ * @returns {Boolean} `true` if `range` is valid, `false` otherwise.
336
+ */
337
+ _validateSelectionRange(range) {
338
+ return validateTextNodePosition(range.start) && validateTextNodePosition(range.end);
339
+ }
340
+ /**
341
+ * Performs post-fixer loops. Executes post-fixer callbacks as long as none of them has done any changes to the model.
342
+ *
343
+ * @private
344
+ * @param {module:engine/model/writer~Writer} writer The writer on which post-fixer callbacks will be called.
345
+ */
346
+ _callPostFixers(writer) {
347
+ let wasFixed = false;
348
+ do {
349
+ for (const callback of this._postFixers) {
350
+ // Ensure selection attributes are up to date before each post-fixer.
351
+ // https://github.com/ckeditor/ckeditor5-engine/issues/1673.
352
+ //
353
+ // It might be good to refresh the selection after each operation but at the moment it leads
354
+ // to losing attributes for composition or and spell checking
355
+ // https://github.com/ckeditor/ckeditor5-typing/issues/188
356
+ this.selection.refresh();
357
+ wasFixed = callback(writer);
358
+ if (wasFixed) {
359
+ break;
360
+ }
361
+ }
362
+ } while (wasFixed);
363
+ }
467
364
  }
468
-
469
- mix( Document, EmitterMixin );
470
-
471
365
  // Checks whether given range boundary position is valid for document selection, meaning that is not between
472
366
  // unicode surrogate pairs or base character and combining marks.
473
- function validateTextNodePosition( rangeBoundary ) {
474
- const textNode = rangeBoundary.textNode;
475
-
476
- if ( textNode ) {
477
- const data = textNode.data;
478
- const offset = rangeBoundary.offset - textNode.startOffset;
479
-
480
- return !isInsideSurrogatePair( data, offset ) && !isInsideCombinedSymbol( data, offset );
481
- }
482
-
483
- return true;
367
+ function validateTextNodePosition(rangeBoundary) {
368
+ const textNode = rangeBoundary.textNode;
369
+ if (textNode) {
370
+ const data = textNode.data;
371
+ const offset = rangeBoundary.offset - textNode.startOffset;
372
+ return !isInsideSurrogatePair(data, offset) && !isInsideCombinedSymbol(data, offset);
373
+ }
374
+ return true;
484
375
  }