liststyleediting.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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 oen.
  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. this.listenTo( model, 'deleteContent', ( evt, [ selection ] ) => {
  105. const firstPosition = selection.getFirstPosition();
  106. const lastPosition = selection.getLastPosition();
  107. // Typing or removing content in a single item. Aborting.
  108. if ( firstPosition.parent === lastPosition.parent ) {
  109. return;
  110. }
  111. // An element before the content that will be removed is not a list.
  112. if ( !firstPosition.parent.is( 'element', 'listItem' ) ) {
  113. return;
  114. }
  115. const nextSibling = lastPosition.parent.nextSibling;
  116. // An element after the content that will be removed is not a list.
  117. if ( !nextSibling || !nextSibling.is( 'element', 'listItem' ) ) {
  118. return;
  119. }
  120. const mostOuterItemList = getSiblingListItem( firstPosition.parent, {
  121. sameIndent: true,
  122. listIndent: 0
  123. } );
  124. if ( mostOuterItemList.getAttribute( 'listType' ) === nextSibling.getAttribute( 'listType' ) ) {
  125. firstMostOuterItem = mostOuterItemList;
  126. }
  127. }, { priority: 'high' } );
  128. this.listenTo( model, 'deleteContent', () => {
  129. if ( !firstMostOuterItem ) {
  130. return;
  131. }
  132. model.change( writer => {
  133. // Find the first most-outer item list in the merged list.
  134. // A case when the first list item in the second list was merged into the last item in the first list.
  135. //
  136. // <listItem listIndent="0" listType="bulleted" listStyle="square">UL List item 1</listItem>
  137. // <listItem listIndent="0" listType="bulleted" listStyle="square">UL List item 2</listItem>
  138. // <listItem listIndent="0" listType="bulleted" listStyle="circle">[]UL List item 1</listItem>
  139. // <listItem listIndent="0" listType="bulleted" listStyle="circle">UL List item 2</listItem>
  140. const secondListMostOuterItem = getSiblingListItem( firstMostOuterItem.nextSibling, {
  141. sameIndent: true,
  142. listIndent: 0,
  143. direction: 'forward'
  144. } );
  145. const items = [
  146. secondListMostOuterItem,
  147. ...getSiblingNodes( writer.createPositionAt( secondListMostOuterItem, 0 ), 'forward' )
  148. ];
  149. for ( const listItem of items ) {
  150. writer.setAttribute( 'listStyle', firstMostOuterItem.getAttribute( 'listStyle' ), listItem );
  151. }
  152. } );
  153. firstMostOuterItem = null;
  154. }, { priority: 'low' } );
  155. }
  156. }
  157. // Returns a converter that consumes the `style` attribute and search for `list-style-type` definition.
  158. // If not found, the `"default"` value will be used.
  159. //
  160. // @private
  161. // @returns {Function}
  162. function upcastListItemStyle() {
  163. return dispatcher => {
  164. dispatcher.on( 'element:li', ( evt, data, conversionApi ) => {
  165. const listParent = data.viewItem.parent;
  166. const listStyle = listParent.getStyle( 'list-style-type' ) || DEFAULT_LIST_TYPE;
  167. const listItem = data.modelRange.start.nodeAfter;
  168. conversionApi.writer.setAttribute( 'listStyle', listStyle, listItem );
  169. }, { priority: 'low' } );
  170. };
  171. }
  172. // Returns a converter that adds the `list-style-type` definition as a value for the `style` attribute.
  173. // The `"default"` value is removed and not present in the view/data.
  174. //
  175. // @private
  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. // @private
  234. // @param {module:core/editor/editor~Editor} editor
  235. // @returns {Function}
  236. function fixListAfterIndentListCommand( editor ) {
  237. return ( evt, changedItems ) => {
  238. let valueToSet;
  239. const root = changedItems[ 0 ];
  240. const rootIndent = root.getAttribute( 'listIndent' );
  241. const itemsToUpdate = changedItems.filter( item => item.getAttribute( 'listIndent' ) === rootIndent );
  242. // A case where a few list items are intended must be checked separately
  243. // since `getSiblingListItem()` returns the first changed element.
  244. // ■ List item 1.
  245. // ○ [List item 2.
  246. // ○ List item 3.]
  247. // ■ List item 4.
  248. //
  249. // List items: `2` and `3` should be adjusted.
  250. if ( root.previousSibling.getAttribute( 'listIndent' ) + 1 === rootIndent ) {
  251. // valueToSet = root.previousSibling.getAttribute( 'listStyle' ) || DEFAULT_LIST_TYPE;
  252. valueToSet = DEFAULT_LIST_TYPE;
  253. } else {
  254. const previousSibling = getSiblingListItem( root.previousSibling, {
  255. sameIndent: true, direction: 'backward', listIndent: rootIndent
  256. } );
  257. valueToSet = previousSibling.getAttribute( 'listStyle' );
  258. }
  259. editor.model.change( writer => {
  260. for ( const item of itemsToUpdate ) {
  261. writer.setAttribute( 'listStyle', valueToSet, item );
  262. }
  263. } );
  264. };
  265. }
  266. // When outdenting a list, a nested list should copy its value for the `listStyle` attribute
  267. // from the previous sibling list item including the same value for the `listIndent` value.
  268. //
  269. // ■ List item 1.
  270. // ○ List item 2.[]
  271. // ■ List item 3.
  272. //
  273. // editor.execute( 'outdentList' );
  274. //
  275. // ■ List item 1.
  276. // ■ List item 2.[]
  277. // ■ List item 3.
  278. //
  279. // @private
  280. // @param {module:core/editor/editor~Editor} editor
  281. // @returns {Function}
  282. function fixListAfterOutdentListCommand( editor ) {
  283. return ( evt, changedItems ) => {
  284. changedItems = changedItems.reverse().filter( item => item.is( 'element', 'listItem' ) );
  285. if ( !changedItems.length ) {
  286. return;
  287. }
  288. const indent = changedItems[ 0 ].getAttribute( 'listIndent' );
  289. const listType = changedItems[ 0 ].getAttribute( 'listType' );
  290. let listItem = changedItems[ 0 ].previousSibling;
  291. // ■ List item 1.
  292. // ○ List item 2.
  293. // ○ List item 3.[]
  294. // ■ List item 4.
  295. //
  296. // After outdenting a list, `List item 3` should inherit the `listStyle` attribute from `List item 1`.
  297. //
  298. // ■ List item 1.
  299. // ○ List item 2.
  300. // ■ List item 3.[]
  301. // ■ List item 4.
  302. if ( listItem.is( 'element', 'listItem' ) ) {
  303. while ( listItem.getAttribute( 'listIndent' ) !== indent ) {
  304. listItem = listItem.previousSibling;
  305. }
  306. } else {
  307. listItem = null;
  308. }
  309. // Outdenting such a list should restore values based on `List item 4`.
  310. // ■ List item 1.[]
  311. // ○ List item 2.
  312. // ○ List item 3.
  313. // ■ List item 4.
  314. if ( !listItem ) {
  315. listItem = changedItems[ changedItems.length - 1 ].nextSibling;
  316. }
  317. // And such a list should not modify anything.
  318. // However, `listItem` can indicate a node below the list. Be sure that we have the `listItem` element.
  319. // ■ List item 1.[]
  320. // ○ List item 2.
  321. // ○ List item 3.
  322. // <paragraph>The later if check.</paragraph>
  323. if ( !listItem || !listItem.is( 'element', 'listItem' ) ) {
  324. return;
  325. }
  326. // Do not modify the list if found `listItem` represents other type of list than outdented list items.
  327. if ( listItem.getAttribute( 'listType' ) !== listType ) {
  328. return;
  329. }
  330. editor.model.change( writer => {
  331. const itemsToUpdate = changedItems.filter( item => item.getAttribute( 'listIndent' ) === indent );
  332. for ( const item of itemsToUpdate ) {
  333. writer.setAttribute( 'listStyle', listItem.getAttribute( 'listStyle' ), item );
  334. }
  335. } );
  336. };
  337. }
  338. // Each `listItem` element must have specified the `listStyle` attribute.
  339. // This post-fixer checks whether inserted elements `listItem` elements should inherit the `listStyle` value from
  340. // their sibling nodes or should use the default value.
  341. //
  342. // Paragraph[]
  343. // ■ List item 1. // [listStyle="square", listType="bulleted"]
  344. // ■ List item 2. // ...
  345. // ■ List item 3. // ...
  346. //
  347. // editor.execute( 'bulletedList' )
  348. //
  349. // ■ Paragraph[] // [listStyle="square", listType="bulleted"]
  350. // ■ List item 1. // [listStyle="square", listType="bulleted"]
  351. // ■ List item 2.
  352. // ■ List item 3.
  353. //
  354. // It also covers a such change:
  355. //
  356. // [Paragraph 1
  357. // Paragraph 2]
  358. // ■ List item 1. // [listStyle="square", listType="bulleted"]
  359. // ■ List item 2. // ...
  360. // ■ List item 3. // ...
  361. //
  362. // editor.execute( 'numberedList' )
  363. //
  364. // 1. [Paragraph 1 // [listStyle="default", listType="numbered"]
  365. // 2. Paragraph 2] // [listStyle="default", listType="numbered"]
  366. // ■ List item 1. // [listStyle="square", listType="bulleted"]
  367. // ■ List item 2. // ...
  368. // ■ List item 3. // ...
  369. //
  370. // @private
  371. // @param {module:core/editor/editor~Editor} editor
  372. // @returns {Function}
  373. function fixListStyleAttributeOnListItemElements( editor ) {
  374. return writer => {
  375. let wasFixed = false;
  376. let insertedListItems = [];
  377. for ( const change of editor.model.document.differ.getChanges() ) {
  378. if ( change.type == 'insert' && change.name == 'listItem' ) {
  379. insertedListItems.push( change.position.nodeAfter );
  380. }
  381. }
  382. // Don't touch todo lists.
  383. insertedListItems = insertedListItems.filter( item => item.getAttribute( 'listType' ) !== 'todo' );
  384. if ( !insertedListItems.length ) {
  385. return wasFixed;
  386. }
  387. // Check whether the last inserted element is next to the `listItem` element.
  388. //
  389. // ■ Paragraph[] // <-- The inserted item.
  390. // ■ List item 1.
  391. let existingListItem = insertedListItems[ insertedListItems.length - 1 ].nextSibling;
  392. // If it doesn't, maybe the `listItem` was inserted at the end of the list.
  393. //
  394. // ■ List item 1.
  395. // ■ Paragraph[] // <-- The inserted item.
  396. if ( !existingListItem || !existingListItem.is( 'element', 'listItem' ) ) {
  397. existingListItem = insertedListItems[ insertedListItems.length - 1 ].previousSibling;
  398. if ( existingListItem ) {
  399. const indent = insertedListItems[ 0 ].getAttribute( 'listIndent' );
  400. // But we need to find a `listItem` with the `listIndent=0` attribute.
  401. // If doesn't, maybe the `listItem` was inserted at the end of the list.
  402. //
  403. // ■ List item 1.
  404. // ○ List item 2.
  405. // ■ Paragraph[] // <-- The inserted item.
  406. while ( existingListItem.is( 'element', 'listItem' ) && existingListItem.getAttribute( 'listIndent' ) !== indent ) {
  407. existingListItem = existingListItem.previousSibling;
  408. }
  409. }
  410. }
  411. for ( const item of insertedListItems ) {
  412. if ( !item.hasAttribute( 'listStyle' ) ) {
  413. if ( shouldInheritListType( existingListItem ) ) {
  414. writer.setAttribute( 'listStyle', existingListItem.getAttribute( 'listStyle' ), item );
  415. } else {
  416. writer.setAttribute( 'listStyle', DEFAULT_LIST_TYPE, item );
  417. }
  418. wasFixed = true;
  419. }
  420. }
  421. return wasFixed;
  422. };
  423. // Checks whether the `listStyle` attribute should be copied from the `baseItem` element.
  424. //
  425. // The attribute should be copied if the inserted element does not have defined it and
  426. // the value for the element is other than default in the base element.
  427. //
  428. // @param {module:engine/model/element~Element|null} baseItem
  429. // @returns {Boolean}
  430. function shouldInheritListType( baseItem ) {
  431. if ( !baseItem ) {
  432. return false;
  433. }
  434. const baseListStyle = baseItem.getAttribute( 'listStyle' );
  435. if ( !baseListStyle ) {
  436. return false;
  437. }
  438. if ( baseListStyle === DEFAULT_LIST_TYPE ) {
  439. return false;
  440. }
  441. return true;
  442. }
  443. }
  444. // Removes the `listStyle` attribute from "todo" list items.
  445. //
  446. // @private
  447. // @param {module:core/editor/editor~Editor} editor
  448. // @returns {Function}
  449. function removeListStyleAttributeFromTodoList( editor ) {
  450. return writer => {
  451. let todoListItems = [];
  452. for ( const change of editor.model.document.differ.getChanges() ) {
  453. const item = getItemFromChange( change );
  454. if ( item && item.is( 'element', 'listItem' ) && item.getAttribute( 'listType' ) === 'todo' ) {
  455. todoListItems.push( item );
  456. }
  457. }
  458. todoListItems = todoListItems.filter( item => item.hasAttribute( 'listStyle' ) );
  459. if ( !todoListItems.length ) {
  460. return false;
  461. }
  462. for ( const item of todoListItems ) {
  463. writer.removeAttribute( 'listStyle', item );
  464. }
  465. return true;
  466. };
  467. function getItemFromChange( change ) {
  468. if ( change.type === 'attribute' ) {
  469. return change.range.start.nodeAfter;
  470. }
  471. if ( change.type === 'insert' ) {
  472. return change.position.nodeAfter;
  473. }
  474. return null;
  475. }
  476. }
  477. // Restores the `listStyle` attribute after changing the list type.
  478. //
  479. // @private
  480. // @param {module:core/editor/editor~Editor} editor
  481. // @returns {Function}
  482. function restoreDefaultListStyle( editor ) {
  483. return ( evt, changedItems ) => {
  484. changedItems = changedItems.filter( item => item.is( 'element', 'listItem' ) );
  485. editor.model.change( writer => {
  486. for ( const item of changedItems ) {
  487. // Remove the attribute. Post-fixer will restore the proper value.
  488. writer.removeAttribute( 'listStyle', item );
  489. }
  490. } );
  491. };
  492. }