8
0

imagecaptionediting.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module image/imagecaption/imagecaptionediting
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import { isImage } from '../image/utils';
  10. import { captionElementCreator, getCaptionFromImage, matchImageCaption } from './utils';
  11. /**
  12. * The image caption engine plugin.
  13. *
  14. * It registers proper converters. It takes care of adding a caption element if the image without it is inserted
  15. * to the model document.
  16. *
  17. * @extends module:core/plugin~Plugin
  18. */
  19. export default class ImageCaptionEditing extends Plugin {
  20. /**
  21. * @inheritDoc
  22. */
  23. static get pluginName() {
  24. return 'ImageCaptionEditing';
  25. }
  26. /**
  27. * @inheritDoc
  28. */
  29. init() {
  30. const editor = this.editor;
  31. const view = editor.editing.view;
  32. const schema = editor.model.schema;
  33. const data = editor.data;
  34. const editing = editor.editing;
  35. const t = editor.t;
  36. /**
  37. * The last selected caption editable.
  38. * It is used for hiding the editable when it is empty and the image widget is no longer selected.
  39. *
  40. * @private
  41. * @member {module:engine/view/editableelement~EditableElement} #_lastSelectedCaption
  42. */
  43. // Schema configuration.
  44. schema.register( 'caption', {
  45. allowIn: 'image',
  46. allowContentOf: '$block',
  47. isLimit: true
  48. } );
  49. // Add caption element to each image inserted without it.
  50. editor.model.document.registerPostFixer( writer => this._insertMissingModelCaptionElement( writer ) );
  51. // View to model converter for the data pipeline.
  52. editor.conversion.for( 'upcast' ).elementToElement( {
  53. view: matchImageCaption,
  54. model: 'caption'
  55. } );
  56. // Model to view converter for the data pipeline.
  57. const createCaptionForData = writer => writer.createContainerElement( 'figcaption' );
  58. data.downcastDispatcher.on( 'insert:caption', captionModelToView( createCaptionForData, false ) );
  59. // Model to view converter for the editing pipeline.
  60. const createCaptionForEditing = captionElementCreator( view, t( 'Enter image caption' ) );
  61. editing.downcastDispatcher.on( 'insert:caption', captionModelToView( createCaptionForEditing ) );
  62. // Always show caption in view when something is inserted in model.
  63. editing.downcastDispatcher.on(
  64. 'insert',
  65. this._fixCaptionVisibility( data => data.item ),
  66. { priority: 'high' }
  67. );
  68. // Hide caption when everything is removed from it.
  69. editing.downcastDispatcher.on( 'remove', this._fixCaptionVisibility( data => data.position.parent ), { priority: 'high' } );
  70. // Update caption visibility on view in post fixer.
  71. view.document.registerPostFixer( writer => this._updateCaptionVisibility( writer ) );
  72. }
  73. /**
  74. * Updates the view before each rendering, making sure that empty captions (so unnecessary ones) are hidden
  75. * and then visible when the image is selected.
  76. *
  77. * @private
  78. * @param {module:engine/view/downcastwriter~DowncastWriter} viewWriter
  79. * @returns {Boolean} Returns `true` when the view is updated.
  80. */
  81. _updateCaptionVisibility( viewWriter ) {
  82. const mapper = this.editor.editing.mapper;
  83. const lastCaption = this._lastSelectedCaption;
  84. let viewCaption;
  85. // If whole image is selected.
  86. const modelSelection = this.editor.model.document.selection;
  87. const selectedElement = modelSelection.getSelectedElement();
  88. if ( selectedElement && selectedElement.is( 'element', 'image' ) ) {
  89. const modelCaption = getCaptionFromImage( selectedElement );
  90. viewCaption = mapper.toViewElement( modelCaption );
  91. }
  92. // If selection is placed inside caption.
  93. const position = modelSelection.getFirstPosition();
  94. const modelCaption = getParentCaption( position.parent );
  95. if ( modelCaption ) {
  96. viewCaption = mapper.toViewElement( modelCaption );
  97. }
  98. // Is currently any caption selected?
  99. if ( viewCaption ) {
  100. // Was any caption selected before?
  101. if ( lastCaption ) {
  102. // Same caption as before?
  103. if ( lastCaption === viewCaption ) {
  104. return showCaption( viewCaption, viewWriter );
  105. } else {
  106. hideCaptionIfEmpty( lastCaption, viewWriter );
  107. this._lastSelectedCaption = viewCaption;
  108. return showCaption( viewCaption, viewWriter );
  109. }
  110. } else {
  111. this._lastSelectedCaption = viewCaption;
  112. return showCaption( viewCaption, viewWriter );
  113. }
  114. } else {
  115. // Was any caption selected before?
  116. if ( lastCaption ) {
  117. const viewModified = hideCaptionIfEmpty( lastCaption, viewWriter );
  118. this._lastSelectedCaption = null;
  119. return viewModified;
  120. } else {
  121. return false;
  122. }
  123. }
  124. }
  125. /**
  126. * Returns a converter that fixes caption visibility during the model-to-view conversion.
  127. * Checks if the changed node is placed inside the caption element and fixes its visibility in the view.
  128. *
  129. * @private
  130. * @param {Function} nodeFinder
  131. * @returns {Function}
  132. */
  133. _fixCaptionVisibility( nodeFinder ) {
  134. return ( evt, data, conversionApi ) => {
  135. const node = nodeFinder( data );
  136. const modelCaption = getParentCaption( node );
  137. const mapper = this.editor.editing.mapper;
  138. const viewWriter = conversionApi.writer;
  139. if ( modelCaption ) {
  140. const viewCaption = mapper.toViewElement( modelCaption );
  141. if ( viewCaption ) {
  142. if ( modelCaption.childCount ) {
  143. viewWriter.removeClass( 'ck-hidden', viewCaption );
  144. } else {
  145. viewWriter.addClass( 'ck-hidden', viewCaption );
  146. }
  147. }
  148. }
  149. };
  150. }
  151. /**
  152. * Checks whether the data inserted to the model document have an image element that has no caption element inside it.
  153. * If there is none, it adds it to the image element.
  154. *
  155. * @private
  156. * @param {module:engine/model/writer~Writer} writer The writer to make changes with.
  157. * @returns {Boolean} `true` if any change was applied, `false` otherwise.
  158. */
  159. _insertMissingModelCaptionElement( writer ) {
  160. const model = this.editor.model;
  161. const changes = model.document.differ.getChanges();
  162. const imagesWithoutCaption = [];
  163. for ( const entry of changes ) {
  164. if ( entry.type == 'insert' && entry.name != '$text' ) {
  165. const item = entry.position.nodeAfter;
  166. if ( item.is( 'element', 'image' ) && !getCaptionFromImage( item ) ) {
  167. imagesWithoutCaption.push( item );
  168. }
  169. // Check elements with children for nested images.
  170. if ( !item.is( 'element', 'image' ) && item.childCount ) {
  171. for ( const nestedItem of model.createRangeIn( item ).getItems() ) {
  172. if ( nestedItem.is( 'element', 'image' ) && !getCaptionFromImage( nestedItem ) ) {
  173. imagesWithoutCaption.push( nestedItem );
  174. }
  175. }
  176. }
  177. }
  178. }
  179. for ( const image of imagesWithoutCaption ) {
  180. writer.appendElement( 'caption', image );
  181. }
  182. return !!imagesWithoutCaption.length;
  183. }
  184. }
  185. // Creates a converter that converts image caption model element to view element.
  186. //
  187. // @private
  188. // @param {Function} elementCreator
  189. // @param {Boolean} [hide=true] When set to `false` view element will not be inserted when it's empty.
  190. // @returns {Function}
  191. function captionModelToView( elementCreator, hide = true ) {
  192. return ( evt, data, conversionApi ) => {
  193. const captionElement = data.item;
  194. // Return if element shouldn't be present when empty.
  195. if ( !captionElement.childCount && !hide ) {
  196. return;
  197. }
  198. if ( isImage( captionElement.parent ) ) {
  199. if ( !conversionApi.consumable.consume( data.item, 'insert' ) ) {
  200. return;
  201. }
  202. const viewImage = conversionApi.mapper.toViewElement( data.range.start.parent );
  203. const viewCaption = elementCreator( conversionApi.writer );
  204. const viewWriter = conversionApi.writer;
  205. // Hide if empty.
  206. if ( !captionElement.childCount ) {
  207. viewWriter.addClass( 'ck-hidden', viewCaption );
  208. }
  209. insertViewCaptionAndBind( viewCaption, data.item, viewImage, conversionApi );
  210. }
  211. };
  212. }
  213. // Inserts `viewCaption` at the end of `viewImage` and binds it to `modelCaption`.
  214. //
  215. // @private
  216. // @param {module:engine/view/containerelement~ContainerElement} viewCaption
  217. // @param {module:engine/model/element~Element} modelCaption
  218. // @param {module:engine/view/containerelement~ContainerElement} viewImage
  219. // @param {module:engine/conversion/downcastdispatcher~DowncastConversionApi} conversionApi
  220. function insertViewCaptionAndBind( viewCaption, modelCaption, viewImage, conversionApi ) {
  221. const viewPosition = conversionApi.writer.createPositionAt( viewImage, 'end' );
  222. conversionApi.writer.insert( viewPosition, viewCaption );
  223. conversionApi.mapper.bindElements( modelCaption, viewCaption );
  224. }
  225. // Checks if the provided node or one of its ancestors is a caption element, and returns it.
  226. //
  227. // @private
  228. // @param {module:engine/model/node~Node} node
  229. // @returns {module:engine/model/element~Element|null}
  230. function getParentCaption( node ) {
  231. const ancestors = node.getAncestors( { includeSelf: true } );
  232. const caption = ancestors.find( ancestor => ancestor.name == 'caption' );
  233. if ( caption && caption.parent && caption.parent.name == 'image' ) {
  234. return caption;
  235. }
  236. return null;
  237. }
  238. // Hides a given caption in the view if it is empty.
  239. //
  240. // @private
  241. // @param {module:engine/view/containerelement~ContainerElement} caption
  242. // @param {module:engine/view/downcastwriter~DowncastWriter} viewWriter
  243. // @returns {Boolean} Returns `true` if the view was modified.
  244. function hideCaptionIfEmpty( caption, viewWriter ) {
  245. if ( !caption.childCount && !caption.hasClass( 'ck-hidden' ) ) {
  246. viewWriter.addClass( 'ck-hidden', caption );
  247. return true;
  248. }
  249. return false;
  250. }
  251. // Shows the caption.
  252. //
  253. // @private
  254. // @param {module:engine/view/containerelement~ContainerElement} caption
  255. // @param {module:engine/view/downcastwriter~DowncastWriter} viewWriter
  256. // @returns {Boolean} Returns `true` if the view was modified.
  257. function showCaption( caption, viewWriter ) {
  258. if ( caption.hasClass( 'ck-hidden' ) ) {
  259. viewWriter.removeClass( 'ck-hidden', caption );
  260. return true;
  261. }
  262. return false;
  263. }