@ckeditor/ckeditor5-engine 30.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/LICENSE.md +17 -0
  2. package/README.md +30 -0
  3. package/package.json +70 -0
  4. package/src/controller/datacontroller.js +563 -0
  5. package/src/controller/editingcontroller.js +149 -0
  6. package/src/conversion/conversion.js +644 -0
  7. package/src/conversion/conversionhelpers.js +40 -0
  8. package/src/conversion/downcastdispatcher.js +914 -0
  9. package/src/conversion/downcasthelpers.js +1706 -0
  10. package/src/conversion/mapper.js +696 -0
  11. package/src/conversion/modelconsumable.js +329 -0
  12. package/src/conversion/upcastdispatcher.js +807 -0
  13. package/src/conversion/upcasthelpers.js +997 -0
  14. package/src/conversion/viewconsumable.js +623 -0
  15. package/src/dataprocessor/basichtmlwriter.js +32 -0
  16. package/src/dataprocessor/dataprocessor.jsdoc +64 -0
  17. package/src/dataprocessor/htmldataprocessor.js +159 -0
  18. package/src/dataprocessor/htmlwriter.js +22 -0
  19. package/src/dataprocessor/xmldataprocessor.js +161 -0
  20. package/src/dev-utils/model.js +482 -0
  21. package/src/dev-utils/operationreplayer.js +140 -0
  22. package/src/dev-utils/utils.js +103 -0
  23. package/src/dev-utils/view.js +1091 -0
  24. package/src/index.js +52 -0
  25. package/src/model/batch.js +82 -0
  26. package/src/model/differ.js +1282 -0
  27. package/src/model/document.js +483 -0
  28. package/src/model/documentfragment.js +390 -0
  29. package/src/model/documentselection.js +1261 -0
  30. package/src/model/element.js +438 -0
  31. package/src/model/history.js +138 -0
  32. package/src/model/item.jsdoc +14 -0
  33. package/src/model/liveposition.js +182 -0
  34. package/src/model/liverange.js +221 -0
  35. package/src/model/markercollection.js +553 -0
  36. package/src/model/model.js +934 -0
  37. package/src/model/node.js +507 -0
  38. package/src/model/nodelist.js +217 -0
  39. package/src/model/operation/attributeoperation.js +202 -0
  40. package/src/model/operation/detachoperation.js +103 -0
  41. package/src/model/operation/insertoperation.js +188 -0
  42. package/src/model/operation/markeroperation.js +154 -0
  43. package/src/model/operation/mergeoperation.js +216 -0
  44. package/src/model/operation/moveoperation.js +209 -0
  45. package/src/model/operation/nooperation.js +58 -0
  46. package/src/model/operation/operation.js +139 -0
  47. package/src/model/operation/operationfactory.js +49 -0
  48. package/src/model/operation/renameoperation.js +155 -0
  49. package/src/model/operation/rootattributeoperation.js +211 -0
  50. package/src/model/operation/splitoperation.js +254 -0
  51. package/src/model/operation/transform.js +2389 -0
  52. package/src/model/operation/utils.js +292 -0
  53. package/src/model/position.js +1164 -0
  54. package/src/model/range.js +1049 -0
  55. package/src/model/rootelement.js +111 -0
  56. package/src/model/schema.js +1851 -0
  57. package/src/model/selection.js +902 -0
  58. package/src/model/text.js +138 -0
  59. package/src/model/textproxy.js +279 -0
  60. package/src/model/treewalker.js +414 -0
  61. package/src/model/utils/autoparagraphing.js +77 -0
  62. package/src/model/utils/deletecontent.js +528 -0
  63. package/src/model/utils/getselectedcontent.js +150 -0
  64. package/src/model/utils/insertcontent.js +824 -0
  65. package/src/model/utils/modifyselection.js +229 -0
  66. package/src/model/utils/selection-post-fixer.js +297 -0
  67. package/src/model/writer.js +1574 -0
  68. package/src/view/attributeelement.js +274 -0
  69. package/src/view/containerelement.js +123 -0
  70. package/src/view/document.js +221 -0
  71. package/src/view/documentfragment.js +273 -0
  72. package/src/view/documentselection.js +387 -0
  73. package/src/view/domconverter.js +1437 -0
  74. package/src/view/downcastwriter.js +2121 -0
  75. package/src/view/editableelement.js +118 -0
  76. package/src/view/element.js +945 -0
  77. package/src/view/elementdefinition.jsdoc +59 -0
  78. package/src/view/emptyelement.js +119 -0
  79. package/src/view/filler.js +161 -0
  80. package/src/view/item.jsdoc +14 -0
  81. package/src/view/matcher.js +776 -0
  82. package/src/view/node.js +391 -0
  83. package/src/view/observer/arrowkeysobserver.js +58 -0
  84. package/src/view/observer/bubblingemittermixin.js +307 -0
  85. package/src/view/observer/bubblingeventinfo.js +71 -0
  86. package/src/view/observer/clickobserver.js +46 -0
  87. package/src/view/observer/compositionobserver.js +79 -0
  88. package/src/view/observer/domeventdata.js +82 -0
  89. package/src/view/observer/domeventobserver.js +99 -0
  90. package/src/view/observer/fakeselectionobserver.js +118 -0
  91. package/src/view/observer/focusobserver.js +106 -0
  92. package/src/view/observer/inputobserver.js +44 -0
  93. package/src/view/observer/keyobserver.js +83 -0
  94. package/src/view/observer/mouseobserver.js +56 -0
  95. package/src/view/observer/mutationobserver.js +345 -0
  96. package/src/view/observer/observer.js +118 -0
  97. package/src/view/observer/selectionobserver.js +242 -0
  98. package/src/view/placeholder.js +285 -0
  99. package/src/view/position.js +426 -0
  100. package/src/view/range.js +533 -0
  101. package/src/view/rawelement.js +148 -0
  102. package/src/view/renderer.js +1037 -0
  103. package/src/view/rooteditableelement.js +107 -0
  104. package/src/view/selection.js +718 -0
  105. package/src/view/styles/background.js +73 -0
  106. package/src/view/styles/border.js +362 -0
  107. package/src/view/styles/margin.js +41 -0
  108. package/src/view/styles/padding.js +40 -0
  109. package/src/view/styles/utils.js +277 -0
  110. package/src/view/stylesmap.js +938 -0
  111. package/src/view/text.js +147 -0
  112. package/src/view/textproxy.js +199 -0
  113. package/src/view/treewalker.js +496 -0
  114. package/src/view/uielement.js +238 -0
  115. package/src/view/upcastwriter.js +484 -0
  116. package/src/view/view.js +721 -0
  117. package/theme/placeholder.css +27 -0
