@ckeditor/ckeditor5-heading 35.4.0 → 36.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/title.js CHANGED
@@ -1,599 +1,426 @@
1
1
  /**
2
- * @license Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
2
+ * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
3
3
  * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
4
  */
5
-
6
5
  /**
7
6
  * @module heading/title
8
7
  */
9
-
10
8
  import { Plugin } from 'ckeditor5/src/core';
11
-
12
9
  import { first } from 'ckeditor5/src/utils';
13
- import {
14
- DowncastWriter,
15
- needsPlaceholder,
16
- showPlaceholder,
17
- hidePlaceholder,
18
- enablePlaceholder
19
- } from 'ckeditor5/src/engine';
20
-
10
+ import { DowncastWriter, enablePlaceholder, hidePlaceholder, needsPlaceholder, showPlaceholder } from 'ckeditor5/src/engine';
21
11
  // A list of element names that should be treated by the Title plugin as title-like.
22
12
  // This means that an element of a type from this list will be changed to a title element
23
13
  // when it is the first element in the root.
24
- const titleLikeElements = new Set( [ 'paragraph', 'heading1', 'heading2', 'heading3', 'heading4', 'heading5', 'heading6' ] );
25
-
14
+ const titleLikeElements = new Set(['paragraph', 'heading1', 'heading2', 'heading3', 'heading4', 'heading5', 'heading6']);
26
15
  /**
27
16
  * The Title plugin.
28
17
  *
29
18
  * It splits the document into `Title` and `Body` sections.
30
- *
31
- * @extends module:core/plugin~Plugin
32
19
  */
