converters.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module list/converters
  7. */
  8. import ModelElement from '@ckeditor/ckeditor5-engine/src/model/element';
  9. import ModelPosition from '@ckeditor/ckeditor5-engine/src/model/position';
  10. import ModelRange from '@ckeditor/ckeditor5-engine/src/model/range';
  11. import ViewPosition from '@ckeditor/ckeditor5-engine/src/view/position';
  12. import ViewRange from '@ckeditor/ckeditor5-engine/src/view/range';
  13. import ViewTreeWalker from '@ckeditor/ckeditor5-engine/src/view/treewalker';
  14. import { createViewListItemElement } from './utils';
  15. /**
  16. * A model-to-view converter for `listItem` model element insertion.
  17. *
  18. * It creates a `<ul><li></li><ul>` (or `<ol>`) view structure out of a `listItem` model element, inserts it at the correct
  19. * position, and merges the list with surrounding lists (if available).
  20. *
  21. * @see module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:insert
  22. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
  23. * @param {Object} data Additional information about the change.
  24. * @param {Object} conversionApi Conversion interface.
  25. */
  26. export function modelViewInsertion( evt, data, conversionApi ) {
  27. const consumable = conversionApi.consumable;
  28. if ( !consumable.test( data.item, 'insert' ) ||
  29. !consumable.test( data.item, 'attribute:listType' ) ||
  30. !consumable.test( data.item, 'attribute:listIndent' )
  31. ) {
  32. return;
  33. }
  34. consumable.consume( data.item, 'insert' );
  35. consumable.consume( data.item, 'attribute:listType' );
  36. consumable.consume( data.item, 'attribute:listIndent' );
  37. const modelItem = data.item;
  38. const viewItem = generateLiInUl( modelItem, conversionApi );
  39. injectViewList( modelItem, viewItem, conversionApi );
  40. }
  41. /**
  42. * A model-to-view converter for `listItem` model element removal.
  43. *
  44. * @see module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:remove
  45. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
  46. * @param {Object} data Additional information about the change.
  47. * @param {Object} conversionApi Conversion interface.
  48. */
  49. export function modelViewRemove( evt, data, conversionApi ) {
  50. const viewStart = conversionApi.mapper.toViewPosition( data.position ).getLastMatchingPosition( value => !value.item.is( 'li' ) );
  51. const viewItem = viewStart.nodeAfter;
  52. const viewWriter = conversionApi.writer;
  53. // 1. Break the container after and before the list item.
  54. // This will create a view list with one view list item - the one to remove.
  55. viewWriter.breakContainer( ViewPosition.createBefore( viewItem ) );
  56. viewWriter.breakContainer( ViewPosition.createAfter( viewItem ) );
  57. // 2. Remove the list with the item to remove.
  58. const viewList = viewItem.parent;
  59. const viewListPrev = viewList.previousSibling;
  60. const removeRange = ViewRange.createOn( viewList );
  61. const removed = viewWriter.remove( removeRange );
  62. // 3. Merge the whole created by breaking and removing the list.
  63. if ( viewListPrev && viewListPrev.nextSibling ) {
  64. mergeViewLists( viewWriter, viewListPrev, viewListPrev.nextSibling );
  65. }
  66. // 4. Bring back nested list that was in the removed <li>.
  67. const modelItem = conversionApi.mapper.toModelElement( viewItem );
  68. hoistNestedLists( modelItem.getAttribute( 'listIndent' ) + 1, data.position, removeRange.start, viewItem, conversionApi );
  69. // 5. Unbind removed view item and all children.
  70. for ( const child of ViewRange.createIn( removed ).getItems() ) {
  71. conversionApi.mapper.unbindViewElement( child );
  72. }
  73. evt.stop();
  74. }
  75. /**
  76. * A model-to-view converter for `type` attribute change on `listItem` model element.
  77. *
  78. * This change means that `<li>` elements parent changes from `<ul>` to `<ol>` (or vice versa). This is accomplished
  79. * by breaking view elements, changing their name and merging them.
  80. *
  81. * @see module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute
  82. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
  83. * @param {Object} data Additional information about the change.
  84. * @param {Object} conversionApi Conversion interface.
  85. */
  86. export function modelViewChangeType( evt, data, conversionApi ) {
  87. if ( !conversionApi.consumable.consume( data.item, 'attribute:listType' ) ) {
  88. return;
  89. }
  90. const viewItem = conversionApi.mapper.toViewElement( data.item );
  91. const viewWriter = conversionApi.writer;
  92. // 1. Break the container after and before the list item.
  93. // This will create a view list with one view list item -- the one that changed type.
  94. viewWriter.breakContainer( ViewPosition.createBefore( viewItem ) );
  95. viewWriter.breakContainer( ViewPosition.createAfter( viewItem ) );
  96. // 2. Change name of the view list that holds the changed view item.
  97. // We cannot just change name property, because that would not render properly.
  98. let viewList = viewItem.parent;
  99. const listName = data.attributeNewValue == 'numbered' ? 'ol' : 'ul';
  100. viewList = viewWriter.rename( viewList, listName );
  101. // 3. Merge the changed view list with other lists, if possible.
  102. mergeViewLists( viewWriter, viewList, viewList.nextSibling );
  103. mergeViewLists( viewWriter, viewList.previousSibling, viewList );
  104. // 4. Consumable insertion of children inside the item. They are already handled by re-building the item in view.
  105. for ( const child of data.item.getChildren() ) {
  106. conversionApi.consumable.consume( child, 'insert' );
  107. }
  108. }
  109. /**
  110. * A model-to-view converter for `indent` attribute change on `listItem` model element.
  111. *
  112. * @see module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:attribute
  113. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
  114. * @param {Object} data Additional information about the change.
  115. * @param {Object} conversionApi Conversion interface.
  116. */
  117. export function modelViewChangeIndent( evt, data, conversionApi ) {
  118. if ( !conversionApi.consumable.consume( data.item, 'attribute:listIndent' ) ) {
  119. return;
  120. }
  121. const viewItem = conversionApi.mapper.toViewElement( data.item );
  122. const viewWriter = conversionApi.writer;
  123. // 1. Break the container after and before the list item.
  124. // This will create a view list with one view list item -- the one that changed type.
  125. viewWriter.breakContainer( ViewPosition.createBefore( viewItem ) );
  126. viewWriter.breakContainer( ViewPosition.createAfter( viewItem ) );
  127. // 2. Extract view list with changed view list item and merge "hole" possibly created by breaking and removing elements.
  128. const viewList = viewItem.parent;
  129. const viewListPrev = viewList.previousSibling;
  130. const removeRange = ViewRange.createOn( viewList );
  131. viewWriter.remove( removeRange );
  132. if ( viewListPrev && viewListPrev.nextSibling ) {
  133. mergeViewLists( viewWriter, viewListPrev, viewListPrev.nextSibling );
  134. }
  135. // 3. Bring back nested list that was in the removed <li>.
  136. hoistNestedLists( data.attributeOldValue + 1, data.range.start, removeRange.start, viewItem, conversionApi );
  137. // 4. Inject view list like it is newly inserted.
  138. injectViewList( data.item, viewItem, conversionApi );
  139. // 5. Consume insertion of children inside the item. They are already handled by re-building the item in view.
  140. for ( const child of data.item.getChildren() ) {
  141. conversionApi.consumable.consume( child, 'insert' );
  142. }
  143. }
  144. /**
  145. * A special model-to-view converter introduced by the {@link module:list/list~List list feature}. This converter is fired for
  146. * insert change of every model item, and should be fired before the actual converter. The converter checks whether the inserted
  147. * model item is a non-`listItem` element. If it is, and it is inserted inside a view list, the converter breaks the
  148. * list so the model element is inserted to the view parent element corresponding to its model parent element.
  149. *
  150. * The converter prevents such situations:
  151. *
  152. * // Model: // View:
  153. * <listItem>foo</listItem> <ul>
  154. * <listItem>bar</listItem> <li>foo</li>
  155. * <li>bar</li>
  156. * </ul>
  157. *
  158. * // After change: // Correct view guaranteed by this converter:
  159. * <listItem>foo</listItem> <ul><li>foo</li></ul><p>xxx</p><ul><li>bar</li></ul>
  160. * <paragraph>xxx</paragraph> // Instead of this wrong view state:
  161. * <listItem>bar</listItem> <ul><li>foo</li><p>xxx</p><li>bar</li></ul>
  162. *
  163. * @see module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:insert
  164. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
  165. * @param {Object} data Additional information about the change.
  166. * @param {Object} conversionApi Conversion interface.
  167. */
  168. export function modelViewSplitOnInsert( evt, data, conversionApi ) {
  169. if ( data.item.name != 'listItem' ) {
  170. let viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
  171. const viewWriter = conversionApi.writer;
  172. const lists = [];
  173. // Break multiple ULs/OLs if there are.
  174. //
  175. // Imagine following list:
  176. //
  177. // 1 --------
  178. // 1.1 --------
  179. // 1.1.1 --------
  180. // 1.1.2 --------
  181. // 1.1.3 --------
  182. // 1.1.3.1 --------
  183. // 1.2 --------
  184. // 1.2.1 --------
  185. // 2 --------
  186. //
  187. // Insert paragraph after item 1.1.1:
  188. //
  189. // 1 --------
  190. // 1.1 --------
  191. // 1.1.1 --------
  192. //
  193. // Lorem ipsum.
  194. //
  195. // 1.1.2 --------
  196. // 1.1.3 --------
  197. // 1.1.3.1 --------
  198. // 1.2 --------
  199. // 1.2.1 --------
  200. // 2 --------
  201. //
  202. // In this case 1.1.2 has to become beginning of a new list.
  203. // We need to break list before 1.1.2 (obvious), then we need to break list also before 1.2.
  204. // Then we need to move those broken pieces one after another and merge:
  205. //
  206. // 1 --------
  207. // 1.1 --------
  208. // 1.1.1 --------
  209. //
  210. // Lorem ipsum.
  211. //
  212. // 1.1.2 --------
  213. // 1.1.3 --------
  214. // 1.1.3.1 --------
  215. // 1.2 --------
  216. // 1.2.1 --------
  217. // 2 --------
  218. //
  219. while ( viewPosition.parent.name == 'ul' || viewPosition.parent.name == 'ol' ) {
  220. viewPosition = viewWriter.breakContainer( viewPosition );
  221. if ( viewPosition.parent.name != 'li' ) {
  222. break;
  223. }
  224. // Remove lists that are after inserted element.
  225. // They will be brought back later, below the inserted element.
  226. const removeStart = viewPosition;
  227. const removeEnd = ViewPosition.createAt( viewPosition.parent, 'end' );
  228. // Don't remove if there is nothing to remove.
  229. if ( !removeStart.isEqual( removeEnd ) ) {
  230. const removed = viewWriter.remove( new ViewRange( removeStart, removeEnd ) );
  231. lists.push( removed );
  232. }
  233. viewPosition = ViewPosition.createAfter( viewPosition.parent );
  234. }
  235. // Bring back removed lists.
  236. if ( lists.length > 0 ) {
  237. for ( let i = 0; i < lists.length; i++ ) {
  238. const previousList = viewPosition.nodeBefore;
  239. const insertedRange = viewWriter.insert( viewPosition, lists[ i ] );
  240. viewPosition = insertedRange.end;
  241. // Don't merge first list! We want a split in that place (this is why this converter is introduced).
  242. if ( i > 0 ) {
  243. const mergePos = mergeViewLists( viewWriter, previousList, previousList.nextSibling );
  244. // If `mergePos` is in `previousList` it means that the lists got merged.
  245. // In this case, we need to fix insert position.
  246. if ( mergePos && mergePos.parent == previousList ) {
  247. viewPosition.offset--;
  248. }
  249. }
  250. }
  251. // Merge last inserted list with element after it.
  252. mergeViewLists( viewWriter, viewPosition.nodeBefore, viewPosition.nodeAfter );
  253. }
  254. }
  255. }
  256. /**
  257. * A special model-to-view converter introduced by the {@link module:list/list~List list feature}. This converter takes care of
  258. * merging view lists after something is removed or moved from near them.
  259. *
  260. * Example:
  261. *
  262. * // Model: // View:
  263. * <listItem>foo</listItem> <ul><li>foo</li></ul>
  264. * <paragraph>xxx</paragraph> <p>xxx</p>
  265. * <listItem>bar</listItem> <ul><li>bar</li></ul>
  266. *
  267. * // After change: // Correct view guaranteed by this converter:
  268. * <listItem>foo</listItem> <ul>
  269. * <listItem>bar</listItem> <li>foo</li>
  270. * <li>bar</li>
  271. * </ul>
  272. *
  273. * @see module:engine/conversion/downcastdispatcher~DowncastDispatcher#event:remove
  274. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
  275. * @param {Object} data Additional information about the change.
  276. * @param {Object} conversionApi Conversion interface.
  277. */
  278. export function modelViewMergeAfter( evt, data, conversionApi ) {
  279. const viewPosition = conversionApi.mapper.toViewPosition( data.position );
  280. const viewItemPrev = viewPosition.nodeBefore;
  281. const viewItemNext = viewPosition.nodeAfter;
  282. // Merge lists if something (remove, move) was done from inside of list.
  283. // Merging will be done only if both items are view lists of the same type.
  284. // The check is done inside the helper function.
  285. mergeViewLists( conversionApi.writer, viewItemPrev, viewItemNext );
  286. }
  287. /**
  288. * A view-to-model converter that converts `<li>` view elements into `listItem` model elements.
  289. *
  290. * To set correct values of the `listType` and `indent` attributes the converter:
  291. * * checks `<li>`'s parent,
  292. * * stores and increases the `conversionApi.store.indent` value when `<li>`'s sub-items are converted.
  293. *
  294. * @see module:engine/conversion/upcastdispatcher~UpcastDispatcher#event:element
  295. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
  296. * @param {Object} data An object containing conversion input and a placeholder for conversion output and possibly other values.
  297. * @param {Object} conversionApi Conversion interface to be used by the callback.
  298. */
  299. export function viewModelConverter( evt, data, conversionApi ) {
  300. if ( conversionApi.consumable.consume( data.viewItem, { name: true } ) ) {
  301. const writer = conversionApi.writer;
  302. const conversionStore = this.conversionApi.store;
  303. // 1. Create `listItem` model element.
  304. const listItem = writer.createElement( 'listItem' );
  305. // 2. Handle `listItem` model element attributes.
  306. conversionStore.indent = conversionStore.indent || 0;
  307. writer.setAttribute( 'listIndent', conversionStore.indent, listItem );
  308. // Set 'bulleted' as default. If this item is pasted into a context,
  309. const type = data.viewItem.parent && data.viewItem.parent.name == 'ol' ? 'numbered' : 'bulleted';
  310. writer.setAttribute( 'listType', type, listItem );
  311. // `listItem`s created recursively should have bigger indent.
  312. conversionStore.indent++;
  313. // Try to find allowed parent for list item.
  314. const splitResult = conversionApi.splitToAllowedParent( listItem, data.modelCursor );
  315. // When there is no allowed parent it means that list item cannot be converted at current model position
  316. // and in any of position ancestors.
  317. if ( !splitResult ) {
  318. return;
  319. }
  320. writer.insert( listItem, splitResult.position );
  321. // Remember position after list item, next list items will be inserted at this position.
  322. let nextPosition = ModelPosition.createAfter( listItem );
  323. // Check all children of the converted `<li>`.
  324. // At this point we assume there are no "whitespace" view text nodes in view list, between view list items.
  325. // This should be handled by `<ul>` and `<ol>` converters.
  326. for ( const child of data.viewItem.getChildren() ) {
  327. // If this is a view list element, we will convert it after last `listItem` model element.
  328. if ( child.name == 'ul' || child.name == 'ol' ) {
  329. nextPosition = conversionApi.convertItem( child, nextPosition ).modelCursor;
  330. }
  331. // If it was not a list it was a "regular" list item content. Just convert it to `listItem`.
  332. else {
  333. conversionApi.convertItem( child, ModelPosition.createAt( listItem, 'end' ) );
  334. }
  335. }
  336. conversionStore.indent--;
  337. // Result range starts before the first item and ends after the last.
  338. data.modelRange = new ModelRange( data.modelCursor, nextPosition );
  339. // When modelCursor parent had to be split to insert list item.
  340. if ( splitResult.cursorParent ) {
  341. // Then continue conversion in split element.
  342. data.modelCursor = ModelPosition.createAt( splitResult.cursorParent );
  343. } else {
  344. // Otherwise continue conversion after last list item.
  345. data.modelCursor = data.modelRange.end;
  346. }
  347. }
  348. }
  349. /**
  350. * A view-to-model converter for `<ul>` and `<ol>` view elements that cleans the input view of garbage.
  351. * This is mostly to clean whitespaces from between `<li>` view elements inside the view list element, however, also
  352. * incorrect data can be cleared if the view was incorrect.
  353. *
  354. * @see module:engine/conversion/upcastdispatcher~UpcastDispatcher#event:element
  355. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
  356. * @param {Object} data An object containing conversion input and a placeholder for conversion output and possibly other values.
  357. * @param {Object} conversionApi Conversion interface to be used by the callback.
  358. */
  359. export function cleanList( evt, data, conversionApi ) {
  360. if ( conversionApi.consumable.test( data.viewItem, { name: true } ) ) {
  361. // Caching children because when we start removing them iterating fails.
  362. const children = Array.from( data.viewItem.getChildren() );
  363. for ( const child of children ) {
  364. if ( !child.is( 'li' ) ) {
  365. child._remove();
  366. }
  367. }
  368. }
  369. }
  370. /**
  371. * A view-to-model converter for `<li>` elements that cleans whitespace formatting from the input view.
  372. *
  373. * @see module:engine/conversion/upcastdispatcher~UpcastDispatcher#event:element
  374. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
  375. * @param {Object} data An object containing conversion input and a placeholder for conversion output and possibly other values.
  376. * @param {Object} conversionApi Conversion interface to be used by the callback.
  377. */
  378. export function cleanListItem( evt, data, conversionApi ) {
  379. if ( conversionApi.consumable.test( data.viewItem, { name: true } ) ) {
  380. if ( data.viewItem.childCount === 0 ) {
  381. return;
  382. }
  383. const children = [ ...data.viewItem.getChildren() ];
  384. let foundList = false;
  385. let firstNode = true;
  386. for ( const child of children ) {
  387. if ( foundList && !child.is( 'ul' ) && !child.is( 'ol' ) ) {
  388. child._remove();
  389. }
  390. if ( child.is( 'text' ) ) {
  391. // If this is the first node and it's a text node, left-trim it.
  392. if ( firstNode ) {
  393. child._data = child.data.replace( /^\s+/, '' );
  394. }
  395. // If this is the last text node before <ul> or <ol>, right-trim it.
  396. if ( !child.nextSibling || ( child.nextSibling.is( 'ul' ) || child.nextSibling.is( 'ol' ) ) ) {
  397. child._data = child.data.replace( /\s+$/, '' );
  398. }
  399. } else if ( child.is( 'ul' ) || child.is( 'ol' ) ) {
  400. // If this is a <ul> or <ol>, do not process it, just mark that we already visited list element.
  401. foundList = true;
  402. }
  403. firstNode = false;
  404. }
  405. }
  406. }
  407. /**
  408. * The callback for model position to view position mapping for {@link module:engine/conversion/mapper~Mapper}. The callback fixes
  409. * positions between `listItem` elements that would be incorrectly mapped because of how list items are represented in model
  410. * and view.
  411. *
  412. * @see module:engine/conversion/mapper~Mapper#event:modelToViewPosition
  413. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
  414. * @param {Object} data An object containing additional data and placeholder for mapping result.
  415. */
  416. export function modelToViewPosition( evt, data ) {
  417. if ( data.isPhantom ) {
  418. return;
  419. }
  420. const modelItem = data.modelPosition.nodeBefore;
  421. if ( modelItem && modelItem.is( 'listItem' ) ) {
  422. const viewItem = data.mapper.toViewElement( modelItem );
  423. const topmostViewList = viewItem.getAncestors().find( element => element.is( 'ul' ) || element.is( 'ol' ) );
  424. const walker = new ViewTreeWalker( {
  425. startPosition: ViewPosition.createAt( viewItem, 0 )
  426. } );
  427. for ( const value of walker ) {
  428. if ( value.type == 'elementStart' && value.item.is( 'li' ) ) {
  429. data.viewPosition = value.previousPosition;
  430. break;
  431. } else if ( value.type == 'elementEnd' && value.item == topmostViewList ) {
  432. data.viewPosition = value.nextPosition;
  433. break;
  434. }
  435. }
  436. }
  437. }
  438. /**
  439. * The callback for view position to model position mapping for {@link module:engine/conversion/mapper~Mapper}. The callback fixes
  440. * positions between `<li>` elements that would be incorrectly mapped because of how list items are represented in model
  441. * and view.
  442. *
  443. * @see module:engine/conversion/mapper~Mapper#event:viewToModelPosition
  444. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
  445. * @param {Object} data An object containing additional data and placeholder for mapping result.
  446. */
  447. export function viewToModelPosition( evt, data ) {
  448. const viewPos = data.viewPosition;
  449. const viewParent = viewPos.parent;
  450. const mapper = data.mapper;
  451. if ( viewParent.name == 'ul' || viewParent.name == 'ol' ) {
  452. // Position is directly in <ul> or <ol>.
  453. if ( !viewPos.isAtEnd ) {
  454. // If position is not at the end, it must be before <li>.
  455. // Get that <li>, map it to `listItem` and set model position before that `listItem`.
  456. const modelNode = mapper.toModelElement( viewPos.nodeAfter );
  457. data.modelPosition = ModelPosition.createBefore( modelNode );
  458. } else {
  459. // Position is at the end of <ul> or <ol>, so there is no <li> after it to be mapped.
  460. // There is <li> before the position, but we cannot just map it to `listItem` and set model position after it,
  461. // because that <li> may contain nested items.
  462. // We will check "model length" of that <li>, in other words - how many `listItem`s are in that <li>.
  463. const modelNode = mapper.toModelElement( viewPos.nodeBefore );
  464. const modelLength = mapper.getModelLength( viewPos.nodeBefore );
  465. // Then we get model position before mapped `listItem` and shift it accordingly.
  466. data.modelPosition = ModelPosition.createBefore( modelNode ).getShiftedBy( modelLength );
  467. }
  468. evt.stop();
  469. } else if ( viewParent.name == 'li' && viewPos.nodeBefore && ( viewPos.nodeBefore.name == 'ul' || viewPos.nodeBefore.name == 'ol' ) ) {
  470. // In most cases when view position is in <li> it is in text and this is a correct position.
  471. // However, if position is after <ul> or <ol> we have to fix it -- because in model <ul>/<ol> are not in the `listItem`.
  472. const modelNode = mapper.toModelElement( viewParent );
  473. // Check all <ul>s and <ol>s that are in the <li> but before mapped position.
  474. // Get model length of those elements and then add it to the offset of `listItem` mapped to the original <li>.
  475. let modelLength = 1; // Starts from 1 because the original <li> has to be counted in too.
  476. let viewList = viewPos.nodeBefore;
  477. while ( viewList && ( viewList.is( 'ul' ) || viewList.is( 'ol' ) ) ) {
  478. modelLength += mapper.getModelLength( viewList );
  479. viewList = viewList.previousSibling;
  480. }
  481. data.modelPosition = ModelPosition.createBefore( modelNode ).getShiftedBy( modelLength );
  482. evt.stop();
  483. }
  484. }
  485. /**
  486. * Post-fixer that reacts to changes on document and fixes incorrect model states.
  487. *
  488. * In an example below, there is a correct list structure.
  489. * Then the middle element will be removed so the list structure will become incorrect:
  490. *
  491. * <listItem listType="bulleted" listIndent=0>Item 1</listItem>
  492. * <listItem listType="bulleted" listIndent=1>Item 2</listItem> <--- this is removed.
  493. * <listItem listType="bulleted" listIndent=2>Item 3</listItem>
  494. *
  495. * List structure after the middle element removed:
  496. *
  497. * <listItem listType="bulleted" listIndent=0>Item 1</listItem>
  498. * <listItem listType="bulleted" listIndent=2>Item 3</listItem>
  499. *
  500. * Should become:
  501. *
  502. * <listItem listType="bulleted" listIndent=0>Item 1</listItem>
  503. * <listItem listType="bulleted" listIndent=1>Item 3</listItem> <--- note that indent got post-fixed.
  504. *
  505. * @param {module:engine/model/model~Model} model The data model.
  506. * @param {module:engine/model/writer~Writer} writer The writer to do changes with.
  507. * @returns {Boolean} `true` if any change has been applied, `false` otherwise.
  508. */
  509. export function modelChangePostFixer( model, writer ) {
  510. const changes = model.document.differ.getChanges();
  511. const itemToListHead = new Map();
  512. let applied = false;
  513. for ( const entry of changes ) {
  514. if ( entry.type == 'insert' && entry.name == 'listItem' ) {
  515. _addListToFix( entry.position );
  516. } else if ( entry.type == 'insert' && entry.name != 'listItem' ) {
  517. if ( entry.name != '$text' ) {
  518. // In case of renamed element.
  519. const item = entry.position.nodeAfter;
  520. if ( item.hasAttribute( 'listIndent' ) ) {
  521. writer.removeAttribute( 'listIndent', item );
  522. applied = true;
  523. }
  524. if ( item.hasAttribute( 'listType' ) ) {
  525. writer.removeAttribute( 'listType', item );
  526. applied = true;
  527. }
  528. }
  529. const posAfter = entry.position.getShiftedBy( entry.length );
  530. _addListToFix( posAfter );
  531. } else if ( entry.type == 'remove' && entry.name == 'listItem' ) {
  532. _addListToFix( entry.position );
  533. } else if ( entry.type == 'attribute' && entry.attributeKey == 'listIndent' ) {
  534. _addListToFix( entry.range.start );
  535. } else if ( entry.type == 'attribute' && entry.attributeKey == 'listType' ) {
  536. _addListToFix( entry.range.start );
  537. }
  538. }
  539. for ( const listHead of itemToListHead.values() ) {
  540. _fixListIndents( listHead );
  541. _fixListTypes( listHead );
  542. }
  543. return applied;
  544. function _addListToFix( position ) {
  545. const prev = position.nodeBefore;
  546. if ( !prev || !prev.is( 'listItem' ) ) {
  547. const item = position.nodeAfter;
  548. if ( item && item.is( 'listItem' ) ) {
  549. itemToListHead.set( item, item );
  550. }
  551. } else {
  552. let listHead = prev;
  553. if ( itemToListHead.has( listHead ) ) {
  554. return;
  555. }
  556. while ( listHead.previousSibling && listHead.previousSibling.is( 'listItem' ) ) {
  557. listHead = listHead.previousSibling;
  558. if ( itemToListHead.has( listHead ) ) {
  559. return;
  560. }
  561. }
  562. itemToListHead.set( position.nodeBefore, listHead );
  563. }
  564. }
  565. function _fixListIndents( item ) {
  566. let maxIndent = 0;
  567. let fixBy = null;
  568. while ( item && item.is( 'listItem' ) ) {
  569. const itemIndent = item.getAttribute( 'listIndent' );
  570. if ( itemIndent > maxIndent ) {
  571. let newIndent;
  572. if ( fixBy === null ) {
  573. fixBy = itemIndent - maxIndent;
  574. newIndent = maxIndent;
  575. } else {
  576. if ( fixBy > itemIndent ) {
  577. fixBy = itemIndent;
  578. }
  579. newIndent = itemIndent - fixBy;
  580. }
  581. writer.setAttribute( 'listIndent', newIndent, item );
  582. applied = true;
  583. } else {
  584. fixBy = null;
  585. maxIndent = item.getAttribute( 'listIndent' ) + 1;
  586. }
  587. item = item.nextSibling;
  588. }
  589. }
  590. function _fixListTypes( item ) {
  591. let typesStack = [];
  592. let prev = null;
  593. while ( item && item.is( 'listItem' ) ) {
  594. const itemIndent = item.getAttribute( 'listIndent' );
  595. if ( prev && prev.getAttribute( 'listIndent' ) > itemIndent ) {
  596. typesStack = typesStack.slice( 0, itemIndent + 1 );
  597. }
  598. if ( itemIndent != 0 ) {
  599. if ( typesStack[ itemIndent ] ) {
  600. const type = typesStack[ itemIndent ];
  601. if ( item.getAttribute( 'listType' ) != type ) {
  602. writer.setAttribute( 'listType', type, item );
  603. applied = true;
  604. }
  605. } else {
  606. typesStack[ itemIndent ] = item.getAttribute( 'listType' );
  607. }
  608. }
  609. prev = item;
  610. item = item.nextSibling;
  611. }
  612. }
  613. }
  614. /**
  615. * A fixer for pasted content that includes list items.
  616. *
  617. * It fixes indentation of pasted list items so the pasted items match correctly to the context they are pasted into.
  618. *
  619. * Example:
  620. *
  621. * <listItem listType="bulleted" listIndent=0>A</listItem>
  622. * <listItem listType="bulleted" listIndent=1>B^</listItem>
  623. * // At ^ paste: <listItem listType="bulleted" listIndent=4>X</listItem>
  624. * // <listItem listType="bulleted" listIndent=5>Y</listItem>
  625. * <listItem listType="bulleted" listIndent=2>C</listItem>
  626. *
  627. * Should become:
  628. *
  629. * <listItem listType="bulleted" listIndent=0>A</listItem>
  630. * <listItem listType="bulleted" listIndent=1>BX</listItem>
  631. * <listItem listType="bulleted" listIndent=2>Y/listItem>
  632. * <listItem listType="bulleted" listIndent=2>C</listItem>
  633. *
  634. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the fired event.
  635. * @param {Array} args Arguments of {@link module:engine/model/model~Model#insertContent}.
  636. */
  637. export function modelIndentPasteFixer( evt, [ content, selection ] ) {
  638. // Check whether inserted content starts from a `listItem`. If it does not, it means that there are some other
  639. // elements before it and there is no need to fix indents, because even if we insert that content into a list,
  640. // that list will be broken.
  641. // Note: we also need to handle singular elements because inserting item with indent 0 into 0,1,[],2
  642. // would create incorrect model.
  643. let item = content.is( 'documentFragment' ) ? content.getChild( 0 ) : content;
  644. if ( item && item.is( 'listItem' ) ) {
  645. // Get a reference list item. Inserted list items will be fixed according to that item.
  646. const pos = selection.getFirstPosition();
  647. let refItem = null;
  648. if ( pos.parent.is( 'listItem' ) ) {
  649. refItem = pos.parent;
  650. } else if ( pos.nodeBefore && pos.nodeBefore.is( 'listItem' ) ) {
  651. refItem = pos.nodeBefore;
  652. }
  653. // If there is `refItem` it means that we do insert list items into an existing list.
  654. if ( refItem ) {
  655. // First list item in `data` has indent equal to 0 (it is a first list item). It should have indent equal
  656. // to the indent of reference item. We have to fix the first item and all of it's children and following siblings.
  657. // Indent of all those items has to be adjusted to reference item.
  658. const indentChange = refItem.getAttribute( 'listIndent' );
  659. // Fix only if there is anything to fix.
  660. if ( indentChange > 0 ) {
  661. // Adjust indent of all "first" list items in inserted data.
  662. while ( item && item.is( 'listItem' ) ) {
  663. item._setAttribute( 'listIndent', item.getAttribute( 'listIndent' ) + indentChange );
  664. item = item.nextSibling;
  665. }
  666. }
  667. }
  668. }
  669. }
  670. // Helper function that creates a `<ul><li></li></ul>` or (`<ol>`) structure out of given `modelItem` model `listItem` element.
  671. // Then, it binds created view list item (<li>) with model `listItem` element.
  672. // The function then returns created view list item (<li>).
  673. function generateLiInUl( modelItem, conversionApi ) {
  674. const mapper = conversionApi.mapper;
  675. const viewWriter = conversionApi.writer;
  676. const listType = modelItem.getAttribute( 'listType' ) == 'numbered' ? 'ol' : 'ul';
  677. const viewItem = createViewListItemElement( viewWriter );
  678. const viewList = viewWriter.createContainerElement( listType, null );
  679. viewWriter.insert( ViewPosition.createAt( viewList ), viewItem );
  680. mapper.bindElements( modelItem, viewItem );
  681. return viewItem;
  682. }
  683. // Helper function that seeks for a list item sibling of given model item (or position) which meets given criteria.
  684. // `options` object may contain one or more of given values (by default they are `false`):
  685. // `options.sameIndent` - whether sought sibling should have same indent (default = no),
  686. // `options.smallerIndent` - whether sought sibling should have smaller indent (default = no).
  687. // `options.indent` - used as reference item when first parameter is a position
  688. // Either `options.sameIndent` or `options.biggerIndent` should be set to `true`.
  689. function getSiblingListItem( modelItemOrPosition, options ) {
  690. const sameIndent = !!options.sameIndent;
  691. const smallerIndent = !!options.smallerIndent;
  692. const indent = modelItemOrPosition instanceof ModelElement ? modelItemOrPosition.getAttribute( 'listIndent' ) : options.listIndent;
  693. let item = modelItemOrPosition instanceof ModelElement ? modelItemOrPosition.previousSibling : modelItemOrPosition.nodeBefore;
  694. while ( item && item.name == 'listItem' ) {
  695. const itemIndent = item.getAttribute( 'listIndent' );
  696. if ( ( sameIndent && indent == itemIndent ) || ( smallerIndent && indent > itemIndent ) ) {
  697. return item;
  698. }
  699. item = item.previousSibling;
  700. }
  701. return null;
  702. }
  703. // Helper function that takes two parameters, that are expected to be view list elements, and merges them.
  704. // The merge happen only if both parameters are UL or OL elements.
  705. function mergeViewLists( viewWriter, firstList, secondList ) {
  706. if ( firstList && secondList && ( firstList.name == 'ul' || firstList.name == 'ol' ) && firstList.name == secondList.name ) {
  707. return viewWriter.mergeContainers( ViewPosition.createAfter( firstList ) );
  708. }
  709. return null;
  710. }
  711. // Helper function that takes model list item element `modelItem`, corresponding view list item element `injectedItem`
  712. // that is not added to the view and is inside a view list element (`ul` or `ol`) and is that's list only child.
  713. // The list is inserted at correct position (element breaking may be needed) and then merged with it's siblings.
  714. // See comments below to better understand the algorithm.
  715. function injectViewList( modelItem, injectedItem, conversionApi ) {
  716. const injectedList = injectedItem.parent;
  717. const mapper = conversionApi.mapper;
  718. const viewWriter = conversionApi.writer;
  719. // Position where view list will be inserted.
  720. let insertPosition = mapper.toViewPosition( ModelPosition.createBefore( modelItem ) );
  721. // 1. Find previous list item that has same or smaller indent. Basically we are looking for a first model item
  722. // that is "parent" or "sibling" of injected model item.
  723. // If there is no such list item, it means that injected list item is the first item in "its list".
  724. const refItem = getSiblingListItem( modelItem, { sameIndent: true, smallerIndent: true } );
  725. const prevItem = modelItem.previousSibling;
  726. if ( refItem && refItem.getAttribute( 'listIndent' ) == modelItem.getAttribute( 'listIndent' ) ) {
  727. // There is a list item with same indent - we found same-level sibling.
  728. // Break the list after it. Inserted view item will be inserted in the broken space.
  729. const viewItem = mapper.toViewElement( refItem );
  730. insertPosition = viewWriter.breakContainer( ViewPosition.createAfter( viewItem ) );
  731. } else {
  732. // There is no list item with same indent. Check previous model item.
  733. if ( prevItem && prevItem.name == 'listItem' ) {
  734. // If it is a list item, it has to have lower indent.
  735. // It means that inserted item should be added to it as its nested item.
  736. insertPosition = mapper.toViewPosition( ModelPosition.createAt( prevItem, 'end' ) );
  737. } else {
  738. // Previous item is not a list item (or does not exist at all).
  739. // Just map the position and insert the view item at mapped position.
  740. insertPosition = mapper.toViewPosition( ModelPosition.createBefore( modelItem ) );
  741. }
  742. }
  743. insertPosition = positionAfterUiElements( insertPosition );
  744. // Insert the view item.
  745. viewWriter.insert( insertPosition, injectedList );
  746. // 2. Handle possible children of injected model item.
  747. if ( prevItem && prevItem.name == 'listItem' ) {
  748. const prevView = mapper.toViewElement( prevItem );
  749. const walker = new ViewTreeWalker( {
  750. boundaries: new ViewRange(
  751. ViewPosition.createAt( prevView, 0 ),
  752. insertPosition
  753. ),
  754. ignoreElementEnd: true
  755. } );
  756. for ( const value of walker ) {
  757. if ( value.item.is( 'li' ) ) {
  758. const breakPosition = viewWriter.breakContainer( ViewPosition.createBefore( value.item ) );
  759. const viewList = value.item.parent;
  760. const targetPosition = ViewPosition.createAt( injectedItem, 'end' );
  761. mergeViewLists( viewWriter, targetPosition.nodeBefore, targetPosition.nodeAfter );
  762. viewWriter.move( ViewRange.createOn( viewList ), targetPosition );
  763. walker.position = breakPosition;
  764. }
  765. }
  766. } else {
  767. const nextViewList = injectedList.nextSibling;
  768. if ( nextViewList && ( nextViewList.is( 'ul' ) || nextViewList.is( 'ol' ) ) ) {
  769. let lastSubChild = null;
  770. for ( const child of nextViewList.getChildren() ) {
  771. const modelChild = mapper.toModelElement( child );
  772. if ( modelChild && modelChild.getAttribute( 'listIndent' ) > modelItem.getAttribute( 'listIndent' ) ) {
  773. lastSubChild = child;
  774. } else {
  775. break;
  776. }
  777. }
  778. if ( lastSubChild ) {
  779. viewWriter.breakContainer( ViewPosition.createAfter( lastSubChild ) );
  780. viewWriter.move( ViewRange.createOn( lastSubChild.parent ), ViewPosition.createAt( injectedItem, 'end' ) );
  781. }
  782. }
  783. }
  784. // Merge inserted view list with its possible neighbour lists.
  785. mergeViewLists( viewWriter, injectedList, injectedList.nextSibling );
  786. mergeViewLists( viewWriter, injectedList.previousSibling, injectedList );
  787. }
  788. // Helper function that takes all children of given `viewRemovedItem` and moves them in a correct place, according
  789. // to other given parameters.
  790. function hoistNestedLists( nextIndent, modelRemoveStartPosition, viewRemoveStartPosition, viewRemovedItem, conversionApi ) {
  791. // Find correct previous model list item element.
  792. // The element has to have either same or smaller indent than given reference indent.
  793. // This will be the model element which will get nested items (if it has smaller indent) or sibling items (if it has same indent).
  794. // Keep in mind that such element might not be found, if removed item was the first item.
  795. const prevModelItem = getSiblingListItem( modelRemoveStartPosition, {
  796. sameIndent: true,
  797. smallerIndent: true,
  798. listIndent: nextIndent
  799. } );
  800. const mapper = conversionApi.mapper;
  801. const viewWriter = conversionApi.writer;
  802. // Indent of found element or `null` if the element has not been found.
  803. const prevIndent = prevModelItem ? prevModelItem.getAttribute( 'listIndent' ) : null;
  804. let insertPosition;
  805. if ( !prevModelItem ) {
  806. // If element has not been found, simply insert lists at the position where the removed item was:
  807. //
  808. // Lorem ipsum.
  809. // 1 -------- <--- this is removed, no previous list item, put nested items in place of removed item.
  810. // 1.1 -------- <--- this is reference indent.
  811. // 1.1.1 --------
  812. // 1.1.2 --------
  813. // 1.2 --------
  814. //
  815. // Becomes:
  816. //
  817. // Lorem ipsum.
  818. // 1.1 --------
  819. // 1.1.1 --------
  820. // 1.1.2 --------
  821. // 1.2 --------
  822. insertPosition = viewRemoveStartPosition;
  823. } else if ( prevIndent == nextIndent ) {
  824. // If element has been found and has same indent as reference indent it means that nested items should
  825. // become siblings of found element:
  826. //
  827. // 1 --------
  828. // 1.1 --------
  829. // 1.2 -------- <--- this is `prevModelItem`.
  830. // 2 -------- <--- this is removed, previous list item has indent same as reference indent.
  831. // 2.1 -------- <--- this is reference indent, this and 2.2 should become siblings of 1.2.
  832. // 2.2 --------
  833. //
  834. // Becomes:
  835. //
  836. // 1 --------
  837. // 1.1 --------
  838. // 1.2 --------
  839. // 2.1 --------
  840. // 2.2 --------
  841. const prevViewList = mapper.toViewElement( prevModelItem ).parent;
  842. insertPosition = ViewPosition.createAfter( prevViewList );
  843. } else {
  844. // If element has been found and has smaller indent as reference indent it means that nested items
  845. // should become nested items of found item:
  846. //
  847. // 1 -------- <--- this is `prevModelItem`.
  848. // 1.1 -------- <--- this is removed, previous list item has indent smaller than reference indent.
  849. // 1.1.1 -------- <--- this is reference indent, this and 1.1.1 should become nested items of 1.
  850. // 1.1.2 --------
  851. // 1.2 --------
  852. //
  853. // Becomes:
  854. //
  855. // 1 --------
  856. // 1.1.1 --------
  857. // 1.1.2 --------
  858. // 1.2 --------
  859. //
  860. // Note: in this case 1.1.1 have indent 2 while 1 have indent 0. In model that should not be possible,
  861. // because following item may have indent bigger only by one. But this is fixed by postfixer.
  862. const modelPosition = ModelPosition.createAt( prevModelItem, 'end' );
  863. insertPosition = mapper.toViewPosition( modelPosition );
  864. }
  865. insertPosition = positionAfterUiElements( insertPosition );
  866. // Handle multiple lists. This happens if list item has nested numbered and bulleted lists. Following lists
  867. // are inserted after the first list (no need to recalculate insertion position for them).
  868. for ( const child of [ ...viewRemovedItem.getChildren() ] ) {
  869. if ( child.is( 'ul' ) || child.is( 'ol' ) ) {
  870. insertPosition = viewWriter.move( ViewRange.createOn( child ), insertPosition ).end;
  871. mergeViewLists( viewWriter, child, child.nextSibling );
  872. mergeViewLists( viewWriter, child.previousSibling, child );
  873. }
  874. }
  875. }
  876. // Helper function that for given `view.Position`, returns a `view.Position` that is after all `view.UIElement`s that
  877. // are after given position.
  878. // For example:
  879. // <container:p>foo^<ui:span></ui:span><ui:span></ui:span>bar</contain:p>
  880. // For position ^, a position before "bar" will be returned.
  881. function positionAfterUiElements( viewPosition ) {
  882. return viewPosition.getLastMatchingPosition( value => value.item.is( 'uiElement' ) );
  883. }