plugin.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. /**
  2. * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or http://ckeditor.com/license
  4. */
  5. /**
  6. * @fileOverview Insert and remove numbered and bulleted lists.
  7. */
  8. ( function() {
  9. var listNodeNames = { ol: 1, ul: 1 };
  10. var whitespaces = CKEDITOR.dom.walker.whitespaces(),
  11. bookmarks = CKEDITOR.dom.walker.bookmark(),
  12. nonEmpty = function( node ) {
  13. return !( whitespaces( node ) || bookmarks( node ) );
  14. },
  15. blockBogus = CKEDITOR.dom.walker.bogus();
  16. function cleanUpDirection( element ) {
  17. var dir, parent, parentDir;
  18. if ( ( dir = element.getDirection() ) ) {
  19. parent = element.getParent();
  20. while ( parent && !( parentDir = parent.getDirection() ) )
  21. parent = parent.getParent();
  22. if ( dir == parentDir )
  23. element.removeAttribute( 'dir' );
  24. }
  25. }
  26. // Inherit inline styles from another element.
  27. function inheritInlineStyles( parent, el ) {
  28. var style = parent.getAttribute( 'style' );
  29. // Put parent styles before child styles.
  30. style && el.setAttribute( 'style', style.replace( /([^;])$/, '$1;' ) + ( el.getAttribute( 'style' ) || '' ) );
  31. }
  32. CKEDITOR.plugins.list = {
  33. /**
  34. * Convert a DOM list tree into a data structure that is easier to
  35. * manipulate. This operation should be non-intrusive in the sense that it
  36. * does not change the DOM tree, with the exception that it may add some
  37. * markers to the list item nodes when database is specified.
  38. *
  39. * @member CKEDITOR.plugins.list
  40. * @todo params
  41. */
  42. listToArray: function( listNode, database, baseArray, baseIndentLevel, grandparentNode ) {
  43. if ( !listNodeNames[ listNode.getName() ] )
  44. return [];
  45. if ( !baseIndentLevel )
  46. baseIndentLevel = 0;
  47. if ( !baseArray )
  48. baseArray = [];
  49. // Iterate over all list items to and look for inner lists.
  50. for ( var i = 0, count = listNode.getChildCount(); i < count; i++ ) {
  51. var listItem = listNode.getChild( i );
  52. // Fixing malformed nested lists by moving it into a previous list item. (#6236)
  53. if ( listItem.type == CKEDITOR.NODE_ELEMENT && listItem.getName() in CKEDITOR.dtd.$list )
  54. CKEDITOR.plugins.list.listToArray( listItem, database, baseArray, baseIndentLevel + 1 );
  55. // It may be a text node or some funny stuff.
  56. if ( listItem.$.nodeName.toLowerCase() != 'li' )
  57. continue;
  58. var itemObj = { 'parent': listNode, indent: baseIndentLevel, element: listItem, contents: [] };
  59. if ( !grandparentNode ) {
  60. itemObj.grandparent = listNode.getParent();
  61. if ( itemObj.grandparent && itemObj.grandparent.$.nodeName.toLowerCase() == 'li' )
  62. itemObj.grandparent = itemObj.grandparent.getParent();
  63. } else {
  64. itemObj.grandparent = grandparentNode;
  65. }
  66. if ( database )
  67. CKEDITOR.dom.element.setMarker( database, listItem, 'listarray_index', baseArray.length );
  68. baseArray.push( itemObj );
  69. for ( var j = 0, itemChildCount = listItem.getChildCount(), child; j < itemChildCount; j++ ) {
  70. child = listItem.getChild( j );
  71. if ( child.type == CKEDITOR.NODE_ELEMENT && listNodeNames[ child.getName() ] )
  72. // Note the recursion here, it pushes inner list items with
  73. // +1 indentation in the correct order.
  74. CKEDITOR.plugins.list.listToArray( child, database, baseArray, baseIndentLevel + 1, itemObj.grandparent );
  75. else
  76. itemObj.contents.push( child );
  77. }
  78. }
  79. return baseArray;
  80. },
  81. /**
  82. * Convert our internal representation of a list back to a DOM forest.
  83. *
  84. * @member CKEDITOR.plugins.list
  85. * @todo params
  86. */
  87. arrayToList: function( listArray, database, baseIndex, paragraphMode, dir ) {
  88. if ( !baseIndex )
  89. baseIndex = 0;
  90. if ( !listArray || listArray.length < baseIndex + 1 )
  91. return null;
  92. var i,
  93. doc = listArray[ baseIndex ].parent.getDocument(),
  94. retval = new CKEDITOR.dom.documentFragment( doc ),
  95. rootNode = null,
  96. currentIndex = baseIndex,
  97. indentLevel = Math.max( listArray[ baseIndex ].indent, 0 ),
  98. currentListItem = null,
  99. orgDir, block,
  100. paragraphName = ( paragraphMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
  101. while ( 1 ) {
  102. var item = listArray[ currentIndex ],
  103. itemGrandParent = item.grandparent;
  104. orgDir = item.element.getDirection( 1 );
  105. if ( item.indent == indentLevel ) {
  106. if ( !rootNode || listArray[ currentIndex ].parent.getName() != rootNode.getName() ) {
  107. rootNode = listArray[ currentIndex ].parent.clone( false, 1 );
  108. dir && rootNode.setAttribute( 'dir', dir );
  109. retval.append( rootNode );
  110. }
  111. currentListItem = rootNode.append( item.element.clone( 0, 1 ) );
  112. if ( orgDir != rootNode.getDirection( 1 ) )
  113. currentListItem.setAttribute( 'dir', orgDir );
  114. for ( i = 0; i < item.contents.length; i++ )
  115. currentListItem.append( item.contents[ i ].clone( 1, 1 ) );
  116. currentIndex++;
  117. } else if ( item.indent == Math.max( indentLevel, 0 ) + 1 ) {
  118. // Maintain original direction (#6861).
  119. var currDir = listArray[ currentIndex - 1 ].element.getDirection( 1 ),
  120. listData = CKEDITOR.plugins.list.arrayToList( listArray, null, currentIndex, paragraphMode, currDir != orgDir ? orgDir : null );
  121. // If the next block is an <li> with another list tree as the first
  122. // child, we'll need to append a filler (<br>/NBSP) or the list item
  123. // wouldn't be editable. (#6724)
  124. if ( !currentListItem.getChildCount() && CKEDITOR.env.needsNbspFiller && doc.$.documentMode <= 7 )
  125. currentListItem.append( doc.createText( '\xa0' ) );
  126. currentListItem.append( listData.listNode );
  127. currentIndex = listData.nextIndex;
  128. } else if ( item.indent == -1 && !baseIndex && itemGrandParent ) {
  129. if ( listNodeNames[ itemGrandParent.getName() ] ) {
  130. currentListItem = item.element.clone( false, true );
  131. if ( orgDir != itemGrandParent.getDirection( 1 ) )
  132. currentListItem.setAttribute( 'dir', orgDir );
  133. } else {
  134. currentListItem = new CKEDITOR.dom.documentFragment( doc );
  135. }
  136. // Migrate all children to the new container,
  137. // apply the proper text direction.
  138. var dirLoose = itemGrandParent.getDirection( 1 ) != orgDir,
  139. li = item.element,
  140. className = li.getAttribute( 'class' ),
  141. style = li.getAttribute( 'style' );
  142. var needsBlock = currentListItem.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT && ( paragraphMode != CKEDITOR.ENTER_BR || dirLoose || style || className );
  143. var child,
  144. count = item.contents.length,
  145. cachedBookmark;
  146. for ( i = 0; i < count; i++ ) {
  147. child = item.contents[ i ];
  148. // Append bookmark if we can, or cache it and append it when we'll know
  149. // what to do with it. Generally - we want to keep it next to its original neighbour.
  150. // Exception: if bookmark is the only child it hasn't got any neighbour, so handle it normally
  151. // (wrap with block if needed).
  152. if ( bookmarks( child ) && count > 1 ) {
  153. // If we don't need block, it's simple - append bookmark directly to the current list item.
  154. if ( !needsBlock )
  155. currentListItem.append( child.clone( 1, 1 ) );
  156. else
  157. cachedBookmark = child.clone( 1, 1 );
  158. }
  159. // Block content goes directly to the current list item, without wrapping.
  160. else if ( child.type == CKEDITOR.NODE_ELEMENT && child.isBlockBoundary() ) {
  161. // Apply direction on content blocks.
  162. if ( dirLoose && !child.getDirection() )
  163. child.setAttribute( 'dir', orgDir );
  164. inheritInlineStyles( li, child );
  165. className && child.addClass( className );
  166. // Close the block which we started for inline content.
  167. block = null;
  168. // Append bookmark directly before current child.
  169. if ( cachedBookmark ) {
  170. currentListItem.append( cachedBookmark );
  171. cachedBookmark = null;
  172. }
  173. // Append this block element to the list item.
  174. currentListItem.append( child.clone( 1, 1 ) );
  175. }
  176. // Some inline content was found - wrap it with block and append that
  177. // block to the current list item or append it to the block previously created.
  178. else if ( needsBlock ) {
  179. // Establish new block to hold text direction and styles.
  180. if ( !block ) {
  181. block = doc.createElement( paragraphName );
  182. currentListItem.append( block );
  183. dirLoose && block.setAttribute( 'dir', orgDir );
  184. }
  185. // Copy over styles to new block;
  186. style && block.setAttribute( 'style', style );
  187. className && block.setAttribute( 'class', className );
  188. // Append bookmark directly before current child.
  189. if ( cachedBookmark ) {
  190. block.append( cachedBookmark );
  191. cachedBookmark = null;
  192. }
  193. block.append( child.clone( 1, 1 ) );
  194. }
  195. // E.g. BR mode - inline content appended directly to the list item.
  196. else {
  197. currentListItem.append( child.clone( 1, 1 ) );
  198. }
  199. }
  200. // No content after bookmark - append it to the block if we had one
  201. // or directly to the current list item if we finished directly in the current list item.
  202. if ( cachedBookmark ) {
  203. ( block || currentListItem ).append( cachedBookmark );
  204. cachedBookmark = null;
  205. }
  206. if ( currentListItem.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT && currentIndex != listArray.length - 1 ) {
  207. var last;
  208. // Remove bogus <br> if this browser uses them.
  209. if ( CKEDITOR.env.needsBrFiller ) {
  210. last = currentListItem.getLast();
  211. if ( last && last.type == CKEDITOR.NODE_ELEMENT && last.is( 'br' ) )
  212. last.remove();
  213. }
  214. // If the last element is not a block, append <br> to separate merged list items.
  215. last = currentListItem.getLast( nonEmpty );
  216. if ( !( last && last.type == CKEDITOR.NODE_ELEMENT && last.is( CKEDITOR.dtd.$block ) ) )
  217. currentListItem.append( doc.createElement( 'br' ) );
  218. }
  219. var currentListItemName = currentListItem.$.nodeName.toLowerCase();
  220. if ( currentListItemName == 'div' || currentListItemName == 'p' ) {
  221. currentListItem.appendBogus();
  222. }
  223. retval.append( currentListItem );
  224. rootNode = null;
  225. currentIndex++;
  226. } else {
  227. return null;
  228. }
  229. block = null;
  230. if ( listArray.length <= currentIndex || Math.max( listArray[ currentIndex ].indent, 0 ) < indentLevel )
  231. break;
  232. }
  233. if ( database ) {
  234. var currentNode = retval.getFirst();
  235. while ( currentNode ) {
  236. if ( currentNode.type == CKEDITOR.NODE_ELEMENT ) {
  237. // Clear marker attributes for the new list tree made of cloned nodes, if any.
  238. CKEDITOR.dom.element.clearMarkers( database, currentNode );
  239. // Clear redundant direction attribute specified on list items.
  240. if ( currentNode.getName() in CKEDITOR.dtd.$listItem )
  241. cleanUpDirection( currentNode );
  242. }
  243. currentNode = currentNode.getNextSourceNode();
  244. }
  245. }
  246. return { listNode: retval, nextIndex: currentIndex };
  247. }
  248. };
  249. function changeListType( editor, groupObj, database, listsCreated ) {
  250. // This case is easy...
  251. // 1. Convert the whole list into a one-dimensional array.
  252. // 2. Change the list type by modifying the array.
  253. // 3. Recreate the whole list by converting the array to a list.
  254. // 4. Replace the original list with the recreated list.
  255. var listArray = CKEDITOR.plugins.list.listToArray( groupObj.root, database ),
  256. selectedListItems = [];
  257. for ( var i = 0; i < groupObj.contents.length; i++ ) {
  258. var itemNode = groupObj.contents[ i ];
  259. itemNode = itemNode.getAscendant( 'li', true );
  260. if ( !itemNode || itemNode.getCustomData( 'list_item_processed' ) )
  261. continue;
  262. selectedListItems.push( itemNode );
  263. CKEDITOR.dom.element.setMarker( database, itemNode, 'list_item_processed', true );
  264. }
  265. var root = groupObj.root,
  266. doc = root.getDocument(),
  267. listNode, newListNode;
  268. for ( i = 0; i < selectedListItems.length; i++ ) {
  269. var listIndex = selectedListItems[ i ].getCustomData( 'listarray_index' );
  270. listNode = listArray[ listIndex ].parent;
  271. // Switch to new list node for this particular item.
  272. if ( !listNode.is( this.type ) ) {
  273. newListNode = doc.createElement( this.type );
  274. // Copy all attributes, except from 'start' and 'type'.
  275. listNode.copyAttributes( newListNode, { start: 1, type: 1 } );
  276. // The list-style-type property should be ignored.
  277. newListNode.removeStyle( 'list-style-type' );
  278. listArray[ listIndex ].parent = newListNode;
  279. }
  280. }
  281. var newList = CKEDITOR.plugins.list.arrayToList( listArray, database, null, editor.config.enterMode );
  282. var child,
  283. length = newList.listNode.getChildCount();
  284. for ( i = 0; i < length && ( child = newList.listNode.getChild( i ) ); i++ ) {
  285. if ( child.getName() == this.type )
  286. listsCreated.push( child );
  287. }
  288. newList.listNode.replace( groupObj.root );
  289. editor.fire( 'contentDomInvalidated' );
  290. }
  291. function createList( editor, groupObj, listsCreated ) {
  292. var contents = groupObj.contents,
  293. doc = groupObj.root.getDocument(),
  294. listContents = [];
  295. // It is possible to have the contents returned by DomRangeIterator to be the same as the root.
  296. // e.g. when we're running into table cells.
  297. // In such a case, enclose the childNodes of contents[0] into a <div>.
  298. if ( contents.length == 1 && contents[ 0 ].equals( groupObj.root ) ) {
  299. var divBlock = doc.createElement( 'div' );
  300. contents[ 0 ].moveChildren && contents[ 0 ].moveChildren( divBlock );
  301. contents[ 0 ].append( divBlock );
  302. contents[ 0 ] = divBlock;
  303. }
  304. // Calculate the common parent node of all content blocks.
  305. var commonParent = groupObj.contents[ 0 ].getParent();
  306. for ( var i = 0; i < contents.length; i++ )
  307. commonParent = commonParent.getCommonAncestor( contents[ i ].getParent() );
  308. var useComputedState = editor.config.useComputedState,
  309. listDir, explicitDirection;
  310. useComputedState = useComputedState === undefined || useComputedState;
  311. // We want to insert things that are in the same tree level only, so calculate the contents again
  312. // by expanding the selected blocks to the same tree level.
  313. for ( i = 0; i < contents.length; i++ ) {
  314. var contentNode = contents[ i ],
  315. parentNode;
  316. while ( ( parentNode = contentNode.getParent() ) ) {
  317. if ( parentNode.equals( commonParent ) ) {
  318. listContents.push( contentNode );
  319. // Determine the lists's direction.
  320. if ( !explicitDirection && contentNode.getDirection() )
  321. explicitDirection = 1;
  322. var itemDir = contentNode.getDirection( useComputedState );
  323. if ( listDir !== null ) {
  324. // If at least one LI have a different direction than current listDir, we can't have listDir.
  325. if ( listDir && listDir != itemDir )
  326. listDir = null;
  327. else
  328. listDir = itemDir;
  329. }
  330. break;
  331. }
  332. contentNode = parentNode;
  333. }
  334. }
  335. if ( listContents.length < 1 )
  336. return;
  337. // Insert the list to the DOM tree.
  338. var insertAnchor = listContents[ listContents.length - 1 ].getNext(),
  339. listNode = doc.createElement( this.type );
  340. listsCreated.push( listNode );
  341. var contentBlock, listItem;
  342. while ( listContents.length ) {
  343. contentBlock = listContents.shift();
  344. listItem = doc.createElement( 'li' );
  345. // If current block should be preserved, append it to list item instead of
  346. // transforming it to <li> element.
  347. if ( shouldPreserveBlock( contentBlock ) )
  348. contentBlock.appendTo( listItem );
  349. else {
  350. contentBlock.copyAttributes( listItem );
  351. // Remove direction attribute after it was merged into list root. (#7657)
  352. if ( listDir && contentBlock.getDirection() ) {
  353. listItem.removeStyle( 'direction' );
  354. listItem.removeAttribute( 'dir' );
  355. }
  356. contentBlock.moveChildren( listItem );
  357. contentBlock.remove();
  358. }
  359. listItem.appendTo( listNode );
  360. }
  361. // Apply list root dir only if it has been explicitly declared.
  362. if ( listDir && explicitDirection )
  363. listNode.setAttribute( 'dir', listDir );
  364. if ( insertAnchor )
  365. listNode.insertBefore( insertAnchor );
  366. else
  367. listNode.appendTo( commonParent );
  368. }
  369. function removeList( editor, groupObj, database ) {
  370. // This is very much like the change list type operation.
  371. // Except that we're changing the selected items' indent to -1 in the list array.
  372. var listArray = CKEDITOR.plugins.list.listToArray( groupObj.root, database ),
  373. selectedListItems = [];
  374. for ( var i = 0; i < groupObj.contents.length; i++ ) {
  375. var itemNode = groupObj.contents[ i ];
  376. itemNode = itemNode.getAscendant( 'li', true );
  377. if ( !itemNode || itemNode.getCustomData( 'list_item_processed' ) )
  378. continue;
  379. selectedListItems.push( itemNode );
  380. CKEDITOR.dom.element.setMarker( database, itemNode, 'list_item_processed', true );
  381. }
  382. var lastListIndex = null;
  383. for ( i = 0; i < selectedListItems.length; i++ ) {
  384. var listIndex = selectedListItems[ i ].getCustomData( 'listarray_index' );
  385. listArray[ listIndex ].indent = -1;
  386. lastListIndex = listIndex;
  387. }
  388. // After cutting parts of the list out with indent=-1, we still have to maintain the array list
  389. // model's nextItem.indent <= currentItem.indent + 1 invariant. Otherwise the array model of the
  390. // list cannot be converted back to a real DOM list.
  391. for ( i = lastListIndex + 1; i < listArray.length; i++ ) {
  392. if ( listArray[ i ].indent > listArray[ i - 1 ].indent + 1 ) {
  393. var indentOffset = listArray[ i - 1 ].indent + 1 - listArray[ i ].indent;
  394. var oldIndent = listArray[ i ].indent;
  395. while ( listArray[ i ] && listArray[ i ].indent >= oldIndent ) {
  396. listArray[ i ].indent += indentOffset;
  397. i++;
  398. }
  399. i--;
  400. }
  401. }
  402. var newList = CKEDITOR.plugins.list.arrayToList( listArray, database, null, editor.config.enterMode, groupObj.root.getAttribute( 'dir' ) );
  403. // Compensate <br> before/after the list node if the surrounds are non-blocks.(#3836)
  404. var docFragment = newList.listNode,
  405. boundaryNode, siblingNode;
  406. function compensateBrs( isStart ) {
  407. if (
  408. ( boundaryNode = docFragment[ isStart ? 'getFirst' : 'getLast' ]() ) &&
  409. !( boundaryNode.is && boundaryNode.isBlockBoundary() ) &&
  410. ( siblingNode = groupObj.root[ isStart ? 'getPrevious' : 'getNext' ]( CKEDITOR.dom.walker.invisible( true ) ) ) &&
  411. !( siblingNode.is && siblingNode.isBlockBoundary( { br: 1 } ) )
  412. ) {
  413. editor.document.createElement( 'br' )[ isStart ? 'insertBefore' : 'insertAfter' ]( boundaryNode );
  414. }
  415. }
  416. compensateBrs( true );
  417. compensateBrs();
  418. docFragment.replace( groupObj.root );
  419. editor.fire( 'contentDomInvalidated' );
  420. }
  421. var headerTagRegex = /^h[1-6]$/;
  422. // Checks wheather this block should be element preserved (not transformed to <li>) when creating list.
  423. function shouldPreserveBlock( block ) {
  424. return (
  425. // #5335
  426. block.is( 'pre' ) ||
  427. // #5271 - this is a header.
  428. headerTagRegex.test( block.getName() ) ||
  429. // 11083 - this is a non-editable element.
  430. block.getAttribute( 'contenteditable' ) == 'false'
  431. );
  432. }
  433. function listCommand( name, type ) {
  434. this.name = name;
  435. this.type = type;
  436. this.context = type;
  437. this.allowedContent = type + ' li';
  438. this.requiredContent = type;
  439. }
  440. var elementType = CKEDITOR.dom.walker.nodeType( CKEDITOR.NODE_ELEMENT );
  441. // Merge child nodes with direction preserved. (#7448)
  442. function mergeChildren( from, into, refNode, forward ) {
  443. var child, itemDir;
  444. while ( ( child = from[ forward ? 'getLast' : 'getFirst' ]( elementType ) ) ) {
  445. if ( ( itemDir = child.getDirection( 1 ) ) !== into.getDirection( 1 ) )
  446. child.setAttribute( 'dir', itemDir );
  447. child.remove();
  448. refNode ? child[ forward ? 'insertBefore' : 'insertAfter' ]( refNode ) : into.append( child, forward );
  449. }
  450. }
  451. listCommand.prototype = {
  452. exec: function( editor ) {
  453. // Run state check first of all.
  454. this.refresh( editor, editor.elementPath() );
  455. var config = editor.config,
  456. selection = editor.getSelection(),
  457. ranges = selection && selection.getRanges();
  458. // Midas lists rule #1 says we can create a list even in an empty document.
  459. // But DOM iterator wouldn't run if the document is really empty.
  460. // So create a paragraph if the document is empty and we're going to create a list.
  461. if ( this.state == CKEDITOR.TRISTATE_OFF ) {
  462. var editable = editor.editable();
  463. if ( !editable.getFirst( nonEmpty ) ) {
  464. config.enterMode == CKEDITOR.ENTER_BR ? editable.appendBogus() : ranges[ 0 ].fixBlock( 1, config.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
  465. selection.selectRanges( ranges );
  466. }
  467. // Maybe a single range there enclosing the whole list,
  468. // turn on the list state manually(#4129).
  469. else {
  470. var range = ranges.length == 1 && ranges[ 0 ],
  471. enclosedNode = range && range.getEnclosedNode();
  472. if ( enclosedNode && enclosedNode.is && this.type == enclosedNode.getName() )
  473. this.setState( CKEDITOR.TRISTATE_ON );
  474. }
  475. }
  476. var bookmarks = selection.createBookmarks( true );
  477. // Group the blocks up because there are many cases where multiple lists have to be created,
  478. // or multiple lists have to be cancelled.
  479. var listGroups = [],
  480. database = {},
  481. rangeIterator = ranges.createIterator(),
  482. index = 0;
  483. while ( ( range = rangeIterator.getNextRange() ) && ++index ) {
  484. var boundaryNodes = range.getBoundaryNodes(),
  485. startNode = boundaryNodes.startNode,
  486. endNode = boundaryNodes.endNode;
  487. if ( startNode.type == CKEDITOR.NODE_ELEMENT && startNode.getName() == 'td' )
  488. range.setStartAt( boundaryNodes.startNode, CKEDITOR.POSITION_AFTER_START );
  489. if ( endNode.type == CKEDITOR.NODE_ELEMENT && endNode.getName() == 'td' )
  490. range.setEndAt( boundaryNodes.endNode, CKEDITOR.POSITION_BEFORE_END );
  491. var iterator = range.createIterator(),
  492. block;
  493. iterator.forceBrBreak = ( this.state == CKEDITOR.TRISTATE_OFF );
  494. while ( ( block = iterator.getNextParagraph() ) ) {
  495. // Avoid duplicate blocks get processed across ranges.
  496. if ( block.getCustomData( 'list_block' ) )
  497. continue;
  498. else
  499. CKEDITOR.dom.element.setMarker( database, block, 'list_block', 1 );
  500. var path = editor.elementPath( block ),
  501. pathElements = path.elements,
  502. pathElementsCount = pathElements.length,
  503. processedFlag = 0,
  504. blockLimit = path.blockLimit,
  505. element;
  506. // First, try to group by a list ancestor.
  507. for ( var i = pathElementsCount - 1; i >= 0 && ( element = pathElements[ i ] ); i-- ) {
  508. // Don't leak outside block limit (#3940).
  509. if ( listNodeNames[ element.getName() ] && blockLimit.contains( element ) ) {
  510. // If we've encountered a list inside a block limit
  511. // The last group object of the block limit element should
  512. // no longer be valid. Since paragraphs after the list
  513. // should belong to a different group of paragraphs before
  514. // the list. (Bug #1309)
  515. blockLimit.removeCustomData( 'list_group_object_' + index );
  516. var groupObj = element.getCustomData( 'list_group_object' );
  517. if ( groupObj )
  518. groupObj.contents.push( block );
  519. else {
  520. groupObj = { root: element, contents: [ block ] };
  521. listGroups.push( groupObj );
  522. CKEDITOR.dom.element.setMarker( database, element, 'list_group_object', groupObj );
  523. }
  524. processedFlag = 1;
  525. break;
  526. }
  527. }
  528. if ( processedFlag )
  529. continue;
  530. // No list ancestor? Group by block limit, but don't mix contents from different ranges.
  531. var root = blockLimit;
  532. if ( root.getCustomData( 'list_group_object_' + index ) )
  533. root.getCustomData( 'list_group_object_' + index ).contents.push( block );
  534. else {
  535. groupObj = { root: root, contents: [ block ] };
  536. CKEDITOR.dom.element.setMarker( database, root, 'list_group_object_' + index, groupObj );
  537. listGroups.push( groupObj );
  538. }
  539. }
  540. }
  541. // Now we have two kinds of list groups, groups rooted at a list, and groups rooted at a block limit element.
  542. // We either have to build lists or remove lists, for removing a list does not makes sense when we are looking
  543. // at the group that's not rooted at lists. So we have three cases to handle.
  544. var listsCreated = [];
  545. while ( listGroups.length > 0 ) {
  546. groupObj = listGroups.shift();
  547. if ( this.state == CKEDITOR.TRISTATE_OFF ) {
  548. if ( listNodeNames[ groupObj.root.getName() ] )
  549. changeListType.call( this, editor, groupObj, database, listsCreated );
  550. else
  551. createList.call( this, editor, groupObj, listsCreated );
  552. } else if ( this.state == CKEDITOR.TRISTATE_ON && listNodeNames[ groupObj.root.getName() ] ) {
  553. removeList.call( this, editor, groupObj, database );
  554. }
  555. }
  556. // For all new lists created, merge into adjacent, same type lists.
  557. for ( i = 0; i < listsCreated.length; i++ )
  558. mergeListSiblings( listsCreated[ i ] );
  559. // Clean up, restore selection and update toolbar button states.
  560. CKEDITOR.dom.element.clearAllMarkers( database );
  561. selection.selectBookmarks( bookmarks );
  562. editor.focus();
  563. },
  564. refresh: function( editor, path ) {
  565. var list = path.contains( listNodeNames, 1 ),
  566. limit = path.blockLimit || path.root;
  567. // 1. Only a single type of list activate.
  568. // 2. Do not show list outside of block limit.
  569. if ( list && limit.contains( list ) )
  570. this.setState( list.is( this.type ) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
  571. else
  572. this.setState( CKEDITOR.TRISTATE_OFF );
  573. }
  574. };
  575. // Merge list adjacent, of same type lists.
  576. function mergeListSiblings( listNode ) {
  577. function mergeSibling( rtl ) {
  578. var sibling = listNode[ rtl ? 'getPrevious' : 'getNext' ]( nonEmpty );
  579. if ( sibling && sibling.type == CKEDITOR.NODE_ELEMENT && sibling.is( listNode.getName() ) ) {
  580. // Move children order by merge direction.(#3820)
  581. mergeChildren( listNode, sibling, null, !rtl );
  582. listNode.remove();
  583. listNode = sibling;
  584. }
  585. }
  586. mergeSibling();
  587. mergeSibling( 1 );
  588. }
  589. // Check if node is block element that recieves text.
  590. function isTextBlock( node ) {
  591. return node.type == CKEDITOR.NODE_ELEMENT && ( node.getName() in CKEDITOR.dtd.$block || node.getName() in CKEDITOR.dtd.$listItem ) && CKEDITOR.dtd[ node.getName() ][ '#' ];
  592. }
  593. // Join visually two block lines.
  594. function joinNextLineToCursor( editor, cursor, nextCursor ) {
  595. editor.fire( 'saveSnapshot' );
  596. // Merge with previous block's content.
  597. nextCursor.enlarge( CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS );
  598. var frag = nextCursor.extractContents();
  599. cursor.trim( false, true );
  600. var bm = cursor.createBookmark();
  601. // Kill original bogus;
  602. var currentPath = new CKEDITOR.dom.elementPath( cursor.startContainer ),
  603. pathBlock = currentPath.block,
  604. currentBlock = currentPath.lastElement.getAscendant( 'li', 1 ) || pathBlock,
  605. nextPath = new CKEDITOR.dom.elementPath( nextCursor.startContainer ),
  606. nextLi = nextPath.contains( CKEDITOR.dtd.$listItem ),
  607. nextList = nextPath.contains( CKEDITOR.dtd.$list ),
  608. last;
  609. // Remove bogus node the current block/pseudo block.
  610. if ( pathBlock ) {
  611. var bogus = pathBlock.getBogus();
  612. bogus && bogus.remove();
  613. }
  614. else if ( nextList ) {
  615. last = nextList.getPrevious( nonEmpty );
  616. if ( last && blockBogus( last ) )
  617. last.remove();
  618. }
  619. // Kill the tail br in extracted.
  620. last = frag.getLast();
  621. if ( last && last.type == CKEDITOR.NODE_ELEMENT && last.is( 'br' ) )
  622. last.remove();
  623. // Insert fragment at the range position.
  624. var nextNode = cursor.startContainer.getChild( cursor.startOffset );
  625. if ( nextNode )
  626. frag.insertBefore( nextNode );
  627. else
  628. cursor.startContainer.append( frag );
  629. // Move the sub list nested in the next list item.
  630. if ( nextLi ) {
  631. var sublist = getSubList( nextLi );
  632. if ( sublist ) {
  633. // If next line is in the sub list of the current list item.
  634. if ( currentBlock.contains( nextLi ) ) {
  635. mergeChildren( sublist, nextLi.getParent(), nextLi );
  636. sublist.remove();
  637. }
  638. // Migrate the sub list to current list item.
  639. else {
  640. currentBlock.append( sublist );
  641. }
  642. }
  643. }
  644. var nextBlock, parent;
  645. // Remove any remaining zombies path blocks at the end after line merged.
  646. while ( nextCursor.checkStartOfBlock() && nextCursor.checkEndOfBlock() ) {
  647. nextPath = nextCursor.startPath();
  648. nextBlock = nextPath.block;
  649. // Abort when nothing to be removed (#10890).
  650. if ( !nextBlock )
  651. break;
  652. // Check if also to remove empty list.
  653. if ( nextBlock.is( 'li' ) ) {
  654. parent = nextBlock.getParent();
  655. if ( nextBlock.equals( parent.getLast( nonEmpty ) ) && nextBlock.equals( parent.getFirst( nonEmpty ) ) )
  656. nextBlock = parent;
  657. }
  658. nextCursor.moveToPosition( nextBlock, CKEDITOR.POSITION_BEFORE_START );
  659. nextBlock.remove();
  660. }
  661. // Check if need to further merge with the list resides after the merged block. (#9080)
  662. var walkerRng = nextCursor.clone(), editable = editor.editable();
  663. walkerRng.setEndAt( editable, CKEDITOR.POSITION_BEFORE_END );
  664. var walker = new CKEDITOR.dom.walker( walkerRng );
  665. walker.evaluator = function( node ) {
  666. return nonEmpty( node ) && !blockBogus( node );
  667. };
  668. var next = walker.next();
  669. if ( next && next.type == CKEDITOR.NODE_ELEMENT && next.getName() in CKEDITOR.dtd.$list )
  670. mergeListSiblings( next );
  671. cursor.moveToBookmark( bm );
  672. // Make fresh selection.
  673. cursor.select();
  674. editor.fire( 'saveSnapshot' );
  675. }
  676. function getSubList( li ) {
  677. var last = li.getLast( nonEmpty );
  678. return last && last.type == CKEDITOR.NODE_ELEMENT && last.getName() in listNodeNames ? last : null;
  679. }
  680. CKEDITOR.plugins.add( 'list', {
  681. // jscs:disable maximumLineLength
  682. lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE%
  683. // jscs:enable maximumLineLength
  684. icons: 'bulletedlist,bulletedlist-rtl,numberedlist,numberedlist-rtl', // %REMOVE_LINE_CORE%
  685. hidpi: true, // %REMOVE_LINE_CORE%
  686. requires: 'indentlist',
  687. init: function( editor ) {
  688. if ( editor.blockless )
  689. return;
  690. // Register commands.
  691. editor.addCommand( 'numberedlist', new listCommand( 'numberedlist', 'ol' ) );
  692. editor.addCommand( 'bulletedlist', new listCommand( 'bulletedlist', 'ul' ) );
  693. // Register the toolbar button.
  694. if ( editor.ui.addButton ) {
  695. editor.ui.addButton( 'NumberedList', {
  696. label: editor.lang.list.numberedlist,
  697. command: 'numberedlist',
  698. directional: true,
  699. toolbar: 'list,10'
  700. } );
  701. editor.ui.addButton( 'BulletedList', {
  702. label: editor.lang.list.bulletedlist,
  703. command: 'bulletedlist',
  704. directional: true,
  705. toolbar: 'list,20'
  706. } );
  707. }
  708. // Handled backspace/del key to join list items. (#8248,#9080)
  709. editor.on( 'key', function( evt ) {
  710. // Use getKey directly in order to ignore modifiers.
  711. // Justification: http://dev.ckeditor.com/ticket/11861#comment:13
  712. var key = evt.data.domEvent.getKey(), li;
  713. // DEl/BACKSPACE
  714. if ( editor.mode == 'wysiwyg' && key in { 8: 1, 46: 1 } ) {
  715. var sel = editor.getSelection(),
  716. range = sel.getRanges()[ 0 ],
  717. path = range && range.startPath();
  718. if ( !range || !range.collapsed )
  719. return;
  720. var isBackspace = key == 8;
  721. var editable = editor.editable();
  722. var walker = new CKEDITOR.dom.walker( range.clone() );
  723. walker.evaluator = function( node ) {
  724. return nonEmpty( node ) && !blockBogus( node );
  725. };
  726. // Backspace/Del behavior at the start/end of table is handled in core.
  727. walker.guard = function( node, isOut ) {
  728. return !( isOut && node.type == CKEDITOR.NODE_ELEMENT && node.is( 'table' ) );
  729. };
  730. var cursor = range.clone();
  731. if ( isBackspace ) {
  732. var previous, joinWith;
  733. // Join a sub list's first line, with the previous visual line in parent.
  734. if (
  735. ( previous = path.contains( listNodeNames ) ) &&
  736. range.checkBoundaryOfElement( previous, CKEDITOR.START ) &&
  737. ( previous = previous.getParent() ) && previous.is( 'li' ) &&
  738. ( previous = getSubList( previous ) )
  739. ) {
  740. joinWith = previous;
  741. previous = previous.getPrevious( nonEmpty );
  742. // Place cursor before the nested list.
  743. cursor.moveToPosition(
  744. previous && blockBogus( previous ) ? previous : joinWith,
  745. CKEDITOR.POSITION_BEFORE_START );
  746. }
  747. // Join any line following a list, with the last visual line of the list.
  748. else {
  749. walker.range.setStartAt( editable, CKEDITOR.POSITION_AFTER_START );
  750. walker.range.setEnd( range.startContainer, range.startOffset );
  751. previous = walker.previous();
  752. if (
  753. previous && previous.type == CKEDITOR.NODE_ELEMENT &&
  754. ( previous.getName() in listNodeNames ||
  755. previous.is( 'li' ) )
  756. ) {
  757. if ( !previous.is( 'li' ) ) {
  758. walker.range.selectNodeContents( previous );
  759. walker.reset();
  760. walker.evaluator = isTextBlock;
  761. previous = walker.previous();
  762. }
  763. joinWith = previous;
  764. // Place cursor at the end of previous block.
  765. cursor.moveToElementEditEnd( joinWith );
  766. // And then just before end of closest block element (#12729).
  767. cursor.moveToPosition( cursor.endPath().block, CKEDITOR.POSITION_BEFORE_END );
  768. }
  769. }
  770. if ( joinWith ) {
  771. joinNextLineToCursor( editor, cursor, range );
  772. evt.cancel();
  773. }
  774. else {
  775. var list = path.contains( listNodeNames );
  776. // Backspace pressed at the start of list outdents the first list item. (#9129)
  777. if ( list && range.checkBoundaryOfElement( list, CKEDITOR.START ) ) {
  778. li = list.getFirst( nonEmpty );
  779. if ( range.checkBoundaryOfElement( li, CKEDITOR.START ) ) {
  780. previous = list.getPrevious( nonEmpty );
  781. // Only if the list item contains a sub list, do nothing but
  782. // simply move cursor backward one character.
  783. if ( getSubList( li ) ) {
  784. if ( previous ) {
  785. range.moveToElementEditEnd( previous );
  786. range.select();
  787. }
  788. evt.cancel();
  789. }
  790. else {
  791. editor.execCommand( 'outdent' );
  792. evt.cancel();
  793. }
  794. }
  795. }
  796. }
  797. } else {
  798. var next, nextLine;
  799. li = path.contains( 'li' );
  800. if ( li ) {
  801. walker.range.setEndAt( editable, CKEDITOR.POSITION_BEFORE_END );
  802. var last = li.getLast( nonEmpty );
  803. var block = last && isTextBlock( last ) ? last : li;
  804. // Indicate cursor at the visual end of an list item.
  805. var isAtEnd = 0;
  806. next = walker.next();
  807. // When list item contains a sub list.
  808. if (
  809. next && next.type == CKEDITOR.NODE_ELEMENT &&
  810. next.getName() in listNodeNames &&
  811. next.equals( last )
  812. ) {
  813. isAtEnd = 1;
  814. // Move to the first item in sub list.
  815. next = walker.next();
  816. }
  817. // Right at the end of list item.
  818. else if ( range.checkBoundaryOfElement( block, CKEDITOR.END ) ) {
  819. isAtEnd = 2;
  820. }
  821. if ( isAtEnd && next ) {
  822. // Put cursor range there.
  823. nextLine = range.clone();
  824. nextLine.moveToElementEditStart( next );
  825. // #13409
  826. // For the following case and similar
  827. //
  828. // <ul>
  829. // <li>
  830. // <p><a href="#one"><em>x^</em></a></p>
  831. // <ul>
  832. // <li><span>y</span></li>
  833. // </ul>
  834. // </li>
  835. // </ul>
  836. if ( isAtEnd == 1 ) {
  837. // Move the cursor to <em> if attached to "x" text node.
  838. cursor.optimize();
  839. // Abort if the range is attached directly in <li>, like
  840. //
  841. // <ul>
  842. // <li>
  843. // x^
  844. // <ul>
  845. // <li><span>y</span></li>
  846. // </ul>
  847. // </li>
  848. // </ul>
  849. if ( !cursor.startContainer.equals( li ) ) {
  850. var node = cursor.startContainer,
  851. farthestInlineAscendant;
  852. // Find <a>, which is farthest from <em> but still inline element.
  853. while ( node.is( CKEDITOR.dtd.$inline ) ) {
  854. farthestInlineAscendant = node;
  855. node = node.getParent();
  856. }
  857. // Move the range so it does not contain inline elements.
  858. // It prevents <span> from being included in <em>.
  859. //
  860. // <ul>
  861. // <li>
  862. // <p><a href="#one"><em>x</em></a>^</p>
  863. // <ul>
  864. // <li><span>y</span></li>
  865. // </ul>
  866. // </li>
  867. // </ul>
  868. //
  869. // so instead of
  870. //
  871. // <ul>
  872. // <li>
  873. // <p><a href="#one"><em>x^<span>y</span></em></a></p>
  874. // </li>
  875. // </ul>
  876. //
  877. // pressing DELETE produces
  878. //
  879. // <ul>
  880. // <li>
  881. // <p><a href="#one"><em>x</em></a>^<span>y</span></p>
  882. // </li>
  883. // </ul>
  884. if ( farthestInlineAscendant ) {
  885. cursor.moveToPosition( farthestInlineAscendant, CKEDITOR.POSITION_AFTER_END );
  886. }
  887. }
  888. }
  889. // Moving `cursor` and `next line` only when at the end literally (#12729).
  890. if ( isAtEnd == 2 ) {
  891. cursor.moveToPosition( cursor.endPath().block, CKEDITOR.POSITION_BEFORE_END );
  892. // Next line might be text node not wrapped in block element.
  893. if ( nextLine.endPath().block ) {
  894. nextLine.moveToPosition( nextLine.endPath().block, CKEDITOR.POSITION_AFTER_START );
  895. }
  896. }
  897. joinNextLineToCursor( editor, cursor, nextLine );
  898. evt.cancel();
  899. }
  900. } else {
  901. // Handle Del key pressed before the list.
  902. walker.range.setEndAt( editable, CKEDITOR.POSITION_BEFORE_END );
  903. next = walker.next();
  904. if ( next && next.type == CKEDITOR.NODE_ELEMENT && next.is( listNodeNames ) ) {
  905. // The start <li>
  906. next = next.getFirst( nonEmpty );
  907. // Simply remove the current empty block, move cursor to the
  908. // subsequent list.
  909. if ( path.block && range.checkStartOfBlock() && range.checkEndOfBlock() ) {
  910. path.block.remove();
  911. range.moveToElementEditStart( next );
  912. range.select();
  913. evt.cancel();
  914. }
  915. // Preventing the default (merge behavior), but simply move
  916. // the cursor one character forward if subsequent list item
  917. // contains sub list.
  918. else if ( getSubList( next ) ) {
  919. range.moveToElementEditStart( next );
  920. range.select();
  921. evt.cancel();
  922. }
  923. // Merge the first list item with the current line.
  924. else {
  925. nextLine = range.clone();
  926. nextLine.moveToElementEditStart( next );
  927. joinNextLineToCursor( editor, cursor, nextLine );
  928. evt.cancel();
  929. }
  930. }
  931. }
  932. }
  933. // The backspace/del could potentially put cursor at a bad position,
  934. // being it handled or not, check immediately the selection to have it fixed.
  935. setTimeout( function() {
  936. editor.selectionChange( 1 );
  937. } );
  938. }
  939. } );
  940. }
  941. } );
  942. } )();