33
20
  export default class Title extends Plugin {
34
- /**
35
- * @inheritDoc
36
- */
37
- static get pluginName() {
38
- return 'Title';
39
- }
40
-
41
- /**
42
- * @inheritDoc
43
- */
44
- static get requires() {
45
- return [ 'Paragraph' ];
46
- }
47
-
48
- /**
49
- * @inheritDoc
50
- */
51
- init() {
52
- const editor = this.editor;
53
- const model = editor.model;
54
-
55
- /**
56
- * A reference to an empty paragraph in the body
57
- * created when there is no element in the body for the placeholder purposes.
58
- *
59
- * @private
60
- * @type {null|module:engine/model/element~Element}
61
- */
62
- this._bodyPlaceholder = null;
63
-
64
- // To use the schema for disabling some features when the selection is inside the title element
65
- // it is needed to create the following structure:
66
- //
67
- // <title>
68
- // <title-content>The title text</title-content>
69
- // </title>
70
- //
71
- // See: https://github.com/ckeditor/ckeditor5/issues/2005.
72
- model.schema.register( 'title', { isBlock: true, allowIn: '$root' } );
73
- model.schema.register( 'title-content', { isBlock: true, allowIn: 'title', allowAttributes: [ 'alignment' ] } );
74
- model.schema.extend( '$text', { allowIn: 'title-content' } );
75
-
76
- // Disallow all attributes in `title-content`.
77
- model.schema.addAttributeCheck( context => {
78
- if ( context.endsWith( 'title-content $text' ) ) {
79
- return false;
80
- }
81
- } );
82
-
83
- // Because `title` is represented by two elements in the model
84
- // but only one in the view, it is needed to adjust Mapper.
85
- editor.editing.mapper.on( 'modelToViewPosition', mapModelPositionToView( editor.editing.view ) );
86
- editor.data.mapper.on( 'modelToViewPosition', mapModelPositionToView( editor.editing.view ) );
87
-
88
- // Conversion.
89
- editor.conversion.for( 'downcast' ).elementToElement( { model: 'title-content', view: 'h1' } );
90
- editor.conversion.for( 'downcast' ).add( dispatcher => dispatcher.on( 'insert:title', ( evt, data, conversionApi ) => {
91
- conversionApi.consumable.consume( data.item, evt.name );
92
- } ) );
93
-
94
- // Custom converter is used for data v -> m conversion to avoid calling post-fixer when setting data.
95
- // See https://github.com/ckeditor/ckeditor5/issues/2036.
96
- editor.data.upcastDispatcher.on( 'element:h1', dataViewModelH1Insertion, { priority: 'high' } );
97
- editor.data.upcastDispatcher.on( 'element:h2', dataViewModelH1Insertion, { priority: 'high' } );
98
- editor.data.upcastDispatcher.on( 'element:h3', dataViewModelH1Insertion, { priority: 'high' } );
99
-
100
- // Take care about correct `title` element structure.
101
- model.document.registerPostFixer( writer => this._fixTitleContent( writer ) );
102
-
103
- // Create and take care of correct position of a `title` element.
104
- model.document.registerPostFixer( writer => this._fixTitleElement( writer ) );
105
-
106
- // Create element for `Body` placeholder if it is missing.
107
- model.document.registerPostFixer( writer => this._fixBodyElement( writer ) );
108
-
109
- // Prevent from adding extra at the end of the document.
110
- model.document.registerPostFixer( writer => this._fixExtraParagraph( writer ) );
111
-
112
- // Attach `Title` and `Body` placeholders to the empty title and/or content.
113
- this._attachPlaceholders();
114
-
115
- // Attach Tab handling.
116
- this._attachTabPressHandling();
117
- }
118
-
119
- /**
120
- * Returns the title of the document. Note that because this plugin does not allow any formatting inside
121
- * the title element, the output of this method will be a plain text, with no HTML tags.
122
- *
123
- * It is not recommended to use this method together with features that insert markers to the
124
- * data output, like comments or track changes features. If such markers start in the title and end in the
125
- * body, the result of this method might be incorrect.
126
- *
127
- * @param {Object} [options] Additional configuration passed to the conversion process.
128
- * See {@link module:engine/controller/datacontroller~DataController#get `DataController#get`}.
129
- * @returns {String} The title of the document.
130
- */
131
- getTitle( options = {} ) {
132
- const titleElement = this._getTitleElement();
133
- const titleContentElement = titleElement.getChild( 0 );
134
-
135
- return this.editor.data.stringify( titleContentElement, options );
136
- }
137
-
138
- /**
139
- * Returns the body of the document.
140
- *
141
- * Note that it is not recommended to use this method together with features that insert markers to the
142
- * data output, like comments or track changes features. If such markers start in the title and end in the
143
- * body, the result of this method might be incorrect.
144
- *
145
- * @param {Object} [options] Additional configuration passed to the conversion process.
146
- * See {@link module:engine/controller/datacontroller~DataController#get `DataController#get`}.
147
- * @returns {String} The body of the document.
148
- */
149
- getBody( options = {} ) {
150
- const editor = this.editor;
151
- const data = editor.data;
152
- const model = editor.model;
153
- const root = editor.model.document.getRoot();
154
- const view = editor.editing.view;
155
- const viewWriter = new DowncastWriter( view.document );
156
-
157
- const rootRange = model.createRangeIn( root );
158
- const viewDocumentFragment = viewWriter.createDocumentFragment();
159
-
160
- // Find all markers that intersects with body.
161
- const bodyStartPosition = model.createPositionAfter( root.getChild( 0 ) );
162
- const bodyRange = model.createRange( bodyStartPosition, model.createPositionAt( root, 'end' ) );
163
-
164
- const markers = new Map();
165
-
166
- for ( const marker of model.markers ) {
167
- const intersection = bodyRange.getIntersection( marker.getRange() );
168
-
169
- if ( intersection ) {
170
- markers.set( marker.name, intersection );
171
- }
172
- }
173
-
174
- // Convert the entire root to view.
175
- data.mapper.clearBindings();
176
- data.mapper.bindElements( root, viewDocumentFragment );
177
- data.downcastDispatcher.convert( rootRange, markers, viewWriter, options );
178
-
179
- // Remove title element from view.
180
- viewWriter.remove( viewWriter.createRangeOn( viewDocumentFragment.getChild( 0 ) ) );
181
-
182
- // view -> data
183
- return editor.data.processor.toData( viewDocumentFragment );
184
- }
185
-
186
- /**
187
- * Returns the `title` element when it is in the document. Returns `undefined` otherwise.
188
- *
189
- * @private
190
- * @returns {module:engine/model/element~Element|undefined}
191
- */
192
- _getTitleElement() {
193
- const root = this.editor.model.document.getRoot();
194
-
195
- for ( const child of root.getChildren() ) {
196
- if ( isTitle( child ) ) {
197
- return child;
198
- }
199
- }
200
- }
201
-
202
- /**
203
- * Model post-fixer callback that ensures that `title` has only one `title-content` child.
204
- * All additional children should be moved after the `title` element and renamed to a paragraph.
205
- *
206
- * @private
207
- * @param {module:engine/model/writer~Writer} writer
208
- * @returns {Boolean}
209
- */
210
- _fixTitleContent( writer ) {
211
- const title = this._getTitleElement();
212
-
213
- // There's no title in the content - it will be created by _fixTitleElement post-fixer.
214
- if ( !title || title.maxOffset === 1 ) {
215
- return false;
216
- }
217
-
218
- const titleChildren = Array.from( title.getChildren() );
219
-
220
- // Skip first child because it is an allowed element.
221
- titleChildren.shift();
222
-
223
- for ( const titleChild of titleChildren ) {
224
- writer.move( writer.createRangeOn( titleChild ), title, 'after' );
225
- writer.rename( titleChild, 'paragraph' );
226
- }
227
-
228
- return true;
229
- }
230
-
231
- /**
232
- * Model post-fixer callback that creates a title element when it is missing,
233
- * takes care of the correct position of it and removes additional title elements.
234
- *
235
- * @private
236
- * @param {module:engine/model/writer~Writer} writer
237
- * @returns {Boolean}
238
- */
239
- _fixTitleElement( writer ) {
240
- const model = this.editor.model;
241
- const modelRoot = model.document.getRoot();
242
-
243
- const titleElements = Array.from( modelRoot.getChildren() ).filter( isTitle );
244
- const firstTitleElement = titleElements[ 0 ];
245
- const firstRootChild = modelRoot.getChild( 0 );
246
-
247
- // When title element is at the beginning of the document then try to fix additional
248
- // title elements (if there are any) and stop post-fixer as soon as possible.
249
- if ( firstRootChild.is( 'element', 'title' ) ) {
250
- return fixAdditionalTitleElements( titleElements, writer, model );
251
- }
252
-
253
- // When there is no title in the document and first element in the document cannot be changed
254
- // to the title then create an empty title element at the beginning of the document.
255
- if ( !firstTitleElement && !titleLikeElements.has( firstRootChild.name ) ) {
256
- const title = writer.createElement( 'title' );
257
-
258
- writer.insert( title, modelRoot );
259
- writer.insertElement( 'title-content', title );
260
-
261
- return true;
262
- }
263
-
264
- // At this stage, we are sure the title is somewhere in the content. It has to be fixed.
265
-
266
- // Change the first element in the document to the title if it can be changed (is title-like).
267
- if ( titleLikeElements.has( firstRootChild.name ) ) {
268
- changeElementToTitle( firstRootChild, writer, model );
269
- // Otherwise, move the first occurrence of the title element to the beginning of the document.
270
- } else {
271
- writer.move( writer.createRangeOn( firstTitleElement ), modelRoot, 0 );
272
- }
273
-
274
- fixAdditionalTitleElements( titleElements, writer, model );
275
-
276
- return true;
277
- }
278
-
279
- /**
280
- * Model post-fixer callback that adds an empty paragraph at the end of the document
281
- * when it is needed for the placeholder purposes.
282
- *
283
- * @private
284
- * @param {module:engine/model/writer~Writer} writer
285
- * @returns {Boolean}
286
- */
287
- _fixBodyElement( writer ) {
288
- const modelRoot = this.editor.model.document.getRoot();
289
-
290
- if ( modelRoot.childCount < 2 ) {
291
- this._bodyPlaceholder = writer.createElement( 'paragraph' );
292
- writer.insert( this._bodyPlaceholder, modelRoot, 1 );
293
-
294
- return true;
295
- }
296
-
297
- return false;
298
- }
299
-
300
- /**
301
- * Model post-fixer callback that removes a paragraph from the end of the document
302
- * if it was created for the placeholder purposes and is not needed anymore.
303
- *
304
- * @private
305
- * @param {module:engine/model/writer~Writer} writer
306
- * @returns {Boolean}
307
- */
308
- _fixExtraParagraph( writer ) {
309
- const root = this.editor.model.document.getRoot();
310
- const placeholder = this._bodyPlaceholder;
311
-
312
- if ( shouldRemoveLastParagraph( placeholder, root ) ) {
313
- this._bodyPlaceholder = null;
314
- writer.remove( placeholder );
315
-
316
- return true;
317
- }
318
-
319
- return false;
320
- }
321
-
322
- /**
323
- * Attaches the `Title` and `Body` placeholders to the title and/or content.
324
- *
325
- * @private
326
- */
327
- _attachPlaceholders() {
328
- const editor = this.editor;
329
- const t = editor.t;
330
- const view = editor.editing.view;
331
- const viewRoot = view.document.getRoot();
332
- const sourceElement = editor.sourceElement;
333
-
334
- const titlePlaceholder = editor.config.get( 'title.placeholder' ) || t( 'Type your title' );
335
- const bodyPlaceholder = editor.config.get( 'placeholder' ) ||
336
- sourceElement && sourceElement.tagName.toLowerCase() === 'textarea' && sourceElement.getAttribute( 'placeholder' ) ||
337
- t( 'Type or paste your content here.' );
338
-
339
- // Attach placeholder to the view title element.
340
- editor.editing.downcastDispatcher.on( 'insert:title-content', ( evt, data, conversionApi ) => {
341
- enablePlaceholder( {
342
- view,
343
- element: conversionApi.mapper.toViewElement( data.item ),
344
- text: titlePlaceholder,
345
- keepOnFocus: true
346
- } );
347
- } );
348
-
349
- // Attach placeholder to first element after a title element and remove it if it's not needed anymore.
350
- // First element after title can change so we need to observe all changes keep placeholder in sync.
351
- let oldBody;
352
-
353
- // This post-fixer runs after the model post-fixer so we can assume that
354
- // the second child in view root will always exist.
355
- view.document.registerPostFixer( writer => {
356
- const body = viewRoot.getChild( 1 );
357
- let hasChanged = false;
358
-
359
- // If body element has changed we need to disable placeholder on the previous element
360
- // and enable on the new one.
361
- if ( body !== oldBody ) {
362
- if ( oldBody ) {
363
- hidePlaceholder( writer, oldBody );
364
- writer.removeAttribute( 'data-placeholder', oldBody );
365
- }
366
-
367
- writer.setAttribute( 'data-placeholder', bodyPlaceholder, body );
368
- oldBody = body;
369
- hasChanged = true;
370
- }
371
-
372
- // Then we need to display placeholder if it is needed.
373
- // See: https://github.com/ckeditor/ckeditor5/issues/8689.
374
- if ( needsPlaceholder( body, true ) && viewRoot.childCount === 2 && body.name === 'p' ) {
375
- hasChanged = showPlaceholder( writer, body ) ? true : hasChanged;
376
- // Or hide if it is not needed.
377
- } else {
378
- hasChanged = hidePlaceholder( writer, body ) ? true : hasChanged;
379
- }
380
-
381
- return hasChanged;
382
- } );
383
- }
384
-
385
- /**
386
- * Creates navigation between the title and body sections using <kbd>Tab</kbd> and <kbd>Shift</kbd>+<kbd>Tab</kbd> keys.
387
- *
388
- * @private
389
- */
390
- _attachTabPressHandling() {
391
- const editor = this.editor;
392
- const model = editor.model;
393
-
394
- // Pressing <kbd>Tab</kbd> inside the title should move the caret to the body.
395
- editor.keystrokes.set( 'TAB', ( data, cancel ) => {
396
- model.change( writer => {
397
- const selection = model.document.selection;
398
- const selectedElements = Array.from( selection.getSelectedBlocks() );
399
-
400
- if ( selectedElements.length === 1 && selectedElements[ 0 ].is( 'element', 'title-content' ) ) {
401
- const firstBodyElement = model.document.getRoot().getChild( 1 );
402
- writer.setSelection( firstBodyElement, 0 );
403
- cancel();
404
- }
405
- } );
406
- } );
407
-
408
- // Pressing <kbd>Shift</kbd>+<kbd>Tab</kbd> at the beginning of the body should move the caret to the title.
409
- editor.keystrokes.set( 'SHIFT + TAB', ( data, cancel ) => {
410
- model.change( writer => {
411
- const selection = model.document.selection;
412
-
413
- if ( !selection.isCollapsed ) {
414
- return;
415
- }
416
-
417
- const root = editor.model.document.getRoot();
418
- const selectedElement = first( selection.getSelectedBlocks() );
419
- const selectionPosition = selection.getFirstPosition();
420
-
421
- const title = root.getChild( 0 );
422
- const body = root.getChild( 1 );
423
-
424
- if ( selectedElement === body && selectionPosition.isAtStart ) {
425
- writer.setSelection( title.getChild( 0 ), 0 );
426
- cancel();
427
- }
428
- } );
429
- } );
430
- }
431
- }
432
-
433
- // A view-to-model converter for the h1 that appears at the beginning of the document (a title element).
434
- //
435
- // @see module:engine/conversion/upcastdispatcher~UpcastDispatcher#event:element
436
- // @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
437
- // @param {Object} data An object containing conversion input, a placeholder for conversion output and possibly other values.
438
- // @param {module:engine/conversion/upcastdispatcher~UpcastConversionApi} conversionApi Conversion interface to be used by the callback.
439
- function dataViewModelH1Insertion( evt, data, conversionApi ) {
440
- const modelCursor = data.modelCursor;
441
- const viewItem = data.viewItem;
442
-
443
- if ( !modelCursor.isAtStart || !modelCursor.parent.is( 'element', '$root' ) ) {
444
- return;
445
- }
446
-
447
- if ( !conversionApi.consumable.consume( viewItem, { name: true } ) ) {
448
- return;
449
- }
450
-
451
- const modelWriter = conversionApi.writer;
452
-
453
- const title = modelWriter.createElement( 'title' );
454
- const titleContent = modelWriter.createElement( 'title-content' );
455
-
456
- modelWriter.append( titleContent, title );
457
- modelWriter.insert( title, modelCursor );
458
-
459
- conversionApi.convertChildren( viewItem, titleContent );
460
-
461
- conversionApi.updateConversionResult( title, data );
462
- }
463
-
464
- // Maps position from the beginning of the model `title` element to the beginning of the view `h1` element.
465
- //
466
- // <title>^<title-content>Foo</title-content></title> -> <h1>^Foo</h1>
467
- //
468
- // @param {module:editor/view/view~View} editingView
469
- function mapModelPositionToView( editingView ) {
470
- return ( evt, data ) => {
471
- const positionParent = data.modelPosition.parent;
472
-
473
- if ( !positionParent.is( 'element', 'title' ) ) {
474
- return;
475
- }
476
-
477
- const modelTitleElement = positionParent.parent;
478
- const viewElement = data.mapper.toViewElement( modelTitleElement );
479
-
480
- data.viewPosition = editingView.createPositionAt( viewElement, 0 );
481
- evt.stop();
482
- };
21
+ /**
22
+ * @inheritDoc
23
+ */
24
+ static get pluginName() {
25
+ return 'Title';
26
+ }
27
+ /**
28
+ * @inheritDoc
29
+ */
30
+ static get requires() {
31
+ return ['Paragraph'];
32
+ }
33
+ /**
34
+ * @inheritDoc
35
+ */
36
+ init() {
37
+ const editor = this.editor;
38
+ const model = editor.model;
39
+ this._bodyPlaceholder = null;
40
+ // To use the schema for disabling some features when the selection is inside the title element
41
+ // it is needed to create the following structure:
42
+ //
43
+ // <title>
44
+ // <title-content>The title text</title-content>
45
+ // </title>
46
+ //
47
+ // See: https://github.com/ckeditor/ckeditor5/issues/2005.
48
+ model.schema.register('title', { isBlock: true, allowIn: '$root' });
49
+ model.schema.register('title-content', { isBlock: true, allowIn: 'title', allowAttributes: ['alignment'] });
50
+ model.schema.extend('$text', { allowIn: 'title-content' });
51
+ // Disallow all attributes in `title-content`.
52
+ model.schema.addAttributeCheck(context => {
53
+ if (context.endsWith('title-content $text')) {
54
+ return false;
55
+ }
56
+ });
57
+ // Because `title` is represented by two elements in the model
58
+ // but only one in the view, it is needed to adjust Mapper.
59
+ editor.editing.mapper.on('modelToViewPosition', mapModelPositionToView(editor.editing.view));
60
+ editor.data.mapper.on('modelToViewPosition', mapModelPositionToView(editor.editing.view));
61
+ // Conversion.
62
+ editor.conversion.for('downcast').elementToElement({ model: 'title-content', view: 'h1' });
63
+ editor.conversion.for('downcast').add(dispatcher => dispatcher.on('insert:title', (evt, data, conversionApi) => {
64
+ conversionApi.consumable.consume(data.item, evt.name);
65
+ }));
66
+ // Custom converter is used for data v -> m conversion to avoid calling post-fixer when setting data.
67
+ // See https://github.com/ckeditor/ckeditor5/issues/2036.
68
+ editor.data.upcastDispatcher.on('element:h1', dataViewModelH1Insertion, { priority: 'high' });
69
+ editor.data.upcastDispatcher.on('element:h2', dataViewModelH1Insertion, { priority: 'high' });
70
+ editor.data.upcastDispatcher.on('element:h3', dataViewModelH1Insertion, { priority: 'high' });
71
+ // Take care about correct `title` element structure.
72
+ model.document.registerPostFixer(writer => this._fixTitleContent(writer));
73
+ // Create and take care of correct position of a `title` element.
74
+ model.document.registerPostFixer(writer => this._fixTitleElement(writer));
75
+ // Create element for `Body` placeholder if it is missing.
76
+ model.document.registerPostFixer(writer => this._fixBodyElement(writer));
77
+ // Prevent from adding extra at the end of the document.
78
+ model.document.registerPostFixer(writer => this._fixExtraParagraph(writer));
79
+ // Attach `Title` and `Body` placeholders to the empty title and/or content.
80
+ this._attachPlaceholders();
81
+ // Attach Tab handling.
82
+ this._attachTabPressHandling();
83
+ }
84
+ /**
85
+ * Returns the title of the document. Note that because this plugin does not allow any formatting inside
86
+ * the title element, the output of this method will be a plain text, with no HTML tags.
87
+ *
88
+ * It is not recommended to use this method together with features that insert markers to the
89
+ * data output, like comments or track changes features. If such markers start in the title and end in the
90
+ * body, the result of this method might be incorrect.
91
+ *
92
+ * @param options Additional configuration passed to the conversion process.
93
+ * See {@link module:engine/controller/datacontroller~DataController#get `DataController#get`}.
94
+ * @returns The title of the document.
95
+ */
96
+ getTitle(options = {}) {
97
+ const titleElement = this._getTitleElement();
98
+ const titleContentElement = titleElement.getChild(0);
99
+ return this.editor.data.stringify(titleContentElement, options);
100
+ }
101
+ /**
102
+ * Returns the body of the document.
103
+ *
104
+ * Note that it is not recommended to use this method together with features that insert markers to the
105
+ * data output, like comments or track changes features. If such markers start in the title and end in the
106
+ * body, the result of this method might be incorrect.
107
+ *
108
+ * @param options Additional configuration passed to the conversion process.
109
+ * See {@link module:engine/controller/datacontroller~DataController#get `DataController#get`}.
110
+ * @returns The body of the document.
111
+ */
112
+ getBody(options = {}) {
113
+ const editor = this.editor;
114
+ const data = editor.data;
115
+ const model = editor.model;
116
+ const root = editor.model.document.getRoot();
117
+ const view = editor.editing.view;
118
+ const viewWriter = new DowncastWriter(view.document);
119
+ const rootRange = model.createRangeIn(root);
120
+ const viewDocumentFragment = viewWriter.createDocumentFragment();
121
+ // Find all markers that intersects with body.
122
+ const bodyStartPosition = model.createPositionAfter(root.getChild(0));
123
+ const bodyRange = model.createRange(bodyStartPosition, model.createPositionAt(root, 'end'));
124
+ const markers = new Map();
125
+ for (const marker of model.markers) {
126
+ const intersection = bodyRange.getIntersection(marker.getRange());
127
+ if (intersection) {
128
+ markers.set(marker.name, intersection);
129
+ }
130
+ }
131
+ // Convert the entire root to view.
132
+ data.mapper.clearBindings();
133
+ data.mapper.bindElements(root, viewDocumentFragment);
134
+ data.downcastDispatcher.convert(rootRange, markers, viewWriter, options);
135
+ // Remove title element from view.
136
+ viewWriter.remove(viewWriter.createRangeOn(viewDocumentFragment.getChild(0)));
137
+ // view -> data
138
+ return editor.data.processor.toData(viewDocumentFragment);
139
+ }
140
+ /**
141
+ * Returns the `title` element when it is in the document. Returns `undefined` otherwise.
142
+ */
143
+ _getTitleElement() {
144
+ const root = this.editor.model.document.getRoot();
145
+ for (const child of root.getChildren()) {
146
+ if (isTitle(child)) {
147
+ return child;
148
+ }
149
+ }
150
+ }
151
+ /**
152
+ * Model post-fixer callback that ensures that `title` has only one `title-content` child.
153
+ * All additional children should be moved after the `title` element and renamed to a paragraph.
154
+ */
155
+ _fixTitleContent(writer) {
156
+ const title = this._getTitleElement();
157
+ // There's no title in the content - it will be created by _fixTitleElement post-fixer.
158
+ if (!title || title.maxOffset === 1) {
159
+ return false;
160
+ }
161
+ const titleChildren = Array.from(title.getChildren());
162
+ // Skip first child because it is an allowed element.
163
+ titleChildren.shift();
164
+ for (const titleChild of titleChildren) {
165
+ writer.move(writer.createRangeOn(titleChild), title, 'after');
166
+ writer.rename(titleChild, 'paragraph');
167
+ }
168
+ return true;
169
+ }
170
+ /**
171
+ * Model post-fixer callback that creates a title element when it is missing,
172
+ * takes care of the correct position of it and removes additional title elements.
173
+ */
174
+ _fixTitleElement(writer) {
175
+ const model = this.editor.model;
176
+ const modelRoot = model.document.getRoot();
177
+ const titleElements = Array.from(modelRoot.getChildren()).filter(isTitle);
178
+ const firstTitleElement = titleElements[0];
179
+ const firstRootChild = modelRoot.getChild(0);
180
+ // When title element is at the beginning of the document then try to fix additional
181
+ // title elements (if there are any) and stop post-fixer as soon as possible.
182
+ if (firstRootChild.is('element', 'title')) {
183
+ return fixAdditionalTitleElements(titleElements, writer, model);
184
+ }
185
+ // When there is no title in the document and first element in the document cannot be changed
186
+ // to the title then create an empty title element at the beginning of the document.
187
+ if (!firstTitleElement && !titleLikeElements.has(firstRootChild.name)) {
188
+ const title = writer.createElement('title');
189
+ writer.insert(title, modelRoot);
190
+ writer.insertElement('title-content', title);
191
+ return true;
192
+ }
193
+ // At this stage, we are sure the title is somewhere in the content. It has to be fixed.
194
+ // Change the first element in the document to the title if it can be changed (is title-like).
195
+ if (titleLikeElements.has(firstRootChild.name)) {
196
+ changeElementToTitle(firstRootChild, writer, model);
197
+ // Otherwise, move the first occurrence of the title element to the beginning of the document.
198
+ }
199
+ else {
200
+ writer.move(writer.createRangeOn(firstTitleElement), modelRoot, 0);
201
+ }
202
+ fixAdditionalTitleElements(titleElements, writer, model);
203
+ return true;
204
+ }
205
+ /**
206
+ * Model post-fixer callback that adds an empty paragraph at the end of the document
207
+ * when it is needed for the placeholder purposes.
208
+ */
209
+ _fixBodyElement(writer) {
210
+ const modelRoot = this.editor.model.document.getRoot();
211
+ if (modelRoot.childCount < 2) {
212
+ this._bodyPlaceholder = writer.createElement('paragraph');
213
+ writer.insert(this._bodyPlaceholder, modelRoot, 1);
214
+ return true;
215
+ }
216
+ return false;
217
+ }
218
+ /**
219
+ * Model post-fixer callback that removes a paragraph from the end of the document
220
+ * if it was created for the placeholder purposes and is not needed anymore.
221
+ */
222
+ _fixExtraParagraph(writer) {
223
+ const root = this.editor.model.document.getRoot();
224
+ const placeholder = this._bodyPlaceholder;
225
+ if (shouldRemoveLastParagraph(placeholder, root)) {
226
+ this._bodyPlaceholder = null;
227
+ writer.remove(placeholder);
228
+ return true;
229
+ }
230
+ return false;
231
+ }
232
+ /**
233
+ * Attaches the `Title` and `Body` placeholders to the title and/or content.
234
+ */
235
+ _attachPlaceholders() {
236
+ const editor = this.editor;
237
+ const t = editor.t;
238
+ const view = editor.editing.view;
239
+ const viewRoot = view.document.getRoot();
240
+ const sourceElement = editor.sourceElement;
241
+ const titlePlaceholder = editor.config.get('title.placeholder') || t('Type your title');
242
+ const bodyPlaceholder = editor.config.get('placeholder') ||
243
+ sourceElement && sourceElement.tagName.toLowerCase() === 'textarea' && sourceElement.getAttribute('placeholder') ||
244
+ t('Type or paste your content here.');
245
+ // Attach placeholder to the view title element.
246
+ editor.editing.downcastDispatcher.on('insert:title-content', (evt, data, conversionApi) => {
247
+ enablePlaceholder({
248
+ view,
249
+ element: conversionApi.mapper.toViewElement(data.item),
250
+ text: titlePlaceholder,
251
+ keepOnFocus: true
252
+ });
253
+ });
254
+ // Attach placeholder to first element after a title element and remove it if it's not needed anymore.
255
+ // First element after title can change so we need to observe all changes keep placeholder in sync.
256
+ let oldBody;
257
+ // This post-fixer runs after the model post-fixer so we can assume that
258
+ // the second child in view root will always exist.
259
+ view.document.registerPostFixer(writer => {
260
+ const body = viewRoot.getChild(1);
261
+ let hasChanged = false;
262
+ // If body element has changed we need to disable placeholder on the previous element
263
+ // and enable on the new one.
264
+ if (body !== oldBody) {
265
+ if (oldBody) {
266
+ hidePlaceholder(writer, oldBody);
267
+ writer.removeAttribute('data-placeholder', oldBody);
268
+ }
269
+ writer.setAttribute('data-placeholder', bodyPlaceholder, body);
270
+ oldBody = body;
271
+ hasChanged = true;
272
+ }
273
+ // Then we need to display placeholder if it is needed.
274
+ // See: https://github.com/ckeditor/ckeditor5/issues/8689.
275
+ if (needsPlaceholder(body, true) && viewRoot.childCount === 2 && body.name === 'p') {
276
+ hasChanged = showPlaceholder(writer, body) ? true : hasChanged;
277
+ // Or hide if it is not needed.
278
+ }
279
+ else {
280
+ hasChanged = hidePlaceholder(writer, body) ? true : hasChanged;
281
+ }
282
+ return hasChanged;
283
+ });
284
+ }
285
+ /**
286
+ * Creates navigation between the title and body sections using <kbd>Tab</kbd> and <kbd>Shift</kbd>+<kbd>Tab</kbd> keys.
287
+ */
288
+ _attachTabPressHandling() {
289
+ const editor = this.editor;
290
+ const model = editor.model;
291
+ // Pressing <kbd>Tab</kbd> inside the title should move the caret to the body.
292
+ editor.keystrokes.set('TAB', (data, cancel) => {
293
+ model.change(writer => {
294
+ const selection = model.document.selection;
295
+ const selectedElements = Array.from(selection.getSelectedBlocks());
296
+ if (selectedElements.length === 1 && selectedElements[0].is('element', 'title-content')) {
297
+ const firstBodyElement = model.document.getRoot().getChild(1);
298
+ writer.setSelection(firstBodyElement, 0);
299
+ cancel();
300
+ }
301
+ });
302
+ });
303
+ // Pressing <kbd>Shift</kbd>+<kbd>Tab</kbd> at the beginning of the body should move the caret to the title.
304
+ editor.keystrokes.set('SHIFT + TAB', (data, cancel) => {
305
+ model.change(writer => {
306
+ const selection = model.document.selection;
307
+ if (!selection.isCollapsed) {
308
+ return;
309
+ }
310
+ const root = editor.model.document.getRoot();
311
+ const selectedElement = first(selection.getSelectedBlocks());
312
+ const selectionPosition = selection.getFirstPosition();
313
+ const title = root.getChild(0);
314
+ const body = root.getChild(1);
315
+ if (selectedElement === body && selectionPosition.isAtStart) {
316
+ writer.setSelection(title.getChild(0), 0);
317
+ cancel();
318
+ }
319
+ });
320
+ });
321
+ }
483
322
  }
