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