package/LICENSE.md ADDED
@@ -0,0 +1,17 @@
1
+ Software License Agreement
2
+ ==========================
3
+
4
+ **CKEditor 5 editing engine** – https://github.com/ckeditor/ckeditor5-engine <br>
5
+ Copyright (c) 2003-2021, [CKSource](http://cksource.com) Frederico Knabben. All rights reserved.
6
+
7
+ Licensed under the terms of [GNU General Public License Version 2 or later](http://www.gnu.org/licenses/gpl.html).
8
+
9
+ Sources of Intellectual Property Included in CKEditor
10
+ -----------------------------------------------------
11
+
12
+ Where not otherwise indicated, all CKEditor content is authored by CKSource engineers and consists of CKSource-owned intellectual property. In some specific instances, CKEditor will incorporate work done by developers outside of CKSource with their express permission.
13
+
14
+ Trademarks
15
+ ----------
16
+
17
+ **CKEditor** is a trademark of [CKSource](http://cksource.com) Frederico Knabben. All other brand and product names are trademarks, registered trademarks or service marks of their respective holders.
package/README.md ADDED
@@ -0,0 +1,30 @@
1
+ CKEditor 5 editing engine
2
+ ========================================
3
+
4
+ [![npm version](https://badge.fury.io/js/%40ckeditor%2Fckeditor5-engine.svg)](https://www.npmjs.com/package/@ckeditor/ckeditor5-engine)
5
+ [![Coverage Status](https://coveralls.io/repos/github/ckeditor/ckeditor5/badge.svg?branch=master)](https://coveralls.io/github/ckeditor/ckeditor5?branch=master)
6
+ [![Build Status](https://travis-ci.com/ckeditor/ckeditor5.svg?branch=master)](https://travis-ci.com/ckeditor/ckeditor5)
7
+
8
+ The CKEditor 5 editing engine implements a flexible MVC-based architecture for creating rich text editing features.
9
+
10
+ ## Architecture overview
11
+
12
+ * **Custom data model.** CKEditor 5 implements a tree-structured custom data model, designed to fit multiple requirements such as enabling real-time collaboration and complex editing features (like tables or nested blocks).
13
+ * **Virtual DOM.** CKEditor 5's editing engine features a custom, editing-oriented virtual DOM implementation that aims to hide browser quirks from your sight. **No more `contentEditable` nightmares!**
14
+ * **Real-time collaborative editing**. The editor implements Operational Transformation for the tree-structured model as well as many other mechanisms which were required to create a seamless collaborative UX. Additionally, we provide cloud infrastructure and plugins enabling real-time collaborative editing in your application! [Check the collaboration demo](https://ckeditor.com/docs/ckeditor5/latest/features/collaboration/overview.html).
15
+ * **Extensible.** The entire editor architecture was designed for maximum flexibility. The code is event-based and highly decoupled, allowing you to plug in or replace selected pieces. Features do not directly depend on each other and communicate in standardized ways.
16
+ * **Schema-less core**. The core makes minimal assumptions and can be controlled through the schema. This leaves all decisions to plugins and to you.
17
+ * **Modular architecture.** Not only can the core modules be reused and recomposed but even the features were implemented in a highly granular way. Feel like running a headless CKEditor 5 with a couple of features in Node.js? Not a problem!
18
+ * **Framework for building rich-text editors.** Every use case is different and every editor needs to fulfill different goals. Therefore, we give you the freedom to create your own editors with custom-tailored features and UI.
19
+ * **Heavily tested from day one.** CKEditor 5 comes with 3x more tests than React itself. All packages have 100% code coverage.
20
+ * **8+ years of support.** It is not yet another framework to be gone next year or a hyped proof-of-concept to fail in a real-life scenario. We have over 15 years of experience in creating rich text editors and invested over 4 years in designing and building your next future-proof rich text editor of choice.
21
+
22
+ ## Documentation
23
+
24
+ For a general introduction see the [Overview of CKEditor 5 Framework](https://ckeditor.com/docs/ckeditor5/latest/framework/guides/overview.html) guide and then the [Editing engine architecture guide](https://ckeditor.com/docs/ckeditor5/latest/framework/guides/architecture/editing-engine.html).
25
+
26
+ Additionally, refer to the [`@ckeditor/ckeditor5-engine` package](https://ckeditor.com/docs/ckeditor5/latest/api/engine.html) page in [CKEditor 5 documentation](https://ckeditor.com/docs/ckeditor5/latest/) for even more information.
27
+
28
+ ## License
29
+
30
+ Licensed under the terms of [GNU General Public License Version 2 or later](http://www.gnu.org/licenses/gpl.html). For full details about the license, please check the `LICENSE.md` file or [https://ckeditor.com/legal/ckeditor-oss-license](https://ckeditor.com/legal/ckeditor-oss-license).
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@ckeditor/ckeditor5-engine",
3
+ "version": "30.0.0",
4
+ "description": "The editing engine of CKEditor 5 – the best browser-based rich text editor.",
5
+ "keywords": [
6
+ "wysiwyg",
7
+ "rich text",
8
+ "editor",
9
+ "html",
10
+ "contentEditable",
11
+ "editing",
12
+ "operational transformation",
13
+ "ot",
14
+ "collaboration",
15
+ "collaborative",
16
+ "real-time",
17
+ "framework",
18
+ "ckeditor",
19
+ "ckeditor5",
20
+ "ckeditor 5",
21
+ "ckeditor5-lib",
22
+ "ckeditor5-dll"
23
+ ],
24
+ "main": "src/index.js",
25
+ "dependencies": {
26
+ "@ckeditor/ckeditor5-utils": "^30.0.0",
27
+ "lodash-es": "^4.17.15"
28
+ },
29
+ "devDependencies": {
30
+ "@ckeditor/ckeditor5-basic-styles": "^30.0.0",
31
+ "@ckeditor/ckeditor5-block-quote": "^30.0.0",
32
+ "@ckeditor/ckeditor5-clipboard": "^30.0.0",
33
+ "@ckeditor/ckeditor5-core": "^30.0.0",
34
+ "@ckeditor/ckeditor5-editor-classic": "^30.0.0",
35
+ "@ckeditor/ckeditor5-enter": "^30.0.0",
36
+ "@ckeditor/ckeditor5-essentials": "^30.0.0",
37
+ "@ckeditor/ckeditor5-heading": "^30.0.0",
38
+ "@ckeditor/ckeditor5-image": "^30.0.0",
39
+ "@ckeditor/ckeditor5-link": "^30.0.0",
40
+ "@ckeditor/ckeditor5-list": "^30.0.0",
41
+ "@ckeditor/ckeditor5-paragraph": "^30.0.0",
42
+ "@ckeditor/ckeditor5-table": "^30.0.0",
43
+ "@ckeditor/ckeditor5-theme-lark": "^30.0.0",
44
+ "@ckeditor/ckeditor5-typing": "^30.0.0",
45
+ "@ckeditor/ckeditor5-ui": "^30.0.0",
46
+ "@ckeditor/ckeditor5-undo": "^30.0.0",
47
+ "@ckeditor/ckeditor5-widget": "^30.0.0",
48
+ "webpack": "^4.43.0",
49
+ "webpack-cli": "^3.3.11"
50
+ },
51
+ "engines": {
52
+ "node": ">=12.0.0",
53
+ "npm": ">=5.7.1"
54
+ },
55
+ "author": "CKSource (http://cksource.com/)",
56
+ "license": "GPL-2.0-or-later",
57
+ "homepage": "https://ckeditor.com/ckeditor-5",
58
+ "bugs": "https://github.com/ckeditor/ckeditor5/issues",
59
+ "repository": {
60
+ "type": "git",
61
+ "url": "https://github.com/ckeditor/ckeditor5.git",
62
+ "directory": "packages/ckeditor5-engine"
63
+ },
64
+ "files": [
65
+ "lang",
66
+ "src",
67
+ "theme",
68
+ "ckeditor5-metadata.json"
69
+ ]
70
+ }
@@ -0,0 +1,563 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+
6
+ /**
7
+ * @module engine/controller/datacontroller
8
+ */
9
+
10
+ import mix from '@ckeditor/ckeditor5-utils/src/mix';
11
+ import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
12
+ import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
13
+
14
+ import Mapper from '../conversion/mapper';
15
+
16
+ import DowncastDispatcher from '../conversion/downcastdispatcher';
17
+ import { insertText } from '../conversion/downcasthelpers';
18
+
19
+ import UpcastDispatcher from '../conversion/upcastdispatcher';
20
+ import { convertText, convertToModelFragment } from '../conversion/upcasthelpers';
21
+
22
+ import ViewDocumentFragment from '../view/documentfragment';
23
+ import ViewDocument from '../view/document';
24
+ import ViewDowncastWriter from '../view/downcastwriter';
25
+
26
+ import ModelRange from '../model/range';
27
+ import { autoParagraphEmptyRoots } from '../model/utils/autoparagraphing';
28
+ import HtmlDataProcessor from '../dataprocessor/htmldataprocessor';
29
+
30
+ /**
31
+ * Controller for the data pipeline. The data pipeline controls how data is retrieved from the document
32
+ * and set inside it. Hence, the controller features two methods which allow to {@link ~DataController#get get}
33
+ * and {@link ~DataController#set set} data of the {@link ~DataController#model model}
34
+ * using given:
35
+ *
36
+ * * {@link module:engine/dataprocessor/dataprocessor~DataProcessor data processor},
37
+ * * downcast converters,
38
+ * * upcast converters.
39
+ *
40
+ * An instance of the data controller is always available in the {@link module:core/editor/editor~Editor#data `editor.data`}
41
+ * property:
42
+ *
43
+ * editor.data.get( { rootName: 'customRoot' } ); // -> '<p>Hello!</p>'
44
+ *
45
+ * @mixes module:utils/observablemixin~ObservableMixin
46
+ */
47
+ export default class DataController {
48
+ /**
49
+ * Creates a data controller instance.
50
+ *
51
+ * @param {module:engine/model/model~Model} model Data model.
52
+ * @param {module:engine/view/stylesmap~StylesProcessor} stylesProcessor The styles processor instance.
53
+ */
54
+ constructor( model, stylesProcessor ) {
55
+ /**
56
+ * Data model.
57
+ *
58
+ * @readonly
59
+ * @member {module:engine/model/model~Model}
60
+ */
61
+ this.model = model;
62
+
63
+ /**
64
+ * Mapper used for the conversion. It has no permanent bindings, because they are created when getting data and
65
+ * cleared directly after the data are converted. However, the mapper is defined as a class property, because
66
+ * it needs to be passed to the `DowncastDispatcher` as a conversion API.
67
+ *
68
+ * @readonly
69
+ * @member {module:engine/conversion/mapper~Mapper}
70
+ */
71
+ this.mapper = new Mapper();
72
+
73
+ /**
74
+ * Downcast dispatcher used by the {@link #get get method}. Downcast converters should be attached to it.
75
+ *
76
+ * @readonly
77
+ * @member {module:engine/conversion/downcastdispatcher~DowncastDispatcher}
78
+ */
79
+ this.downcastDispatcher = new DowncastDispatcher( {
80
+ mapper: this.mapper,
81
+ schema: model.schema
82
+ } );
83
+ this.downcastDispatcher.on( 'insert:$text', insertText(), { priority: 'lowest' } );
84
+
85
+ /**
86
+ * Upcast dispatcher used by the {@link #set set method}. Upcast converters should be attached to it.
87
+ *
88
+ * @readonly
89
+ * @member {module:engine/conversion/upcastdispatcher~UpcastDispatcher}
90
+ */
91
+ this.upcastDispatcher = new UpcastDispatcher( {
92
+ schema: model.schema
93
+ } );
94
+
95
+ /**
96
+ * The view document used by the data controller.
97
+ *
98
+ * @readonly
99
+ * @member {module:engine/view/document~Document}
100
+ */
101
+ this.viewDocument = new ViewDocument( stylesProcessor );
102
+
103
+ /**
104
+ * Styles processor used during the conversion.
105
+ *
106
+ * @readonly
107
+ * @member {module:engine/view/stylesmap~StylesProcessor}
108
+ */
109
+ this.stylesProcessor = stylesProcessor;
110
+
111
+ /**
112
+ * Data processor used specifically for HTML conversion.
113
+ *
114
+ * @readonly
115
+ * @member {module:engine/dataprocessor/htmldataprocessor~HtmlDataProcessor} #htmlProcessor
116
+ */
117
+ this.htmlProcessor = new HtmlDataProcessor( this.viewDocument );
118
+
119
+ /**
120
+ * Data processor used during the conversion.
121
+ * Same instance as {@link #htmlProcessor} by default. Can be replaced at run time to handle different format, e.g. XML or Markdown.
122
+ *
123
+ * @member {module:engine/dataprocessor/dataprocessor~DataProcessor} #processor
124
+ */
125
+ this.processor = this.htmlProcessor;
126
+
127
+ /**
128
+ * The view downcast writer just for data conversion purposes, i.e. to modify
129
+ * the {@link #viewDocument}.
130
+ *
131
+ * @private
132
+ * @readonly
133
+ * @member {module:engine/view/downcastwriter~DowncastWriter}
134
+ */
135
+ this._viewWriter = new ViewDowncastWriter( this.viewDocument );
136
+
137
+ // Define default converters for text and elements.
138
+ //
139
+ // Note that if there is no default converter for the element it will be skipped, for instance `<b>foo</b>` will be
140
+ // converted to nothing. We therefore add `convertToModelFragment` as a last converter so it converts children of that
141
+ // element to the document fragment and so `<b>foo</b>` will be converted to `foo` if there is no converter for `<b>`.
142
+ this.upcastDispatcher.on( 'text', convertText(), { priority: 'lowest' } );
143
+ this.upcastDispatcher.on( 'element', convertToModelFragment(), { priority: 'lowest' } );
144
+ this.upcastDispatcher.on( 'documentFragment', convertToModelFragment(), { priority: 'lowest' } );
145
+
146
+ this.decorate( 'init' );
147
+ this.decorate( 'set' );
148
+
149
+ // Fire the `ready` event when the initialization has completed. Such low-level listener gives possibility
150
+ // to plug into the initialization pipeline without interrupting the initialization flow.
151
+ this.on( 'init', () => {
152
+ this.fire( 'ready' );
153
+ }, { priority: 'lowest' } );
154
+
155
+ // Fix empty roots after DataController is 'ready' (note that init method could be decorated and stopped).
156
+ // We need to handle this event because initial data could be empty and post-fixer would not get triggered.
157
+ this.on( 'ready', () => {
158
+ this.model.enqueueChange( 'transparent', autoParagraphEmptyRoots );
159
+ }, { priority: 'lowest' } );
160
+ }
161
+
162
+ /**
163
+ * Returns the model's data converted by downcast dispatchers attached to {@link #downcastDispatcher} and
164
+ * formatted by the {@link #processor data processor}.
165
+ *
166
+ * @param {Object} [options] Additional configuration for the retrieved data. `DataController` provides two optional
167
+ * properties: `rootName` and `trim`. Other properties of this object are specified by various editor features.
168
+ * @param {String} [options.rootName='main'] Root name.
169
+ * @param {String} [options.trim='empty'] Whether returned data should be trimmed. This option is set to `empty` by default,
170
+ * which means whenever editor content is considered empty, an empty string will be returned. To turn off trimming completely
171
+ * use `'none'`. In such cases exact content will be returned (for example `<p>&nbsp;</p>` for an empty editor).
172
+ * @returns {String} Output data.
173
+ */
174
+ get( options = {} ) {
175
+ const { rootName = 'main', trim = 'empty' } = options;
176
+
177
+ if ( !this._checkIfRootsExists( [ rootName ] ) ) {
178
+ /**
179
+ * Cannot get data from a non-existing root. This error is thrown when {@link #get DataController#get() method}
180
+ * is called with non-existent root name. For example, if there is an editor instance with only `main` root,
181
+ * calling {@link #get} like:
182
+ *
183
+ * data.get( { rootName: 'root2' } );
184
+ *
185
+ * will throw this error.
186
+ *
187
+ * @error datacontroller-get-non-existent-root
188
+ */
189
+ throw new CKEditorError( 'datacontroller-get-non-existent-root', this );
190
+ }
191
+
192
+ const root = this.model.document.getRoot( rootName );
193
+
194
+ if ( trim === 'empty' && !this.model.hasContent( root, { ignoreWhitespaces: true } ) ) {
195
+ return '';
196
+ }
197
+
198
+ return this.stringify( root, options );
199
+ }
200
+
201
+ /**
202
+ * Returns the content of the given {@link module:engine/model/element~Element model's element} or
203
+ * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the downcast converters
204
+ * attached to {@link #downcastDispatcher} and formatted by the {@link #processor data processor}.
205
+ *
206
+ * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} modelElementOrFragment
207
+ * Element whose content will be stringified.
208
+ * @param {Object} [options] Additional configuration passed to the conversion process.
209
+ * @returns {String} Output data.
210
+ */
211
+ stringify( modelElementOrFragment, options = {} ) {
212
+ // Model -> view.
213
+ const viewDocumentFragment = this.toView( modelElementOrFragment, options );
214
+
215
+ // View -> data.
216
+ return this.processor.toData( viewDocumentFragment );
217
+ }
218
+
219
+ /**
220
+ * Returns the content of the given {@link module:engine/model/element~Element model element} or
221
+ * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the downcast
222
+ * converters attached to {@link #downcastDispatcher} to a
223
+ * {@link module:engine/view/documentfragment~DocumentFragment view document fragment}.
224
+ *
225
+ * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} modelElementOrFragment
226
+ * Element or document fragment whose content will be converted.
227
+ * @param {Object} [options={}] Additional configuration that will be available through
228
+ * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi#options} during the conversion process.
229
+ * @returns {module:engine/view/documentfragment~DocumentFragment} Output view DocumentFragment.
230
+ */
231
+ toView( modelElementOrFragment, options = {} ) {
232
+ const viewDocument = this.viewDocument;
233
+ const viewWriter = this._viewWriter;
234
+
235
+ // Clear bindings so the call to this method gives correct results.
236
+ this.mapper.clearBindings();
237
+
238
+ // First, convert elements.
239
+ const modelRange = ModelRange._createIn( modelElementOrFragment );
240
+ const viewDocumentFragment = new ViewDocumentFragment( viewDocument );
241
+
242
+ this.mapper.bindElements( modelElementOrFragment, viewDocumentFragment );
243
+
244
+ // Make additional options available during conversion process through `conversionApi`.
245
+ this.downcastDispatcher.conversionApi.options = options;
246
+
247
+ // We have no view controller and rendering to DOM in DataController so view.change() block is not used here.
248
+ this.downcastDispatcher.convertInsert( modelRange, viewWriter );
249
+
250
+ // Convert markers.
251
+ // For document fragment, simply take the markers assigned to this document fragment.
252
+ // For model root, all markers in that root will be taken.
253
+ // For model element, we need to check which markers are intersecting with this element and relatively modify the markers' ranges.
254
+ // Collapsed markers at element boundary, although considered as not intersecting with the element, will also be returned.
255
+ const markers = modelElementOrFragment.is( 'documentFragment' ) ?
256
+ Array.from( modelElementOrFragment.markers ) :
257
+ _getMarkersRelativeToElement( modelElementOrFragment );
258
+
259
+ for ( const [ name, range ] of markers ) {
260
+ this.downcastDispatcher.convertMarkerAdd( name, range, viewWriter );
261
+ }
262
+
263
+ // Clean `conversionApi`.
264
+ delete this.downcastDispatcher.conversionApi.options;
265
+
266
+ return viewDocumentFragment;
267
+ }
268
+
269
+ /**
270
+ * Sets initial input data parsed by the {@link #processor data processor} and
271
+ * converted by the {@link #upcastDispatcher view-to-model converters}.
272
+ * Initial data can be set only to document that {@link module:engine/model/document~Document#version} is equal 0.
273
+ *
274
+ * **Note** This method is {@link module:utils/observablemixin~ObservableMixin#decorate decorated} which is
275
+ * used by e.g. collaborative editing plugin that syncs remote data on init.
276
+ *
277
+ * When data is passed as a string it is initialized on a default `main` root:
278
+ *
279
+ * dataController.init( '<p>Foo</p>' ); // Initializes data on the `main` root.
280
+ *
281
+ * To initialize data on a different root or multiple roots at once, object containing `rootName` - `data` pairs should be passed:
282
+ *
283
+ * dataController.init( { main: '<p>Foo</p>', title: '<h1>Bar</h1>' } ); // Initializes data on the `main` and `title` roots.
284
+ *
285
+ * @fires init
286
+ * @param {String|Object.<String,String>} data Input data as a string or an object containing `rootName` - `data`
287
+ * pairs to initialize data on multiple roots at once.
288
+ * @returns {Promise} Promise that is resolved after the data is set on the editor.
289
+ */
290
+ init( data ) {
291
+ if ( this.model.document.version ) {
292
+ /**
293
+ * Cannot set initial data to not empty {@link module:engine/model/document~Document}.
294
+ * Initial data should be set once, during {@link module:core/editor/editor~Editor} initialization,
295
+ * when the {@link module:engine/model/document~Document#version} is equal 0.
296
+ *
297
+ * @error datacontroller-init-document-not-empty
298
+ */
299
+ throw new CKEditorError( 'datacontroller-init-document-not-empty', this );
300
+ }
301
+
302
+ let initialData = {};
303
+ if ( typeof data === 'string' ) {
304
+ initialData.main = data; // Default root is 'main'. To initiate data on a different root, object should be passed.
305
+ } else {
306
+ initialData = data;
307
+ }
308
+
309
+ if ( !this._checkIfRootsExists( Object.keys( initialData ) ) ) {
310
+ /**
311
+ * Cannot init data on a non-existing root. This error is thrown when {@link #init DataController#init() method}
312
+ * is called with non-existent root name. For example, if there is an editor instance with only `main` root,
313
+ * calling {@link #init} like:
314
+ *
315
+ * data.init( { main: '<p>Foo</p>', root2: '<p>Bar</p>' } );
316
+ *
317
+ * will throw this error.
318
+ *
319
+ * @error datacontroller-init-non-existent-root
320
+ */
321
+ throw new CKEditorError( 'datacontroller-init-non-existent-root', this );
322
+ }
323
+
324
+ this.model.enqueueChange( 'transparent', writer => {
325
+ for ( const rootName of Object.keys( initialData ) ) {
326
+ const modelRoot = this.model.document.getRoot( rootName );
327
+ writer.insert( this.parse( initialData[ rootName ], modelRoot ), modelRoot, 0 );
328
+ }
329
+ } );
330
+
331
+ return Promise.resolve();
332
+ }
333
+
334
+ /**
335
+ * Sets input data parsed by the {@link #processor data processor} and
336
+ * converted by the {@link #upcastDispatcher view-to-model converters}.
337
+ * This method can be used any time to replace existing editor data by the new one without clearing the
338
+ * {@link module:engine/model/document~Document#history document history}.
339
+ *
340
+ * This method also creates a batch with all the changes applied. If all you need is to parse data, use
341
+ * the {@link #parse} method.
342
+ *
343
+ * When data is passed as a string it is set on a default `main` root:
344
+ *
345
+ * dataController.set( '<p>Foo</p>' ); // Sets data on the `main` root.
346
+ *
347
+ * To set data on a different root or multiple roots at once, object containing `rootName` - `data` pairs should be passed:
348
+ *
349
+ * dataController.set( { main: '<p>Foo</p>', title: '<h1>Bar</h1>' } ); // Sets data on the `main` and `title` roots.
350
+ *
351
+ * To set the data with preserved undo stacks and set the current change to this stack, use the `{ batchType: 'default' }` option.
352
+ *
353
+ * dataController.set( '<p>Foo</p>', { batchType: 'default' } ); // Sets data as a new change.
354
+ *
355
+ * @fires set
356
+ * @param {String|Object.<String,String>} data Input data as a string or an object containing `rootName` - `data`
357
+ * pairs to set data on multiple roots at once.
358
+ * @param {Object} [options={}] Options for setting data.
359
+ * @param {'default'|'transparent'} [options.batchType='default'] The batch type that will be used to create a batch for the changes.
360
+ * When set to `default`, the undo and redo stacks will be preserved. Note that when not set, the undo feature (when present) will
361
+ * override it to `transparent` and all undo steps will be lost.
362
+ */
363
+ set( data, options = {} ) {
364
+ let newData = {};
365
+
366
+ if ( typeof data === 'string' ) {
367
+ newData.main = data; // Default root is 'main'. To set data on a different root, object should be passed.
368
+ } else {
369
+ newData = data;
370
+ }
371
+
372
+ if ( !this._checkIfRootsExists( Object.keys( newData ) ) ) {
373
+ /**
374
+ * Cannot set data on a non-existing root. This error is thrown when {@link #set DataController#set() method}
375
+ * is called with non-existent root name. For example, if there is an editor instance with only `main` root,
376
+ * calling {@link #set} like:
377
+ *
378
+ * data.set( { main: '<p>Foo</p>', root2: '<p>Bar</p>' } );
379
+ *
380
+ * will throw this error.
381
+ *
382
+ * @error datacontroller-set-non-existent-root
383
+ */
384
+ throw new CKEditorError( 'datacontroller-set-non-existent-root', this );
385
+ }
386
+
387
+ const batchType = options.batchType || 'default';
388
+
389
+ this.model.enqueueChange( batchType, writer => {
390
+ writer.setSelection( null );
391
+ writer.removeSelectionAttribute( this.model.document.selection.getAttributeKeys() );
392
+
393
+ for ( const rootName of Object.keys( newData ) ) {
394
+ // Save to model.
395
+ const modelRoot = this.model.document.getRoot( rootName );
396
+
397
+ writer.remove( writer.createRangeIn( modelRoot ) );
398
+ writer.insert( this.parse( newData[ rootName ], modelRoot ), modelRoot, 0 );
399
+ }
400
+ } );
401
+ }
402
+
403
+ /**
404
+ * Returns the data parsed by the {@link #processor data processor} and then converted by upcast converters
405
+ * attached to the {@link #upcastDispatcher}.
406
+ *
407
+ * @see #set
408
+ * @param {String} data Data to parse.
409
+ * @param {module:engine/model/schema~SchemaContextDefinition} [context='$root'] Base context in which the view will
410
+ * be converted to the model. See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
411
+ * @returns {module:engine/model/documentfragment~DocumentFragment} Parsed data.
412
+ */
413
+ parse( data, context = '$root' ) {
414
+ // data -> view
415
+ const viewDocumentFragment = this.processor.toView( data );
416
+
417
+ // view -> model
418
+ return this.toModel( viewDocumentFragment, context );
419
+ }
420
+
421
+ /**
422
+ * Returns the result of the given {@link module:engine/view/element~Element view element} or
423
+ * {@link module:engine/view/documentfragment~DocumentFragment view document fragment} converted by the
424
+ * {@link #upcastDispatcher view-to-model converters}, wrapped by {@link module:engine/model/documentfragment~DocumentFragment}.
425
+ *
426
+ * When marker elements were converted during the conversion process, it will be set as a document fragment's
427
+ * {@link module:engine/model/documentfragment~DocumentFragment#markers static markers map}.
428
+ *
429
+ * @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment} viewElementOrFragment
430
+ * Element or document fragment whose content will be converted.
431
+ * @param {module:engine/model/schema~SchemaContextDefinition} [context='$root'] Base context in which the view will
432
+ * be converted to the model. See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
433
+ * @returns {module:engine/model/documentfragment~DocumentFragment} Output document fragment.
434
+ */
435
+ toModel( viewElementOrFragment, context = '$root' ) {
436
+ return this.model.change( writer => {
437
+ return this.upcastDispatcher.convert( viewElementOrFragment, writer, context );
438
+ } );
439
+ }
440
+
441
+ /**
442
+ * Adds a style processor normalization rules.
443
+ *
444
+ * You can implement your own rules as well as use one of the available processor rules:
445
+ *
446
+ * * background: {@link module:engine/view/styles/background~addBackgroundRules}
447
+ * * border: {@link module:engine/view/styles/border~addBorderRules}
448
+ * * margin: {@link module:engine/view/styles/margin~addMarginRules}
449
+ * * padding: {@link module:engine/view/styles/padding~addPaddingRules}
450
+ *
451
+ * @param {Function} callback
452
+ */
453
+ addStyleProcessorRules( callback ) {
454
+ callback( this.stylesProcessor );
455
+ }
456
+
457
+ /**
458
+ * Registers a {@link module:engine/view/matcher~MatcherPattern} on {@link #htmlProcessor htmlProcessor}
459
+ * and {@link #processor processor} for view elements whose content should be treated as a raw data
460
+ * and not processed during conversion from DOM to view elements.
461
+ *
462
+ * The raw data can be later accessed by {@link module:engine/view/element~Element#getCustomProperty view element custom property}
463
+ * `"$rawContent"`.
464
+ *
465
+ * @param {module:engine/view/matcher~MatcherPattern} pattern Pattern matching all view elements whose content should
466
+ * be treated as a raw data.
467
+ */
468
+ registerRawContentMatcher( pattern ) {
469
+ // No need to register the pattern if both `htmlProcessor` and `processor` are the same instances.
470
+ if ( this.processor && this.processor !== this.htmlProcessor ) {
471
+ this.processor.registerRawContentMatcher( pattern );
472
+ }
473
+
474
+ this.htmlProcessor.registerRawContentMatcher( pattern );
475
+ }
476
+
477
+ /**
478
+ * Removes all event listeners set by the DataController.
479
+ */
480
+ destroy() {
481
+ this.stopListening();
482
+ }
483
+
484
+ /**
485
+ * Checks if all provided root names are existing editor roots.
486
+ *
487
+ * @private
488
+ * @param {Array.<String>} rootNames Root names to check.
489
+ * @returns {Boolean} Whether all provided root names are existing editor roots.
490
+ */
491
+ _checkIfRootsExists( rootNames ) {
492
+ for ( const rootName of rootNames ) {
493
+ if ( !this.model.document.getRootNames().includes( rootName ) ) {
494
+ return false;
495
+ }
496
+ }
497
+
498
+ return true;
499
+ }
500
+
501
+ /**
502
+ * Event fired once the data initialization has finished.
503
+ *
504
+ * @event ready
505
+ */
506
+
507
+ /**
508
+ * Event fired after the {@link #init `init()` method} was run. It can be {@link #listenTo listened to} in order to adjust or modify
509
+ * the initialization flow. However, if the `init` event is stopped or prevented, the {@link #event:ready `ready` event}
510
+ * should be fired manually.
511
+ *
512
+ * The `init` event is fired by the decorated {@link #init} method.
513
+ * See {@link module:utils/observablemixin~ObservableMixin#decorate} for more information and samples.
514
+ *
515
+ * @event init
516
+ */
517
+
518
+ /**
519
+ * Event fired after {@link #set set() method} has been run.
520
+ *
521
+ * The `set` event is fired by decorated {@link #set} method.
522
+ * See {@link module:utils/observablemixin~ObservableMixin#decorate} for more information and samples.
523
+ *
524
+ * @event set
525
+ */
526
+ }
527
+
528
+ mix( DataController, ObservableMixin );
529
+
530
+ // Helper function for downcast conversion.
531
+ //
532
+ // Takes a document element (element that is added to a model document) and checks which markers are inside it. If the marker is collapsed
533
+ // at element boundary, it is considered as contained inside the element and marker range is returned. Otherwise, if the marker is
534
+ // intersecting with the element, the intersection is returned.
535
+ function _getMarkersRelativeToElement( element ) {
536
+ const result = [];
537
+ const doc = element.root.document;
538
+
539
+ if ( !doc ) {
540
+ return [];
541
+ }
542
+
543
+ const elementRange = ModelRange._createIn( element );
544
+
545
+ for ( const marker of doc.model.markers ) {
546
+ const markerRange = marker.getRange();
547
+
548
+ const isMarkerCollapsed = markerRange.isCollapsed;
549
+ const isMarkerAtElementBoundary = markerRange.start.isEqual( elementRange.start ) || markerRange.end.isEqual( elementRange.end );
550
+
551
+ if ( isMarkerCollapsed && isMarkerAtElementBoundary ) {
552
+ result.push( [ marker.name, markerRange ] );
553
+ } else {
554
+ const updatedMarkerRange = elementRange.getIntersection( markerRange );
555
+
556
+ if ( updatedMarkerRange ) {
557
+ result.push( [ marker.name, updatedMarkerRange ] );
558
+ }
559
+ }
560
+ }
561
+
562
+ return result;
563
+ }