484
-
485
- // Returns true when given element is a title. Returns false otherwise.
486
- //
487
- // @param {module:engine/model/element~Element} element
488
- // @returns {Boolean}
489
- function isTitle( element ) {
490
- return element.is( 'element', 'title' );
491
- }
492
-
493
- // Changes the given element to the title element.
494
- //
495
- // @param {module:engine/model/element~Element} element
496
- // @param {module:engine/model/writer~Writer} writer
497
- // @param {module:engine/model/model~Model} model
498
- function changeElementToTitle( element, writer, model ) {
499
- const title = writer.createElement( 'title' );
500
-
501
- writer.insert( title, element, 'before' );
502
- writer.insert( element, title, 0 );
503
- writer.rename( element, 'title-content' );
504
- model.schema.removeDisallowedAttributes( [ element ], writer );
323
+ /**
324
+ * A view-to-model converter for the h1 that appears at the beginning of the document (a title element).
325
+ *
326
+ * @see module:engine/conversion/upcastdispatcher~UpcastDispatcher#event:element
327
+ * @param evt An object containing information about the fired event.
328
+ * @param data An object containing conversion input, a placeholder for conversion output and possibly other values.
329
+ * @param conversionApi Conversion interface to be used by the callback.
330
+ */
331
+ function dataViewModelH1Insertion(evt, data, conversionApi) {
332
+ const modelCursor = data.modelCursor;
333
+ const viewItem = data.viewItem;
334
+ if (!modelCursor.isAtStart || !modelCursor.parent.is('element', '$root')) {
335
+ return;
336
+ }
337
+ if (!conversionApi.consumable.consume(viewItem, { name: true })) {
338
+ return;
339
+ }
340
+ const modelWriter = conversionApi.writer;
341
+ const title = modelWriter.createElement('title');
342
+ const titleContent = modelWriter.createElement('title-content');
343
+ modelWriter.append(titleContent, title);
344
+ modelWriter.insert(title, modelCursor);
345
+ conversionApi.convertChildren(viewItem, titleContent);
346
+ conversionApi.updateConversionResult(title, data);
505
347
  }
506
-
507
- // Loops over the list of title elements and fixes additional ones.
508
- //
509
- // @param {Array.<module:engine/model/element~Element>} titleElements
510
- // @param {module:engine/model/writer~Writer} writer
511
- // @param {module:engine/model/model~Model} model
512
- // @returns {Boolean} Returns true when there was any change. Returns false otherwise.
513
- function fixAdditionalTitleElements( titleElements, writer, model ) {
514
- let hasChanged = false;
515
-
516
- for ( const title of titleElements ) {
517
- if ( title.index !== 0 ) {
518
- fixTitleElement( title, writer, model );
519
- hasChanged = true;
520
- }
521
- }
522
-
523
- return hasChanged;
348
+ /**
349
+ * Maps position from the beginning of the model `title` element to the beginning of the view `h1` element.
350
+ *
351
+ * ```html
352
+ * <title>^<title-content>Foo</title-content></title> -> <h1>^Foo</h1>
353
+ * ```
354
+ */
355
+ function mapModelPositionToView(editingView) {
356
+ return (evt, data) => {
357
+ const positionParent = data.modelPosition.parent;
358
+ if (!positionParent.is('element', 'title')) {
359
+ return;
360
+ }
361
+ const modelTitleElement = positionParent.parent;
362
+ const viewElement = data.mapper.toViewElement(modelTitleElement);
363
+ data.viewPosition = editingView.createPositionAt(viewElement, 0);
364
+ evt.stop();
365
+ };
524
366
  }
525
-
526
- // Changes given title element to a paragraph or removes it when it is empty.
527
- //
528
- // @param {module:engine/model/element~Element} title
529
- // @param {module:engine/model/writer~Writer} writer
530
- // @param {module:engine/model/model~Model} model
531
- function fixTitleElement( title, writer, model ) {
532
- const child = title.getChild( 0 );
533
-
534
- // Empty title should be removed.
535
- // It is created as a result of pasting to the title element.
536
- if ( child.isEmpty ) {
537
- writer.remove( title );
538
-
539
- return;
540
- }
541
-
542
- writer.move( writer.createRangeOn( child ), title, 'before' );
543
- writer.rename( child, 'paragraph' );
544
- writer.remove( title );
545
- model.schema.removeDisallowedAttributes( [ child ], writer );
367
+ /**
368
+ * @returns Returns true when given element is a title. Returns false otherwise.
369
+ */
370
+ function isTitle(element) {
371
+ return element.is('element', 'title');
546
372
  }
547
-
548
- // Returns true when the last paragraph in the document was created only for the placeholder
549
- // purpose and it's not needed anymore. Returns false otherwise.
550
- //
551
- // @param {module:engine/model/rootelement~RootElement} root
552
- // @param {module:engine/model/element~Element} placeholder
553
- // @returns {Boolean}
554
- function shouldRemoveLastParagraph( placeholder, root ) {
555
- if ( !placeholder || !placeholder.is( 'element', 'paragraph' ) || placeholder.childCount ) {
556
- return false;
557
- }
558
-
559
- if ( root.childCount <= 2 || root.getChild( root.childCount - 1 ) !== placeholder ) {
560
- return false;
561
- }
562
-
563
- return true;
373
+ /**
374
+ * Changes the given element to the title element.
375
+ */
376
+ function changeElementToTitle(element, writer, model) {
377
+ const title = writer.createElement('title');
378
+ writer.insert(title, element, 'before');
379
+ writer.insert(element, title, 0);
380
+ writer.rename(element, 'title-content');
381
+ model.schema.removeDisallowedAttributes([element], writer);
564
382
  }
565
-
566
383
  /**
567
- * The configuration of the {@link module:heading/title~Title title feature}.
568
- *
569
- * Read more in {@link module:heading/title~TitleConfig}.
384
+ * Loops over the list of title elements and fixes additional ones.
570
385
  *
571
- * @member {module:heading/title~TitleConfig} module:core/editor/editorconfig~EditorConfig#title
386
+ * @returns Returns true when there was any change. Returns false otherwise.
572
387
  */
573
-
388
+ function fixAdditionalTitleElements(titleElements, writer, model) {
389
+ let hasChanged = false;
390
+ for (const title of titleElements) {
391
+ if (title.index !== 0) {
392
+ fixTitleElement(title, writer, model);
393
+ hasChanged = true;
394
+ }
395
+ }
396
+ return hasChanged;
397
+ }
574
398
  /**
575
- * The configuration of the {@link module:heading/title~Title title feature}.
576
- *
577
- * ClassicEditor
578
- * .create( document.querySelector( '#editor' ), {
579
- * plugins: [ Title, ... ],
580
- * title: {
581
- * placeholder: 'My custom placeholder for the title'
582
- * },
583
- * placeholder: 'My custom placeholder for the body'
584
- * } )
585
- * .then( ... )
586
- * .catch( ... );
587
- *
588
- * See {@link module:core/editor/editorconfig~EditorConfig all editor configuration options}.
589
- *
590
- * @interface TitleConfig
399
+ * Changes given title element to a paragraph or removes it when it is empty.
591
400
  */
592
-
401
+ function fixTitleElement(title, writer, model) {
402
+ const child = title.getChild(0);
403
+ // Empty title should be removed.
404
+ // It is created as a result of pasting to the title element.
405
+ if (child.isEmpty) {
406
+ writer.remove(title);
407
+ return;
408
+ }
409
+ writer.move(writer.createRangeOn(child), title, 'before');
410
+ writer.rename(child, 'paragraph');
411
+ writer.remove(title);
412
+ model.schema.removeDisallowedAttributes([child], writer);
413
+ }
593
414
  /**
594
- * Defines a custom value of the placeholder for the title field.
595
- *
596
- * Read more in {@link module:heading/title~TitleConfig}.
597
- *
598
- * @member {String} module:heading/title~TitleConfig#placeholder
415
+ * Returns true when the last paragraph in the document was created only for the placeholder
416
+ * purpose and it's not needed anymore. Returns false otherwise.
599
417
  */
418
+ function shouldRemoveLastParagraph(placeholder, root) {
419
+ if (!placeholder || !placeholder.is('element', 'paragraph') || placeholder.childCount) {
420
+ return false;
421
+ }
422
+ if (root.childCount <= 2 || root.getChild(root.childCount - 1) !== placeholder) {
423
+ return false;
424
+ }
425
+ return true;
426
+ }