@ckeditor/ckeditor5-editor-multi-root 41.2.0 → 41.3.0-alpha.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.
package/dist/index.js ADDED
@@ -0,0 +1,1126 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, 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
+ import { Context, Editor, secureSourceElement } from '@ckeditor/ckeditor5-core/dist/index.js';
6
+ import { CKEditorError, logWarning, setDataInElement, getDataFromElement } from '@ckeditor/ckeditor5-utils/dist/index.js';
7
+ import { EditorWatchdog, ContextWatchdog } from '@ckeditor/ckeditor5-watchdog/dist/index.js';
8
+ import { EditorUI, EditorUIView, ToolbarView, InlineEditableUIView } from '@ckeditor/ckeditor5-ui/dist/index.js';
9
+ import { enablePlaceholder } from '@ckeditor/ckeditor5-engine/dist/index.js';
10
+ import { isElement as isElement$1 } from 'lodash-es';
11
+
12
+ /**
13
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
14
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
15
+ */
16
+ /**
17
+ * The multi-root editor UI class.
18
+ */
19
+ class MultiRootEditorUI extends EditorUI {
20
+ /**
21
+ * Creates an instance of the multi-root editor UI class.
22
+ *
23
+ * @param editor The editor instance.
24
+ * @param view The view of the UI.
25
+ */
26
+ constructor(editor, view) {
27
+ super(editor);
28
+ this.view = view;
29
+ this._lastFocusedEditableElement = null;
30
+ }
31
+ /**
32
+ * Initializes the UI.
33
+ */
34
+ init() {
35
+ const view = this.view;
36
+ view.render();
37
+ // Keep track of the last focused editable element. Knowing which one was focused
38
+ // is useful when the focus moves from editable to other UI components like balloons
39
+ // (especially inputs) but the editable remains the "focus context" (e.g. link balloon
40
+ // attached to a link in an editable). In this case, the editable should preserve visual
41
+ // focus styles.
42
+ this.focusTracker.on('change:focusedElement', (evt, name, focusedElement) => {
43
+ for (const editable of Object.values(this.view.editables)) {
44
+ if (focusedElement === editable.element) {
45
+ this._lastFocusedEditableElement = editable.element;
46
+ }
47
+ }
48
+ });
49
+ // If the focus tracker loses focus, stop tracking the last focused editable element.
50
+ // Wherever the focus is restored, it will no longer be in the context of that editable
51
+ // because the focus "came from the outside", as opposed to the focus moving from one element
52
+ // to another within the editor UI.
53
+ this.focusTracker.on('change:isFocused', (evt, name, isFocused) => {
54
+ if (!isFocused) {
55
+ this._lastFocusedEditableElement = null;
56
+ }
57
+ });
58
+ for (const editable of Object.values(this.view.editables)) {
59
+ this.addEditable(editable);
60
+ }
61
+ this._initToolbar();
62
+ this.fire('ready');
63
+ }
64
+ /**
65
+ * Adds the editable to the editor UI.
66
+ *
67
+ * After the editable is added to the editor UI it can be considered "active".
68
+ *
69
+ * The editable is attached to the editor editing pipeline, which means that it will be updated as the editor model updates and
70
+ * changing its content will be reflected in the editor model. Keystrokes, focus handling and placeholder are initialized.
71
+ *
72
+ * @param editable The editable instance to add.
73
+ * @param placeholder Placeholder for the editable element. If not set, placeholder value from the
74
+ * {@link module:core/editor/editorconfig~EditorConfig#placeholder editor configuration} will be used (if it was provided).
75
+ */
76
+ addEditable(editable, placeholder) {
77
+ // The editable UI element in DOM is available for sure only after the editor UI view has been rendered.
78
+ // But it can be available earlier if a DOM element has been passed to `MultiRootEditor.create()`.
79
+ const editableElement = editable.element;
80
+ // Bind the editable UI element to the editing view, making it an end– and entry–point
81
+ // of the editor's engine. This is where the engine meets the UI.
82
+ this.editor.editing.view.attachDomRoot(editableElement, editable.name);
83
+ // Register each editable UI view in the editor.
84
+ this.setEditableElement(editable.name, editableElement);
85
+ // Let the editable UI element respond to the changes in the global editor focus
86
+ // tracker. It has been added to the same tracker a few lines above but, in reality, there are
87
+ // many focusable areas in the editor, like balloons, toolbars or dropdowns and as long
88
+ // as they have focus, the editable should act like it is focused too (although technically
89
+ // it isn't), e.g. by setting the proper CSS class, visually announcing focus to the user.
90
+ // Doing otherwise will result in editable focus styles disappearing, once e.g. the
91
+ // toolbar gets focused.
92
+ editable.bind('isFocused').to(this.focusTracker, 'isFocused', this.focusTracker, 'focusedElement', (isFocused, focusedElement) => {
93
+ // When the focus tracker is blurred, it means the focus moved out of the editor UI.
94
+ // No editable will maintain focus then.
95
+ if (!isFocused) {
96
+ return false;
97
+ }
98
+ // If the focus tracker says the editor UI is focused and currently focused element
99
+ // is the editable, then the editable should be visually marked as focused too.
100
+ if (focusedElement === editableElement) {
101
+ return true;
102
+ }
103
+ // If the focus tracker says the editor UI is focused but the focused element is
104
+ // not an editable, it is possible that the editable is still (context–)focused.
105
+ // For instance, the focused element could be an input inside of a balloon attached
106
+ // to the content in the editable. In such case, the editable should remain _visually_
107
+ // focused even though technically the focus is somewhere else. The focus moved from
108
+ // the editable to the input but the focus context remained the same.
109
+ else {
110
+ return this._lastFocusedEditableElement === editableElement;
111
+ }
112
+ });
113
+ this._initPlaceholder(editable, placeholder);
114
+ }
115
+ /**
116
+ * Removes the editable instance from the editor UI.
117
+ *
118
+ * Removed editable can be considered "deactivated".
119
+ *
120
+ * The editable is detached from the editing pipeline, so model changes are no longer reflected in it. All handling added in
121
+ * {@link #addEditable} is removed.
122
+ *
123
+ * @param editable Editable to remove from the editor UI.
124
+ */
125
+ removeEditable(editable) {
126
+ this.editor.editing.view.detachDomRoot(editable.name);
127
+ editable.unbind('isFocused');
128
+ this.removeEditableElement(editable.name);
129
+ }
130
+ /**
131
+ * @inheritDoc
132
+ */
133
+ destroy() {
134
+ super.destroy();
135
+ for (const editable of Object.values(this.view.editables)) {
136
+ this.removeEditable(editable);
137
+ }
138
+ this.view.destroy();
139
+ }
140
+ /**
141
+ * Initializes the editor main toolbar and its panel.
142
+ */
143
+ _initToolbar() {
144
+ const editor = this.editor;
145
+ const view = this.view;
146
+ const toolbar = view.toolbar;
147
+ toolbar.fillFromConfig(editor.config.get('toolbar'), this.componentFactory);
148
+ // Register the toolbar, so it becomes available for Alt+F10 and Esc navigation.
149
+ this.addToolbar(view.toolbar);
150
+ }
151
+ /**
152
+ * Enables the placeholder text on a given editable.
153
+ *
154
+ * @param editable Editable on which the placeholder should be set.
155
+ * @param placeholder Placeholder for the editable element. If not set, placeholder value from the
156
+ * {@link module:core/editor/editorconfig~EditorConfig#placeholder editor configuration} will be used (if it was provided).
157
+ */
158
+ _initPlaceholder(editable, placeholder) {
159
+ if (!placeholder) {
160
+ const configPlaceholder = this.editor.config.get('placeholder');
161
+ if (configPlaceholder) {
162
+ placeholder = typeof configPlaceholder === 'string' ? configPlaceholder : configPlaceholder[editable.name];
163
+ }
164
+ }
165
+ const editingView = this.editor.editing.view;
166
+ const editingRoot = editingView.document.getRoot(editable.name);
167
+ if (placeholder) {
168
+ editingRoot.placeholder = placeholder;
169
+ }
170
+ enablePlaceholder({
171
+ view: editingView,
172
+ element: editingRoot,
173
+ isDirectHost: false,
174
+ keepOnFocus: true
175
+ });
176
+ }
177
+ }
178
+
179
+ /**
180
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
181
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
182
+ */
183
+ /**
184
+ * @module editor-multi-root/multirooteditoruiview
185
+ */
186
+ /**
187
+ * The multi-root editor UI view. It is a virtual view providing an inline
188
+ * {@link module:editor-multi-root/multirooteditoruiview~MultiRootEditorUIView#editable} and a
189
+ * {@link module:editor-multi-root/multirooteditoruiview~MultiRootEditorUIView#toolbar}, but without any
190
+ * specific arrangement of the components in the DOM.
191
+ *
192
+ * See {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`}
193
+ * to learn more about this view.
194
+ */
195
+ class MultiRootEditorUIView extends EditorUIView {
196
+ /**
197
+ * Creates an instance of the multi-root editor UI view.
198
+ *
199
+ * @param locale The {@link module:core/editor/editor~Editor#locale} instance.
200
+ * @param editingView The editing view instance this view is related to.
201
+ * @param editableNames Names for all editable views. For each name, one
202
+ * {@link module:ui/editableui/inline/inlineeditableuiview~InlineEditableUIView `InlineEditableUIView`} instance will be initialized.
203
+ * @param options Configuration options for the view instance.
204
+ * @param options.editableElements The editable elements to be used, assigned to their names. If not specified, they will be
205
+ * automatically created by {@link module:ui/editableui/inline/inlineeditableuiview~InlineEditableUIView `InlineEditableUIView`}
206
+ * instances.
207
+ * @param options.shouldToolbarGroupWhenFull When set to `true` enables automatic items grouping
208
+ * in the main {@link module:editor-multi-root/multirooteditoruiview~MultiRootEditorUIView#toolbar toolbar}.
209
+ * See {@link module:ui/toolbar/toolbarview~ToolbarOptions#shouldGroupWhenFull} to learn more.
210
+ */
211
+ constructor(locale, editingView, editableNames, options = {}) {
212
+ super(locale);
213
+ this._editingView = editingView;
214
+ this.toolbar = new ToolbarView(locale, {
215
+ shouldGroupWhenFull: options.shouldToolbarGroupWhenFull
216
+ });
217
+ this.editables = {};
218
+ // Create `InlineEditableUIView` instance for each editable.
219
+ for (const editableName of editableNames) {
220
+ const editableElement = options.editableElements ? options.editableElements[editableName] : undefined;
221
+ this.createEditable(editableName, editableElement);
222
+ }
223
+ this.editable = Object.values(this.editables)[0];
224
+ // This toolbar may be placed anywhere in the page so things like font size need to be reset in it.
225
+ // Because of the above, make sure the toolbar supports rounded corners.
226
+ // Also, make sure the toolbar has the proper dir attribute because its ancestor may not have one
227
+ // and some toolbar item styles depend on this attribute.
228
+ this.toolbar.extendTemplate({
229
+ attributes: {
230
+ class: [
231
+ 'ck-reset_all',
232
+ 'ck-rounded-corners'
233
+ ],
234
+ dir: locale.uiLanguageDirection
235
+ }
236
+ });
237
+ }
238
+ /**
239
+ * Creates an editable instance with given name and registers it in the editor UI view.
240
+ *
241
+ * If `editableElement` is provided, the editable instance will be created on top of it. Otherwise, the editor will create a new
242
+ * DOM element and use it instead.
243
+ *
244
+ * @param editableName The name for the editable.
245
+ * @param editableElement DOM element for which the editable should be created.
246
+ * @returns The created editable instance.
247
+ */
248
+ createEditable(editableName, editableElement) {
249
+ const t = this.locale.t;
250
+ const editable = new InlineEditableUIView(this.locale, this._editingView, editableElement, {
251
+ label: editable => {
252
+ return t('Rich Text Editor. Editing area: %0', editable.name);
253
+ }
254
+ });
255
+ this.editables[editableName] = editable;
256
+ editable.name = editableName;
257
+ if (this.isRendered) {
258
+ this.registerChild(editable);
259
+ }
260
+ return editable;
261
+ }
262
+ /**
263
+ * Destroys and removes the editable from the editor UI view.
264
+ *
265
+ * @param editableName The name of the editable that should be removed.
266
+ */
267
+ removeEditable(editableName) {
268
+ const editable = this.editables[editableName];
269
+ if (this.isRendered) {
270
+ this.deregisterChild(editable);
271
+ }
272
+ delete this.editables[editableName];
273
+ editable.destroy();
274
+ }
275
+ /**
276
+ * @inheritDoc
277
+ */
278
+ render() {
279
+ super.render();
280
+ this.registerChild(Object.values(this.editables));
281
+ this.registerChild(this.toolbar);
282
+ }
283
+ }
284
+
285
+ /**
286
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
287
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
288
+ */
289
+ /**
290
+ * @module editor-multi-root/multirooteditor
291
+ */
292
+ /**
293
+ * The {@glink installation/getting-started/predefined-builds#multi-root-editor multi-root editor} implementation.
294
+ *
295
+ * The multi-root editor provides multiple inline editable elements and a toolbar. All editable areas are controlled by one editor
296
+ * instance, which means that they share common configuration, document ID, or undo stack.
297
+ *
298
+ * This type of editor is dedicated to integrations which require a customized UI with an open structure, featuring multiple editable areas,
299
+ * allowing developers to have a control over the exact location of these editable areas.
300
+ *
301
+ * In order to create a multi-root editor instance, use the static
302
+ * {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`} method.
303
+ *
304
+ * Note that you will need to attach the editor toolbar to your web page manually, in a desired place, after the editor is initialized.
305
+ *
306
+ * # Multi-root editor and multi-root editor build
307
+ *
308
+ * The multi-root editor can be used directly from source (if you installed the
309
+ * [`@ckeditor/ckeditor5-editor-multi-root/dist/index.js`](https://www.npmjs.com/package/@ckeditor/ckeditor5-editor-multi-root/dist/index.js) package)
310
+ * but it is also available in the
311
+ * {@glink installation/getting-started/predefined-builds#multi-root-editor multi-root editor build}.
312
+ *
313
+ * {@glink installation/getting-started/predefined-builds Builds} are ready-to-use editors with plugins bundled in.
314
+ *
315
+ * When using the editor from source you need to take care of loading all plugins by yourself
316
+ * (through the {@link module:core/editor/editorconfig~EditorConfig#plugins `config.plugins`} option).
317
+ * Using the editor from source gives much better flexibility and allows for easier customization.
318
+ *
319
+ * Read more about initializing the editor from source or as a build in
320
+ * {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`}.
321
+ */
322
+ class MultiRootEditor extends Editor {
323
+ /**
324
+ * Creates an instance of the multi-root editor.
325
+ *
326
+ * **Note:** Do not use the constructor to create editor instances. Use the static
327
+ * {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`} method instead.
328
+ *
329
+ * @param sourceElementsOrData The DOM elements that will be the source for the created editor
330
+ * or the editor's initial data. The editor will initialize multiple roots with names according to the keys in the passed object.
331
+ * For more information see {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`}.
332
+ * @param config The editor configuration.
333
+ */
334
+ constructor(sourceElementsOrData, config = {}) {
335
+ const rootNames = Object.keys(sourceElementsOrData);
336
+ const sourceIsData = rootNames.length === 0 || typeof sourceElementsOrData[rootNames[0]] === 'string';
337
+ if (sourceIsData && config.initialData !== undefined && Object.keys(config.initialData).length > 0) {
338
+ // Documented in core/editor/editorconfig.jsdoc.
339
+ // eslint-disable-next-line ckeditor5-rules/ckeditor-error-message
340
+ throw new CKEditorError('editor-create-initial-data', null);
341
+ }
342
+ super(config);
343
+ /**
344
+ * Holds attributes keys that were passed in {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes `rootsAttributes`}
345
+ * config property and should be returned by {@link #getRootsAttributes}.
346
+ */
347
+ this._registeredRootsAttributesKeys = new Set();
348
+ /**
349
+ * A set of lock IDs for enabling or disabling particular root.
350
+ */
351
+ this._readOnlyRootLocks = new Map();
352
+ if (!sourceIsData) {
353
+ this.sourceElements = sourceElementsOrData;
354
+ }
355
+ else {
356
+ this.sourceElements = {};
357
+ }
358
+ if (this.config.get('initialData') === undefined) {
359
+ // Create initial data object containing data from all roots.
360
+ const initialData = {};
361
+ for (const rootName of rootNames) {
362
+ initialData[rootName] = getInitialData(sourceElementsOrData[rootName]);
363
+ }
364
+ this.config.set('initialData', initialData);
365
+ }
366
+ if (!sourceIsData) {
367
+ for (const rootName of rootNames) {
368
+ secureSourceElement(this, sourceElementsOrData[rootName]);
369
+ }
370
+ }
371
+ this.editing.view.document.roots.on('add', (evt, viewRoot) => {
372
+ // Here we change the standard binding of readOnly flag by adding
373
+ // additional constraint that multi-root has (enabling / disabling particular root).
374
+ viewRoot.unbind('isReadOnly');
375
+ viewRoot.bind('isReadOnly').to(this.editing.view.document, 'isReadOnly', isReadOnly => {
376
+ return isReadOnly || this._readOnlyRootLocks.has(viewRoot.rootName);
377
+ });
378
+ // Hacky solution to nested editables.
379
+ // Nested editables should be managed each separately and do not base on view document or view root.
380
+ viewRoot.on('change:isReadOnly', (evt, prop, value) => {
381
+ const viewRange = this.editing.view.createRangeIn(viewRoot);
382
+ for (const viewItem of viewRange.getItems()) {
383
+ if (viewItem.is('editableElement')) {
384
+ viewItem.unbind('isReadOnly');
385
+ viewItem.isReadOnly = value;
386
+ }
387
+ }
388
+ });
389
+ });
390
+ for (const rootName of rootNames) {
391
+ // Create root and `UIView` element for each editable container.
392
+ this.model.document.createRoot('$root', rootName);
393
+ }
394
+ if (this.config.get('lazyRoots')) {
395
+ for (const rootName of this.config.get('lazyRoots')) {
396
+ const root = this.model.document.createRoot('$root', rootName);
397
+ root._isLoaded = false;
398
+ }
399
+ }
400
+ if (this.config.get('rootsAttributes')) {
401
+ const rootsAttributes = this.config.get('rootsAttributes');
402
+ for (const [rootName, attributes] of Object.entries(rootsAttributes)) {
403
+ if (!this.model.document.getRoot(rootName)) {
404
+ /**
405
+ * Trying to set attributes on a non-existing root.
406
+ *
407
+ * Roots specified in {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes} do not match initial
408
+ * editor roots.
409
+ *
410
+ * @error multi-root-editor-root-attributes-no-root
411
+ */
412
+ throw new CKEditorError('multi-root-editor-root-attributes-no-root', null);
413
+ }
414
+ for (const key of Object.keys(attributes)) {
415
+ this.registerRootAttribute(key);
416
+ }
417
+ }
418
+ this.data.on('init', () => {
419
+ this.model.enqueueChange({ isUndoable: false }, writer => {
420
+ for (const [name, attributes] of Object.entries(rootsAttributes)) {
421
+ const root = this.model.document.getRoot(name);
422
+ for (const [key, value] of Object.entries(attributes)) {
423
+ if (value !== null) {
424
+ writer.setAttribute(key, value, root);
425
+ }
426
+ }
427
+ }
428
+ });
429
+ });
430
+ }
431
+ const options = {
432
+ shouldToolbarGroupWhenFull: !this.config.get('toolbar.shouldNotGroupWhenFull'),
433
+ editableElements: sourceIsData ? undefined : sourceElementsOrData
434
+ };
435
+ const view = new MultiRootEditorUIView(this.locale, this.editing.view, rootNames, options);
436
+ this.ui = new MultiRootEditorUI(this, view);
437
+ this.model.document.on('change:data', () => {
438
+ const changedRoots = this.model.document.differ.getChangedRoots();
439
+ // Fire detaches first. If there are multiple roots removed and added in one batch, it should be easier to handle if
440
+ // changes aren't mixed. Detaching will usually lead to just removing DOM elements. Detaching first will lead to a clean DOM
441
+ // when new editables are added in `addRoot` event.
442
+ for (const changes of changedRoots) {
443
+ const root = this.model.document.getRoot(changes.name);
444
+ if (changes.state == 'detached') {
445
+ this.fire('detachRoot', root);
446
+ }
447
+ }
448
+ for (const changes of changedRoots) {
449
+ const root = this.model.document.getRoot(changes.name);
450
+ if (changes.state == 'attached') {
451
+ this.fire('addRoot', root);
452
+ }
453
+ }
454
+ });
455
+ // Overwrite `Model#canEditAt()` decorated method.
456
+ // Check if the provided selection is inside a read-only root. If so, return `false`.
457
+ this.listenTo(this.model, 'canEditAt', (evt, [selection]) => {
458
+ // Skip empty selections.
459
+ if (!selection) {
460
+ return;
461
+ }
462
+ let selectionInReadOnlyRoot = false;
463
+ for (const range of selection.getRanges()) {
464
+ const root = range.root;
465
+ if (this._readOnlyRootLocks.has(root.rootName)) {
466
+ selectionInReadOnlyRoot = true;
467
+ break;
468
+ }
469
+ }
470
+ // If selection is in read-only root, return `false` and prevent further processing.
471
+ // Otherwise, allow for other callbacks (or default callback) to evaluate.
472
+ if (selectionInReadOnlyRoot) {
473
+ evt.return = false;
474
+ evt.stop();
475
+ }
476
+ }, { priority: 'high' });
477
+ this.decorate('loadRoot');
478
+ this.on('loadRoot', (evt, [rootName]) => {
479
+ const root = this.model.document.getRoot(rootName);
480
+ if (!root) {
481
+ /**
482
+ * The root to load does not exist.
483
+ *
484
+ * @error multi-root-editor-load-root-no-root
485
+ */
486
+ throw new CKEditorError('multi-root-editor-load-root-no-root', this, { rootName });
487
+ }
488
+ if (root._isLoaded) {
489
+ /**
490
+ * The root to load was already loaded before. The `loadRoot()` call has no effect.
491
+ *
492
+ * @error multi-root-editor-load-root-already-loaded
493
+ */
494
+ logWarning('multi-root-editor-load-root-already-loaded');
495
+ evt.stop();
496
+ }
497
+ }, { priority: 'highest' });
498
+ }
499
+ /**
500
+ * Destroys the editor instance, releasing all resources used by it.
501
+ *
502
+ * Updates the original editor element with the data if the
503
+ * {@link module:core/editor/editorconfig~EditorConfig#updateSourceElementOnDestroy `updateSourceElementOnDestroy`}
504
+ * configuration option is set to `true`.
505
+ *
506
+ * **Note**: The multi-root editor does not remove the toolbar and editable when destroyed. You can
507
+ * do that yourself in the destruction chain, if you need to:
508
+ *
509
+ * ```ts
510
+ * editor.destroy().then( () => {
511
+ * // Remove the toolbar from DOM.
512
+ * editor.ui.view.toolbar.element.remove();
513
+ *
514
+ * // Remove editable elements from DOM.
515
+ * for ( const editable of Object.values( editor.ui.view.editables ) ) {
516
+ * editable.element.remove();
517
+ * }
518
+ *
519
+ * console.log( 'Editor was destroyed' );
520
+ * } );
521
+ * ```
522
+ */
523
+ destroy() {
524
+ const shouldUpdateSourceElement = this.config.get('updateSourceElementOnDestroy');
525
+ // Cache the data and editable DOM elements, then destroy.
526
+ // It's safe to assume that the model->view conversion will not work after `super.destroy()`,
527
+ // same as `ui.getEditableElement()` method will not return editables.
528
+ const data = {};
529
+ for (const rootName of Object.keys(this.sourceElements)) {
530
+ data[rootName] = shouldUpdateSourceElement ? this.getData({ rootName }) : '';
531
+ }
532
+ this.ui.destroy();
533
+ return super.destroy()
534
+ .then(() => {
535
+ for (const rootName of Object.keys(this.sourceElements)) {
536
+ setDataInElement(this.sourceElements[rootName], data[rootName]);
537
+ }
538
+ });
539
+ }
540
+ /**
541
+ * Adds a new root to the editor.
542
+ *
543
+ * ```ts
544
+ * editor.addRoot( 'myRoot', { data: '<p>Initial root data.</p>' } );
545
+ * ```
546
+ *
547
+ * After a root is added, you will be able to modify and retrieve its data.
548
+ *
549
+ * All root names must be unique. An error will be thrown if you will try to create a root with the name same as
550
+ * an already existing, attached root. However, you can call this method for a detached root. See also {@link #detachRoot}.
551
+ *
552
+ * Whenever a root is added, the editor instance will fire {@link #event:addRoot `addRoot` event}. The event is also called when
553
+ * the root is added indirectly, e.g. by the undo feature or on a remote client during real-time collaboration.
554
+ *
555
+ * Note, that this method only adds a root to the editor model. It **does not** create a DOM editable element for the new root.
556
+ * Until such element is created (and attached to the root), the root is "virtual": it is not displayed anywhere and its data can
557
+ * be changed only using the editor API.
558
+ *
559
+ * To create a DOM editable element for the root, listen to {@link #event:addRoot `addRoot` event} and call {@link #createEditable}.
560
+ * Then, insert the DOM element in a desired place, that will depend on the integration with your application and your requirements.
561
+ *
562
+ * ```ts
563
+ * editor.on( 'addRoot', ( evt, root ) => {
564
+ * const editableElement = editor.createEditable( root );
565
+ *
566
+ * // You may want to create a more complex DOM structure here.
567
+ * //
568
+ * // Alternatively, you may want to create a DOM structure before
569
+ * // calling `editor.addRoot()` and only append `editableElement` at
570
+ * // a proper place.
571
+ *
572
+ * document.querySelector( '#editors' ).appendChild( editableElement );
573
+ * } );
574
+ *
575
+ * // ...
576
+ *
577
+ * editor.addRoot( 'myRoot' ); // Will create a root, a DOM editable element and append it to `#editors` container element.
578
+ * ```
579
+ *
580
+ * You can set root attributes on the new root while you add it:
581
+ *
582
+ * ```ts
583
+ * // Add a collapsed root at fourth position from top.
584
+ * // Keep in mind that these are just examples of attributes. You need to provide your own features that will handle the attributes.
585
+ * editor.addRoot( 'myRoot', { attributes: { isCollapsed: true, index: 4 } } );
586
+ * ```
587
+ *
588
+ * Note that attributes added together with a root are automatically registered.
589
+ *
590
+ * See also {@link ~MultiRootEditor#registerRootAttribute `MultiRootEditor#registerRootAttribute()`} and
591
+ * {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes `config.rootsAttributes` configuration option}.
592
+ *
593
+ * By setting `isUndoable` flag to `true`, you can allow for detaching the root using the undo feature.
594
+ *
595
+ * Additionally, you can group adding multiple roots in one undo step. This can be useful if you add multiple roots that are
596
+ * combined into one, bigger UI element, and want them all to be undone together.
597
+ *
598
+ * ```ts
599
+ * let rowId = 0;
600
+ *
601
+ * editor.model.change( () => {
602
+ * editor.addRoot( 'left-row-' + rowId, { isUndoable: true } );
603
+ * editor.addRoot( 'center-row-' + rowId, { isUndoable: true } );
604
+ * editor.addRoot( 'right-row-' + rowId, { isUndoable: true } );
605
+ *
606
+ * rowId++;
607
+ * } );
608
+ * ```
609
+ *
610
+ * @param rootName Name of the root to add.
611
+ * @param options Additional options for the added root.
612
+ */
613
+ addRoot(rootName, { data = '', attributes = {}, elementName = '$root', isUndoable = false } = {}) {
614
+ const _addRoot = (writer) => {
615
+ const root = writer.addRoot(rootName, elementName);
616
+ if (data) {
617
+ writer.insert(this.data.parse(data, root), root, 0);
618
+ }
619
+ for (const key of Object.keys(attributes)) {
620
+ this.registerRootAttribute(key);
621
+ writer.setAttribute(key, attributes[key], root);
622
+ }
623
+ };
624
+ if (isUndoable) {
625
+ this.model.change(_addRoot);
626
+ }
627
+ else {
628
+ this.model.enqueueChange({ isUndoable: false }, _addRoot);
629
+ }
630
+ }
631
+ /**
632
+ * Detaches a root from the editor.
633
+ *
634
+ * ```ts
635
+ * editor.detachRoot( 'myRoot' );
636
+ * ```
637
+ *
638
+ * A detached root is not entirely removed from the editor model, however it can be considered removed.
639
+ *
640
+ * After a root is detached all its children are removed, all markers inside it are removed, and whenever something is inserted to it,
641
+ * it is automatically removed as well. Finally, a detached root is not returned by
642
+ * {@link module:engine/model/document~Document#getRootNames} by default.
643
+ *
644
+ * It is possible to re-add a previously detached root calling {@link #addRoot}.
645
+ *
646
+ * Whenever a root is detached, the editor instance will fire {@link #event:detachRoot `detachRoot` event}. The event is also
647
+ * called when the root is detached indirectly, e.g. by the undo feature or on a remote client during real-time collaboration.
648
+ *
649
+ * Note, that this method only detached a root in the editor model. It **does not** destroy the DOM editable element linked with
650
+ * the root and it **does not** remove the DOM element from the DOM structure of your application.
651
+ *
652
+ * To properly remove a DOM editable element after a root was detached, listen to {@link #event:detachRoot `detachRoot` event}
653
+ * and call {@link #detachEditable}. Then, remove the DOM element from your application.
654
+ *
655
+ * ```ts
656
+ * editor.on( 'detachRoot', ( evt, root ) => {
657
+ * const editableElement = editor.detachEditable( root );
658
+ *
659
+ * // You may want to do an additional DOM clean-up here.
660
+ *
661
+ * editableElement.remove();
662
+ * } );
663
+ *
664
+ * // ...
665
+ *
666
+ * editor.detachRoot( 'myRoot' ); // Will detach the root, and remove the DOM editable element.
667
+ * ```
668
+ *
669
+ * By setting `isUndoable` flag to `true`, you can allow for re-adding the root using the undo feature.
670
+ *
671
+ * Additionally, you can group detaching multiple roots in one undo step. This can be useful if the roots are combined into one,
672
+ * bigger UI element, and you want them all to be re-added together.
673
+ *
674
+ * ```ts
675
+ * editor.model.change( () => {
676
+ * editor.detachRoot( 'left-row-3', true );
677
+ * editor.detachRoot( 'center-row-3', true );
678
+ * editor.detachRoot( 'right-row-3', true );
679
+ * } );
680
+ * ```
681
+ *
682
+ * @param rootName Name of the root to detach.
683
+ * @param isUndoable Whether detaching the root can be undone (using the undo feature) or not.
684
+ */
685
+ detachRoot(rootName, isUndoable = false) {
686
+ if (isUndoable) {
687
+ this.model.change(writer => writer.detachRoot(rootName));
688
+ }
689
+ else {
690
+ this.model.enqueueChange({ isUndoable: false }, writer => writer.detachRoot(rootName));
691
+ }
692
+ }
693
+ /**
694
+ * Creates and returns a new DOM editable element for the given root element.
695
+ *
696
+ * The new DOM editable is attached to the model root and can be used to modify the root content.
697
+ *
698
+ * @param root Root for which the editable element should be created.
699
+ * @param placeholder Placeholder for the editable element. If not set, placeholder value from the
700
+ * {@link module:core/editor/editorconfig~EditorConfig#placeholder editor configuration} will be used (if it was provided).
701
+ * @returns The created DOM element. Append it in a desired place in your application.
702
+ */
703
+ createEditable(root, placeholder) {
704
+ const editable = this.ui.view.createEditable(root.rootName);
705
+ this.ui.addEditable(editable, placeholder);
706
+ this.editing.view.forceRender();
707
+ return editable.element;
708
+ }
709
+ /**
710
+ * Detaches the DOM editable element that was attached to the given root.
711
+ *
712
+ * @param root Root for which the editable element should be detached.
713
+ * @returns The DOM element that was detached. You may want to remove it from your application DOM structure.
714
+ */
715
+ detachEditable(root) {
716
+ const rootName = root.rootName;
717
+ const editable = this.ui.view.editables[rootName];
718
+ this.ui.removeEditable(editable);
719
+ this.ui.view.removeEditable(rootName);
720
+ return editable.element;
721
+ }
722
+ /**
723
+ * Loads a root that has previously been declared in {@link module:core/editor/editorconfig~EditorConfig#lazyRoots `lazyRoots`}
724
+ * configuration option.
725
+ *
726
+ * Only roots specified in the editor config can be loaded. A root cannot be loaded multiple times. A root cannot be unloaded and
727
+ * loading a root cannot be reverted using the undo feature.
728
+ *
729
+ * When a root becomes loaded, it will be treated by the editor as though it was just added. This, among others, means that all
730
+ * related events and mechanisms will be fired, including {@link ~MultiRootEditor#event:addRoot `addRoot` event},
731
+ * {@link module:engine/model/document~Document#event:change `model.Document` `change` event}, model post-fixers and conversion.
732
+ *
733
+ * Until the root becomes loaded, all above mechanisms are suppressed.
734
+ *
735
+ * This method is {@link module:utils/observablemixin~Observable#decorate decorated}.
736
+ *
737
+ * Note that attributes loaded together with a root are automatically registered.
738
+ *
739
+ * See also {@link ~MultiRootEditor#registerRootAttribute `MultiRootEditor#registerRootAttribute()`} and
740
+ * {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes `config.rootsAttributes` configuration option}.
741
+ *
742
+ * When this method is used in real-time collaboration environment, its effects become asynchronous as the editor will first synchronize
743
+ * with the remote editing session, before the root is added to the editor.
744
+ *
745
+ * If the root has been already loaded by any other client, the additional data passed in `loadRoot()` parameters will be ignored.
746
+ *
747
+ * @param rootName Name of the root to load.
748
+ * @param options Additional options for the loaded root.
749
+ * @fires loadRoot
750
+ */
751
+ loadRoot(rootName, { data = '', attributes = {} } = {}) {
752
+ // `root` will be defined as it is guaranteed by a check in a higher priority callback.
753
+ const root = this.model.document.getRoot(rootName);
754
+ this.model.enqueueChange({ isUndoable: false }, writer => {
755
+ if (data) {
756
+ writer.insert(this.data.parse(data, root), root, 0);
757
+ }
758
+ for (const key of Object.keys(attributes)) {
759
+ this.registerRootAttribute(key);
760
+ writer.setAttribute(key, attributes[key], root);
761
+ }
762
+ root._isLoaded = true;
763
+ this.model.document.differ._bufferRootLoad(root);
764
+ });
765
+ }
766
+ /**
767
+ * Returns the document data for all attached roots.
768
+ *
769
+ * @param options Additional configuration for the retrieved data.
770
+ * Editor features may introduce more configuration options that can be set through this parameter.
771
+ * @param options.trim Whether returned data should be trimmed. This option is set to `'empty'` by default,
772
+ * which means that whenever editor content is considered empty, an empty string is returned. To turn off trimming
773
+ * use `'none'`. In such cases exact content will be returned (for example `'<p>&nbsp;</p>'` for an empty editor).
774
+ * @returns The full document data.
775
+ */
776
+ getFullData(options) {
777
+ const data = {};
778
+ for (const rootName of this.model.document.getRootNames()) {
779
+ data[rootName] = this.data.get({ ...options, rootName });
780
+ }
781
+ return data;
782
+ }
783
+ /**
784
+ * Returns attributes for all attached roots.
785
+ *
786
+ * Note: all and only {@link ~MultiRootEditor#registerRootAttribute registered} roots attributes will be returned.
787
+ * If a registered root attribute is not set for a given root, `null` will be returned.
788
+ *
789
+ * @returns Object with roots attributes. Keys are roots names, while values are attributes set on given root.
790
+ */
791
+ getRootsAttributes() {
792
+ const rootsAttributes = {};
793
+ for (const rootName of this.model.document.getRootNames()) {
794
+ rootsAttributes[rootName] = this.getRootAttributes(rootName);
795
+ }
796
+ return rootsAttributes;
797
+ }
798
+ /**
799
+ * Returns attributes for the specified root.
800
+ *
801
+ * Note: all and only {@link ~MultiRootEditor#registerRootAttribute registered} roots attributes will be returned.
802
+ * If a registered root attribute is not set for a given root, `null` will be returned.
803
+ */
804
+ getRootAttributes(rootName) {
805
+ const rootAttributes = {};
806
+ const root = this.model.document.getRoot(rootName);
807
+ for (const key of this._registeredRootsAttributesKeys) {
808
+ rootAttributes[key] = root.hasAttribute(key) ? root.getAttribute(key) : null;
809
+ }
810
+ return rootAttributes;
811
+ }
812
+ /**
813
+ * Registers given string as a root attribute key. Registered root attributes are added to
814
+ * {@link module:engine/model/schema~Schema schema}, and also returned by
815
+ * {@link ~MultiRootEditor#getRootAttributes `getRootAttributes()`} and
816
+ * {@link ~MultiRootEditor#getRootsAttributes `getRootsAttributes()`}.
817
+ *
818
+ * Note: attributes passed in {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes `config.rootsAttributes`} are
819
+ * automatically registered as the editor is initialized. However, registering the same attribute twice does not have any negative
820
+ * impact, so it is recommended to use this method in any feature that uses roots attributes.
821
+ */
822
+ registerRootAttribute(key) {
823
+ if (this._registeredRootsAttributesKeys.has(key)) {
824
+ return;
825
+ }
826
+ this._registeredRootsAttributesKeys.add(key);
827
+ this.editing.model.schema.extend('$root', { allowAttributes: key });
828
+ }
829
+ /**
830
+ * Switches given editor root to the read-only mode.
831
+ *
832
+ * In contrary to {@link module:core/editor/editor~Editor#enableReadOnlyMode `enableReadOnlyMode()`}, which switches the whole editor
833
+ * to the read-only mode, this method turns only a particular root to the read-only mode. This can be useful when you want to prevent
834
+ * editing only a part of the editor content.
835
+ *
836
+ * When you switch a root to the read-only mode, you need provide a unique identifier (`lockId`) that will identify this request. You
837
+ * will need to provide the same `lockId` when you will want to
838
+ * {@link module:editor-multi-root/multirooteditor~MultiRootEditor#enableRoot re-enable} the root.
839
+ *
840
+ * ```ts
841
+ * const model = editor.model;
842
+ * const myRoot = model.document.getRoot( 'myRoot' );
843
+ *
844
+ * editor.disableRoot( 'myRoot', 'my-lock' );
845
+ * model.canEditAt( myRoot ); // `false`
846
+ *
847
+ * editor.disableRoot( 'myRoot', 'other-lock' );
848
+ * editor.disableRoot( 'myRoot', 'other-lock' ); // Multiple locks with the same ID have no effect.
849
+ * model.canEditAt( myRoot ); // `false`
850
+ *
851
+ * editor.enableRoot( 'myRoot', 'my-lock' );
852
+ * model.canEditAt( myRoot ); // `false`
853
+ *
854
+ * editor.enableRoot( 'myRoot', 'other-lock' );
855
+ * model.canEditAt( myRoot ); // `true`
856
+ * ```
857
+ *
858
+ * See also {@link module:core/editor/editor~Editor#enableReadOnlyMode `Editor#enableReadOnlyMode()`} and
859
+ * {@link module:editor-multi-root/multirooteditor~MultiRootEditor#enableRoot `MultiRootEditor#enableRoot()`}.
860
+ *
861
+ * @param rootName Name of the root to switch to read-only mode.
862
+ * @param lockId A unique ID for setting the editor to the read-only state.
863
+ */
864
+ disableRoot(rootName, lockId) {
865
+ if (rootName == '$graveyard') {
866
+ /**
867
+ * You cannot disable the `$graveyard` root.
868
+ *
869
+ * @error multi-root-editor-cannot-disable-graveyard-root
870
+ */
871
+ throw new CKEditorError('multi-root-editor-cannot-disable-graveyard-root', this);
872
+ }
873
+ const locksForGivenRoot = this._readOnlyRootLocks.get(rootName);
874
+ if (locksForGivenRoot) {
875
+ locksForGivenRoot.add(lockId);
876
+ }
877
+ else {
878
+ this._readOnlyRootLocks.set(rootName, new Set([lockId]));
879
+ const editableRootElement = this.editing.view.document.getRoot(rootName);
880
+ editableRootElement.isReadOnly = true;
881
+ // Since one of the roots has changed read-only state, we need to refresh all commands that affect data.
882
+ Array.from(this.commands.commands()).forEach(command => command.affectsData && command.refresh());
883
+ }
884
+ }
885
+ /**
886
+ * Removes given read-only lock from the given root.
887
+ *
888
+ * See {@link module:editor-multi-root/multirooteditor~MultiRootEditor#disableRoot `disableRoot()`}.
889
+ *
890
+ * @param rootName Name of the root to switch back from the read-only mode.
891
+ * @param lockId A unique ID for setting the editor to the read-only state.
892
+ */
893
+ enableRoot(rootName, lockId) {
894
+ const locksForGivenRoot = this._readOnlyRootLocks.get(rootName);
895
+ if (!locksForGivenRoot || !locksForGivenRoot.has(lockId)) {
896
+ return;
897
+ }
898
+ if (locksForGivenRoot.size === 1) {
899
+ this._readOnlyRootLocks.delete(rootName);
900
+ const editableRootElement = this.editing.view.document.getRoot(rootName);
901
+ editableRootElement.isReadOnly = this.isReadOnly;
902
+ // Since one of the roots has changed read-only state, we need to refresh all commands that affect data.
903
+ Array.from(this.commands.commands()).forEach(command => command.affectsData && command.refresh());
904
+ }
905
+ else {
906
+ locksForGivenRoot.delete(lockId);
907
+ }
908
+ }
909
+ /**
910
+ * Creates a new multi-root editor instance.
911
+ *
912
+ * **Note:** remember that `MultiRootEditor` does not append the toolbar element to your web page, so you have to do it manually
913
+ * after the editor has been initialized.
914
+ *
915
+ * There are a few different ways to initialize the multi-root editor.
916
+ *
917
+ * # Using existing DOM elements:
918
+ *
919
+ * ```ts
920
+ * MultiRootEditor.create( {
921
+ * intro: document.querySelector( '#editor-intro' ),
922
+ * content: document.querySelector( '#editor-content' ),
923
+ * sidePanelLeft: document.querySelector( '#editor-side-left' ),
924
+ * sidePanelRight: document.querySelector( '#editor-side-right' ),
925
+ * outro: document.querySelector( '#editor-outro' )
926
+ * } )
927
+ * .then( editor => {
928
+ * console.log( 'Editor was initialized', editor );
929
+ *
930
+ * // Append the toolbar inside a provided DOM element.
931
+ * document.querySelector( '#toolbar-container' ).appendChild( editor.ui.view.toolbar.element );
932
+ * } )
933
+ * .catch( err => {
934
+ * console.error( err.stack );
935
+ * } );
936
+ * ```
937
+ *
938
+ * The elements' content will be used as the editor data and elements will become editable elements.
939
+ *
940
+ * # Creating a detached editor
941
+ *
942
+ * Alternatively, you can initialize the editor by passing the initial data directly as strings.
943
+ * In this case, you will have to manually append both the toolbar element and the editable elements to your web page.
944
+ *
945
+ * ```ts
946
+ * MultiRootEditor.create( {
947
+ * intro: '<p><strong>Exciting</strong> intro text to an article.</p>',
948
+ * content: '<p>Lorem ipsum dolor sit amet.</p>',
949
+ * sidePanelLeft: '<blockquote>Strong quotation from article.</blockquote>',
950
+ * sidePanelRight: '<p>List of similar articles...</p>',
951
+ * outro: '<p>Closing text.</p>'
952
+ * } )
953
+ * .then( editor => {
954
+ * console.log( 'Editor was initialized', editor );
955
+ *
956
+ * // Append the toolbar inside a provided DOM element.
957
+ * document.querySelector( '#toolbar-container' ).appendChild( editor.ui.view.toolbar.element );
958
+ *
959
+ * // Append DOM editable elements created by the editor.
960
+ * const editables = editor.ui.view.editables;
961
+ * const container = document.querySelector( '#editable-container' );
962
+ *
963
+ * container.appendChild( editables.intro.element );
964
+ * container.appendChild( editables.content.element );
965
+ * container.appendChild( editables.outro.element );
966
+ * } )
967
+ * .catch( err => {
968
+ * console.error( err.stack );
969
+ * } );
970
+ * ```
971
+ *
972
+ * This lets you dynamically append the editor to your web page whenever it is convenient for you. You may use this method if your
973
+ * web page content is generated on the client side and the DOM structure is not ready at the moment when you initialize the editor.
974
+ *
975
+ * # Using an existing DOM element (and data provided in `config.initialData`)
976
+ *
977
+ * You can also mix these two ways by providing a DOM element to be used and passing the initial data through the configuration:
978
+ *
979
+ * ```ts
980
+ * MultiRootEditor.create( {
981
+ * intro: document.querySelector( '#editor-intro' ),
982
+ * content: document.querySelector( '#editor-content' ),
983
+ * sidePanelLeft: document.querySelector( '#editor-side-left' ),
984
+ * sidePanelRight: document.querySelector( '#editor-side-right' ),
985
+ * outro: document.querySelector( '#editor-outro' )
986
+ * }, {
987
+ * initialData: {
988
+ * intro: '<p><strong>Exciting</strong> intro text to an article.</p>',
989
+ * content: '<p>Lorem ipsum dolor sit amet.</p>',
990
+ * sidePanelLeft '<blockquote>Strong quotation from article.</blockquote>':
991
+ * sidePanelRight '<p>List of similar articles...</p>':
992
+ * outro: '<p>Closing text.</p>'
993
+ * }
994
+ * } )
995
+ * .then( editor => {
996
+ * console.log( 'Editor was initialized', editor );
997
+ *
998
+ * // Append the toolbar inside a provided DOM element.
999
+ * document.querySelector( '#toolbar-container' ).appendChild( editor.ui.view.toolbar.element );
1000
+ * } )
1001
+ * .catch( err => {
1002
+ * console.error( err.stack );
1003
+ * } );
1004
+ * ```
1005
+ *
1006
+ * This method can be used to initialize the editor on an existing element with the specified content in case if your integration
1007
+ * makes it difficult to set the content of the source element.
1008
+ *
1009
+ * Note that an error will be thrown if you pass the initial data both as the first parameter and also in the configuration.
1010
+ *
1011
+ * # Configuring the editor
1012
+ *
1013
+ * See the {@link module:core/editor/editorconfig~EditorConfig editor configuration documentation} to learn more about
1014
+ * customizing plugins, toolbar and more.
1015
+ *
1016
+ * # Using the editor from source
1017
+ *
1018
+ * The code samples listed in the previous sections of this documentation assume that you are using an
1019
+ * {@glink installation/getting-started/predefined-builds editor build}
1020
+ * (for example – `@ckeditor/ckeditor5-build-multi-root/dist/index.js`).
1021
+ *
1022
+ * If you want to use the multi-root editor from source (`@ckeditor/ckeditor5-editor-multi-root-editor/dist/index.js`),
1023
+ * you need to define the list of
1024
+ * {@link module:core/editor/editorconfig~EditorConfig#plugins plugins to be initialized} and
1025
+ * {@link module:core/editor/editorconfig~EditorConfig#toolbar toolbar items}. Read more about using the editor from
1026
+ * source in the {@glink installation/advanced/alternative-setups/integrating-from-source-webpack dedicated guide}.
1027
+ *
1028
+ * @param sourceElementsOrData The DOM elements that will be the source for the created editor
1029
+ * or the editor's initial data. The editor will initialize multiple roots with names according to the keys in the passed object.
1030
+ *
1031
+ * If DOM elements are passed, their content will be automatically loaded to the editor upon initialization and the elements will be
1032
+ * used as the editor's editable areas. The editor data will be set back to the original element once the editor is destroyed if the
1033
+ * {@link module:core/editor/editorconfig~EditorConfig#updateSourceElementOnDestroy updateSourceElementOnDestroy} option
1034
+ * is set to `true`.
1035
+ *
1036
+ * If the initial data is passed, a detached editor will be created. For each entry in the passed object, one editor root and one
1037
+ * editable DOM element will be created. You will need to attach the editable elements into the DOM manually. The elements are available
1038
+ * through the {@link module:editor-multi-root/multirooteditorui~MultiRootEditorUI#getEditableElement `editor.ui.getEditableElement()`}
1039
+ * method.
1040
+ * @param config The editor configuration.
1041
+ * @returns A promise resolved once the editor is ready. The promise resolves with the created editor instance.
1042
+ */
1043
+ static create(sourceElementsOrData, config = {}) {
1044
+ return new Promise(resolve => {
1045
+ for (const sourceItem of Object.values(sourceElementsOrData)) {
1046
+ if (isElement(sourceItem) && sourceItem.tagName === 'TEXTAREA') {
1047
+ // Documented in core/editor/editor.js
1048
+ // eslint-disable-next-line ckeditor5-rules/ckeditor-error-message
1049
+ throw new CKEditorError('editor-wrong-element', null);
1050
+ }
1051
+ }
1052
+ const editor = new this(sourceElementsOrData, config);
1053
+ resolve(editor.initPlugins()
1054
+ .then(() => editor.ui.init())
1055
+ .then(() => {
1056
+ // This is checked directly before setting the initial data,
1057
+ // as plugins may change `EditorConfig#initialData` value.
1058
+ editor._verifyRootsWithInitialData();
1059
+ return editor.data.init(editor.config.get('initialData'));
1060
+ })
1061
+ .then(() => editor.fire('ready'))
1062
+ .then(() => editor));
1063
+ });
1064
+ }
1065
+ /**
1066
+ * @internal
1067
+ */
1068
+ _verifyRootsWithInitialData() {
1069
+ const initialData = this.config.get('initialData');
1070
+ // Roots that are not in the initial data.
1071
+ for (const rootName of this.model.document.getRootNames()) {
1072
+ if (!(rootName in initialData)) {
1073
+ /**
1074
+ * Editor roots do not match the
1075
+ * {@link module:core/editor/editorconfig~EditorConfig#initialData `initialData` configuration}.
1076
+ *
1077
+ * This may happen for one of the two reasons:
1078
+ *
1079
+ * * Configuration error. The `sourceElementsOrData` parameter in
1080
+ * {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`} contains different
1081
+ * roots than {@link module:core/editor/editorconfig~EditorConfig#initialData `initialData` configuration}.
1082
+ * * As the editor was initialized, the {@link module:core/editor/editorconfig~EditorConfig#initialData `initialData`}
1083
+ * configuration value or the state of the editor roots has been changed.
1084
+ *
1085
+ * @error multi-root-editor-root-initial-data-mismatch
1086
+ */
1087
+ throw new CKEditorError('multi-root-editor-root-initial-data-mismatch', null);
1088
+ }
1089
+ }
1090
+ // Roots that are not in the editor.
1091
+ for (const rootName of Object.keys(initialData)) {
1092
+ const root = this.model.document.getRoot(rootName);
1093
+ if (!root || !root.isAttached()) {
1094
+ // eslint-disable-next-line ckeditor5-rules/ckeditor-error-message
1095
+ throw new CKEditorError('multi-root-editor-root-initial-data-mismatch', null);
1096
+ }
1097
+ }
1098
+ }
1099
+ }
1100
+ /**
1101
+ * The {@link module:core/context~Context} class.
1102
+ *
1103
+ * Exposed as static editor field for easier access in editor builds.
1104
+ */
1105
+ MultiRootEditor.Context = Context;
1106
+ /**
1107
+ * The {@link module:watchdog/editorwatchdog~EditorWatchdog} class.
1108
+ *
1109
+ * Exposed as static editor field for easier access in editor builds.
1110
+ */
1111
+ MultiRootEditor.EditorWatchdog = EditorWatchdog;
1112
+ /**
1113
+ * The {@link module:watchdog/contextwatchdog~ContextWatchdog} class.
1114
+ *
1115
+ * Exposed as static editor field for easier access in editor builds.
1116
+ */
1117
+ MultiRootEditor.ContextWatchdog = ContextWatchdog;
1118
+ function getInitialData(sourceElementOrData) {
1119
+ return isElement(sourceElementOrData) ? getDataFromElement(sourceElementOrData) : sourceElementOrData;
1120
+ }
1121
+ function isElement(value) {
1122
+ return isElement$1(value);
1123
+ }
1124
+
1125
+ export { MultiRootEditor };
1126
+ //# sourceMappingURL=index.js.map