listcommand.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module list/listcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import Position from '@ckeditor/ckeditor5-engine/src/model/position';
  10. import first from '@ckeditor/ckeditor5-utils/src/first';
  11. /**
  12. * The list command. It is used by the {@link module:list/list~List list feature}.
  13. *
  14. * @extends module:core/command~Command
  15. */
  16. export default class ListCommand extends Command {
  17. /**
  18. * Creates an instance of the command.
  19. *
  20. * @param {module:core/editor/editor~Editor} editor Editor instance.
  21. * @param {'numbered'|'bulleted'} type List type that will be handled by this command.
  22. */
  23. constructor( editor, type ) {
  24. super( editor );
  25. /**
  26. * The type of list created by the command.
  27. *
  28. * @readonly
  29. * @member {'numbered'|'bulleted'}
  30. */
  31. this.type = type == 'bulleted' ? 'bulleted' : 'numbered';
  32. /**
  33. * Flag indicating whether the command is active, which means that selection starts in a list of the same type.
  34. *
  35. * @observable
  36. * @readonly
  37. * @member {Boolean} #value
  38. */
  39. }
  40. /**
  41. * @inheritDoc
  42. */
  43. refresh() {
  44. this.value = this._getValue();
  45. this.isEnabled = this._checkEnabled();
  46. }
  47. /**
  48. * Executes command.
  49. *
  50. * @protected
  51. * @param {Object} [options] Options for executed command.
  52. * @param {module:engine/model/batch~Batch} [options.batch] Batch to collect all the change steps.
  53. * New batch will be created if this option is not set.
  54. */
  55. execute( options = {} ) {
  56. const document = this.editor.document;
  57. const blocks = Array.from( document.selection.getSelectedBlocks() );
  58. // Whether we are turning off some items.
  59. const turnOff = this.value === true;
  60. // If we are turning off items, we are going to rename them to paragraphs.
  61. document.enqueueChanges( () => {
  62. const batch = options.batch || document.batch();
  63. // If part of a list got turned off, we need to handle (outdent) all of sub-items of the last turned-off item.
  64. // To be sure that model is all the time in a good state, we first fix items below turned-off item.
  65. if ( turnOff ) {
  66. // Start from the model item that is just after the last turned-off item.
  67. let next = blocks[ blocks.length - 1 ].nextSibling;
  68. let currentIndent = Number.POSITIVE_INFINITY;
  69. let changes = [];
  70. // Correct indent of all items after the last turned off item.
  71. // Rules that should be followed:
  72. // 1. All direct sub-items of turned-off item should become indent 0, because the first item after it
  73. // will be the first item of a new list. Other items are at the same level, so should have same 0 index.
  74. // 2. All items with indent lower than indent of turned-off item should become indent 0, because they
  75. // should not end up as a child of any of list items that they were not children of before.
  76. // 3. All other items should have their indent changed relatively to it's parent.
  77. //
  78. // For example:
  79. // 1 * --------
  80. // 2 * --------
  81. // 3 * -------- <-- this is turned off.
  82. // 4 * -------- <-- this has to become indent = 0, because it will be first item on a new list.
  83. // 5 * -------- <-- this should be still be a child of item above, so indent = 1.
  84. // 6 * -------- <-- this has to become indent = 0, because it should not be a child of any of items above.
  85. // 7 * -------- <-- this should be still be a child of item above, so indent = 1.
  86. // 8 * -------- <-- this has to become indent = 0.
  87. // 9 * -------- <-- this should still be a child of item above, so indent = 1.
  88. // 10 * -------- <-- this should still be a child of item above, so indent = 2.
  89. // 11 * -------- <-- this should still be at the same level as item above, so indent = 2.
  90. // 12 * -------- <-- this and all below are left unchanged.
  91. // 13 * --------
  92. // 14 * --------
  93. //
  94. // After turning off 3 the list becomes:
  95. //
  96. // 1 * --------
  97. // 2 * --------
  98. //
  99. // 3 --------
  100. //
  101. // 4 * --------
  102. // 5 * --------
  103. // 6 * --------
  104. // 7 * --------
  105. // 8 * --------
  106. // 9 * --------
  107. // 10 * --------
  108. // 11 * --------
  109. // 12 * --------
  110. // 13 * --------
  111. // 14 * --------
  112. //
  113. // Thanks to this algorithm no lists are mismatched and no items get unexpected children/parent, while
  114. // those parent-child connection which are possible to maintain are still maintained. It's worth noting
  115. // that this is the same effect that we would be get by multiple use of outdent command. However doing
  116. // it like this is much more efficient because it's less operation (less memory usage, easier OT) and
  117. // less conversion (faster).
  118. while ( next && next.name == 'listItem' && next.getAttribute( 'indent' ) !== 0 ) {
  119. // Check each next list item, as long as its indent is bigger than 0.
  120. // If the indent is 0 we are not going to change anything anyway.
  121. const indent = next.getAttribute( 'indent' );
  122. // We check if that's item indent is lower as current relative indent.
  123. if ( indent < currentIndent ) {
  124. // If it is, current relative indent becomes that indent.
  125. currentIndent = indent;
  126. }
  127. // Fix indent relatively to current relative indent.
  128. // Note, that if we just changed the current relative indent, the newIndent will be equal to 0.
  129. const newIndent = indent - currentIndent;
  130. // Save the entry in changes array. We do not apply it at the moment, because we will need to
  131. // reverse the changes so the last item is changed first.
  132. // This is to keep model in correct state all the time.
  133. changes.push( { element: next, indent: newIndent } );
  134. // Find next item.
  135. next = next.nextSibling;
  136. }
  137. changes = changes.reverse();
  138. for ( const item of changes ) {
  139. batch.setAttribute( item.element, 'indent', item.indent );
  140. }
  141. }
  142. // If we are turning on, we might change some items that are already `listItem`s but with different type.
  143. // Changing one nested list item to other type should also trigger changing all its siblings so the
  144. // whole nested list is of the same type.
  145. // Example (assume changing to numbered list):
  146. // * ------ <-- do not fix, top level item
  147. // * ------ <-- fix, because latter list item of this item's list is changed
  148. // * ------ <-- do not fix, item is not affected (different list)
  149. // * ------ <-- fix, because latter list item of this item's list is changed
  150. // * ------ <-- fix, because latter list item of this item's list is changed
  151. // * ---[-- <-- already in selection
  152. // * ------ <-- already in selection
  153. // * ------ <-- already in selection
  154. // * ------ <-- already in selection, but does not cause other list items to change because is top-level
  155. // * ---]-- <-- already in selection
  156. // * ------ <-- fix, because preceding list item of this item's list is changed
  157. // * ------ <-- do not fix, item is not affected (different list)
  158. // * ------ <-- do not fix, top level item
  159. if ( !turnOff ) {
  160. // Find lowest indent among selected items. This will be indicator what is the indent of
  161. // top-most list affected by the command.
  162. let lowestIndent = Number.POSITIVE_INFINITY;
  163. for ( const item of blocks ) {
  164. if ( item.is( 'listItem' ) && item.getAttribute( 'indent' ) < lowestIndent ) {
  165. lowestIndent = item.getAttribute( 'indent' );
  166. }
  167. }
  168. // Do not execute the fix for top-level lists.
  169. lowestIndent = lowestIndent === 0 ? 1 : lowestIndent;
  170. // Fix types of list items that are "before" the selected blocks.
  171. _fixType( blocks, true, lowestIndent );
  172. // Fix types of list items that are "after" the selected blocks.
  173. _fixType( blocks, false, lowestIndent );
  174. }
  175. // Phew! Now it will be easier :).
  176. // For each block element that was in the selection, we will either: turn it to list item,
  177. // turn it to paragraph, or change it's type. Or leave it as it is.
  178. // Do it in reverse as there might be multiple blocks (same as with changing indents).
  179. for ( const element of blocks.reverse() ) {
  180. if ( turnOff && element.name == 'listItem' ) {
  181. // We are turning off and the element is a `listItem` - it should be converted to `paragraph`.
  182. // List item specific attributes are removed by post fixer.
  183. batch.rename( element, 'paragraph' );
  184. } else if ( !turnOff && element.name != 'listItem' ) {
  185. // We are turning on and the element is not a `listItem` - it should be converted to `listItem`.
  186. // The order of operations is important to keep model in correct state.
  187. batch.setAttribute( element, 'type', this.type ).setAttribute( element, 'indent', 0 ).rename( element, 'listItem' );
  188. } else if ( !turnOff && element.name == 'listItem' && element.getAttribute( 'type' ) != this.type ) {
  189. // We are turning on and the element is a `listItem` but has different type - change it's type and
  190. // type of it's all siblings that have same indent.
  191. batch.setAttribute( element, 'type', this.type );
  192. }
  193. }
  194. } );
  195. }
  196. /**
  197. * Checks the command's {@link #value}.
  198. *
  199. * @private
  200. * @returns {Boolean} The current value.
  201. */
  202. _getValue() {
  203. // Check whether closest `listItem` ancestor of the position has a correct type.
  204. const listItem = first( this.editor.document.selection.getSelectedBlocks() );
  205. return !!listItem && listItem.is( 'listItem' ) && listItem.getAttribute( 'type' ) == this.type;
  206. }
  207. /**
  208. * Checks whether the command can be enabled in the current context.
  209. *
  210. * @private
  211. * @returns {Boolean} Whether the command should be enabled.
  212. */
  213. _checkEnabled() {
  214. // If command value is true it means that we are in list item, so the command should be enabled.
  215. if ( this.value ) {
  216. return true;
  217. }
  218. const selection = this.editor.document.selection;
  219. const schema = this.editor.document.schema;
  220. const firstBlock = first( selection.getSelectedBlocks() );
  221. if ( !firstBlock ) {
  222. return false;
  223. }
  224. // Otherwise, check if list item can be inserted at the position start.
  225. return schema.check( {
  226. name: 'listItem',
  227. attributes: [ 'type', 'indent' ],
  228. inside: Position.createBefore( firstBlock )
  229. } );
  230. }
  231. }
  232. // Helper function used when one or more list item have their type changed. Fixes type of other list items
  233. // that are affected by the change (are in same lists) but are not directly in selection. The function got extracted
  234. // not to duplicated code, as same fix has to be performed before and after selection.
  235. //
  236. // @param {Array.<module:engine/model/node~Node>} blocks Blocks that are in selection.
  237. // @param {Boolean} isBackward Specified whether fix will be applied for blocks before first selected block (`true`)
  238. // or blocks after last selected block (`false`).
  239. // @param {Number} lowestIndent Lowest indent among selected blocks.
  240. function _fixType( blocks, isBackward, lowestIndent ) {
  241. // We need to check previous sibling of first changed item and next siblings of last changed item.
  242. const startingItem = isBackward ? blocks[ 0 ] : blocks[ blocks.length - 1 ];
  243. if ( startingItem.is( 'listItem' ) ) {
  244. let item = startingItem[ isBackward ? 'previousSibling' : 'nextSibling' ];
  245. // During processing items, keeps the lowest indent of already processed items.
  246. // This saves us from changing too many items.
  247. // Following example is for going forward as it is easier to read, however same applies to going backward.
  248. // * ------
  249. // * ------
  250. // * --[---
  251. // * ------ <-- `lowestIndent` should be 1
  252. // * --]--- <-- `startingItem`, `currentIndent` = 2, `lowestIndent` == 1
  253. // * ------ <-- should be fixed, `indent` == 2 == `currentIndent`
  254. // * ------ <-- should be fixed, set `currentIndent` to 1, `indent` == 1 == `currentIndent`
  255. // * ------ <-- should not be fixed, item is in different list, `indent` = 2, `indent` != `currentIndent`
  256. // * ------ <-- should be fixed, `indent` == 1 == `currentIndent`
  257. // * ------ <-- break loop (`indent` < `lowestIndent`)
  258. let currentIndent = startingItem.getAttribute( 'indent' );
  259. // Look back until a list item with indent lower than reference `lowestIndent`.
  260. // That would be the parent of nested sublist which contains item having `lowestIndent`.
  261. while ( item && item.is( 'listItem' ) && item.getAttribute( 'indent' ) >= lowestIndent ) {
  262. if ( currentIndent > item.getAttribute( 'indent' ) ) {
  263. currentIndent = item.getAttribute( 'indent' );
  264. }
  265. // Found an item that is in the same nested sublist.
  266. if ( item.getAttribute( 'indent' ) == currentIndent ) {
  267. // Just add the item to selected blocks like it was selected by the user.
  268. blocks[ isBackward ? 'unshift' : 'push' ]( item );
  269. }
  270. item = item[ isBackward ? 'previousSibling' : 'nextSibling' ];
  271. }
  272. }
  273. }