utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 list/utils
  7. */
  8. import { getFillerOffset } from '@ckeditor/ckeditor5-engine/src/view/containerelement';
  9. import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';
  10. /**
  11. * Creates a list item {@link module:engine/view/containerelement~ContainerElement}.
  12. *
  13. * @param {module:engine/view/downcastwriter~DowncastWriter} writer The writer instance.
  14. * @returns {module:engine/view/containerelement~ContainerElement}
  15. */
  16. export function createViewListItemElement( writer ) {
  17. const viewItem = writer.createContainerElement( 'li' );
  18. viewItem.getFillerOffset = getListItemFillerOffset;
  19. return viewItem;
  20. }
  21. /**
  22. * Helper function that creates a `<ul><li></li></ul>` or (`<ol>`) structure out of the given `modelItem` model `listItem` element.
  23. * Then, it binds the created view list item (`<li>`) with the model `listItem` element.
  24. * The function then returns the created view list item (`<li>`).
  25. *
  26. * @param {module:engine/model/item~Item} modelItem Model list item.
  27. * @param {module:engine/conversion/upcastdispatcher~UpcastConversionApi} conversionApi Conversion interface.
  28. * @returns {module:engine/view/containerelement~ContainerElement} View list element.
  29. */
  30. export function generateLiInUl( modelItem, conversionApi ) {
  31. const mapper = conversionApi.mapper;
  32. const viewWriter = conversionApi.writer;
  33. const listType = modelItem.getAttribute( 'listType' ) == 'numbered' ? 'ol' : 'ul';
  34. const viewItem = createViewListItemElement( viewWriter );
  35. const viewList = viewWriter.createContainerElement( listType, null );
  36. viewWriter.insert( viewWriter.createPositionAt( viewList, 0 ), viewItem );
  37. mapper.bindElements( modelItem, viewItem );
  38. return viewItem;
  39. }
  40. /**
  41. * Helper function that inserts a view list at a correct place and merges it with its siblings.
  42. * It takes a model list item element (`modelItem`) and a corresponding view list item element (`injectedItem`). The view list item
  43. * should be in a view list element (`<ul>` or `<ol>`) and should be its only child.
  44. * See comments below to better understand the algorithm.
  45. *
  46. * @param {module:engine/view/item~Item} modelItem Model list item.
  47. * @param {module:engine/view/containerelement~ContainerElement} injectedItem
  48. * @param {module:engine/conversion/upcastdispatcher~UpcastConversionApi} conversionApi Conversion interface.
  49. * @param {module:engine/model/model~Model} model The model instance.
  50. */
  51. export function injectViewList( modelItem, injectedItem, conversionApi, model ) {
  52. const injectedList = injectedItem.parent;
  53. const mapper = conversionApi.mapper;
  54. const viewWriter = conversionApi.writer;
  55. // The position where the view list will be inserted.
  56. let insertPosition = mapper.toViewPosition( model.createPositionBefore( modelItem ) );
  57. // 1. Find the previous list item that has the same or smaller indent. Basically we are looking for the first model item
  58. // that is a "parent" or "sibling" of the injected model item.
  59. // If there is no such list item, it means that the injected list item is the first item in "its list".
  60. const refItem = getSiblingListItem( modelItem.previousSibling, {
  61. sameIndent: true,
  62. smallerIndent: true,
  63. listIndent: modelItem.getAttribute( 'listIndent' )
  64. } );
  65. const prevItem = modelItem.previousSibling;
  66. if ( refItem && refItem.getAttribute( 'listIndent' ) == modelItem.getAttribute( 'listIndent' ) ) {
  67. // There is a list item with the same indent - we found the same-level sibling.
  68. // Break the list after it. The inserted view item will be added in the broken space.
  69. const viewItem = mapper.toViewElement( refItem );
  70. insertPosition = viewWriter.breakContainer( viewWriter.createPositionAfter( viewItem ) );
  71. } else {
  72. // There is no list item with the same indent. Check the previous model item.
  73. if ( prevItem && prevItem.name == 'listItem' ) {
  74. // If it is a list item, it has to have a lower indent.
  75. // It means that the inserted item should be added to it as its nested item.
  76. insertPosition = mapper.toViewPosition( model.createPositionAt( prevItem, 'end' ) );
  77. // There could be some not mapped elements (eg. span in to-do list) but we need to insert
  78. // a nested list directly inside the li element.
  79. const mappedViewAncestor = mapper.findMappedViewAncestor( insertPosition );
  80. const nestedList = findNestedList( mappedViewAncestor );
  81. // If there already is some nested list, then use it's position.
  82. if ( nestedList ) {
  83. insertPosition = viewWriter.createPositionBefore( nestedList );
  84. } else {
  85. // Else just put new list on the end of list item content.
  86. insertPosition = viewWriter.createPositionAt( mappedViewAncestor, 'end' );
  87. }
  88. } else {
  89. // The previous item is not a list item (or does not exist at all).
  90. // Just map the position and insert the view item at the mapped position.
  91. insertPosition = mapper.toViewPosition( model.createPositionBefore( modelItem ) );
  92. }
  93. }
  94. insertPosition = positionAfterUiElements( insertPosition );
  95. // Insert the view item.
  96. viewWriter.insert( insertPosition, injectedList );
  97. // 2. Handle possible children of the injected model item.
  98. if ( prevItem && prevItem.name == 'listItem' ) {
  99. const prevView = mapper.toViewElement( prevItem );
  100. const walkerBoundaries = viewWriter.createRange( viewWriter.createPositionAt( prevView, 0 ), insertPosition );
  101. const walker = walkerBoundaries.getWalker( { ignoreElementEnd: true } );
  102. for ( const value of walker ) {
  103. if ( value.item.is( 'element', 'li' ) ) {
  104. const breakPosition = viewWriter.breakContainer( viewWriter.createPositionBefore( value.item ) );
  105. const viewList = value.item.parent;
  106. const targetPosition = viewWriter.createPositionAt( injectedItem, 'end' );
  107. mergeViewLists( viewWriter, targetPosition.nodeBefore, targetPosition.nodeAfter );
  108. viewWriter.move( viewWriter.createRangeOn( viewList ), targetPosition );
  109. walker.position = breakPosition;
  110. }
  111. }
  112. } else {
  113. const nextViewList = injectedList.nextSibling;
  114. if ( nextViewList && ( nextViewList.is( 'element', 'ul' ) || nextViewList.is( 'element', 'ol' ) ) ) {
  115. let lastSubChild = null;
  116. for ( const child of nextViewList.getChildren() ) {
  117. const modelChild = mapper.toModelElement( child );
  118. if ( modelChild && modelChild.getAttribute( 'listIndent' ) > modelItem.getAttribute( 'listIndent' ) ) {
  119. lastSubChild = child;
  120. } else {
  121. break;
  122. }
  123. }
  124. if ( lastSubChild ) {
  125. viewWriter.breakContainer( viewWriter.createPositionAfter( lastSubChild ) );
  126. viewWriter.move( viewWriter.createRangeOn( lastSubChild.parent ), viewWriter.createPositionAt( injectedItem, 'end' ) );
  127. }
  128. }
  129. }
  130. // Merge the inserted view list with its possible neighbor lists.
  131. mergeViewLists( viewWriter, injectedList, injectedList.nextSibling );
  132. mergeViewLists( viewWriter, injectedList.previousSibling, injectedList );
  133. }
  134. /**
  135. * Helper function that takes two parameters that are expected to be view list elements, and merges them.
  136. * The merge happens only if both parameters are list elements of the same type (the same element name and the same class attributes).
  137. *
  138. * @param {module:engine/view/downcastwriter~DowncastWriter} viewWriter The writer instance.
  139. * @param {module:engine/view/item~Item} firstList The first element to compare.
  140. * @param {module:engine/view/item~Item} secondList The second element to compare.
  141. * @returns {module:engine/view/position~Position|null} The position after merge or `null` when there was no merge.
  142. */
  143. export function mergeViewLists( viewWriter, firstList, secondList ) {
  144. // Check if two lists are going to be merged.
  145. if ( !firstList || !secondList || ( firstList.name != 'ul' && firstList.name != 'ol' ) ) {
  146. return null;
  147. }
  148. // Both parameters are list elements, so compare types now.
  149. if ( firstList.name != secondList.name || firstList.getAttribute( 'class' ) !== secondList.getAttribute( 'class' ) ) {
  150. return null;
  151. }
  152. return viewWriter.mergeContainers( viewWriter.createPositionAfter( firstList ) );
  153. }
  154. /**
  155. * Helper function that for a given `view.Position`, returns a `view.Position` that is after all `view.UIElement`s that
  156. * are after the given position.
  157. *
  158. * For example:
  159. * `<container:p>foo^<ui:span></ui:span><ui:span></ui:span>bar</container:p>`
  160. * For position ^, the position before "bar" will be returned.
  161. *
  162. * @param {module:engine/view/position~Position} viewPosition
  163. * @returns {module:engine/view/position~Position}
  164. */
  165. export function positionAfterUiElements( viewPosition ) {
  166. return viewPosition.getLastMatchingPosition( value => value.item.is( 'uiElement' ) );
  167. }
  168. /**
  169. * Helper function that searches for a previous list item sibling of a given model item that meets the given criteria
  170. * passed by the options object.
  171. *
  172. * @param {module:engine/model/item~Item} modelItem
  173. * @param {Object} options Search criteria.
  174. * @param {Boolean} [options.sameIndent=false] Whether the sought sibling should have the same indentation.
  175. * @param {Boolean} [options.smallerIndent=false] Whether the sought sibling should have a smaller indentation.
  176. * @param {Number} [options.listIndent] The reference indentation.
  177. * @returns {module:engine/model/item~Item|null}
  178. */
  179. export function getSiblingListItem( modelItem, options ) {
  180. const sameIndent = !!options.sameIndent;
  181. const smallerIndent = !!options.smallerIndent;
  182. const indent = options.listIndent;
  183. let item = modelItem;
  184. while ( item && item.name == 'listItem' ) {
  185. const itemIndent = item.getAttribute( 'listIndent' );
  186. if ( ( sameIndent && indent == itemIndent ) || ( smallerIndent && indent > itemIndent ) ) {
  187. return item;
  188. }
  189. item = item.previousSibling;
  190. }
  191. return null;
  192. }
  193. /**
  194. * Helper method for creating a UI button and linking it with an appropriate command.
  195. *
  196. * @private
  197. * @param {module:core/editor/editor~Editor} editor The editor instance to which the UI component will be added.
  198. * @param {String} commandName The name of the command.
  199. * @param {Object} label The button label.
  200. * @param {String} icon The source of the icon.
  201. */
  202. export function createUIComponent( editor, commandName, label, icon ) {
  203. editor.ui.componentFactory.add( commandName, locale => {
  204. const command = editor.commands.get( commandName );
  205. const buttonView = new ButtonView( locale );
  206. buttonView.set( {
  207. label,
  208. icon,
  209. tooltip: true,
  210. isToggleable: true
  211. } );
  212. // Bind button model to command.
  213. buttonView.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' );
  214. // Execute command.
  215. buttonView.on( 'execute', () => {
  216. editor.execute( commandName );
  217. editor.editing.view.focus();
  218. } );
  219. return buttonView;
  220. } );
  221. }
  222. /**
  223. * Returns a first list view element that is direct child of the given view element.
  224. *
  225. * @param {module:engine/view/element~Element} viewElement
  226. * @return {module:engine/view/element~Element|null}
  227. */
  228. export function findNestedList( viewElement ) {
  229. for ( const node of viewElement.getChildren() ) {
  230. if ( node.name == 'ul' || node.name == 'ol' ) {
  231. return node;
  232. }
  233. }
  234. return null;
  235. }
  236. // Implementation of getFillerOffset for view list item element.
  237. //
  238. // @returns {Number|null} Block filler offset or `null` if block filler is not needed.
  239. function getListItemFillerOffset() {
  240. const hasOnlyLists = !this.isEmpty && ( this.getChild( 0 ).name == 'ul' || this.getChild( 0 ).name == 'ol' );
  241. if ( this.isEmpty || hasOnlyLists ) {
  242. return 0;
  243. }
  244. return getFillerOffset.call( this );
  245. }