@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,547 +1,547 @@
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/conversion/downcastdispatcher
7
- */
8
- import Consumable from './modelconsumable';
9
- import Range from '../model/range';
10
- import { EmitterMixin } from '@ckeditor/ckeditor5-utils';
11
- /**
12
- * The downcast dispatcher is a central point of downcasting (conversion from the model to the view), which is a process of reacting
13
- * to changes in the model and firing a set of events. The callbacks listening to these events are called converters. The
14
- * converters' role is to convert the model changes to changes in view (for example, adding view nodes or
15
- * changing attributes on view elements).
16
- *
17
- * During the conversion process, downcast dispatcher fires events basing on the state of the model and prepares
18
- * data for these events. It is important to understand that the events are connected with the changes done on the model,
19
- * for example: "a node has been inserted" or "an attribute has changed". This is in contrary to upcasting (a view-to-model conversion)
20
- * where you convert the view state (view nodes) to a model tree.
21
- *
22
- * The events are prepared basing on a diff created by the {@link module:engine/model/differ~Differ Differ}, which buffers them
23
- * and then passes to the downcast dispatcher as a diff between the old model state and the new model state.
24
- *
25
- * Note that because the changes are converted, there is a need to have a mapping between the model structure and the view structure.
26
- * To map positions and elements during the downcast (a model-to-view conversion), use {@link module:engine/conversion/mapper~Mapper}.
27
- *
28
- * Downcast dispatcher fires the following events for model tree changes:
29
- *
30
- * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:insert `insert`} –
31
- * If a range of nodes was inserted to the model tree.
32
- * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:remove `remove`} –
33
- * If a range of nodes was removed from the model tree.
34
- * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute `attribute`} –
35
- * If an attribute was added, changed or removed from a model node.
36
- *
37
- * For {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:insert `insert`}
38
- * and {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute `attribute`},
39
- * the downcast dispatcher generates {@link module:engine/conversion/modelconsumable~ModelConsumable consumables}.
40
- * These are used to have control over which changes have already been consumed. It is useful when some converters
41
- * overwrite others or convert multiple changes (for example, it converts an insertion of an element and also converts that
42
- * element's attributes during the insertion).
43
- *
44
- * Additionally, downcast dispatcher fires events for {@link module:engine/model/markercollection~Marker marker} changes:
45
- *
46
- * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarker `addMarker`} – If a marker was added.
47
- * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:removeMarker `removeMarker`} – If a marker was
48
- * removed.
49
- *
50
- * Note that changing a marker is done through removing the marker from the old range and adding it to the new range,
51
- * so both of these events are fired.
52
- *
53
- * Finally, a downcast dispatcher also handles firing events for the {@link module:engine/model/selection model selection}
54
- * conversion:
55
- *
56
- * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:selection `selection`}
57
- * – Converts the selection from the model to the view.
58
- * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute `attribute`}
59
- * – Fired for every selection attribute.
60
- * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarker `addMarker`}
61
- * – Fired for every marker that contains a selection.
62
- *
63
- * Unlike the model tree and the markers, the events for selection are not fired for changes but for a selection state.
64
- *
65
- * When providing custom listeners for a downcast dispatcher, remember to check whether a given change has not been
66
- * {@link module:engine/conversion/modelconsumable~ModelConsumable#consume consumed} yet.
67
- *
68
- * When providing custom listeners for a downcast dispatcher, keep in mind that you **should not** stop the event. If you stop it,
69
- * then the default converter at the `lowest` priority will not trigger the conversion of this node's attributes and child nodes.
70
- *
71
- * When providing custom listeners for a downcast dispatcher, remember to use the provided
72
- * {@link module:engine/view/downcastwriter~DowncastWriter view downcast writer} to apply changes to the view document.
73
- *
74
- * You can read more about conversion in the following guide:
75
- *
76
- * * {@glink framework/deep-dive/conversion/downcast Downcast conversion}
77
- *
78
- * An example of a custom converter for the downcast dispatcher:
79
- *
80
- * ```ts
81
- * // You will convert inserting a "paragraph" model element into the model.
82
- * downcastDispatcher.on( 'insert:paragraph', ( evt, data, conversionApi ) => {
83
- * // Remember to check whether the change has not been consumed yet and consume it.
84
- * if ( !conversionApi.consumable.consume( data.item, 'insert' ) ) {
85
- * return;
86
- * }
87
- *
88
- * // Translate the position in the model to a position in the view.
89
- * const viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
90
- *
91
- * // Create a <p> element that will be inserted into the view at the `viewPosition`.
92
- * const viewElement = conversionApi.writer.createContainerElement( 'p' );
93
- *
94
- * // Bind the newly created view element to the model element so positions will map accordingly in the future.
95
- * conversionApi.mapper.bindElements( data.item, viewElement );
96
- *
97
- * // Add the newly created view element to the view.
98
- * conversionApi.writer.insert( viewPosition, viewElement );
99
- * } );
100
- * ```
101
- */
102
- export default class DowncastDispatcher extends EmitterMixin() {
103
- /**
104
- * Creates a downcast dispatcher instance.
105
- *
106
- * @see module:engine/conversion/downcastdispatcher~DowncastConversionApi
107
- *
108
- * @param conversionApi Additional properties for an interface that will be passed to events fired
109
- * by the downcast dispatcher.
110
- */
111
- constructor(conversionApi) {
112
- super();
113
- this._conversionApi = { dispatcher: this, ...conversionApi };
114
- this._firedEventsMap = new WeakMap();
115
- }
116
- /**
117
- * Converts changes buffered in the given {@link module:engine/model/differ~Differ model differ}
118
- * and fires conversion events based on it.
119
- *
120
- * @fires insert
121
- * @fires remove
122
- * @fires attribute
123
- * @fires addMarker
124
- * @fires removeMarker
125
- * @fires reduceChanges
126
- * @param differ The differ object with buffered changes.
127
- * @param markers Markers related to the model fragment to convert.
128
- * @param writer The view writer that should be used to modify the view document.
129
- */
130
- convertChanges(differ, markers, writer) {
131
- const conversionApi = this._createConversionApi(writer, differ.getRefreshedItems());
132
- // Before the view is updated, remove markers which have changed.
133
- for (const change of differ.getMarkersToRemove()) {
134
- this._convertMarkerRemove(change.name, change.range, conversionApi);
135
- }
136
- // Let features modify the change list (for example to allow reconversion).
137
- const changes = this._reduceChanges(differ.getChanges());
138
- // Convert changes that happened on model tree.
139
- for (const entry of changes) {
140
- if (entry.type === 'insert') {
141
- this._convertInsert(Range._createFromPositionAndShift(entry.position, entry.length), conversionApi);
142
- }
143
- else if (entry.type === 'reinsert') {
144
- this._convertReinsert(Range._createFromPositionAndShift(entry.position, entry.length), conversionApi);
145
- }
146
- else if (entry.type === 'remove') {
147
- this._convertRemove(entry.position, entry.length, entry.name, conversionApi);
148
- }
149
- else {
150
- // Defaults to 'attribute' change.
151
- this._convertAttribute(entry.range, entry.attributeKey, entry.attributeOldValue, entry.attributeNewValue, conversionApi);
152
- }
153
- }
154
- for (const markerName of conversionApi.mapper.flushUnboundMarkerNames()) {
155
- const markerRange = markers.get(markerName).getRange();
156
- this._convertMarkerRemove(markerName, markerRange, conversionApi);
157
- this._convertMarkerAdd(markerName, markerRange, conversionApi);
158
- }
159
- // After the view is updated, convert markers which have changed.
160
- for (const change of differ.getMarkersToAdd()) {
161
- this._convertMarkerAdd(change.name, change.range, conversionApi);
162
- }
163
- // Remove mappings for all removed view elements.
164
- conversionApi.mapper.flushDeferredBindings();
165
- // Verify if all insert consumables were consumed.
166
- conversionApi.consumable.verifyAllConsumed('insert');
167
- }
168
- /**
169
- * Starts a conversion of a model range and the provided markers.
170
- *
171
- * @fires insert
172
- * @fires attribute
173
- * @fires addMarker
174
- * @param range The inserted range.
175
- * @param markers The map of markers that should be down-casted.
176
- * @param writer The view writer that should be used to modify the view document.
177
- * @param options Optional options object passed to `convertionApi.options`.
178
- */
179
- convert(range, markers, writer, options = {}) {
180
- const conversionApi = this._createConversionApi(writer, undefined, options);
181
- this._convertInsert(range, conversionApi);
182
- for (const [name, range] of markers) {
183
- this._convertMarkerAdd(name, range, conversionApi);
184
- }
185
- // Verify if all insert consumables were consumed.
186
- conversionApi.consumable.verifyAllConsumed('insert');
187
- }
188
- /**
189
- * Starts the model selection conversion.
190
- *
191
- * Fires events for a given {@link module:engine/model/selection~Selection selection} to start the selection conversion.
192
- *
193
- * @fires selection
194
- * @fires addMarker
195
- * @fires attribute
196
- * @param selection The selection to convert.
197
- * @param markers Markers connected with the converted model.
198
- * @param writer View writer that should be used to modify the view document.
199
- */
200
- convertSelection(selection, markers, writer) {
201
- const conversionApi = this._createConversionApi(writer);
202
- // First perform a clean-up at the current position of the selection.
203
- this.fire('cleanSelection', { selection }, conversionApi);
204
- // Don't convert selection if it is in a model root that does not have a view root (for now this is only the graveyard root).
205
- const modelRoot = selection.getFirstPosition().root;
206
- if (!conversionApi.mapper.toViewElement(modelRoot)) {
207
- return;
208
- }
209
- // Now, perform actual selection conversion.
210
- const markersAtSelection = Array.from(markers.getMarkersAtPosition(selection.getFirstPosition()));
211
- this._addConsumablesForSelection(conversionApi.consumable, selection, markersAtSelection);
212
- this.fire('selection', { selection }, conversionApi);
213
- if (!selection.isCollapsed) {
214
- return;
215
- }
216
- for (const marker of markersAtSelection) {
217
- // Do not fire event if the marker has been consumed.
218
- if (conversionApi.consumable.test(selection, 'addMarker:' + marker.name)) {
219
- const markerRange = marker.getRange();
220
- if (!shouldMarkerChangeBeConverted(selection.getFirstPosition(), marker, conversionApi.mapper)) {
221
- continue;
222
- }
223
- const data = {
224
- item: selection,
225
- markerName: marker.name,
226
- markerRange
227
- };
228
- this.fire(`addMarker:${marker.name}`, data, conversionApi);
229
- }
230
- }
231
- for (const key of selection.getAttributeKeys()) {
232
- // Do not fire event if the attribute has been consumed.
233
- if (conversionApi.consumable.test(selection, 'attribute:' + key)) {
234
- const data = {
235
- item: selection,
236
- range: selection.getFirstRange(),
237
- attributeKey: key,
238
- attributeOldValue: null,
239
- attributeNewValue: selection.getAttribute(key)
240
- };
241
- this.fire(`attribute:${key}:$text`, data, conversionApi);
242
- }
243
- }
244
- }
245
- /**
246
- * Fires insertion conversion of a range of nodes.
247
- *
248
- * For each node in the range, {@link #event:insert `insert` event is fired}. For each attribute on each node,
249
- * {@link #event:attribute `attribute` event is fired}.
250
- *
251
- * @fires insert
252
- * @fires attribute
253
- * @param range The inserted range.
254
- * @param conversionApi The conversion API object.
255
- * @param options.doNotAddConsumables Whether the ModelConsumable should not get populated
256
- * for items in the provided range.
257
- */
258
- _convertInsert(range, conversionApi, options = {}) {
259
- if (!options.doNotAddConsumables) {
260
- // Collect a list of things that can be consumed, consisting of nodes and their attributes.
261
- this._addConsumablesForInsert(conversionApi.consumable, Array.from(range));
262
- }
263
- // Fire a separate insert event for each node and text fragment contained in the range.
264
- for (const data of Array.from(range.getWalker({ shallow: true })).map(walkerValueToEventData)) {
265
- this._testAndFire('insert', data, conversionApi);
266
- }
267
- }
268
- /**
269
- * Fires conversion of a single node removal. Fires {@link #event:remove remove event} with provided data.
270
- *
271
- * @param position Position from which node was removed.
272
- * @param length Offset size of removed node.
273
- * @param name Name of removed node.
274
- * @param conversionApi The conversion API object.
275
- */
276
- _convertRemove(position, length, name, conversionApi) {
277
- this.fire(`remove:${name}`, { position, length }, conversionApi);
278
- }
279
- /**
280
- * Starts a conversion of an attribute change on a given `range`.
281
- *
282
- * For each node in the given `range`, {@link #event:attribute attribute event} is fired with the passed data.
283
- *
284
- * @fires attribute
285
- * @param range Changed range.
286
- * @param key Key of the attribute that has changed.
287
- * @param oldValue Attribute value before the change or `null` if the attribute has not been set before.
288
- * @param newValue New attribute value or `null` if the attribute has been removed.
289
- * @param conversionApi The conversion API object.
290
- */
291
- _convertAttribute(range, key, oldValue, newValue, conversionApi) {
292
- // Create a list with attributes to consume.
293
- this._addConsumablesForRange(conversionApi.consumable, range, `attribute:${key}`);
294
- // Create a separate attribute event for each node in the range.
295
- for (const value of range) {
296
- const data = {
297
- item: value.item,
298
- range: Range._createFromPositionAndShift(value.previousPosition, value.length),
299
- attributeKey: key,
300
- attributeOldValue: oldValue,
301
- attributeNewValue: newValue
302
- };
303
- this._testAndFire(`attribute:${key}`, data, conversionApi);
304
- }
305
- }
306
- /**
307
- * Fires re-insertion conversion (with a `reconversion` flag passed to `insert` events)
308
- * of a range of elements (only elements on the range depth, without children).
309
- *
310
- * For each node in the range on its depth (without children), {@link #event:insert `insert` event} is fired.
311
- * For each attribute on each node, {@link #event:attribute `attribute` event} is fired.
312
- *
313
- * @fires insert
314
- * @fires attribute
315
- * @param range The range to reinsert.
316
- * @param conversionApi The conversion API object.
317
- */
318
- _convertReinsert(range, conversionApi) {
319
- // Convert the elements - without converting children.
320
- const walkerValues = Array.from(range.getWalker({ shallow: true }));
321
- // Collect a list of things that can be consumed, consisting of nodes and their attributes.
322
- this._addConsumablesForInsert(conversionApi.consumable, walkerValues);
323
- // Fire a separate insert event for each node and text fragment contained shallowly in the range.
324
- for (const data of walkerValues.map(walkerValueToEventData)) {
325
- this._testAndFire('insert', { ...data, reconversion: true }, conversionApi);
326
- }
327
- }
328
- /**
329
- * Converts the added marker. Fires the {@link #event:addMarker `addMarker`} event for each item
330
- * in the marker's range. If the range is collapsed, a single event is dispatched. See the event description for more details.
331
- *
332
- * @fires addMarker
333
- * @param markerName Marker name.
334
- * @param markerRange The marker range.
335
- * @param conversionApi The conversion API object.
336
- */
337
- _convertMarkerAdd(markerName, markerRange, conversionApi) {
338
- // Do not convert if range is in graveyard.
339
- if (markerRange.root.rootName == '$graveyard') {
340
- return;
341
- }
342
- // In markers' case, event name == consumable name.
343
- const eventName = `addMarker:${markerName}`;
344
- //
345
- // First, fire an event for the whole marker.
346
- //
347
- conversionApi.consumable.add(markerRange, eventName);
348
- this.fire(eventName, { markerName, markerRange }, conversionApi);
349
- //
350
- // Do not fire events for each item inside the range if the range got consumed.
351
- // Also consume the whole marker consumable if it wasn't consumed.
352
- //
353
- if (!conversionApi.consumable.consume(markerRange, eventName)) {
354
- return;
355
- }
356
- //
357
- // Then, fire an event for each item inside the marker range.
358
- //
359
- this._addConsumablesForRange(conversionApi.consumable, markerRange, eventName);
360
- for (const item of markerRange.getItems()) {
361
- // Do not fire event for already consumed items.
362
- if (!conversionApi.consumable.test(item, eventName)) {
363
- continue;
364
- }
365
- const data = { item, range: Range._createOn(item), markerName, markerRange };
366
- this.fire(eventName, data, conversionApi);
367
- }
368
- }
369
- /**
370
- * Fires the conversion of the marker removal. Fires the {@link #event:removeMarker `removeMarker`} event with the provided data.
371
- *
372
- * @fires removeMarker
373
- * @param markerName Marker name.
374
- * @param markerRange The marker range.
375
- * @param conversionApi The conversion API object.
376
- */
377
- _convertMarkerRemove(markerName, markerRange, conversionApi) {
378
- // Do not convert if range is in graveyard.
379
- if (markerRange.root.rootName == '$graveyard') {
380
- return;
381
- }
382
- this.fire(`removeMarker:${markerName}`, { markerName, markerRange }, conversionApi);
383
- }
384
- /**
385
- * Fires the reduction of changes buffered in the {@link module:engine/model/differ~Differ `Differ`}.
386
- *
387
- * Features can replace selected {@link module:engine/model/differ~DiffItem `DiffItem`}s with `reinsert` entries to trigger
388
- * reconversion. The {@link module:engine/conversion/downcasthelpers~DowncastHelpers#elementToStructure
389
- * `DowncastHelpers.elementToStructure()`} is using this event to trigger reconversion.
390
- *
391
- * @fires reduceChanges
392
- */
393
- _reduceChanges(changes) {
394
- const data = { changes };
395
- this.fire('reduceChanges', data);
396
- return data.changes;
397
- }
398
- /**
399
- * Populates provided {@link module:engine/conversion/modelconsumable~ModelConsumable} with values to consume from a given range,
400
- * assuming that the range has just been inserted to the model.
401
- *
402
- * @param consumable The consumable.
403
- * @param walkerValues The walker values for the inserted range.
404
- * @returns The values to consume.
405
- */
406
- _addConsumablesForInsert(consumable, walkerValues) {
407
- for (const value of walkerValues) {
408
- const item = value.item;
409
- // Add consumable if it wasn't there yet.
410
- if (consumable.test(item, 'insert') === null) {
411
- consumable.add(item, 'insert');
412
- for (const key of item.getAttributeKeys()) {
413
- consumable.add(item, 'attribute:' + key);
414
- }
415
- }
416
- }
417
- return consumable;
418
- }
419
- /**
420
- * Populates provided {@link module:engine/conversion/modelconsumable~ModelConsumable} with values to consume for a given range.
421
- *
422
- * @param consumable The consumable.
423
- * @param range The affected range.
424
- * @param type Consumable type.
425
- * @returns The values to consume.
426
- */
427
- _addConsumablesForRange(consumable, range, type) {
428
- for (const item of range.getItems()) {
429
- consumable.add(item, type);
430
- }
431
- return consumable;
432
- }
433
- /**
434
- * Populates provided {@link module:engine/conversion/modelconsumable~ModelConsumable} with selection consumable values.
435
- *
436
- * @param consumable The consumable.
437
- * @param selection The selection to create the consumable from.
438
- * @param markers Markers that contain the selection.
439
- * @returns The values to consume.
440
- */
441
- _addConsumablesForSelection(consumable, selection, markers) {
442
- consumable.add(selection, 'selection');
443
- for (const marker of markers) {
444
- consumable.add(selection, 'addMarker:' + marker.name);
445
- }
446
- for (const key of selection.getAttributeKeys()) {
447
- consumable.add(selection, 'attribute:' + key);
448
- }
449
- return consumable;
450
- }
451
- /**
452
- * Tests whether given event wasn't already fired and if so, fires it.
453
- *
454
- * @fires insert
455
- * @fires attribute
456
- * @param type Event type.
457
- * @param data Event data.
458
- * @param conversionApi The conversion API object.
459
- */
460
- _testAndFire(type, data, conversionApi) {
461
- const eventName = getEventName(type, data);
462
- const itemKey = data.item.is('$textProxy') ? conversionApi.consumable._getSymbolForTextProxy(data.item) : data.item;
463
- const eventsFiredForConversion = this._firedEventsMap.get(conversionApi);
464
- const eventsFiredForItem = eventsFiredForConversion.get(itemKey);
465
- if (!eventsFiredForItem) {
466
- eventsFiredForConversion.set(itemKey, new Set([eventName]));
467
- }
468
- else if (!eventsFiredForItem.has(eventName)) {
469
- eventsFiredForItem.add(eventName);
470
- }
471
- else {
472
- return;
473
- }
474
- this.fire(eventName, data, conversionApi);
475
- }
476
- /**
477
- * Fires not already fired events for setting attributes on just inserted item.
478
- *
479
- * @param item The model item to convert attributes for.
480
- * @param conversionApi The conversion API object.
481
- */
482
- _testAndFireAddAttributes(item, conversionApi) {
483
- const data = {
484
- item,
485
- range: Range._createOn(item)
486
- };
487
- for (const key of data.item.getAttributeKeys()) {
488
- data.attributeKey = key;
489
- data.attributeOldValue = null;
490
- data.attributeNewValue = data.item.getAttribute(key);
491
- this._testAndFire(`attribute:${key}`, data, conversionApi);
492
- }
493
- }
494
- /**
495
- * Builds an instance of the {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi} from a template and a given
496
- * {@link module:engine/view/downcastwriter~DowncastWriter `DowncastWriter`} and options object.
497
- *
498
- * @param writer View writer that should be used to modify the view document.
499
- * @param refreshedItems A set of model elements that should not reuse their
500
- * previous view representations.
501
- * @param options Optional options passed to `convertionApi.options`.
502
- * @return The conversion API object.
503
- */
504
- _createConversionApi(writer, refreshedItems = new Set(), options = {}) {
505
- const conversionApi = {
506
- ...this._conversionApi,
507
- consumable: new Consumable(),
508
- writer,
509
- options,
510
- convertItem: item => this._convertInsert(Range._createOn(item), conversionApi),
511
- convertChildren: element => this._convertInsert(Range._createIn(element), conversionApi, { doNotAddConsumables: true }),
512
- convertAttributes: item => this._testAndFireAddAttributes(item, conversionApi),
513
- canReuseView: viewElement => !refreshedItems.has(conversionApi.mapper.toModelElement(viewElement))
514
- };
515
- this._firedEventsMap.set(conversionApi, new Map());
516
- return conversionApi;
517
- }
518
- }
519
- /**
520
- * Helper function, checks whether change of `marker` at `modelPosition` should be converted. Marker changes are not
521
- * converted if they happen inside an element with custom conversion method.
522
- */
523
- function shouldMarkerChangeBeConverted(modelPosition, marker, mapper) {
524
- const range = marker.getRange();
525
- const ancestors = Array.from(modelPosition.getAncestors());
526
- ancestors.shift(); // Remove root element. It cannot be passed to `model.Range#containsItem`.
527
- ancestors.reverse();
528
- const hasCustomHandling = ancestors.some(element => {
529
- if (range.containsItem(element)) {
530
- const viewElement = mapper.toViewElement(element);
531
- return !!viewElement.getCustomProperty('addHighlight');
532
- }
533
- });
534
- return !hasCustomHandling;
535
- }
536
- function getEventName(type, data) {
537
- const name = data.item.is('element') ? data.item.name : '$text';
538
- return `${type}:${name}`;
539
- }
540
- function walkerValueToEventData(value) {
541
- const item = value.item;
542
- const itemRange = Range._createFromPositionAndShift(value.previousPosition, value.length);
543
- return {
544
- item,
545
- range: itemRange
546
- };
547
- }
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/conversion/downcastdispatcher
7
+ */
8
+ import Consumable from './modelconsumable';
9
+ import Range from '../model/range';
10
+ import { EmitterMixin } from '@ckeditor/ckeditor5-utils';
11
+ /**
12
+ * The downcast dispatcher is a central point of downcasting (conversion from the model to the view), which is a process of reacting
13
+ * to changes in the model and firing a set of events. The callbacks listening to these events are called converters. The
14
+ * converters' role is to convert the model changes to changes in view (for example, adding view nodes or
15
+ * changing attributes on view elements).
16
+ *
17
+ * During the conversion process, downcast dispatcher fires events basing on the state of the model and prepares
18
+ * data for these events. It is important to understand that the events are connected with the changes done on the model,
19
+ * for example: "a node has been inserted" or "an attribute has changed". This is in contrary to upcasting (a view-to-model conversion)
20
+ * where you convert the view state (view nodes) to a model tree.
21
+ *
22
+ * The events are prepared basing on a diff created by the {@link module:engine/model/differ~Differ Differ}, which buffers them
23
+ * and then passes to the downcast dispatcher as a diff between the old model state and the new model state.
24
+ *
25
+ * Note that because the changes are converted, there is a need to have a mapping between the model structure and the view structure.
26
+ * To map positions and elements during the downcast (a model-to-view conversion), use {@link module:engine/conversion/mapper~Mapper}.
27
+ *
28
+ * Downcast dispatcher fires the following events for model tree changes:
29
+ *
30
+ * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:insert `insert`} &ndash;
31
+ * If a range of nodes was inserted to the model tree.
32
+ * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:remove `remove`} &ndash;
33
+ * If a range of nodes was removed from the model tree.
34
+ * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute `attribute`} &ndash;
35
+ * If an attribute was added, changed or removed from a model node.
36
+ *
37
+ * For {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:insert `insert`}
38
+ * and {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute `attribute`},
39
+ * the downcast dispatcher generates {@link module:engine/conversion/modelconsumable~ModelConsumable consumables}.
40
+ * These are used to have control over which changes have already been consumed. It is useful when some converters
41
+ * overwrite others or convert multiple changes (for example, it converts an insertion of an element and also converts that
42
+ * element's attributes during the insertion).
43
+ *
44
+ * Additionally, downcast dispatcher fires events for {@link module:engine/model/markercollection~Marker marker} changes:
45
+ *
46
+ * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarker `addMarker`} &ndash; If a marker was added.
47
+ * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:removeMarker `removeMarker`} &ndash; If a marker was
48
+ * removed.
49
+ *
50
+ * Note that changing a marker is done through removing the marker from the old range and adding it to the new range,
51
+ * so both of these events are fired.
52
+ *
53
+ * Finally, a downcast dispatcher also handles firing events for the {@link module:engine/model/selection model selection}
54
+ * conversion:
55
+ *
56
+ * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:selection `selection`}
57
+ * &ndash; Converts the selection from the model to the view.
58
+ * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute `attribute`}
59
+ * &ndash; Fired for every selection attribute.
60
+ * * {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:addMarker `addMarker`}
61
+ * &ndash; Fired for every marker that contains a selection.
62
+ *
63
+ * Unlike the model tree and the markers, the events for selection are not fired for changes but for a selection state.
64
+ *
65
+ * When providing custom listeners for a downcast dispatcher, remember to check whether a given change has not been
66
+ * {@link module:engine/conversion/modelconsumable~ModelConsumable#consume consumed} yet.
67
+ *
68
+ * When providing custom listeners for a downcast dispatcher, keep in mind that you **should not** stop the event. If you stop it,
69
+ * then the default converter at the `lowest` priority will not trigger the conversion of this node's attributes and child nodes.
70
+ *
71
+ * When providing custom listeners for a downcast dispatcher, remember to use the provided
72
+ * {@link module:engine/view/downcastwriter~DowncastWriter view downcast writer} to apply changes to the view document.
73
+ *
74
+ * You can read more about conversion in the following guide:
75
+ *
76
+ * * {@glink framework/deep-dive/conversion/downcast Downcast conversion}
77
+ *
78
+ * An example of a custom converter for the downcast dispatcher:
79
+ *
80
+ * ```ts
81
+ * // You will convert inserting a "paragraph" model element into the model.
82
+ * downcastDispatcher.on( 'insert:paragraph', ( evt, data, conversionApi ) => {
83
+ * // Remember to check whether the change has not been consumed yet and consume it.
84
+ * if ( !conversionApi.consumable.consume( data.item, 'insert' ) ) {
85
+ * return;
86
+ * }
87
+ *
88
+ * // Translate the position in the model to a position in the view.
89
+ * const viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
90
+ *
91
+ * // Create a <p> element that will be inserted into the view at the `viewPosition`.
92
+ * const viewElement = conversionApi.writer.createContainerElement( 'p' );
93
+ *
94
+ * // Bind the newly created view element to the model element so positions will map accordingly in the future.
95
+ * conversionApi.mapper.bindElements( data.item, viewElement );
96
+ *
97
+ * // Add the newly created view element to the view.
98
+ * conversionApi.writer.insert( viewPosition, viewElement );
99
+ * } );
100
+ * ```
101
+ */
102
+ export default class DowncastDispatcher extends EmitterMixin() {
103
+ /**
104
+ * Creates a downcast dispatcher instance.
105
+ *
106
+ * @see module:engine/conversion/downcastdispatcher~DowncastConversionApi
107
+ *
108
+ * @param conversionApi Additional properties for an interface that will be passed to events fired
109
+ * by the downcast dispatcher.
110
+ */
111
+ constructor(conversionApi) {
112
+ super();
113
+ this._conversionApi = { dispatcher: this, ...conversionApi };
114
+ this._firedEventsMap = new WeakMap();
115
+ }
116
+ /**
117
+ * Converts changes buffered in the given {@link module:engine/model/differ~Differ model differ}
118
+ * and fires conversion events based on it.
119
+ *
120
+ * @fires insert
121
+ * @fires remove
122
+ * @fires attribute
123
+ * @fires addMarker
124
+ * @fires removeMarker
125
+ * @fires reduceChanges
126
+ * @param differ The differ object with buffered changes.
127
+ * @param markers Markers related to the model fragment to convert.
128
+ * @param writer The view writer that should be used to modify the view document.
129
+ */
130
+ convertChanges(differ, markers, writer) {
131
+ const conversionApi = this._createConversionApi(writer, differ.getRefreshedItems());
132
+ // Before the view is updated, remove markers which have changed.
133
+ for (const change of differ.getMarkersToRemove()) {
134
+ this._convertMarkerRemove(change.name, change.range, conversionApi);
135
+ }
136
+ // Let features modify the change list (for example to allow reconversion).
137
+ const changes = this._reduceChanges(differ.getChanges());
138
+ // Convert changes that happened on model tree.
139
+ for (const entry of changes) {
140
+ if (entry.type === 'insert') {
141
+ this._convertInsert(Range._createFromPositionAndShift(entry.position, entry.length), conversionApi);
142
+ }
143
+ else if (entry.type === 'reinsert') {
144
+ this._convertReinsert(Range._createFromPositionAndShift(entry.position, entry.length), conversionApi);
145
+ }
146
+ else if (entry.type === 'remove') {
147
+ this._convertRemove(entry.position, entry.length, entry.name, conversionApi);
148
+ }
149
+ else {
150
+ // Defaults to 'attribute' change.
151
+ this._convertAttribute(entry.range, entry.attributeKey, entry.attributeOldValue, entry.attributeNewValue, conversionApi);
152
+ }
153
+ }
154
+ for (const markerName of conversionApi.mapper.flushUnboundMarkerNames()) {
155
+ const markerRange = markers.get(markerName).getRange();
156
+ this._convertMarkerRemove(markerName, markerRange, conversionApi);
157
+ this._convertMarkerAdd(markerName, markerRange, conversionApi);
158
+ }
159
+ // After the view is updated, convert markers which have changed.
160
+ for (const change of differ.getMarkersToAdd()) {
161
+ this._convertMarkerAdd(change.name, change.range, conversionApi);
162
+ }
163
+ // Remove mappings for all removed view elements.
164
+ conversionApi.mapper.flushDeferredBindings();
165
+ // Verify if all insert consumables were consumed.
166
+ conversionApi.consumable.verifyAllConsumed('insert');
167
+ }
168
+ /**
169
+ * Starts a conversion of a model range and the provided markers.
170
+ *
171
+ * @fires insert
172
+ * @fires attribute
173
+ * @fires addMarker
174
+ * @param range The inserted range.
175
+ * @param markers The map of markers that should be down-casted.
176
+ * @param writer The view writer that should be used to modify the view document.
177
+ * @param options Optional options object passed to `convertionApi.options`.
178
+ */
179
+ convert(range, markers, writer, options = {}) {
180
+ const conversionApi = this._createConversionApi(writer, undefined, options);
181
+ this._convertInsert(range, conversionApi);
182
+ for (const [name, range] of markers) {
183
+ this._convertMarkerAdd(name, range, conversionApi);
184
+ }
185
+ // Verify if all insert consumables were consumed.
186
+ conversionApi.consumable.verifyAllConsumed('insert');
187
+ }
188
+ /**
189
+ * Starts the model selection conversion.
190
+ *
191
+ * Fires events for a given {@link module:engine/model/selection~Selection selection} to start the selection conversion.
192
+ *
193
+ * @fires selection
194
+ * @fires addMarker
195
+ * @fires attribute
196
+ * @param selection The selection to convert.
197
+ * @param markers Markers connected with the converted model.
198
+ * @param writer View writer that should be used to modify the view document.
199
+ */
200
+ convertSelection(selection, markers, writer) {
201
+ const conversionApi = this._createConversionApi(writer);
202
+ // First perform a clean-up at the current position of the selection.
203
+ this.fire('cleanSelection', { selection }, conversionApi);
204
+ // Don't convert selection if it is in a model root that does not have a view root (for now this is only the graveyard root).
205
+ const modelRoot = selection.getFirstPosition().root;
206
+ if (!conversionApi.mapper.toViewElement(modelRoot)) {
207
+ return;
208
+ }
209
+ // Now, perform actual selection conversion.
210
+ const markersAtSelection = Array.from(markers.getMarkersAtPosition(selection.getFirstPosition()));
211
+ this._addConsumablesForSelection(conversionApi.consumable, selection, markersAtSelection);
212
+ this.fire('selection', { selection }, conversionApi);
213
+ if (!selection.isCollapsed) {
214
+ return;
215
+ }
216
+ for (const marker of markersAtSelection) {
217
+ // Do not fire event if the marker has been consumed.
218
+ if (conversionApi.consumable.test(selection, 'addMarker:' + marker.name)) {
219
+ const markerRange = marker.getRange();
220
+ if (!shouldMarkerChangeBeConverted(selection.getFirstPosition(), marker, conversionApi.mapper)) {
221
+ continue;
222
+ }
223
+ const data = {
224
+ item: selection,
225
+ markerName: marker.name,
226
+ markerRange
227
+ };
228
+ this.fire(`addMarker:${marker.name}`, data, conversionApi);
229
+ }
230
+ }
231
+ for (const key of selection.getAttributeKeys()) {
232
+ // Do not fire event if the attribute has been consumed.
233
+ if (conversionApi.consumable.test(selection, 'attribute:' + key)) {
234
+ const data = {
235
+ item: selection,
236
+ range: selection.getFirstRange(),
237
+ attributeKey: key,
238
+ attributeOldValue: null,
239
+ attributeNewValue: selection.getAttribute(key)
240
+ };
241
+ this.fire(`attribute:${key}:$text`, data, conversionApi);
242
+ }
243
+ }
244
+ }
245
+ /**
246
+ * Fires insertion conversion of a range of nodes.
247
+ *
248
+ * For each node in the range, {@link #event:insert `insert` event is fired}. For each attribute on each node,
249
+ * {@link #event:attribute `attribute` event is fired}.
250
+ *
251
+ * @fires insert
252
+ * @fires attribute
253
+ * @param range The inserted range.
254
+ * @param conversionApi The conversion API object.
255
+ * @param options.doNotAddConsumables Whether the ModelConsumable should not get populated
256
+ * for items in the provided range.
257
+ */
258
+ _convertInsert(range, conversionApi, options = {}) {
259
+ if (!options.doNotAddConsumables) {
260
+ // Collect a list of things that can be consumed, consisting of nodes and their attributes.
261
+ this._addConsumablesForInsert(conversionApi.consumable, Array.from(range));
262
+ }
263
+ // Fire a separate insert event for each node and text fragment contained in the range.
264
+ for (const data of Array.from(range.getWalker({ shallow: true })).map(walkerValueToEventData)) {
265
+ this._testAndFire('insert', data, conversionApi);
266
+ }
267
+ }
268
+ /**
269
+ * Fires conversion of a single node removal. Fires {@link #event:remove remove event} with provided data.
270
+ *
271
+ * @param position Position from which node was removed.
272
+ * @param length Offset size of removed node.
273
+ * @param name Name of removed node.
274
+ * @param conversionApi The conversion API object.
275
+ */
276
+ _convertRemove(position, length, name, conversionApi) {
277
+ this.fire(`remove:${name}`, { position, length }, conversionApi);
278
+ }
279
+ /**
280
+ * Starts a conversion of an attribute change on a given `range`.
281
+ *
282
+ * For each node in the given `range`, {@link #event:attribute attribute event} is fired with the passed data.
283
+ *
284
+ * @fires attribute
285
+ * @param range Changed range.
286
+ * @param key Key of the attribute that has changed.
287
+ * @param oldValue Attribute value before the change or `null` if the attribute has not been set before.
288
+ * @param newValue New attribute value or `null` if the attribute has been removed.
289
+ * @param conversionApi The conversion API object.
290
+ */
291
+ _convertAttribute(range, key, oldValue, newValue, conversionApi) {
292
+ // Create a list with attributes to consume.
293
+ this._addConsumablesForRange(conversionApi.consumable, range, `attribute:${key}`);
294
+ // Create a separate attribute event for each node in the range.
295
+ for (const value of range) {
296
+ const data = {
297
+ item: value.item,
298
+ range: Range._createFromPositionAndShift(value.previousPosition, value.length),
299
+ attributeKey: key,
300
+ attributeOldValue: oldValue,
301
+ attributeNewValue: newValue
302
+ };
303
+ this._testAndFire(`attribute:${key}`, data, conversionApi);
304
+ }
305
+ }
306
+ /**
307
+ * Fires re-insertion conversion (with a `reconversion` flag passed to `insert` events)
308
+ * of a range of elements (only elements on the range depth, without children).
309
+ *
310
+ * For each node in the range on its depth (without children), {@link #event:insert `insert` event} is fired.
311
+ * For each attribute on each node, {@link #event:attribute `attribute` event} is fired.
312
+ *
313
+ * @fires insert
314
+ * @fires attribute
315
+ * @param range The range to reinsert.
316
+ * @param conversionApi The conversion API object.
317
+ */
318
+ _convertReinsert(range, conversionApi) {
319
+ // Convert the elements - without converting children.
320
+ const walkerValues = Array.from(range.getWalker({ shallow: true }));
321
+ // Collect a list of things that can be consumed, consisting of nodes and their attributes.
322
+ this._addConsumablesForInsert(conversionApi.consumable, walkerValues);
323
+ // Fire a separate insert event for each node and text fragment contained shallowly in the range.
324
+ for (const data of walkerValues.map(walkerValueToEventData)) {
325
+ this._testAndFire('insert', { ...data, reconversion: true }, conversionApi);
326
+ }
327
+ }
328
+ /**
329
+ * Converts the added marker. Fires the {@link #event:addMarker `addMarker`} event for each item
330
+ * in the marker's range. If the range is collapsed, a single event is dispatched. See the event description for more details.
331
+ *
332
+ * @fires addMarker
333
+ * @param markerName Marker name.
334
+ * @param markerRange The marker range.
335
+ * @param conversionApi The conversion API object.
336
+ */
337
+ _convertMarkerAdd(markerName, markerRange, conversionApi) {
338
+ // Do not convert if range is in graveyard.
339
+ if (markerRange.root.rootName == '$graveyard') {
340
+ return;
341
+ }
342
+ // In markers' case, event name == consumable name.
343
+ const eventName = `addMarker:${markerName}`;
344
+ //
345
+ // First, fire an event for the whole marker.
346
+ //
347
+ conversionApi.consumable.add(markerRange, eventName);
348
+ this.fire(eventName, { markerName, markerRange }, conversionApi);
349
+ //
350
+ // Do not fire events for each item inside the range if the range got consumed.
351
+ // Also consume the whole marker consumable if it wasn't consumed.
352
+ //
353
+ if (!conversionApi.consumable.consume(markerRange, eventName)) {
354
+ return;
355
+ }
356
+ //
357
+ // Then, fire an event for each item inside the marker range.
358
+ //
359
+ this._addConsumablesForRange(conversionApi.consumable, markerRange, eventName);
360
+ for (const item of markerRange.getItems()) {
361
+ // Do not fire event for already consumed items.
362
+ if (!conversionApi.consumable.test(item, eventName)) {
363
+ continue;
364
+ }
365
+ const data = { item, range: Range._createOn(item), markerName, markerRange };
366
+ this.fire(eventName, data, conversionApi);
367
+ }
368
+ }
369
+ /**
370
+ * Fires the conversion of the marker removal. Fires the {@link #event:removeMarker `removeMarker`} event with the provided data.
371
+ *
372
+ * @fires removeMarker
373
+ * @param markerName Marker name.
374
+ * @param markerRange The marker range.
375
+ * @param conversionApi The conversion API object.
376
+ */
377
+ _convertMarkerRemove(markerName, markerRange, conversionApi) {
378
+ // Do not convert if range is in graveyard.
379
+ if (markerRange.root.rootName == '$graveyard') {
380
+ return;
381
+ }
382
+ this.fire(`removeMarker:${markerName}`, { markerName, markerRange }, conversionApi);
383
+ }
384
+ /**
385
+ * Fires the reduction of changes buffered in the {@link module:engine/model/differ~Differ `Differ`}.
386
+ *
387
+ * Features can replace selected {@link module:engine/model/differ~DiffItem `DiffItem`}s with `reinsert` entries to trigger
388
+ * reconversion. The {@link module:engine/conversion/downcasthelpers~DowncastHelpers#elementToStructure
389
+ * `DowncastHelpers.elementToStructure()`} is using this event to trigger reconversion.
390
+ *
391
+ * @fires reduceChanges
392
+ */
393
+ _reduceChanges(changes) {
394
+ const data = { changes };
395
+ this.fire('reduceChanges', data);
396
+ return data.changes;
397
+ }
398
+ /**
399
+ * Populates provided {@link module:engine/conversion/modelconsumable~ModelConsumable} with values to consume from a given range,
400
+ * assuming that the range has just been inserted to the model.
401
+ *
402
+ * @param consumable The consumable.
403
+ * @param walkerValues The walker values for the inserted range.
404
+ * @returns The values to consume.
405
+ */
406
+ _addConsumablesForInsert(consumable, walkerValues) {
407
+ for (const value of walkerValues) {
408
+ const item = value.item;
409
+ // Add consumable if it wasn't there yet.
410
+ if (consumable.test(item, 'insert') === null) {
411
+ consumable.add(item, 'insert');
412
+ for (const key of item.getAttributeKeys()) {
413
+ consumable.add(item, 'attribute:' + key);
414
+ }
415
+ }
416
+ }
417
+ return consumable;
418
+ }
419
+ /**
420
+ * Populates provided {@link module:engine/conversion/modelconsumable~ModelConsumable} with values to consume for a given range.
421
+ *
422
+ * @param consumable The consumable.
423
+ * @param range The affected range.
424
+ * @param type Consumable type.
425
+ * @returns The values to consume.
426
+ */
427
+ _addConsumablesForRange(consumable, range, type) {
428
+ for (const item of range.getItems()) {
429
+ consumable.add(item, type);
430
+ }
431
+ return consumable;
432
+ }
433
+ /**
434
+ * Populates provided {@link module:engine/conversion/modelconsumable~ModelConsumable} with selection consumable values.
435
+ *
436
+ * @param consumable The consumable.
437
+ * @param selection The selection to create the consumable from.
438
+ * @param markers Markers that contain the selection.
439
+ * @returns The values to consume.
440
+ */
441
+ _addConsumablesForSelection(consumable, selection, markers) {
442
+ consumable.add(selection, 'selection');
443
+ for (const marker of markers) {
444
+ consumable.add(selection, 'addMarker:' + marker.name);
445
+ }
446
+ for (const key of selection.getAttributeKeys()) {
447
+ consumable.add(selection, 'attribute:' + key);
448
+ }
449
+ return consumable;
450
+ }
451
+ /**
452
+ * Tests whether given event wasn't already fired and if so, fires it.
453
+ *
454
+ * @fires insert
455
+ * @fires attribute
456
+ * @param type Event type.
457
+ * @param data Event data.
458
+ * @param conversionApi The conversion API object.
459
+ */
460
+ _testAndFire(type, data, conversionApi) {
461
+ const eventName = getEventName(type, data);
462
+ const itemKey = data.item.is('$textProxy') ? conversionApi.consumable._getSymbolForTextProxy(data.item) : data.item;
463
+ const eventsFiredForConversion = this._firedEventsMap.get(conversionApi);
464
+ const eventsFiredForItem = eventsFiredForConversion.get(itemKey);
465
+ if (!eventsFiredForItem) {
466
+ eventsFiredForConversion.set(itemKey, new Set([eventName]));
467
+ }
468
+ else if (!eventsFiredForItem.has(eventName)) {
469
+ eventsFiredForItem.add(eventName);
470
+ }
471
+ else {
472
+ return;
473
+ }
474
+ this.fire(eventName, data, conversionApi);
475
+ }
476
+ /**
477
+ * Fires not already fired events for setting attributes on just inserted item.
478
+ *
479
+ * @param item The model item to convert attributes for.
480
+ * @param conversionApi The conversion API object.
481
+ */
482
+ _testAndFireAddAttributes(item, conversionApi) {
483
+ const data = {
484
+ item,
485
+ range: Range._createOn(item)
486
+ };
487
+ for (const key of data.item.getAttributeKeys()) {
488
+ data.attributeKey = key;
489
+ data.attributeOldValue = null;
490
+ data.attributeNewValue = data.item.getAttribute(key);
491
+ this._testAndFire(`attribute:${key}`, data, conversionApi);
492
+ }
493
+ }
494
+ /**
495
+ * Builds an instance of the {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi} from a template and a given
496
+ * {@link module:engine/view/downcastwriter~DowncastWriter `DowncastWriter`} and options object.
497
+ *
498
+ * @param writer View writer that should be used to modify the view document.
499
+ * @param refreshedItems A set of model elements that should not reuse their
500
+ * previous view representations.
501
+ * @param options Optional options passed to `convertionApi.options`.
502
+ * @return The conversion API object.
503
+ */
504
+ _createConversionApi(writer, refreshedItems = new Set(), options = {}) {
505
+ const conversionApi = {
506
+ ...this._conversionApi,
507
+ consumable: new Consumable(),
508
+ writer,
509
+ options,
510
+ convertItem: item => this._convertInsert(Range._createOn(item), conversionApi),
511
+ convertChildren: element => this._convertInsert(Range._createIn(element), conversionApi, { doNotAddConsumables: true }),
512
+ convertAttributes: item => this._testAndFireAddAttributes(item, conversionApi),
513
+ canReuseView: viewElement => !refreshedItems.has(conversionApi.mapper.toModelElement(viewElement))
514
+ };
515
+ this._firedEventsMap.set(conversionApi, new Map());
516
+ return conversionApi;
517
+ }
518
+ }
519
+ /**
520
+ * Helper function, checks whether change of `marker` at `modelPosition` should be converted. Marker changes are not
521
+ * converted if they happen inside an element with custom conversion method.
522
+ */
523
+ function shouldMarkerChangeBeConverted(modelPosition, marker, mapper) {
524
+ const range = marker.getRange();
525
+ const ancestors = Array.from(modelPosition.getAncestors());
526
+ ancestors.shift(); // Remove root element. It cannot be passed to `model.Range#containsItem`.
527
+ ancestors.reverse();
528
+ const hasCustomHandling = ancestors.some(element => {
529
+ if (range.containsItem(element)) {
530
+ const viewElement = mapper.toViewElement(element);
531
+ return !!viewElement.getCustomProperty('addHighlight');
532
+ }
533
+ });
534
+ return !hasCustomHandling;
535
+ }
536
+ function getEventName(type, data) {
537
+ const name = data.item.is('element') ? data.item.name : '$text';
538
+ return `${type}:${name}`;
539
+ }
540
+ function walkerValueToEventData(value) {
541
+ const item = value.item;
542
+ const itemRange = Range._createFromPositionAndShift(value.previousPosition, value.length);
543
+ return {
544
+ item,
545
+ range: itemRange
546
+ };
547
+ }