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