listcommand.js 13 KB

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