title.js 18 KB

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