@ckeditor/ckeditor5-editor-multi-root 38.1.0 → 38.1.1

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.
@@ -1,747 +1,747 @@
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 editor-multi-root/multirooteditor
7
- */
8
- import { Editor, Context, DataApiMixin, secureSourceElement } from 'ckeditor5/src/core';
9
- import { CKEditorError, getDataFromElement, setDataInElement } from 'ckeditor5/src/utils';
10
- import { ContextWatchdog, EditorWatchdog } from 'ckeditor5/src/watchdog';
11
- import MultiRootEditorUI from './multirooteditorui';
12
- import MultiRootEditorUIView from './multirooteditoruiview';
13
- import { isElement as _isElement } from 'lodash-es';
14
- /**
15
- * The {@glink installation/getting-started/predefined-builds#multi-root-editor multi-root editor} implementation.
16
- *
17
- * The multi-root editor provides multiple inline editable elements and a toolbar. All editable areas are controlled by one editor
18
- * instance, which means that they share common configuration, document ID, or undo stack.
19
- *
20
- * This type of editor is dedicated to integrations which require a customized UI with an open structure, featuring multiple editable areas,
21
- * allowing developers to have a control over the exact location of these editable areas.
22
- *
23
- * In order to create a multi-root editor instance, use the static
24
- * {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`} method.
25
- *
26
- * Note that you will need to attach the editor toolbar to your web page manually, in a desired place, after the editor is initialized.
27
- *
28
- * # Multi-root editor and multi-root editor build
29
- *
30
- * The multi-root editor can be used directly from source (if you installed the
31
- * [`@ckeditor/ckeditor5-editor-multi-root`](https://www.npmjs.com/package/@ckeditor/ckeditor5-editor-multi-root) package)
32
- * but it is also available in the
33
- * {@glink installation/getting-started/predefined-builds#multi-root-editor multi-root editor build}.
34
- *
35
- * {@glink installation/getting-started/predefined-builds Builds} are ready-to-use editors with plugins bundled in.
36
- *
37
- * When using the editor from source you need to take care of loading all plugins by yourself
38
- * (through the {@link module:core/editor/editorconfig~EditorConfig#plugins `config.plugins`} option).
39
- * Using the editor from source gives much better flexibility and allows for easier customization.
40
- *
41
- * Read more about initializing the editor from source or as a build in
42
- * {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`}.
43
- */
44
- export default class MultiRootEditor extends DataApiMixin(Editor) {
45
- /**
46
- * Creates an instance of the multi-root editor.
47
- *
48
- * **Note:** Do not use the constructor to create editor instances. Use the static
49
- * {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`} method instead.
50
- *
51
- * @param sourceElementsOrData The DOM elements that will be the source for the created editor
52
- * or the editor's initial data. The editor will initialize multiple roots with names according to the keys in the passed object.
53
- * For more information see {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`}.
54
- * @param config The editor configuration.
55
- */
56
- constructor(sourceElementsOrData, config = {}) {
57
- const rootNames = Object.keys(sourceElementsOrData);
58
- const sourceIsData = rootNames.length === 0 || typeof sourceElementsOrData[rootNames[0]] === 'string';
59
- if (sourceIsData && config.initialData !== undefined) {
60
- // Documented in core/editor/editorconfig.jsdoc.
61
- // eslint-disable-next-line ckeditor5-rules/ckeditor-error-message
62
- throw new CKEditorError('editor-create-initial-data', null);
63
- }
64
- super(config);
65
- /**
66
- * Holds attributes keys that were passed in {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes `rootsAttributes`}
67
- * config property and should be returned by {@link #getRootsAttributes}.
68
- */
69
- this._registeredRootsAttributesKeys = new Set();
70
- /**
71
- * A set of lock IDs for enabling or disabling particular root.
72
- */
73
- this._readOnlyRootLocks = new Map();
74
- if (!sourceIsData) {
75
- this.sourceElements = sourceElementsOrData;
76
- }
77
- else {
78
- this.sourceElements = {};
79
- }
80
- if (this.config.get('initialData') === undefined) {
81
- // Create initial data object containing data from all roots.
82
- const initialData = {};
83
- for (const rootName of rootNames) {
84
- initialData[rootName] = getInitialData(sourceElementsOrData[rootName]);
85
- }
86
- this.config.set('initialData', initialData);
87
- }
88
- if (!sourceIsData) {
89
- for (const rootName of rootNames) {
90
- secureSourceElement(this, sourceElementsOrData[rootName]);
91
- }
92
- }
93
- this.editing.view.document.roots.on('add', (evt, viewRoot) => {
94
- // Here we change the standard binding of readOnly flag by adding
95
- // additional constraint that multi-root has (enabling / disabling particular root).
96
- viewRoot.unbind('isReadOnly');
97
- viewRoot.bind('isReadOnly').to(this.editing.view.document, 'isReadOnly', isReadOnly => {
98
- return isReadOnly || this._readOnlyRootLocks.has(viewRoot.rootName);
99
- });
100
- // Hacky solution to nested editables.
101
- // Nested editables should be managed each separately and do not base on view document or view root.
102
- viewRoot.on('change:isReadOnly', (evt, prop, value) => {
103
- const viewRange = this.editing.view.createRangeIn(viewRoot);
104
- for (const viewItem of viewRange.getItems()) {
105
- if (viewItem.is('editableElement')) {
106
- viewItem.unbind('isReadOnly');
107
- viewItem.isReadOnly = value;
108
- }
109
- }
110
- });
111
- });
112
- for (const rootName of rootNames) {
113
- // Create root and `UIView` element for each editable container.
114
- this.model.document.createRoot('$root', rootName);
115
- }
116
- if (this.config.get('rootsAttributes')) {
117
- const rootsAttributes = this.config.get('rootsAttributes');
118
- for (const [rootName, attributes] of Object.entries(rootsAttributes)) {
119
- if (!rootNames.includes(rootName)) {
120
- /**
121
- * Trying to set attributes on a non-existing root.
122
- *
123
- * Roots specified in {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes} do not match initial
124
- * editor roots.
125
- *
126
- * @error multi-root-editor-root-attributes-no-root
127
- */
128
- throw new CKEditorError('multi-root-editor-root-attributes-no-root', null);
129
- }
130
- for (const key of Object.keys(attributes)) {
131
- this._registeredRootsAttributesKeys.add(key);
132
- }
133
- }
134
- this.data.on('init', () => {
135
- this.model.enqueueChange({ isUndoable: false }, writer => {
136
- for (const [name, attributes] of Object.entries(rootsAttributes)) {
137
- const root = this.model.document.getRoot(name);
138
- for (const [key, value] of Object.entries(attributes)) {
139
- if (value !== null) {
140
- writer.setAttribute(key, value, root);
141
- }
142
- }
143
- }
144
- });
145
- });
146
- }
147
- const options = {
148
- shouldToolbarGroupWhenFull: !this.config.get('toolbar.shouldNotGroupWhenFull'),
149
- editableElements: sourceIsData ? undefined : sourceElementsOrData
150
- };
151
- const view = new MultiRootEditorUIView(this.locale, this.editing.view, rootNames, options);
152
- this.ui = new MultiRootEditorUI(this, view);
153
- this.model.document.on('change:data', () => {
154
- const changedRoots = this.model.document.differ.getChangedRoots();
155
- // Fire detaches first. If there are multiple roots removed and added in one batch, it should be easier to handle if
156
- // changes aren't mixed. Detaching will usually lead to just removing DOM elements. Detaching first will lead to a clean DOM
157
- // when new editables are added in `addRoot` event.
158
- for (const changes of changedRoots) {
159
- const root = this.model.document.getRoot(changes.name);
160
- if (changes.state == 'detached') {
161
- this.fire('detachRoot', root);
162
- }
163
- }
164
- for (const changes of changedRoots) {
165
- const root = this.model.document.getRoot(changes.name);
166
- if (changes.state == 'attached') {
167
- this.fire('addRoot', root);
168
- }
169
- }
170
- });
171
- // Overwrite `Model#canEditAt()` decorated method.
172
- // Check if the provided selection is inside a read-only root. If so, return `false`.
173
- this.listenTo(this.model, 'canEditAt', (evt, [selection]) => {
174
- // Skip empty selections.
175
- if (!selection) {
176
- return;
177
- }
178
- let selectionInReadOnlyRoot = false;
179
- for (const range of selection.getRanges()) {
180
- const rootName = range.root.rootName;
181
- if (this._readOnlyRootLocks.has(rootName)) {
182
- selectionInReadOnlyRoot = true;
183
- break;
184
- }
185
- }
186
- // If selection is in read-only root, return `false` and prevent further processing.
187
- // Otherwise, allow for other callbacks (or default callback) to evaluate.
188
- if (selectionInReadOnlyRoot) {
189
- evt.return = false;
190
- evt.stop();
191
- }
192
- }, { priority: 'high' });
193
- }
194
- /**
195
- * Destroys the editor instance, releasing all resources used by it.
196
- *
197
- * Updates the original editor element with the data if the
198
- * {@link module:core/editor/editorconfig~EditorConfig#updateSourceElementOnDestroy `updateSourceElementOnDestroy`}
199
- * configuration option is set to `true`.
200
- *
201
- * **Note**: The multi-root editor does not remove the toolbar and editable when destroyed. You can
202
- * do that yourself in the destruction chain, if you need to:
203
- *
204
- * ```ts
205
- * editor.destroy().then( () => {
206
- * // Remove the toolbar from DOM.
207
- * editor.ui.view.toolbar.element.remove();
208
- *
209
- * // Remove editable elements from DOM.
210
- * for ( const editable of Object.values( editor.ui.view.editables ) ) {
211
- * editable.element.remove();
212
- * }
213
- *
214
- * console.log( 'Editor was destroyed' );
215
- * } );
216
- * ```
217
- */
218
- destroy() {
219
- const shouldUpdateSourceElement = this.config.get('updateSourceElementOnDestroy');
220
- // Cache the data and editable DOM elements, then destroy.
221
- // It's safe to assume that the model->view conversion will not work after `super.destroy()`,
222
- // same as `ui.getEditableElement()` method will not return editables.
223
- const data = {};
224
- for (const rootName of Object.keys(this.sourceElements)) {
225
- data[rootName] = shouldUpdateSourceElement ? this.getData({ rootName }) : '';
226
- }
227
- this.ui.destroy();
228
- return super.destroy()
229
- .then(() => {
230
- for (const rootName of Object.keys(this.sourceElements)) {
231
- setDataInElement(this.sourceElements[rootName], data[rootName]);
232
- }
233
- });
234
- }
235
- /**
236
- * Adds a new root to the editor.
237
- *
238
- * ```ts
239
- * editor.addRoot( 'myRoot', { data: '<p>Initial root data.</p>' } );
240
- * ```
241
- *
242
- * After a root is added, you will be able to modify and retrieve its data.
243
- *
244
- * All root names must be unique. An error will be thrown if you will try to create a root with the name same as
245
- * an already existing, attached root. However, you can call this method for a detached root. See also {@link #detachRoot}.
246
- *
247
- * Whenever a root is added, the editor instance will fire {@link #event:addRoot `addRoot` event}. The event is also called when
248
- * the root is added indirectly, e.g. by the undo feature or on a remote client during real-time collaboration.
249
- *
250
- * Note, that this method only adds a root to the editor model. It **does not** create a DOM editable element for the new root.
251
- * Until such element is created (and attached to the root), the root is "virtual": it is not displayed anywhere and its data can
252
- * be changed only using the editor API.
253
- *
254
- * To create a DOM editable element for the root, listen to {@link #event:addRoot `addRoot` event} and call {@link #createEditable}.
255
- * Then, insert the DOM element in a desired place, that will depend on the integration with your application and your requirements.
256
- *
257
- * ```ts
258
- * editor.on( 'addRoot', ( evt, root ) => {
259
- * const editableElement = editor.createEditable( root );
260
- *
261
- * // You may want to create a more complex DOM structure here.
262
- * //
263
- * // Alternatively, you may want to create a DOM structure before
264
- * // calling `editor.addRoot()` and only append `editableElement` at
265
- * // a proper place.
266
- *
267
- * document.querySelector( '#editors' ).appendChild( editableElement );
268
- * } );
269
- *
270
- * // ...
271
- *
272
- * editor.addRoot( 'myRoot' ); // Will create a root, a DOM editable element and append it to `#editors` container element.
273
- * ```
274
- *
275
- * You can set root attributes on the new root while you add it:
276
- *
277
- * ```ts
278
- * // Add a collapsed root at fourth position from top.
279
- * // Keep in mind that these are just examples of attributes. You need to provide your own features that will handle the attributes.
280
- * editor.addRoot( 'myRoot', { attributes: { isCollapsed: true, index: 4 } } );
281
- * ```
282
- *
283
- * See also {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes `rootsAttributes` configuration option}.
284
- *
285
- * Note that attributes keys of attributes added in `attributes` option are also included in {@link #getRootsAttributes} return value.
286
- *
287
- * By setting `isUndoable` flag to `true`, you can allow for detaching the root using the undo feature.
288
- *
289
- * Additionally, you can group adding multiple roots in one undo step. This can be useful if you add multiple roots that are
290
- * combined into one, bigger UI element, and want them all to be undone together.
291
- *
292
- * ```ts
293
- * let rowId = 0;
294
- *
295
- * editor.model.change( () => {
296
- * editor.addRoot( 'left-row-' + rowId, { isUndoable: true } );
297
- * editor.addRoot( 'center-row-' + rowId, { isUndoable: true } );
298
- * editor.addRoot( 'right-row-' + rowId, { isUndoable: true } );
299
- *
300
- * rowId++;
301
- * } );
302
- * ```
303
- *
304
- * @param rootName Name of the root to add.
305
- * @param options Additional options for the added root.
306
- */
307
- addRoot(rootName, { data = '', attributes = {}, elementName = '$root', isUndoable = false } = {}) {
308
- const dataController = this.data;
309
- const registeredKeys = this._registeredRootsAttributesKeys;
310
- if (isUndoable) {
311
- this.model.change(_addRoot);
312
- }
313
- else {
314
- this.model.enqueueChange({ isUndoable: false }, _addRoot);
315
- }
316
- function _addRoot(writer) {
317
- const root = writer.addRoot(rootName, elementName);
318
- if (data) {
319
- writer.insert(dataController.parse(data, root), root, 0);
320
- }
321
- for (const key of Object.keys(attributes)) {
322
- registeredKeys.add(key);
323
- writer.setAttribute(key, attributes[key], root);
324
- }
325
- }
326
- }
327
- /**
328
- * Detaches a root from the editor.
329
- *
330
- * ```ts
331
- * editor.detachRoot( 'myRoot' );
332
- * ```
333
- *
334
- * A detached root is not entirely removed from the editor model, however it can be considered removed.
335
- *
336
- * After a root is detached all its children are removed, all markers inside it are removed, and whenever something is inserted to it,
337
- * it is automatically removed as well. Finally, a detached root is not returned by
338
- * {@link module:engine/model/document~Document#getRootNames} by default.
339
- *
340
- * It is possible to re-add a previously detached root calling {@link #addRoot}.
341
- *
342
- * Whenever a root is detached, the editor instance will fire {@link #event:detachRoot `detachRoot` event}. The event is also
343
- * called when the root is detached indirectly, e.g. by the undo feature or on a remote client during real-time collaboration.
344
- *
345
- * Note, that this method only detached a root in the editor model. It **does not** destroy the DOM editable element linked with
346
- * the root and it **does not** remove the DOM element from the DOM structure of your application.
347
- *
348
- * To properly remove a DOM editable element after a root was detached, listen to {@link #event:detachRoot `detachRoot` event}
349
- * and call {@link #detachEditable}. Then, remove the DOM element from your application.
350
- *
351
- * ```ts
352
- * editor.on( 'detachRoot', ( evt, root ) => {
353
- * const editableElement = editor.detachEditable( root );
354
- *
355
- * // You may want to do an additional DOM clean-up here.
356
- *
357
- * editableElement.remove();
358
- * } );
359
- *
360
- * // ...
361
- *
362
- * editor.detachRoot( 'myRoot' ); // Will detach the root, and remove the DOM editable element.
363
- * ```
364
- *
365
- * By setting `isUndoable` flag to `true`, you can allow for re-adding the root using the undo feature.
366
- *
367
- * Additionally, you can group detaching multiple roots in one undo step. This can be useful if the roots are combined into one,
368
- * bigger UI element, and you want them all to be re-added together.
369
- *
370
- * ```ts
371
- * editor.model.change( () => {
372
- * editor.detachRoot( 'left-row-3', true );
373
- * editor.detachRoot( 'center-row-3', true );
374
- * editor.detachRoot( 'right-row-3', true );
375
- * } );
376
- * ```
377
- *
378
- * @param rootName Name of the root to detach.
379
- * @param isUndoable Whether detaching the root can be undone (using the undo feature) or not.
380
- */
381
- detachRoot(rootName, isUndoable = false) {
382
- if (isUndoable) {
383
- this.model.change(writer => writer.detachRoot(rootName));
384
- }
385
- else {
386
- this.model.enqueueChange({ isUndoable: false }, writer => writer.detachRoot(rootName));
387
- }
388
- }
389
- /**
390
- * Creates and returns a new DOM editable element for the given root element.
391
- *
392
- * The new DOM editable is attached to the model root and can be used to modify the root content.
393
- *
394
- * @param root Root for which the editable element should be created.
395
- * @param placeholder Placeholder for the editable element. If not set, placeholder value from the
396
- * {@link module:core/editor/editorconfig~EditorConfig#placeholder editor configuration} will be used (if it was provided).
397
- * @returns The created DOM element. Append it in a desired place in your application.
398
- */
399
- createEditable(root, placeholder) {
400
- const editable = this.ui.view.createEditable(root.rootName);
401
- this.ui.addEditable(editable, placeholder);
402
- this.editing.view.forceRender();
403
- return editable.element;
404
- }
405
- /**
406
- * Detaches the DOM editable element that was attached to the given root.
407
- *
408
- * @param root Root for which the editable element should be detached.
409
- * @returns The DOM element that was detached. You may want to remove it from your application DOM structure.
410
- */
411
- detachEditable(root) {
412
- const rootName = root.rootName;
413
- const editable = this.ui.view.editables[rootName];
414
- this.ui.removeEditable(editable);
415
- this.ui.view.removeEditable(rootName);
416
- return editable.element;
417
- }
418
- /**
419
- * Returns the document data for all attached roots.
420
- *
421
- * @param options Additional configuration for the retrieved data.
422
- * Editor features may introduce more configuration options that can be set through this parameter.
423
- * @param options.trim Whether returned data should be trimmed. This option is set to `'empty'` by default,
424
- * which means that whenever editor content is considered empty, an empty string is returned. To turn off trimming
425
- * use `'none'`. In such cases exact content will be returned (for example `'<p>&nbsp;</p>'` for an empty editor).
426
- * @returns The full document data.
427
- */
428
- getFullData(options) {
429
- const data = {};
430
- for (const rootName of this.model.document.getRootNames()) {
431
- data[rootName] = this.data.get({ ...options, rootName });
432
- }
433
- return data;
434
- }
435
- /**
436
- * Returns currently set roots attributes for attributes specified in
437
- * {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes `rootsAttributes`} configuration option.
438
- *
439
- * @returns Object with roots attributes. Keys are roots names, while values are attributes set on given root.
440
- */
441
- getRootsAttributes() {
442
- const rootsAttributes = {};
443
- const keys = Array.from(this._registeredRootsAttributesKeys);
444
- for (const rootName of this.model.document.getRootNames()) {
445
- rootsAttributes[rootName] = {};
446
- const root = this.model.document.getRoot(rootName);
447
- for (const key of keys) {
448
- rootsAttributes[rootName][key] = root.hasAttribute(key) ? root.getAttribute(key) : null;
449
- }
450
- }
451
- return rootsAttributes;
452
- }
453
- /**
454
- * Switches given editor root to the read-only mode.
455
- *
456
- * In contrary to {@link module:core/editor/editor~Editor#enableReadOnlyMode `enableReadOnlyMode()`}, which switches the whole editor
457
- * 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
458
- * editing only a part of the editor content.
459
- *
460
- * When you switch a root to the read-only mode, you need provide a unique identifier (`lockId`) that will identify this request. You
461
- * will need to provide the same `lockId` when you will want to
462
- * {@link module:editor-multi-root/multirooteditor~MultiRootEditor#enableRoot re-enable} the root.
463
- *
464
- * ```ts
465
- * const model = editor.model;
466
- * const myRoot = model.document.getRoot( 'myRoot' );
467
- *
468
- * editor.disableRoot( 'myRoot', 'my-lock' );
469
- * model.canEditAt( myRoot ); // `false`
470
- *
471
- * editor.disableRoot( 'myRoot', 'other-lock' );
472
- * editor.disableRoot( 'myRoot', 'other-lock' ); // Multiple locks with the same ID have no effect.
473
- * model.canEditAt( myRoot ); // `false`
474
- *
475
- * editor.enableRoot( 'myRoot', 'my-lock' );
476
- * model.canEditAt( myRoot ); // `false`
477
- *
478
- * editor.enableRoot( 'myRoot', 'other-lock' );
479
- * model.canEditAt( myRoot ); // `true`
480
- * ```
481
- *
482
- * See also {@link module:core/editor/editor~Editor#enableReadOnlyMode `Editor#enableReadOnlyMode()`} and
483
- * {@link module:editor-multi-root/multirooteditor~MultiRootEditor#enableRoot `MultiRootEditor#enableRoot()`}.
484
- *
485
- * @param rootName Name of the root to switch to read-only mode.
486
- * @param lockId A unique ID for setting the editor to the read-only state.
487
- */
488
- disableRoot(rootName, lockId) {
489
- if (rootName == '$graveyard') {
490
- /**
491
- * You cannot disable the `$graveyard` root.
492
- *
493
- * @error multi-root-editor-cannot-disable-graveyard-root
494
- */
495
- throw new CKEditorError('multi-root-editor-cannot-disable-graveyard-root', this);
496
- }
497
- const locksForGivenRoot = this._readOnlyRootLocks.get(rootName);
498
- if (locksForGivenRoot) {
499
- locksForGivenRoot.add(lockId);
500
- }
501
- else {
502
- this._readOnlyRootLocks.set(rootName, new Set([lockId]));
503
- const editableRootElement = this.editing.view.document.getRoot(rootName);
504
- editableRootElement.isReadOnly = true;
505
- // Since one of the roots has changed read-only state, we need to refresh all commands that affect data.
506
- Array.from(this.commands.commands()).forEach(command => command.affectsData && command.refresh());
507
- }
508
- }
509
- /**
510
- * Removes given read-only lock from the given root.
511
- *
512
- * See {@link module:editor-multi-root/multirooteditor~MultiRootEditor#disableRoot `disableRoot()`}.
513
- *
514
- * @param rootName Name of the root to switch back from the read-only mode.
515
- * @param lockId A unique ID for setting the editor to the read-only state.
516
- */
517
- enableRoot(rootName, lockId) {
518
- const locksForGivenRoot = this._readOnlyRootLocks.get(rootName);
519
- if (!locksForGivenRoot || !locksForGivenRoot.has(lockId)) {
520
- return;
521
- }
522
- if (locksForGivenRoot.size === 1) {
523
- this._readOnlyRootLocks.delete(rootName);
524
- const editableRootElement = this.editing.view.document.getRoot(rootName);
525
- editableRootElement.isReadOnly = this.isReadOnly;
526
- // Since one of the roots has changed read-only state, we need to refresh all commands that affect data.
527
- Array.from(this.commands.commands()).forEach(command => command.affectsData && command.refresh());
528
- }
529
- else {
530
- locksForGivenRoot.delete(lockId);
531
- }
532
- }
533
- /**
534
- * Creates a new multi-root editor instance.
535
- *
536
- * **Note:** remember that `MultiRootEditor` does not append the toolbar element to your web page, so you have to do it manually
537
- * after the editor has been initialized.
538
- *
539
- * There are a few different ways to initialize the multi-root editor.
540
- *
541
- * # Using existing DOM elements:
542
- *
543
- * ```ts
544
- * MultiRootEditor.create( {
545
- * intro: document.querySelector( '#editor-intro' ),
546
- * content: document.querySelector( '#editor-content' ),
547
- * sidePanelLeft: document.querySelector( '#editor-side-left' ),
548
- * sidePanelRight: document.querySelector( '#editor-side-right' ),
549
- * outro: document.querySelector( '#editor-outro' )
550
- * } )
551
- * .then( editor => {
552
- * console.log( 'Editor was initialized', editor );
553
- *
554
- * // Append the toolbar inside a provided DOM element.
555
- * document.querySelector( '#toolbar-container' ).appendChild( editor.ui.view.toolbar.element );
556
- * } )
557
- * .catch( err => {
558
- * console.error( err.stack );
559
- * } );
560
- * ```
561
- *
562
- * The elements' content will be used as the editor data and elements will become editable elements.
563
- *
564
- * # Creating a detached editor
565
- *
566
- * Alternatively, you can initialize the editor by passing the initial data directly as strings.
567
- * In this case, you will have to manually append both the toolbar element and the editable elements to your web page.
568
- *
569
- * ```ts
570
- * MultiRootEditor.create( {
571
- * intro: '<p><strong>Exciting</strong> intro text to an article.</p>',
572
- * content: '<p>Lorem ipsum dolor sit amet.</p>',
573
- * sidePanelLeft: '<blockquote>Strong quotation from article.</blockquote>',
574
- * sidePanelRight: '<p>List of similar articles...</p>',
575
- * outro: '<p>Closing text.</p>'
576
- * } )
577
- * .then( editor => {
578
- * console.log( 'Editor was initialized', editor );
579
- *
580
- * // Append the toolbar inside a provided DOM element.
581
- * document.querySelector( '#toolbar-container' ).appendChild( editor.ui.view.toolbar.element );
582
- *
583
- * // Append DOM editable elements created by the editor.
584
- * const editables = editor.ui.view.editables;
585
- * const container = document.querySelector( '#editable-container' );
586
- *
587
- * container.appendChild( editables.intro.element );
588
- * container.appendChild( editables.content.element );
589
- * container.appendChild( editables.outro.element );
590
- * } )
591
- * .catch( err => {
592
- * console.error( err.stack );
593
- * } );
594
- * ```
595
- *
596
- * This lets you dynamically append the editor to your web page whenever it is convenient for you. You may use this method if your
597
- * web page content is generated on the client side and the DOM structure is not ready at the moment when you initialize the editor.
598
- *
599
- * # Using an existing DOM element (and data provided in `config.initialData`)
600
- *
601
- * You can also mix these two ways by providing a DOM element to be used and passing the initial data through the configuration:
602
- *
603
- * ```ts
604
- * MultiRootEditor.create( {
605
- * intro: document.querySelector( '#editor-intro' ),
606
- * content: document.querySelector( '#editor-content' ),
607
- * sidePanelLeft: document.querySelector( '#editor-side-left' ),
608
- * sidePanelRight: document.querySelector( '#editor-side-right' ),
609
- * outro: document.querySelector( '#editor-outro' )
610
- * }, {
611
- * initialData: {
612
- * intro: '<p><strong>Exciting</strong> intro text to an article.</p>',
613
- * content: '<p>Lorem ipsum dolor sit amet.</p>',
614
- * sidePanelLeft '<blockquote>Strong quotation from article.</blockquote>':
615
- * sidePanelRight '<p>List of similar articles...</p>':
616
- * outro: '<p>Closing text.</p>'
617
- * }
618
- * } )
619
- * .then( editor => {
620
- * console.log( 'Editor was initialized', editor );
621
- *
622
- * // Append the toolbar inside a provided DOM element.
623
- * document.querySelector( '#toolbar-container' ).appendChild( editor.ui.view.toolbar.element );
624
- * } )
625
- * .catch( err => {
626
- * console.error( err.stack );
627
- * } );
628
- * ```
629
- *
630
- * This method can be used to initialize the editor on an existing element with the specified content in case if your integration
631
- * makes it difficult to set the content of the source element.
632
- *
633
- * Note that an error will be thrown if you pass the initial data both as the first parameter and also in the configuration.
634
- *
635
- * # Configuring the editor
636
- *
637
- * See the {@link module:core/editor/editorconfig~EditorConfig editor configuration documentation} to learn more about
638
- * customizing plugins, toolbar and more.
639
- *
640
- * # Using the editor from source
641
- *
642
- * The code samples listed in the previous sections of this documentation assume that you are using an
643
- * {@glink installation/getting-started/predefined-builds editor build}
644
- * (for example – `@ckeditor/ckeditor5-build-multi-root`).
645
- *
646
- * If you want to use the multi-root editor from source (`@ckeditor/ckeditor5-editor-multi-root-editor/src/multirooteditor`),
647
- * you need to define the list of
648
- * {@link module:core/editor/editorconfig~EditorConfig#plugins plugins to be initialized} and
649
- * {@link module:core/editor/editorconfig~EditorConfig#toolbar toolbar items}. Read more about using the editor from
650
- * source in the {@glink installation/advanced/alternative-setups/integrating-from-source-webpack dedicated guide}.
651
- *
652
- * @param sourceElementsOrData The DOM elements that will be the source for the created editor
653
- * or the editor's initial data. The editor will initialize multiple roots with names according to the keys in the passed object.
654
- *
655
- * If DOM elements are passed, their content will be automatically loaded to the editor upon initialization and the elements will be
656
- * 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
657
- * {@link module:core/editor/editorconfig~EditorConfig#updateSourceElementOnDestroy updateSourceElementOnDestroy} option
658
- * is set to `true`.
659
- *
660
- * If the initial data is passed, a detached editor will be created. For each entry in the passed object, one editor root and one
661
- * editable DOM element will be created. You will need to attach the editable elements into the DOM manually. The elements are available
662
- * through the {@link module:editor-multi-root/multirooteditorui~MultiRootEditorUI#getEditableElement `editor.ui.getEditableElement()`}
663
- * method.
664
- * @param config The editor configuration.
665
- * @returns A promise resolved once the editor is ready. The promise resolves with the created editor instance.
666
- */
667
- static create(sourceElementsOrData, config = {}) {
668
- return new Promise(resolve => {
669
- for (const sourceItem of Object.values(sourceElementsOrData)) {
670
- if (isElement(sourceItem) && sourceItem.tagName === 'TEXTAREA') {
671
- // Documented in core/editor/editor.js
672
- // eslint-disable-next-line ckeditor5-rules/ckeditor-error-message
673
- throw new CKEditorError('editor-wrong-element', null);
674
- }
675
- }
676
- const editor = new this(sourceElementsOrData, config);
677
- resolve(editor.initPlugins()
678
- .then(() => editor.ui.init())
679
- .then(() => {
680
- // This is checked directly before setting the initial data,
681
- // as plugins may change `EditorConfig#initialData` value.
682
- editor._verifyRootsWithInitialData();
683
- return editor.data.init(editor.config.get('initialData'));
684
- })
685
- .then(() => editor.fire('ready'))
686
- .then(() => editor));
687
- });
688
- }
689
- /**
690
- * @internal
691
- */
692
- _verifyRootsWithInitialData() {
693
- const initialData = this.config.get('initialData');
694
- // Roots that are not in the initial data.
695
- for (const rootName of this.model.document.getRootNames()) {
696
- if (!(rootName in initialData)) {
697
- /**
698
- * Editor roots do not match the
699
- * {@link module:core/editor/editorconfig~EditorConfig#initialData `initialData` configuration}.
700
- *
701
- * This may happen for one of the two reasons:
702
- *
703
- * * Configuration error. The `sourceElementsOrData` parameter in
704
- * {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`} contains different
705
- * roots than {@link module:core/editor/editorconfig~EditorConfig#initialData `initialData` configuration}.
706
- * * As the editor was initialized, the {@link module:core/editor/editorconfig~EditorConfig#initialData `initialData`}
707
- * configuration value or the state of the editor roots has been changed.
708
- *
709
- * @error multi-root-editor-root-initial-data-mismatch
710
- */
711
- throw new CKEditorError('multi-root-editor-root-initial-data-mismatch', null);
712
- }
713
- }
714
- // Roots that are not in the editor.
715
- for (const rootName of Object.keys(initialData)) {
716
- const root = this.model.document.getRoot(rootName);
717
- if (!root || !root.isAttached()) {
718
- // eslint-disable-next-line ckeditor5-rules/ckeditor-error-message
719
- throw new CKEditorError('multi-root-editor-root-initial-data-mismatch', null);
720
- }
721
- }
722
- }
723
- }
724
- /**
725
- * The {@link module:core/context~Context} class.
726
- *
727
- * Exposed as static editor field for easier access in editor builds.
728
- */
729
- MultiRootEditor.Context = Context;
730
- /**
731
- * The {@link module:watchdog/editorwatchdog~EditorWatchdog} class.
732
- *
733
- * Exposed as static editor field for easier access in editor builds.
734
- */
735
- MultiRootEditor.EditorWatchdog = EditorWatchdog;
736
- /**
737
- * The {@link module:watchdog/contextwatchdog~ContextWatchdog} class.
738
- *
739
- * Exposed as static editor field for easier access in editor builds.
740
- */
741
- MultiRootEditor.ContextWatchdog = ContextWatchdog;
742
- function getInitialData(sourceElementOrData) {
743
- return isElement(sourceElementOrData) ? getDataFromElement(sourceElementOrData) : sourceElementOrData;
744
- }
745
- function isElement(value) {
746
- return _isElement(value);
747
- }
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 editor-multi-root/multirooteditor
7
+ */
8
+ import { Editor, Context, DataApiMixin, secureSourceElement } from 'ckeditor5/src/core';
9
+ import { CKEditorError, getDataFromElement, setDataInElement } from 'ckeditor5/src/utils';
10
+ import { ContextWatchdog, EditorWatchdog } from 'ckeditor5/src/watchdog';
11
+ import MultiRootEditorUI from './multirooteditorui';
12
+ import MultiRootEditorUIView from './multirooteditoruiview';
13
+ import { isElement as _isElement } from 'lodash-es';
14
+ /**
15
+ * The {@glink installation/getting-started/predefined-builds#multi-root-editor multi-root editor} implementation.
16
+ *
17
+ * The multi-root editor provides multiple inline editable elements and a toolbar. All editable areas are controlled by one editor
18
+ * instance, which means that they share common configuration, document ID, or undo stack.
19
+ *
20
+ * This type of editor is dedicated to integrations which require a customized UI with an open structure, featuring multiple editable areas,
21
+ * allowing developers to have a control over the exact location of these editable areas.
22
+ *
23
+ * In order to create a multi-root editor instance, use the static
24
+ * {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`} method.
25
+ *
26
+ * Note that you will need to attach the editor toolbar to your web page manually, in a desired place, after the editor is initialized.
27
+ *
28
+ * # Multi-root editor and multi-root editor build
29
+ *
30
+ * The multi-root editor can be used directly from source (if you installed the
31
+ * [`@ckeditor/ckeditor5-editor-multi-root`](https://www.npmjs.com/package/@ckeditor/ckeditor5-editor-multi-root) package)
32
+ * but it is also available in the
33
+ * {@glink installation/getting-started/predefined-builds#multi-root-editor multi-root editor build}.
34
+ *
35
+ * {@glink installation/getting-started/predefined-builds Builds} are ready-to-use editors with plugins bundled in.
36
+ *
37
+ * When using the editor from source you need to take care of loading all plugins by yourself
38
+ * (through the {@link module:core/editor/editorconfig~EditorConfig#plugins `config.plugins`} option).
39
+ * Using the editor from source gives much better flexibility and allows for easier customization.
40
+ *
41
+ * Read more about initializing the editor from source or as a build in
42
+ * {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`}.
43
+ */
44
+ export default class MultiRootEditor extends DataApiMixin(Editor) {
45
+ /**
46
+ * Creates an instance of the multi-root editor.
47
+ *
48
+ * **Note:** Do not use the constructor to create editor instances. Use the static
49
+ * {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`} method instead.
50
+ *
51
+ * @param sourceElementsOrData The DOM elements that will be the source for the created editor
52
+ * or the editor's initial data. The editor will initialize multiple roots with names according to the keys in the passed object.
53
+ * For more information see {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`}.
54
+ * @param config The editor configuration.
55
+ */
56
+ constructor(sourceElementsOrData, config = {}) {
57
+ const rootNames = Object.keys(sourceElementsOrData);
58
+ const sourceIsData = rootNames.length === 0 || typeof sourceElementsOrData[rootNames[0]] === 'string';
59
+ if (sourceIsData && config.initialData !== undefined) {
60
+ // Documented in core/editor/editorconfig.jsdoc.
61
+ // eslint-disable-next-line ckeditor5-rules/ckeditor-error-message
62
+ throw new CKEditorError('editor-create-initial-data', null);
63
+ }
64
+ super(config);
65
+ /**
66
+ * Holds attributes keys that were passed in {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes `rootsAttributes`}
67
+ * config property and should be returned by {@link #getRootsAttributes}.
68
+ */
69
+ this._registeredRootsAttributesKeys = new Set();
70
+ /**
71
+ * A set of lock IDs for enabling or disabling particular root.
72
+ */
73
+ this._readOnlyRootLocks = new Map();
74
+ if (!sourceIsData) {
75
+ this.sourceElements = sourceElementsOrData;
76
+ }
77
+ else {
78
+ this.sourceElements = {};
79
+ }
80
+ if (this.config.get('initialData') === undefined) {
81
+ // Create initial data object containing data from all roots.
82
+ const initialData = {};
83
+ for (const rootName of rootNames) {
84
+ initialData[rootName] = getInitialData(sourceElementsOrData[rootName]);
85
+ }
86
+ this.config.set('initialData', initialData);
87
+ }
88
+ if (!sourceIsData) {
89
+ for (const rootName of rootNames) {
90
+ secureSourceElement(this, sourceElementsOrData[rootName]);
91
+ }
92
+ }
93
+ this.editing.view.document.roots.on('add', (evt, viewRoot) => {
94
+ // Here we change the standard binding of readOnly flag by adding
95
+ // additional constraint that multi-root has (enabling / disabling particular root).
96
+ viewRoot.unbind('isReadOnly');
97
+ viewRoot.bind('isReadOnly').to(this.editing.view.document, 'isReadOnly', isReadOnly => {
98
+ return isReadOnly || this._readOnlyRootLocks.has(viewRoot.rootName);
99
+ });
100
+ // Hacky solution to nested editables.
101
+ // Nested editables should be managed each separately and do not base on view document or view root.
102
+ viewRoot.on('change:isReadOnly', (evt, prop, value) => {
103
+ const viewRange = this.editing.view.createRangeIn(viewRoot);
104
+ for (const viewItem of viewRange.getItems()) {
105
+ if (viewItem.is('editableElement')) {
106
+ viewItem.unbind('isReadOnly');
107
+ viewItem.isReadOnly = value;
108
+ }
109
+ }
110
+ });
111
+ });
112
+ for (const rootName of rootNames) {
113
+ // Create root and `UIView` element for each editable container.
114
+ this.model.document.createRoot('$root', rootName);
115
+ }
116
+ if (this.config.get('rootsAttributes')) {
117
+ const rootsAttributes = this.config.get('rootsAttributes');
118
+ for (const [rootName, attributes] of Object.entries(rootsAttributes)) {
119
+ if (!rootNames.includes(rootName)) {
120
+ /**
121
+ * Trying to set attributes on a non-existing root.
122
+ *
123
+ * Roots specified in {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes} do not match initial
124
+ * editor roots.
125
+ *
126
+ * @error multi-root-editor-root-attributes-no-root
127
+ */
128
+ throw new CKEditorError('multi-root-editor-root-attributes-no-root', null);
129
+ }
130
+ for (const key of Object.keys(attributes)) {
131
+ this._registeredRootsAttributesKeys.add(key);
132
+ }
133
+ }
134
+ this.data.on('init', () => {
135
+ this.model.enqueueChange({ isUndoable: false }, writer => {
136
+ for (const [name, attributes] of Object.entries(rootsAttributes)) {
137
+ const root = this.model.document.getRoot(name);
138
+ for (const [key, value] of Object.entries(attributes)) {
139
+ if (value !== null) {
140
+ writer.setAttribute(key, value, root);
141
+ }
142
+ }
143
+ }
144
+ });
145
+ });
146
+ }
147
+ const options = {
148
+ shouldToolbarGroupWhenFull: !this.config.get('toolbar.shouldNotGroupWhenFull'),
149
+ editableElements: sourceIsData ? undefined : sourceElementsOrData
150
+ };
151
+ const view = new MultiRootEditorUIView(this.locale, this.editing.view, rootNames, options);
152
+ this.ui = new MultiRootEditorUI(this, view);
153
+ this.model.document.on('change:data', () => {
154
+ const changedRoots = this.model.document.differ.getChangedRoots();
155
+ // Fire detaches first. If there are multiple roots removed and added in one batch, it should be easier to handle if
156
+ // changes aren't mixed. Detaching will usually lead to just removing DOM elements. Detaching first will lead to a clean DOM
157
+ // when new editables are added in `addRoot` event.
158
+ for (const changes of changedRoots) {
159
+ const root = this.model.document.getRoot(changes.name);
160
+ if (changes.state == 'detached') {
161
+ this.fire('detachRoot', root);
162
+ }
163
+ }
164
+ for (const changes of changedRoots) {
165
+ const root = this.model.document.getRoot(changes.name);
166
+ if (changes.state == 'attached') {
167
+ this.fire('addRoot', root);
168
+ }
169
+ }
170
+ });
171
+ // Overwrite `Model#canEditAt()` decorated method.
172
+ // Check if the provided selection is inside a read-only root. If so, return `false`.
173
+ this.listenTo(this.model, 'canEditAt', (evt, [selection]) => {
174
+ // Skip empty selections.
175
+ if (!selection) {
176
+ return;
177
+ }
178
+ let selectionInReadOnlyRoot = false;
179
+ for (const range of selection.getRanges()) {
180
+ const rootName = range.root.rootName;
181
+ if (this._readOnlyRootLocks.has(rootName)) {
182
+ selectionInReadOnlyRoot = true;
183
+ break;
184
+ }
185
+ }
186
+ // If selection is in read-only root, return `false` and prevent further processing.
187
+ // Otherwise, allow for other callbacks (or default callback) to evaluate.
188
+ if (selectionInReadOnlyRoot) {
189
+ evt.return = false;
190
+ evt.stop();
191
+ }
192
+ }, { priority: 'high' });
193
+ }
194
+ /**
195
+ * Destroys the editor instance, releasing all resources used by it.
196
+ *
197
+ * Updates the original editor element with the data if the
198
+ * {@link module:core/editor/editorconfig~EditorConfig#updateSourceElementOnDestroy `updateSourceElementOnDestroy`}
199
+ * configuration option is set to `true`.
200
+ *
201
+ * **Note**: The multi-root editor does not remove the toolbar and editable when destroyed. You can
202
+ * do that yourself in the destruction chain, if you need to:
203
+ *
204
+ * ```ts
205
+ * editor.destroy().then( () => {
206
+ * // Remove the toolbar from DOM.
207
+ * editor.ui.view.toolbar.element.remove();
208
+ *
209
+ * // Remove editable elements from DOM.
210
+ * for ( const editable of Object.values( editor.ui.view.editables ) ) {
211
+ * editable.element.remove();
212
+ * }
213
+ *
214
+ * console.log( 'Editor was destroyed' );
215
+ * } );
216
+ * ```
217
+ */
218
+ destroy() {
219
+ const shouldUpdateSourceElement = this.config.get('updateSourceElementOnDestroy');
220
+ // Cache the data and editable DOM elements, then destroy.
221
+ // It's safe to assume that the model->view conversion will not work after `super.destroy()`,
222
+ // same as `ui.getEditableElement()` method will not return editables.
223
+ const data = {};
224
+ for (const rootName of Object.keys(this.sourceElements)) {
225
+ data[rootName] = shouldUpdateSourceElement ? this.getData({ rootName }) : '';
226
+ }
227
+ this.ui.destroy();
228
+ return super.destroy()
229
+ .then(() => {
230
+ for (const rootName of Object.keys(this.sourceElements)) {
231
+ setDataInElement(this.sourceElements[rootName], data[rootName]);
232
+ }
233
+ });
234
+ }
235
+ /**
236
+ * Adds a new root to the editor.
237
+ *
238
+ * ```ts
239
+ * editor.addRoot( 'myRoot', { data: '<p>Initial root data.</p>' } );
240
+ * ```
241
+ *
242
+ * After a root is added, you will be able to modify and retrieve its data.
243
+ *
244
+ * All root names must be unique. An error will be thrown if you will try to create a root with the name same as
245
+ * an already existing, attached root. However, you can call this method for a detached root. See also {@link #detachRoot}.
246
+ *
247
+ * Whenever a root is added, the editor instance will fire {@link #event:addRoot `addRoot` event}. The event is also called when
248
+ * the root is added indirectly, e.g. by the undo feature or on a remote client during real-time collaboration.
249
+ *
250
+ * Note, that this method only adds a root to the editor model. It **does not** create a DOM editable element for the new root.
251
+ * Until such element is created (and attached to the root), the root is "virtual": it is not displayed anywhere and its data can
252
+ * be changed only using the editor API.
253
+ *
254
+ * To create a DOM editable element for the root, listen to {@link #event:addRoot `addRoot` event} and call {@link #createEditable}.
255
+ * Then, insert the DOM element in a desired place, that will depend on the integration with your application and your requirements.
256
+ *
257
+ * ```ts
258
+ * editor.on( 'addRoot', ( evt, root ) => {
259
+ * const editableElement = editor.createEditable( root );
260
+ *
261
+ * // You may want to create a more complex DOM structure here.
262
+ * //
263
+ * // Alternatively, you may want to create a DOM structure before
264
+ * // calling `editor.addRoot()` and only append `editableElement` at
265
+ * // a proper place.
266
+ *
267
+ * document.querySelector( '#editors' ).appendChild( editableElement );
268
+ * } );
269
+ *
270
+ * // ...
271
+ *
272
+ * editor.addRoot( 'myRoot' ); // Will create a root, a DOM editable element and append it to `#editors` container element.
273
+ * ```
274
+ *
275
+ * You can set root attributes on the new root while you add it:
276
+ *
277
+ * ```ts
278
+ * // Add a collapsed root at fourth position from top.
279
+ * // Keep in mind that these are just examples of attributes. You need to provide your own features that will handle the attributes.
280
+ * editor.addRoot( 'myRoot', { attributes: { isCollapsed: true, index: 4 } } );
281
+ * ```
282
+ *
283
+ * See also {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes `rootsAttributes` configuration option}.
284
+ *
285
+ * Note that attributes keys of attributes added in `attributes` option are also included in {@link #getRootsAttributes} return value.
286
+ *
287
+ * By setting `isUndoable` flag to `true`, you can allow for detaching the root using the undo feature.
288
+ *
289
+ * Additionally, you can group adding multiple roots in one undo step. This can be useful if you add multiple roots that are
290
+ * combined into one, bigger UI element, and want them all to be undone together.
291
+ *
292
+ * ```ts
293
+ * let rowId = 0;
294
+ *
295
+ * editor.model.change( () => {
296
+ * editor.addRoot( 'left-row-' + rowId, { isUndoable: true } );
297
+ * editor.addRoot( 'center-row-' + rowId, { isUndoable: true } );
298
+ * editor.addRoot( 'right-row-' + rowId, { isUndoable: true } );
299
+ *
300
+ * rowId++;
301
+ * } );
302
+ * ```
303
+ *
304
+ * @param rootName Name of the root to add.
305
+ * @param options Additional options for the added root.
306
+ */
307
+ addRoot(rootName, { data = '', attributes = {}, elementName = '$root', isUndoable = false } = {}) {
308
+ const dataController = this.data;
309
+ const registeredKeys = this._registeredRootsAttributesKeys;
310
+ if (isUndoable) {
311
+ this.model.change(_addRoot);
312
+ }
313
+ else {
314
+ this.model.enqueueChange({ isUndoable: false }, _addRoot);
315
+ }
316
+ function _addRoot(writer) {
317
+ const root = writer.addRoot(rootName, elementName);
318
+ if (data) {
319
+ writer.insert(dataController.parse(data, root), root, 0);
320
+ }
321
+ for (const key of Object.keys(attributes)) {
322
+ registeredKeys.add(key);
323
+ writer.setAttribute(key, attributes[key], root);
324
+ }
325
+ }
326
+ }
327
+ /**
328
+ * Detaches a root from the editor.
329
+ *
330
+ * ```ts
331
+ * editor.detachRoot( 'myRoot' );
332
+ * ```
333
+ *
334
+ * A detached root is not entirely removed from the editor model, however it can be considered removed.
335
+ *
336
+ * After a root is detached all its children are removed, all markers inside it are removed, and whenever something is inserted to it,
337
+ * it is automatically removed as well. Finally, a detached root is not returned by
338
+ * {@link module:engine/model/document~Document#getRootNames} by default.
339
+ *
340
+ * It is possible to re-add a previously detached root calling {@link #addRoot}.
341
+ *
342
+ * Whenever a root is detached, the editor instance will fire {@link #event:detachRoot `detachRoot` event}. The event is also
343
+ * called when the root is detached indirectly, e.g. by the undo feature or on a remote client during real-time collaboration.
344
+ *
345
+ * Note, that this method only detached a root in the editor model. It **does not** destroy the DOM editable element linked with
346
+ * the root and it **does not** remove the DOM element from the DOM structure of your application.
347
+ *
348
+ * To properly remove a DOM editable element after a root was detached, listen to {@link #event:detachRoot `detachRoot` event}
349
+ * and call {@link #detachEditable}. Then, remove the DOM element from your application.
350
+ *
351
+ * ```ts
352
+ * editor.on( 'detachRoot', ( evt, root ) => {
353
+ * const editableElement = editor.detachEditable( root );
354
+ *
355
+ * // You may want to do an additional DOM clean-up here.
356
+ *
357
+ * editableElement.remove();
358
+ * } );
359
+ *
360
+ * // ...
361
+ *
362
+ * editor.detachRoot( 'myRoot' ); // Will detach the root, and remove the DOM editable element.
363
+ * ```
364
+ *
365
+ * By setting `isUndoable` flag to `true`, you can allow for re-adding the root using the undo feature.
366
+ *
367
+ * Additionally, you can group detaching multiple roots in one undo step. This can be useful if the roots are combined into one,
368
+ * bigger UI element, and you want them all to be re-added together.
369
+ *
370
+ * ```ts
371
+ * editor.model.change( () => {
372
+ * editor.detachRoot( 'left-row-3', true );
373
+ * editor.detachRoot( 'center-row-3', true );
374
+ * editor.detachRoot( 'right-row-3', true );
375
+ * } );
376
+ * ```
377
+ *
378
+ * @param rootName Name of the root to detach.
379
+ * @param isUndoable Whether detaching the root can be undone (using the undo feature) or not.
380
+ */
381
+ detachRoot(rootName, isUndoable = false) {
382
+ if (isUndoable) {
383
+ this.model.change(writer => writer.detachRoot(rootName));
384
+ }
385
+ else {
386
+ this.model.enqueueChange({ isUndoable: false }, writer => writer.detachRoot(rootName));
387
+ }
388
+ }
389
+ /**
390
+ * Creates and returns a new DOM editable element for the given root element.
391
+ *
392
+ * The new DOM editable is attached to the model root and can be used to modify the root content.
393
+ *
394
+ * @param root Root for which the editable element should be created.
395
+ * @param placeholder Placeholder for the editable element. If not set, placeholder value from the
396
+ * {@link module:core/editor/editorconfig~EditorConfig#placeholder editor configuration} will be used (if it was provided).
397
+ * @returns The created DOM element. Append it in a desired place in your application.
398
+ */
399
+ createEditable(root, placeholder) {
400
+ const editable = this.ui.view.createEditable(root.rootName);
401
+ this.ui.addEditable(editable, placeholder);
402
+ this.editing.view.forceRender();
403
+ return editable.element;
404
+ }
405
+ /**
406
+ * Detaches the DOM editable element that was attached to the given root.
407
+ *
408
+ * @param root Root for which the editable element should be detached.
409
+ * @returns The DOM element that was detached. You may want to remove it from your application DOM structure.
410
+ */
411
+ detachEditable(root) {
412
+ const rootName = root.rootName;
413
+ const editable = this.ui.view.editables[rootName];
414
+ this.ui.removeEditable(editable);
415
+ this.ui.view.removeEditable(rootName);
416
+ return editable.element;
417
+ }
418
+ /**
419
+ * Returns the document data for all attached roots.
420
+ *
421
+ * @param options Additional configuration for the retrieved data.
422
+ * Editor features may introduce more configuration options that can be set through this parameter.
423
+ * @param options.trim Whether returned data should be trimmed. This option is set to `'empty'` by default,
424
+ * which means that whenever editor content is considered empty, an empty string is returned. To turn off trimming
425
+ * use `'none'`. In such cases exact content will be returned (for example `'<p>&nbsp;</p>'` for an empty editor).
426
+ * @returns The full document data.
427
+ */
428
+ getFullData(options) {
429
+ const data = {};
430
+ for (const rootName of this.model.document.getRootNames()) {
431
+ data[rootName] = this.data.get({ ...options, rootName });
432
+ }
433
+ return data;
434
+ }
435
+ /**
436
+ * Returns currently set roots attributes for attributes specified in
437
+ * {@link module:core/editor/editorconfig~EditorConfig#rootsAttributes `rootsAttributes`} configuration option.
438
+ *
439
+ * @returns Object with roots attributes. Keys are roots names, while values are attributes set on given root.
440
+ */
441
+ getRootsAttributes() {
442
+ const rootsAttributes = {};
443
+ const keys = Array.from(this._registeredRootsAttributesKeys);
444
+ for (const rootName of this.model.document.getRootNames()) {
445
+ rootsAttributes[rootName] = {};
446
+ const root = this.model.document.getRoot(rootName);
447
+ for (const key of keys) {
448
+ rootsAttributes[rootName][key] = root.hasAttribute(key) ? root.getAttribute(key) : null;
449
+ }
450
+ }
451
+ return rootsAttributes;
452
+ }
453
+ /**
454
+ * Switches given editor root to the read-only mode.
455
+ *
456
+ * In contrary to {@link module:core/editor/editor~Editor#enableReadOnlyMode `enableReadOnlyMode()`}, which switches the whole editor
457
+ * 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
458
+ * editing only a part of the editor content.
459
+ *
460
+ * When you switch a root to the read-only mode, you need provide a unique identifier (`lockId`) that will identify this request. You
461
+ * will need to provide the same `lockId` when you will want to
462
+ * {@link module:editor-multi-root/multirooteditor~MultiRootEditor#enableRoot re-enable} the root.
463
+ *
464
+ * ```ts
465
+ * const model = editor.model;
466
+ * const myRoot = model.document.getRoot( 'myRoot' );
467
+ *
468
+ * editor.disableRoot( 'myRoot', 'my-lock' );
469
+ * model.canEditAt( myRoot ); // `false`
470
+ *
471
+ * editor.disableRoot( 'myRoot', 'other-lock' );
472
+ * editor.disableRoot( 'myRoot', 'other-lock' ); // Multiple locks with the same ID have no effect.
473
+ * model.canEditAt( myRoot ); // `false`
474
+ *
475
+ * editor.enableRoot( 'myRoot', 'my-lock' );
476
+ * model.canEditAt( myRoot ); // `false`
477
+ *
478
+ * editor.enableRoot( 'myRoot', 'other-lock' );
479
+ * model.canEditAt( myRoot ); // `true`
480
+ * ```
481
+ *
482
+ * See also {@link module:core/editor/editor~Editor#enableReadOnlyMode `Editor#enableReadOnlyMode()`} and
483
+ * {@link module:editor-multi-root/multirooteditor~MultiRootEditor#enableRoot `MultiRootEditor#enableRoot()`}.
484
+ *
485
+ * @param rootName Name of the root to switch to read-only mode.
486
+ * @param lockId A unique ID for setting the editor to the read-only state.
487
+ */
488
+ disableRoot(rootName, lockId) {
489
+ if (rootName == '$graveyard') {
490
+ /**
491
+ * You cannot disable the `$graveyard` root.
492
+ *
493
+ * @error multi-root-editor-cannot-disable-graveyard-root
494
+ */
495
+ throw new CKEditorError('multi-root-editor-cannot-disable-graveyard-root', this);
496
+ }
497
+ const locksForGivenRoot = this._readOnlyRootLocks.get(rootName);
498
+ if (locksForGivenRoot) {
499
+ locksForGivenRoot.add(lockId);
500
+ }
501
+ else {
502
+ this._readOnlyRootLocks.set(rootName, new Set([lockId]));
503
+ const editableRootElement = this.editing.view.document.getRoot(rootName);
504
+ editableRootElement.isReadOnly = true;
505
+ // Since one of the roots has changed read-only state, we need to refresh all commands that affect data.
506
+ Array.from(this.commands.commands()).forEach(command => command.affectsData && command.refresh());
507
+ }
508
+ }
509
+ /**
510
+ * Removes given read-only lock from the given root.
511
+ *
512
+ * See {@link module:editor-multi-root/multirooteditor~MultiRootEditor#disableRoot `disableRoot()`}.
513
+ *
514
+ * @param rootName Name of the root to switch back from the read-only mode.
515
+ * @param lockId A unique ID for setting the editor to the read-only state.
516
+ */
517
+ enableRoot(rootName, lockId) {
518
+ const locksForGivenRoot = this._readOnlyRootLocks.get(rootName);
519
+ if (!locksForGivenRoot || !locksForGivenRoot.has(lockId)) {
520
+ return;
521
+ }
522
+ if (locksForGivenRoot.size === 1) {
523
+ this._readOnlyRootLocks.delete(rootName);
524
+ const editableRootElement = this.editing.view.document.getRoot(rootName);
525
+ editableRootElement.isReadOnly = this.isReadOnly;
526
+ // Since one of the roots has changed read-only state, we need to refresh all commands that affect data.
527
+ Array.from(this.commands.commands()).forEach(command => command.affectsData && command.refresh());
528
+ }
529
+ else {
530
+ locksForGivenRoot.delete(lockId);
531
+ }
532
+ }
533
+ /**
534
+ * Creates a new multi-root editor instance.
535
+ *
536
+ * **Note:** remember that `MultiRootEditor` does not append the toolbar element to your web page, so you have to do it manually
537
+ * after the editor has been initialized.
538
+ *
539
+ * There are a few different ways to initialize the multi-root editor.
540
+ *
541
+ * # Using existing DOM elements:
542
+ *
543
+ * ```ts
544
+ * MultiRootEditor.create( {
545
+ * intro: document.querySelector( '#editor-intro' ),
546
+ * content: document.querySelector( '#editor-content' ),
547
+ * sidePanelLeft: document.querySelector( '#editor-side-left' ),
548
+ * sidePanelRight: document.querySelector( '#editor-side-right' ),
549
+ * outro: document.querySelector( '#editor-outro' )
550
+ * } )
551
+ * .then( editor => {
552
+ * console.log( 'Editor was initialized', editor );
553
+ *
554
+ * // Append the toolbar inside a provided DOM element.
555
+ * document.querySelector( '#toolbar-container' ).appendChild( editor.ui.view.toolbar.element );
556
+ * } )
557
+ * .catch( err => {
558
+ * console.error( err.stack );
559
+ * } );
560
+ * ```
561
+ *
562
+ * The elements' content will be used as the editor data and elements will become editable elements.
563
+ *
564
+ * # Creating a detached editor
565
+ *
566
+ * Alternatively, you can initialize the editor by passing the initial data directly as strings.
567
+ * In this case, you will have to manually append both the toolbar element and the editable elements to your web page.
568
+ *
569
+ * ```ts
570
+ * MultiRootEditor.create( {
571
+ * intro: '<p><strong>Exciting</strong> intro text to an article.</p>',
572
+ * content: '<p>Lorem ipsum dolor sit amet.</p>',
573
+ * sidePanelLeft: '<blockquote>Strong quotation from article.</blockquote>',
574
+ * sidePanelRight: '<p>List of similar articles...</p>',
575
+ * outro: '<p>Closing text.</p>'
576
+ * } )
577
+ * .then( editor => {
578
+ * console.log( 'Editor was initialized', editor );
579
+ *
580
+ * // Append the toolbar inside a provided DOM element.
581
+ * document.querySelector( '#toolbar-container' ).appendChild( editor.ui.view.toolbar.element );
582
+ *
583
+ * // Append DOM editable elements created by the editor.
584
+ * const editables = editor.ui.view.editables;
585
+ * const container = document.querySelector( '#editable-container' );
586
+ *
587
+ * container.appendChild( editables.intro.element );
588
+ * container.appendChild( editables.content.element );
589
+ * container.appendChild( editables.outro.element );
590
+ * } )
591
+ * .catch( err => {
592
+ * console.error( err.stack );
593
+ * } );
594
+ * ```
595
+ *
596
+ * This lets you dynamically append the editor to your web page whenever it is convenient for you. You may use this method if your
597
+ * web page content is generated on the client side and the DOM structure is not ready at the moment when you initialize the editor.
598
+ *
599
+ * # Using an existing DOM element (and data provided in `config.initialData`)
600
+ *
601
+ * You can also mix these two ways by providing a DOM element to be used and passing the initial data through the configuration:
602
+ *
603
+ * ```ts
604
+ * MultiRootEditor.create( {
605
+ * intro: document.querySelector( '#editor-intro' ),
606
+ * content: document.querySelector( '#editor-content' ),
607
+ * sidePanelLeft: document.querySelector( '#editor-side-left' ),
608
+ * sidePanelRight: document.querySelector( '#editor-side-right' ),
609
+ * outro: document.querySelector( '#editor-outro' )
610
+ * }, {
611
+ * initialData: {
612
+ * intro: '<p><strong>Exciting</strong> intro text to an article.</p>',
613
+ * content: '<p>Lorem ipsum dolor sit amet.</p>',
614
+ * sidePanelLeft '<blockquote>Strong quotation from article.</blockquote>':
615
+ * sidePanelRight '<p>List of similar articles...</p>':
616
+ * outro: '<p>Closing text.</p>'
617
+ * }
618
+ * } )
619
+ * .then( editor => {
620
+ * console.log( 'Editor was initialized', editor );
621
+ *
622
+ * // Append the toolbar inside a provided DOM element.
623
+ * document.querySelector( '#toolbar-container' ).appendChild( editor.ui.view.toolbar.element );
624
+ * } )
625
+ * .catch( err => {
626
+ * console.error( err.stack );
627
+ * } );
628
+ * ```
629
+ *
630
+ * This method can be used to initialize the editor on an existing element with the specified content in case if your integration
631
+ * makes it difficult to set the content of the source element.
632
+ *
633
+ * Note that an error will be thrown if you pass the initial data both as the first parameter and also in the configuration.
634
+ *
635
+ * # Configuring the editor
636
+ *
637
+ * See the {@link module:core/editor/editorconfig~EditorConfig editor configuration documentation} to learn more about
638
+ * customizing plugins, toolbar and more.
639
+ *
640
+ * # Using the editor from source
641
+ *
642
+ * The code samples listed in the previous sections of this documentation assume that you are using an
643
+ * {@glink installation/getting-started/predefined-builds editor build}
644
+ * (for example – `@ckeditor/ckeditor5-build-multi-root`).
645
+ *
646
+ * If you want to use the multi-root editor from source (`@ckeditor/ckeditor5-editor-multi-root-editor/src/multirooteditor`),
647
+ * you need to define the list of
648
+ * {@link module:core/editor/editorconfig~EditorConfig#plugins plugins to be initialized} and
649
+ * {@link module:core/editor/editorconfig~EditorConfig#toolbar toolbar items}. Read more about using the editor from
650
+ * source in the {@glink installation/advanced/alternative-setups/integrating-from-source-webpack dedicated guide}.
651
+ *
652
+ * @param sourceElementsOrData The DOM elements that will be the source for the created editor
653
+ * or the editor's initial data. The editor will initialize multiple roots with names according to the keys in the passed object.
654
+ *
655
+ * If DOM elements are passed, their content will be automatically loaded to the editor upon initialization and the elements will be
656
+ * 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
657
+ * {@link module:core/editor/editorconfig~EditorConfig#updateSourceElementOnDestroy updateSourceElementOnDestroy} option
658
+ * is set to `true`.
659
+ *
660
+ * If the initial data is passed, a detached editor will be created. For each entry in the passed object, one editor root and one
661
+ * editable DOM element will be created. You will need to attach the editable elements into the DOM manually. The elements are available
662
+ * through the {@link module:editor-multi-root/multirooteditorui~MultiRootEditorUI#getEditableElement `editor.ui.getEditableElement()`}
663
+ * method.
664
+ * @param config The editor configuration.
665
+ * @returns A promise resolved once the editor is ready. The promise resolves with the created editor instance.
666
+ */
667
+ static create(sourceElementsOrData, config = {}) {
668
+ return new Promise(resolve => {
669
+ for (const sourceItem of Object.values(sourceElementsOrData)) {
670
+ if (isElement(sourceItem) && sourceItem.tagName === 'TEXTAREA') {
671
+ // Documented in core/editor/editor.js
672
+ // eslint-disable-next-line ckeditor5-rules/ckeditor-error-message
673
+ throw new CKEditorError('editor-wrong-element', null);
674
+ }
675
+ }
676
+ const editor = new this(sourceElementsOrData, config);
677
+ resolve(editor.initPlugins()
678
+ .then(() => editor.ui.init())
679
+ .then(() => {
680
+ // This is checked directly before setting the initial data,
681
+ // as plugins may change `EditorConfig#initialData` value.
682
+ editor._verifyRootsWithInitialData();
683
+ return editor.data.init(editor.config.get('initialData'));
684
+ })
685
+ .then(() => editor.fire('ready'))
686
+ .then(() => editor));
687
+ });
688
+ }
689
+ /**
690
+ * @internal
691
+ */
692
+ _verifyRootsWithInitialData() {
693
+ const initialData = this.config.get('initialData');
694
+ // Roots that are not in the initial data.
695
+ for (const rootName of this.model.document.getRootNames()) {
696
+ if (!(rootName in initialData)) {
697
+ /**
698
+ * Editor roots do not match the
699
+ * {@link module:core/editor/editorconfig~EditorConfig#initialData `initialData` configuration}.
700
+ *
701
+ * This may happen for one of the two reasons:
702
+ *
703
+ * * Configuration error. The `sourceElementsOrData` parameter in
704
+ * {@link module:editor-multi-root/multirooteditor~MultiRootEditor.create `MultiRootEditor.create()`} contains different
705
+ * roots than {@link module:core/editor/editorconfig~EditorConfig#initialData `initialData` configuration}.
706
+ * * As the editor was initialized, the {@link module:core/editor/editorconfig~EditorConfig#initialData `initialData`}
707
+ * configuration value or the state of the editor roots has been changed.
708
+ *
709
+ * @error multi-root-editor-root-initial-data-mismatch
710
+ */
711
+ throw new CKEditorError('multi-root-editor-root-initial-data-mismatch', null);
712
+ }
713
+ }
714
+ // Roots that are not in the editor.
715
+ for (const rootName of Object.keys(initialData)) {
716
+ const root = this.model.document.getRoot(rootName);
717
+ if (!root || !root.isAttached()) {
718
+ // eslint-disable-next-line ckeditor5-rules/ckeditor-error-message
719
+ throw new CKEditorError('multi-root-editor-root-initial-data-mismatch', null);
720
+ }
721
+ }
722
+ }
723
+ }
724
+ /**
725
+ * The {@link module:core/context~Context} class.
726
+ *
727
+ * Exposed as static editor field for easier access in editor builds.
728
+ */
729
+ MultiRootEditor.Context = Context;
730
+ /**
731
+ * The {@link module:watchdog/editorwatchdog~EditorWatchdog} class.
732
+ *
733
+ * Exposed as static editor field for easier access in editor builds.
734
+ */
735
+ MultiRootEditor.EditorWatchdog = EditorWatchdog;
736
+ /**
737
+ * The {@link module:watchdog/contextwatchdog~ContextWatchdog} class.
738
+ *
739
+ * Exposed as static editor field for easier access in editor builds.
740
+ */
741
+ MultiRootEditor.ContextWatchdog = ContextWatchdog;
742
+ function getInitialData(sourceElementOrData) {
743
+ return isElement(sourceElementOrData) ? getDataFromElement(sourceElementOrData) : sourceElementOrData;
744
+ }
745
+ function isElement(value) {
746
+ return _isElement(value);
747
+ }