liststyleediting.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module list/liststyleediting
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import ListEditing from './listediting';
  10. import ListStyleCommand from './liststylecommand';
  11. import { getSiblingListItem, getSiblingNodes } from './utils';
  12. const DEFAULT_LIST_TYPE = 'default';
  13. /**
  14. * The list styles engine feature.
  15. *
  16. * It sets value for the `listItem` attribute for the {@link module:list/list~List `<listItem>`} element that
  17. * allows modifying list style type.
  18. *
  19. * It registers the `'listStyle'` command.
  20. *
  21. * @extends module:core/plugin~Plugin
  22. */
  23. export default class ListStyleEditing extends Plugin {
  24. /**
  25. * @inheritDoc
  26. */
  27. static get requires() {
  28. return [ ListEditing ];
  29. }
  30. /**
  31. * @inheritDoc
  32. */
  33. static get pluginName() {
  34. return 'ListStyleEditing';
  35. }
  36. /**
  37. * @inheritDoc
  38. */
  39. init() {
  40. const editor = this.editor;
  41. const model = editor.model;
  42. // Extend schema.
  43. model.schema.extend( 'listItem', {
  44. allowAttributes: [ 'listStyle' ]
  45. } );
  46. editor.commands.add( 'listStyle', new ListStyleCommand( editor, DEFAULT_LIST_TYPE ) );
  47. // Fix list attributes when modifying their nesting levels (the `listIndent` attribute).
  48. this.listenTo( editor.commands.get( 'indentList' ), '_executeCleanup', fixListAfterIndentListCommand( editor ) );
  49. this.listenTo( editor.commands.get( 'outdentList' ), '_executeCleanup', fixListAfterOutdentListCommand( editor ) );
  50. this.listenTo( editor.commands.get( 'bulletedList' ), '_executeCleanup', restoreDefaultListStyle( editor ) );
  51. this.listenTo( editor.commands.get( 'numberedList' ), '_executeCleanup', restoreDefaultListStyle( editor ) );
  52. // Register a post-fixer that ensures that the `listStyle` attribute is specified in each `listItem` element.
  53. model.document.registerPostFixer( fixListStyleAttributeOnListItemElements( editor ) );
  54. // Set up conversion.
  55. editor.conversion.for( 'upcast' ).add( upcastListItemStyle() );
  56. editor.conversion.for( 'downcast' ).add( downcastListStyleAttribute() );
  57. // Handle merging two separated lists into the single one.
  58. this._mergeListStyleAttributeWhileMergingLists();
  59. }
  60. /**
  61. * @inheritDoc
  62. */
  63. afterInit() {
  64. const editor = this.editor;
  65. // Enable post-fixer that removes the `listStyle` attribute from to-do list items only if the "TodoList" plugin is on.
  66. // We need to registry the hook here since the `TodoList` plugin can be added after the `ListStyleEditing`.
  67. if ( editor.commands.get( 'todoList' ) ) {
  68. editor.model.document.registerPostFixer( removeListStyleAttributeFromTodoList( editor ) );
  69. }
  70. }
  71. /**
  72. * Starts listening to {@link module:engine/model/model~Model#deleteContent} checks whether two lists will be merged into a single one
  73. * after deleting the content.
  74. *
  75. * The purpose of this action is to adjust the `listStyle` value for the list that was merged.
  76. *
  77. * Consider the following model's content:
  78. *
  79. * <listItem listIndent="0" listType="bulleted" listStyle="square">UL List item 1</listItem>
  80. * <listItem listIndent="0" listType="bulleted" listStyle="square">UL List item 2</listItem>
  81. * <paragraph>[A paragraph.]</paragraph>
  82. * <listItem listIndent="0" listType="bulleted" listStyle="circle">UL List item 1</listItem>
  83. * <listItem listIndent="0" listType="bulleted" listStyle="circle">UL List item 2</listItem>
  84. *
  85. * After removing the paragraph element, the second list will be merged into the first one.
  86. * We want to inherit the `listStyle` attribute for the second list from the first one.
  87. *
  88. * <listItem listIndent="0" listType="bulleted" listStyle="square">UL List item 1</listItem>
  89. * <listItem listIndent="0" listType="bulleted" listStyle="square">UL List item 2</listItem>
  90. * <listItem listIndent="0" listType="bulleted" listStyle="square">UL List item 1</listItem>
  91. * <listItem listIndent="0" listType="bulleted" listStyle="square">UL List item 2</listItem>
  92. *
  93. * See https://github.com/ckeditor/ckeditor5/issues/7879.
  94. *
  95. * @private
  96. */
  97. _mergeListStyleAttributeWhileMergingLists() {
  98. const editor = this.editor;
  99. const model = editor.model;
  100. // First the most-outer `listItem` in the first list reference.
  101. // If found, lists should be merged and this `listItem` provides the `listStyle` attribute
  102. // and it' also a starting point when searching for items in the second list.
  103. let firstMostOuterItem;
  104. // Check whether the removed content is between two lists.
  105. this.listenTo( model, 'deleteContent', ( evt, [ selection ] ) => {
  106. const firstPosition = selection.getFirstPosition();
  107. const lastPosition = selection.getLastPosition();
  108. // Typing or removing content in a single item. Aborting.
  109. if ( firstPosition.parent === lastPosition.parent ) {
  110. return;
  111. }
  112. // An element before the content that will be removed is not a list.
  113. if ( !firstPosition.parent.is( 'element', 'listItem' ) ) {
  114. return;
  115. }
  116. const nextSibling = lastPosition.parent.nextSibling;
  117. // An element after the content that will be removed is not a list.
  118. if ( !nextSibling || !nextSibling.is( 'element', 'listItem' ) ) {
  119. return;
  120. }
  121. const mostOuterItemList = getSiblingListItem( firstPosition.parent, {
  122. sameIndent: true,
  123. listIndent: 0
  124. } );
  125. if ( mostOuterItemList.getAttribute( 'listType' ) === nextSibling.getAttribute( 'listType' ) ) {
  126. firstMostOuterItem = mostOuterItemList;
  127. }
  128. }, { priority: 'high' } );
  129. // If so, update the `listStyle` attribute for the second list.
  130. this.listenTo( model, 'deleteContent', () => {
  131. if ( !firstMostOuterItem ) {
  132. return;
  133. }
  134. model.change( writer => {
  135. // Find the first most-outer item list in the merged list.
  136. // A case when the first list item in the second list was merged into the last item in the first list.
  137. //
  138. // <listItem listIndent="0" listType="bulleted" listStyle="square">UL List item 1</listItem>
  139. // <listItem listIndent="0" listType="bulleted" listStyle="square">UL List item 2</listItem>
  140. // <listItem listIndent="0" listType="bulleted" listStyle="circle">[]UL List item 1</listItem>
  141. // <listItem listIndent="0" listType="bulleted" listStyle="circle">UL List item 2</listItem>
  142. const secondListMostOuterItem = getSiblingListItem( firstMostOuterItem.nextSibling, {
  143. sameIndent: true,
  144. listIndent: 0,
  145. direction: 'forward'
  146. } );
  147. const items = [
  148. secondListMostOuterItem,
  149. ...getSiblingNodes( writer.createPositionAt( secondListMostOuterItem, 0 ), 'forward' )
  150. ];
  151. for ( const listItem of items ) {
  152. writer.setAttribute( 'listStyle', firstMostOuterItem.getAttribute( 'listStyle' ), listItem );
  153. }
  154. } );
  155. firstMostOuterItem = null;
  156. }, { priority: 'low' } );
  157. }
  158. }
  159. // Returns a converter that consumes the `style` attribute and search for `list-style-type` definition.
  160. // If not found, the `"default"` value will be used.
  161. //
  162. // @returns {Function}
  163. function upcastListItemStyle() {
  164. return dispatcher => {
  165. dispatcher.on( 'element:li', ( evt, data, conversionApi ) => {
  166. const listParent = data.viewItem.parent;
  167. const listStyle = listParent.getStyle( 'list-style-type' ) || DEFAULT_LIST_TYPE;
  168. const listItem = data.modelRange.start.nodeAfter;
  169. conversionApi.writer.setAttribute( 'listStyle', listStyle, listItem );
  170. }, { priority: 'low' } );
  171. };
  172. }
  173. // Returns a converter that adds the `list-style-type` definition as a value for the `style` attribute.
  174. // The `"default"` value is removed and not present in the view/data.
  175. //
  176. // @returns {Function}
  177. function downcastListStyleAttribute() {
  178. return dispatcher => {
  179. dispatcher.on( 'attribute:listStyle:listItem', ( evt, data, conversionApi ) => {
  180. const viewWriter = conversionApi.writer;
  181. const currentElement = data.item;
  182. const listStyle = data.attributeNewValue;
  183. const previousElement = getSiblingListItem( currentElement.previousSibling, {
  184. sameIndent: true,
  185. listIndent: currentElement.getAttribute( 'listIndent' ),
  186. direction: 'backward'
  187. } );
  188. const viewItem = conversionApi.mapper.toViewElement( currentElement );
  189. // Single item list.
  190. if ( !previousElement ) {
  191. setListStyle( viewWriter, listStyle, viewItem.parent );
  192. } else if ( !areRepresentingSameList( previousElement, currentElement ) ) {
  193. viewWriter.breakContainer( viewWriter.createPositionBefore( viewItem ) );
  194. viewWriter.breakContainer( viewWriter.createPositionAfter( viewItem ) );
  195. setListStyle( viewWriter, listStyle, viewItem.parent );
  196. }
  197. }, { priority: 'low' } );
  198. };
  199. // Checks whether specified list items belong to the same list.
  200. //
  201. // @param {module:engine/model/element~Element} listItem1 The first list item to check.
  202. // @param {module:engine/model/element~Element} listItem2 The second list item to check.
  203. // @returns {Boolean}
  204. function areRepresentingSameList( listItem1, listItem2 ) {
  205. return listItem1.getAttribute( 'listType' ) === listItem2.getAttribute( 'listType' ) &&
  206. listItem1.getAttribute( 'listIndent' ) === listItem2.getAttribute( 'listIndent' ) &&
  207. listItem1.getAttribute( 'listStyle' ) === listItem2.getAttribute( 'listStyle' );
  208. }
  209. // Updates or removes the `list-style-type` from the `element`.
  210. //
  211. // @param {module:engine/view/downcastwriter~DowncastWriter} writer
  212. // @param {String} listStyle
  213. // @param {module:engine/view/element~Element} element
  214. function setListStyle( writer, listStyle, element ) {
  215. if ( listStyle && listStyle !== DEFAULT_LIST_TYPE ) {
  216. writer.setStyle( 'list-style-type', listStyle, element );
  217. } else {
  218. writer.removeStyle( 'list-style-type', element );
  219. }
  220. }
  221. }
  222. // When indenting list, nested list should clear its value for the `listStyle` attribute or inherit from nested lists.
  223. //
  224. // ■ List item 1.
  225. // ■ List item 2.[]
  226. // ■ List item 3.
  227. // editor.execute( 'indentList' );
  228. //
  229. // ■ List item 1.
  230. // ○ List item 2.[]
  231. // ■ List item 3.
  232. //
  233. // @param {module:core/editor/editor~Editor} editor
  234. // @returns {Function}
  235. function fixListAfterIndentListCommand( editor ) {
  236. return ( evt, changedItems ) => {
  237. let valueToSet;
  238. const root = changedItems[ 0 ];
  239. const rootIndent = root.getAttribute( 'listIndent' );
  240. const itemsToUpdate = changedItems.filter( item => item.getAttribute( 'listIndent' ) === rootIndent );
  241. // A case where a few list items are intended must be checked separately
  242. // since `getSiblingListItem()` returns the first changed element.
  243. // ■ List item 1.
  244. // ○ [List item 2.
  245. // ○ List item 3.]
  246. // ■ List item 4.
  247. //
  248. // List items: `2` and `3` should be adjusted.
  249. if ( root.previousSibling.getAttribute( 'listIndent' ) + 1 === rootIndent ) {
  250. // valueToSet = root.previousSibling.getAttribute( 'listStyle' ) || DEFAULT_LIST_TYPE;
  251. valueToSet = DEFAULT_LIST_TYPE;
  252. } else {
  253. const previousSibling = getSiblingListItem( root.previousSibling, {
  254. sameIndent: true, direction: 'backward', listIndent: rootIndent
  255. } );
  256. valueToSet = previousSibling.getAttribute( 'listStyle' );
  257. }
  258. editor.model.change( writer => {
  259. for ( const item of itemsToUpdate ) {
  260. writer.setAttribute( 'listStyle', valueToSet, item );
  261. }
  262. } );
  263. };
  264. }
  265. // When outdenting a list, a nested list should copy its value for the `listStyle` attribute
  266. // from the previous sibling list item including the same value for the `listIndent` value.
  267. //
  268. // ■ List item 1.
  269. // ○ List item 2.[]
  270. // ■ List item 3.
  271. //
  272. // editor.execute( 'outdentList' );
  273. //
  274. // ■ List item 1.
  275. // ■ List item 2.[]
  276. // ■ List item 3.
  277. //
  278. // @param {module:core/editor/editor~Editor} editor
  279. // @returns {Function}
  280. function fixListAfterOutdentListCommand( editor ) {
  281. return ( evt, changedItems ) => {
  282. changedItems = changedItems.reverse().filter( item => item.is( 'element', 'listItem' ) );
  283. if ( !changedItems.length ) {
  284. return;
  285. }
  286. const indent = changedItems[ 0 ].getAttribute( 'listIndent' );
  287. const listType = changedItems[ 0 ].getAttribute( 'listType' );
  288. let listItem = changedItems[ 0 ].previousSibling;
  289. // ■ List item 1.
  290. // ○ List item 2.
  291. // ○ List item 3.[]
  292. // ■ List item 4.
  293. //
  294. // After outdenting a list, `List item 3` should inherit the `listStyle` attribute from `List item 1`.
  295. //
  296. // ■ List item 1.
  297. // ○ List item 2.
  298. // ■ List item 3.[]
  299. // ■ List item 4.
  300. if ( listItem.is( 'element', 'listItem' ) ) {
  301. while ( listItem.getAttribute( 'listIndent' ) !== indent ) {
  302. listItem = listItem.previousSibling;
  303. }
  304. } else {
  305. listItem = null;
  306. }
  307. // Outdenting such a list should restore values based on `List item 4`.
  308. // ■ List item 1.[]
  309. // ○ List item 2.
  310. // ○ List item 3.
  311. // ■ List item 4.
  312. if ( !listItem ) {
  313. listItem = changedItems[ changedItems.length - 1 ].nextSibling;
  314. }
  315. // And such a list should not modify anything.
  316. // However, `listItem` can indicate a node below the list. Be sure that we have the `listItem` element.
  317. // ■ List item 1.[]
  318. // ○ List item 2.
  319. // ○ List item 3.
  320. // <paragraph>The later if check.</paragraph>
  321. if ( !listItem || !listItem.is( 'element', 'listItem' ) ) {
  322. return;
  323. }
  324. // Do not modify the list if found `listItem` represents other type of list than outdented list items.
  325. if ( listItem.getAttribute( 'listType' ) !== listType ) {
  326. return;
  327. }
  328. editor.model.change( writer => {
  329. const itemsToUpdate = changedItems.filter( item => item.getAttribute( 'listIndent' ) === indent );
  330. for ( const item of itemsToUpdate ) {
  331. writer.setAttribute( 'listStyle', listItem.getAttribute( 'listStyle' ), item );
  332. }
  333. } );
  334. };
  335. }
  336. // Each `listItem` element must have specified the `listStyle` attribute.
  337. // This post-fixer checks whether inserted elements `listItem` elements should inherit the `listStyle` value from
  338. // their sibling nodes or should use the default value.
  339. //
  340. // Paragraph[]
  341. // ■ List item 1. // [listStyle="square", listType="bulleted"]
  342. // ■ List item 2. // ...
  343. // ■ List item 3. // ...
  344. //
  345. // editor.execute( 'bulletedList' )
  346. //
  347. // ■ Paragraph[] // [listStyle="square", listType="bulleted"]
  348. // ■ List item 1. // [listStyle="square", listType="bulleted"]
  349. // ■ List item 2.
  350. // ■ List item 3.
  351. //
  352. // It also covers a such change:
  353. //
  354. // [Paragraph 1
  355. // Paragraph 2]
  356. // ■ List item 1. // [listStyle="square", listType="bulleted"]
  357. // ■ List item 2. // ...
  358. // ■ List item 3. // ...
  359. //
  360. // editor.execute( 'numberedList' )
  361. //
  362. // 1. [Paragraph 1 // [listStyle="default", listType="numbered"]
  363. // 2. Paragraph 2] // [listStyle="default", listType="numbered"]
  364. // ■ List item 1. // [listStyle="square", listType="bulleted"]
  365. // ■ List item 2. // ...
  366. // ■ List item 3. // ...
  367. //
  368. // @param {module:core/editor/editor~Editor} editor
  369. // @returns {Function}
  370. function fixListStyleAttributeOnListItemElements( editor ) {
  371. return writer => {
  372. let wasFixed = false;
  373. const insertedListItems = getChangedListItems( editor.model.document.differ.getChanges() )
  374. .filter( item => {
  375. // Don't touch todo lists. They are handled in another post-fixer.
  376. return item.getAttribute( 'listType' ) !== 'todo';
  377. } );
  378. if ( !insertedListItems.length ) {
  379. return wasFixed;
  380. }
  381. // Check whether the last inserted element is next to the `listItem` element.
  382. //
  383. // ■ Paragraph[] // <-- The inserted item.
  384. // ■ List item 1.
  385. let existingListItem = insertedListItems[ insertedListItems.length - 1 ].nextSibling;
  386. // If it doesn't, maybe the `listItem` was inserted at the end of the list.
  387. //
  388. // ■ List item 1.
  389. // ■ Paragraph[] // <-- The inserted item.
  390. if ( !existingListItem || !existingListItem.is( 'element', 'listItem' ) ) {
  391. existingListItem = insertedListItems[ insertedListItems.length - 1 ].previousSibling;
  392. if ( existingListItem ) {
  393. const indent = insertedListItems[ 0 ].getAttribute( 'listIndent' );
  394. // But we need to find a `listItem` with the `listIndent=0` attribute.
  395. // If doesn't, maybe the `listItem` was inserted at the end of the list.
  396. //
  397. // ■ List item 1.
  398. // ○ List item 2.
  399. // ■ Paragraph[] // <-- The inserted item.
  400. while ( existingListItem.is( 'element', 'listItem' ) && existingListItem.getAttribute( 'listIndent' ) !== indent ) {
  401. existingListItem = existingListItem.previousSibling;
  402. }
  403. }
  404. }
  405. for ( const item of insertedListItems ) {
  406. if ( !item.hasAttribute( 'listStyle' ) ) {
  407. if ( shouldInheritListType( existingListItem, item ) ) {
  408. writer.setAttribute( 'listStyle', existingListItem.getAttribute( 'listStyle' ), item );
  409. } else {
  410. writer.setAttribute( 'listStyle', DEFAULT_LIST_TYPE, item );
  411. }
  412. wasFixed = true;
  413. }
  414. }
  415. return wasFixed;
  416. };
  417. // Checks whether the `listStyle` attribute should be copied from the `baseItem` element.
  418. //
  419. // The attribute should be copied if the inserted element does not have defined it and
  420. // the value for the element is other than default in the base element.
  421. //
  422. // @param {module:engine/model/element~Element|null} baseItem
  423. // @param {module:engine/model/element~Element} itemToChange
  424. // @returns {Boolean}
  425. function shouldInheritListType( baseItem, itemToChange ) {
  426. if ( !baseItem ) {
  427. return false;
  428. }
  429. const baseListStyle = baseItem.getAttribute( 'listStyle' );
  430. if ( !baseListStyle ) {
  431. return false;
  432. }
  433. if ( baseListStyle === DEFAULT_LIST_TYPE ) {
  434. return false;
  435. }
  436. if ( baseItem.getAttribute( 'listType' ) !== itemToChange.getAttribute( 'listType' ) ) {
  437. return false;
  438. }
  439. return true;
  440. }
  441. }
  442. // Removes the `listStyle` attribute from "todo" list items.
  443. //
  444. // @param {module:core/editor/editor~Editor} editor
  445. // @returns {Function}
  446. function removeListStyleAttributeFromTodoList( editor ) {
  447. return writer => {
  448. const todoListItems = getChangedListItems( editor.model.document.differ.getChanges() )
  449. .filter( item => {
  450. // Handle the todo lists only. The rest is handled in another post-fixer.
  451. return item.getAttribute( 'listType' ) === 'todo' && item.hasAttribute( 'listStyle' );
  452. } );
  453. if ( !todoListItems.length ) {
  454. return false;
  455. }
  456. for ( const item of todoListItems ) {
  457. writer.removeAttribute( 'listStyle', item );
  458. }
  459. return true;
  460. };
  461. }
  462. // Restores the `listStyle` attribute after changing the list type.
  463. //
  464. // @param {module:core/editor/editor~Editor} editor
  465. // @returns {Function}
  466. function restoreDefaultListStyle( editor ) {
  467. return ( evt, changedItems ) => {
  468. changedItems = changedItems.filter( item => item.is( 'element', 'listItem' ) );
  469. editor.model.change( writer => {
  470. for ( const item of changedItems ) {
  471. // Remove the attribute. Post-fixer will restore the proper value.
  472. writer.removeAttribute( 'listStyle', item );
  473. }
  474. } );
  475. };
  476. }
  477. // Returns `listItem` that were inserted or changed.
  478. //
  479. // @param {Array.<Object>} changes The changes list returned by the differ.
  480. // @returns {Array.<module:engine/model/element~Element>}
  481. function getChangedListItems( changes ) {
  482. const items = [];
  483. for ( const change of changes ) {
  484. const item = getItemFromChange( change );
  485. if ( item && item.is( 'element', 'listItem' ) ) {
  486. items.push( item );
  487. }
  488. }
  489. return items;
  490. }
  491. function getItemFromChange( change ) {
  492. if ( change.type === 'attribute' ) {
  493. return change.range.start.nodeAfter;
  494. }
  495. if ( change.type === 'insert' ) {
  496. return change.position.nodeAfter;
  497. }
  498. return null;
  499. }