liststyleediting.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. // @private
  163. // @returns {Function}
  164. function upcastListItemStyle() {
  165. return dispatcher => {
  166. dispatcher.on( 'element:li', ( evt, data, conversionApi ) => {
  167. const listParent = data.viewItem.parent;
  168. const listStyle = listParent.getStyle( 'list-style-type' ) || DEFAULT_LIST_TYPE;
  169. const listItem = data.modelRange.start.nodeAfter;
  170. conversionApi.writer.setAttribute( 'listStyle', listStyle, listItem );
  171. }, { priority: 'low' } );
  172. };
  173. }
  174. // Returns a converter that adds the `list-style-type` definition as a value for the `style` attribute.
  175. // The `"default"` value is removed and not present in the view/data.
  176. //
  177. // @private
  178. // @returns {Function}
  179. function downcastListStyleAttribute() {
  180. return dispatcher => {
  181. dispatcher.on( 'attribute:listStyle:listItem', ( evt, data, conversionApi ) => {
  182. const viewWriter = conversionApi.writer;
  183. const currentElement = data.item;
  184. const listStyle = data.attributeNewValue;
  185. const previousElement = getSiblingListItem( currentElement.previousSibling, {
  186. sameIndent: true,
  187. listIndent: currentElement.getAttribute( 'listIndent' ),
  188. direction: 'backward'
  189. } );
  190. const viewItem = conversionApi.mapper.toViewElement( currentElement );
  191. // Single item list.
  192. if ( !previousElement ) {
  193. setListStyle( viewWriter, listStyle, viewItem.parent );
  194. } else if ( !areRepresentingSameList( previousElement, currentElement ) ) {
  195. viewWriter.breakContainer( viewWriter.createPositionBefore( viewItem ) );
  196. viewWriter.breakContainer( viewWriter.createPositionAfter( viewItem ) );
  197. setListStyle( viewWriter, listStyle, viewItem.parent );
  198. }
  199. }, { priority: 'low' } );
  200. };
  201. // Checks whether specified list items belong to the same list.
  202. //
  203. // @param {module:engine/model/element~Element} listItem1 The first list item to check.
  204. // @param {module:engine/model/element~Element} listItem2 The second list item to check.
  205. // @returns {Boolean}
  206. function areRepresentingSameList( listItem1, listItem2 ) {
  207. return listItem1.getAttribute( 'listType' ) === listItem2.getAttribute( 'listType' ) &&
  208. listItem1.getAttribute( 'listIndent' ) === listItem2.getAttribute( 'listIndent' ) &&
  209. listItem1.getAttribute( 'listStyle' ) === listItem2.getAttribute( 'listStyle' );
  210. }
  211. // Updates or removes the `list-style-type` from the `element`.
  212. //
  213. // @param {module:engine/view/downcastwriter~DowncastWriter} writer
  214. // @param {String} listStyle
  215. // @param {module:engine/view/element~Element} element
  216. function setListStyle( writer, listStyle, element ) {
  217. if ( listStyle && listStyle !== DEFAULT_LIST_TYPE ) {
  218. writer.setStyle( 'list-style-type', listStyle, element );
  219. } else {
  220. writer.removeStyle( 'list-style-type', element );
  221. }
  222. }
  223. }
  224. // When indenting list, nested list should clear its value for the `listStyle` attribute or inherit from nested lists.
  225. //
  226. // ■ List item 1.
  227. // ■ List item 2.[]
  228. // ■ List item 3.
  229. // editor.execute( 'indentList' );
  230. //
  231. // ■ List item 1.
  232. // ○ List item 2.[]
  233. // ■ List item 3.
  234. //
  235. // @private
  236. // @param {module:core/editor/editor~Editor} editor
  237. // @returns {Function}
  238. function fixListAfterIndentListCommand( editor ) {
  239. return ( evt, changedItems ) => {
  240. let valueToSet;
  241. const root = changedItems[ 0 ];
  242. const rootIndent = root.getAttribute( 'listIndent' );
  243. const itemsToUpdate = changedItems.filter( item => item.getAttribute( 'listIndent' ) === rootIndent );
  244. // A case where a few list items are intended must be checked separately
  245. // since `getSiblingListItem()` returns the first changed element.
  246. // ■ List item 1.
  247. // ○ [List item 2.
  248. // ○ List item 3.]
  249. // ■ List item 4.
  250. //
  251. // List items: `2` and `3` should be adjusted.
  252. if ( root.previousSibling.getAttribute( 'listIndent' ) + 1 === rootIndent ) {
  253. // valueToSet = root.previousSibling.getAttribute( 'listStyle' ) || DEFAULT_LIST_TYPE;
  254. valueToSet = DEFAULT_LIST_TYPE;
  255. } else {
  256. const previousSibling = getSiblingListItem( root.previousSibling, {
  257. sameIndent: true, direction: 'backward', listIndent: rootIndent
  258. } );
  259. valueToSet = previousSibling.getAttribute( 'listStyle' );
  260. }
  261. editor.model.change( writer => {
  262. for ( const item of itemsToUpdate ) {
  263. writer.setAttribute( 'listStyle', valueToSet, item );
  264. }
  265. } );
  266. };
  267. }
  268. // When outdenting a list, a nested list should copy its value for the `listStyle` attribute
  269. // from the previous sibling list item including the same value for the `listIndent` value.
  270. //
  271. // ■ List item 1.
  272. // ○ List item 2.[]
  273. // ■ List item 3.
  274. //
  275. // editor.execute( 'outdentList' );
  276. //
  277. // ■ List item 1.
  278. // ■ List item 2.[]
  279. // ■ List item 3.
  280. //
  281. // @private
  282. // @param {module:core/editor/editor~Editor} editor
  283. // @returns {Function}
  284. function fixListAfterOutdentListCommand( editor ) {
  285. return ( evt, changedItems ) => {
  286. changedItems = changedItems.reverse().filter( item => item.is( 'element', 'listItem' ) );
  287. if ( !changedItems.length ) {
  288. return;
  289. }
  290. const indent = changedItems[ 0 ].getAttribute( 'listIndent' );
  291. const listType = changedItems[ 0 ].getAttribute( 'listType' );
  292. let listItem = changedItems[ 0 ].previousSibling;
  293. // ■ List item 1.
  294. // ○ List item 2.
  295. // ○ List item 3.[]
  296. // ■ List item 4.
  297. //
  298. // After outdenting a list, `List item 3` should inherit the `listStyle` attribute from `List item 1`.
  299. //
  300. // ■ List item 1.
  301. // ○ List item 2.
  302. // ■ List item 3.[]
  303. // ■ List item 4.
  304. if ( listItem.is( 'element', 'listItem' ) ) {
  305. while ( listItem.getAttribute( 'listIndent' ) !== indent ) {
  306. listItem = listItem.previousSibling;
  307. }
  308. } else {
  309. listItem = null;
  310. }
  311. // Outdenting such a list should restore values based on `List item 4`.
  312. // ■ List item 1.[]
  313. // ○ List item 2.
  314. // ○ List item 3.
  315. // ■ List item 4.
  316. if ( !listItem ) {
  317. listItem = changedItems[ changedItems.length - 1 ].nextSibling;
  318. }
  319. // And such a list should not modify anything.
  320. // However, `listItem` can indicate a node below the list. Be sure that we have the `listItem` element.
  321. // ■ List item 1.[]
  322. // ○ List item 2.
  323. // ○ List item 3.
  324. // <paragraph>The later if check.</paragraph>
  325. if ( !listItem || !listItem.is( 'element', 'listItem' ) ) {
  326. return;
  327. }
  328. // Do not modify the list if found `listItem` represents other type of list than outdented list items.
  329. if ( listItem.getAttribute( 'listType' ) !== listType ) {
  330. return;
  331. }
  332. editor.model.change( writer => {
  333. const itemsToUpdate = changedItems.filter( item => item.getAttribute( 'listIndent' ) === indent );
  334. for ( const item of itemsToUpdate ) {
  335. writer.setAttribute( 'listStyle', listItem.getAttribute( 'listStyle' ), item );
  336. }
  337. } );
  338. };
  339. }
  340. // Each `listItem` element must have specified the `listStyle` attribute.
  341. // This post-fixer checks whether inserted elements `listItem` elements should inherit the `listStyle` value from
  342. // their sibling nodes or should use the default value.
  343. //
  344. // Paragraph[]
  345. // ■ List item 1. // [listStyle="square", listType="bulleted"]
  346. // ■ List item 2. // ...
  347. // ■ List item 3. // ...
  348. //
  349. // editor.execute( 'bulletedList' )
  350. //
  351. // ■ Paragraph[] // [listStyle="square", listType="bulleted"]
  352. // ■ List item 1. // [listStyle="square", listType="bulleted"]
  353. // ■ List item 2.
  354. // ■ List item 3.
  355. //
  356. // It also covers a such change:
  357. //
  358. // [Paragraph 1
  359. // Paragraph 2]
  360. // ■ List item 1. // [listStyle="square", listType="bulleted"]
  361. // ■ List item 2. // ...
  362. // ■ List item 3. // ...
  363. //
  364. // editor.execute( 'numberedList' )
  365. //
  366. // 1. [Paragraph 1 // [listStyle="default", listType="numbered"]
  367. // 2. Paragraph 2] // [listStyle="default", listType="numbered"]
  368. // ■ List item 1. // [listStyle="square", listType="bulleted"]
  369. // ■ List item 2. // ...
  370. // ■ List item 3. // ...
  371. //
  372. // @private
  373. // @param {module:core/editor/editor~Editor} editor
  374. // @returns {Function}
  375. function fixListStyleAttributeOnListItemElements( editor ) {
  376. return writer => {
  377. let wasFixed = false;
  378. let insertedListItems = [];
  379. for ( const change of editor.model.document.differ.getChanges() ) {
  380. if ( change.type == 'insert' && change.name == 'listItem' ) {
  381. insertedListItems.push( change.position.nodeAfter );
  382. }
  383. }
  384. // Don't touch todo lists.
  385. insertedListItems = insertedListItems.filter( item => item.getAttribute( 'listType' ) !== 'todo' );
  386. if ( !insertedListItems.length ) {
  387. return wasFixed;
  388. }
  389. // Check whether the last inserted element is next to the `listItem` element.
  390. //
  391. // ■ Paragraph[] // <-- The inserted item.
  392. // ■ List item 1.
  393. let existingListItem = insertedListItems[ insertedListItems.length - 1 ].nextSibling;
  394. // If it doesn't, maybe the `listItem` was inserted at the end of the list.
  395. //
  396. // ■ List item 1.
  397. // ■ Paragraph[] // <-- The inserted item.
  398. if ( !existingListItem || !existingListItem.is( 'element', 'listItem' ) ) {
  399. existingListItem = insertedListItems[ insertedListItems.length - 1 ].previousSibling;
  400. if ( existingListItem ) {
  401. const indent = insertedListItems[ 0 ].getAttribute( 'listIndent' );
  402. // But we need to find a `listItem` with the `listIndent=0` attribute.
  403. // If doesn't, maybe the `listItem` was inserted at the end of the list.
  404. //
  405. // ■ List item 1.
  406. // ○ List item 2.
  407. // ■ Paragraph[] // <-- The inserted item.
  408. while ( existingListItem.is( 'element', 'listItem' ) && existingListItem.getAttribute( 'listIndent' ) !== indent ) {
  409. existingListItem = existingListItem.previousSibling;
  410. }
  411. }
  412. }
  413. for ( const item of insertedListItems ) {
  414. if ( !item.hasAttribute( 'listStyle' ) ) {
  415. if ( shouldInheritListType( existingListItem ) ) {
  416. writer.setAttribute( 'listStyle', existingListItem.getAttribute( 'listStyle' ), item );
  417. } else {
  418. writer.setAttribute( 'listStyle', DEFAULT_LIST_TYPE, item );
  419. }
  420. wasFixed = true;
  421. }
  422. }
  423. return wasFixed;
  424. };
  425. // Checks whether the `listStyle` attribute should be copied from the `baseItem` element.
  426. //
  427. // The attribute should be copied if the inserted element does not have defined it and
  428. // the value for the element is other than default in the base element.
  429. //
  430. // @param {module:engine/model/element~Element|null} baseItem
  431. // @returns {Boolean}
  432. function shouldInheritListType( baseItem ) {
  433. if ( !baseItem ) {
  434. return false;
  435. }
  436. const baseListStyle = baseItem.getAttribute( 'listStyle' );
  437. if ( !baseListStyle ) {
  438. return false;
  439. }
  440. if ( baseListStyle === DEFAULT_LIST_TYPE ) {
  441. return false;
  442. }
  443. return true;
  444. }
  445. }
  446. // Removes the `listStyle` attribute from "todo" list items.
  447. //
  448. // @private
  449. // @param {module:core/editor/editor~Editor} editor
  450. // @returns {Function}
  451. function removeListStyleAttributeFromTodoList( editor ) {
  452. return writer => {
  453. let todoListItems = [];
  454. for ( const change of editor.model.document.differ.getChanges() ) {
  455. const item = getItemFromChange( change );
  456. if ( item && item.is( 'element', 'listItem' ) && item.getAttribute( 'listType' ) === 'todo' ) {
  457. todoListItems.push( item );
  458. }
  459. }
  460. todoListItems = todoListItems.filter( item => item.hasAttribute( 'listStyle' ) );
  461. if ( !todoListItems.length ) {
  462. return false;
  463. }
  464. for ( const item of todoListItems ) {
  465. writer.removeAttribute( 'listStyle', item );
  466. }
  467. return true;
  468. };
  469. function getItemFromChange( change ) {
  470. if ( change.type === 'attribute' ) {
  471. return change.range.start.nodeAfter;
  472. }
  473. if ( change.type === 'insert' ) {
  474. return change.position.nodeAfter;
  475. }
  476. return null;
  477. }
  478. }
  479. // Restores the `listStyle` attribute after changing the list type.
  480. //
  481. // @private
  482. // @param {module:core/editor/editor~Editor} editor
  483. // @returns {Function}
  484. function restoreDefaultListStyle( editor ) {
  485. return ( evt, changedItems ) => {
  486. changedItems = changedItems.filter( item => item.is( 'element', 'listItem' ) );
  487. editor.model.change( writer => {
  488. for ( const item of changedItems ) {
  489. // Remove the attribute. Post-fixer will restore the proper value.
  490. writer.removeAttribute( 'listStyle', item );
  491. }
  492. } );
  493. };
  494. }