8
0

writer.js 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module module:engine/view/writer
  7. */
  8. import Position from './position';
  9. import ContainerElement from './containerelement';
  10. import AttributeElement from './attributeelement';
  11. import EmptyElement from './emptyelement';
  12. import UIElement from './uielement';
  13. import Text from './text';
  14. import Range from './range';
  15. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  16. import DocumentFragment from './documentfragment';
  17. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  18. /**
  19. * Contains functions used for composing view tree.
  20. *
  21. * @namespace writer
  22. */
  23. const writer = {
  24. breakAttributes,
  25. breakContainer,
  26. mergeAttributes,
  27. mergeContainers,
  28. insert,
  29. remove,
  30. clear,
  31. move,
  32. wrap,
  33. unwrap,
  34. rename
  35. };
  36. export default writer;
  37. /**
  38. * Breaks attribute nodes at provided position or at boundaries of provided range. It breaks attribute elements inside
  39. * up to a container element.
  40. *
  41. * In following examples `<p>` is a container, `<b>` and `<u>` are attribute nodes:
  42. *
  43. * <p>foo<b><u>bar{}</u></b></p> -> <p>foo<b><u>bar</u></b>[]</p>
  44. * <p>foo<b><u>{}bar</u></b></p> -> <p>foo{}<b><u>bar</u></b></p>
  45. * <p>foo<b><u>b{}ar</u></b></p> -> <p>foo<b><u>b</u></b>[]<b><u>ar</u></b></p>
  46. * <p><b>fo{o</b><u>ba}r</u></p> -> <p><b>fo</b><b>o</b><u>ba</u><u>r</u></b></p>
  47. *
  48. * **Note:** {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment} is treated like a container.
  49. *
  50. * **Note:** Difference between {@link module:engine/view/writer~writer.breakAttributes breakAttributes} and
  51. * {@link module:engine/view/writer~writer.breakContainer breakContainer} is that `breakAttributes` breaks all
  52. * {@link module:engine/view/attributeelement~AttributeElement attribute elements} that are ancestors of given `position`, up to the first
  53. * encountered {@link module:engine/view/containerelement~ContainerElement container element}. `breakContainer` assumes that given
  54. * `position`
  55. * is directly in container element and breaks that container element.
  56. *
  57. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container`
  58. * when {@link module:engine/view/range~Range#start start}
  59. * and {@link module:engine/view/range~Range#end end} positions of a passed range are not placed inside same parent container.
  60. *
  61. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-empty-element`
  62. * when trying to break attributes
  63. * inside {@link module:engine/view/emptyelement~EmptyElement EmptyElement}.
  64. *
  65. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-ui-element`
  66. * when trying to break attributes
  67. * inside {@link module:engine/view/uielement~UIElement UIElement}.
  68. *
  69. * @see module:engine/view/attributeelement~AttributeElement
  70. * @see module:engine/view/containerelement~ContainerElement
  71. * @see module:engine/view/writer~writer.breakContainer
  72. * @function module:engine/view/writer~writer.breakAttributes
  73. * @param {module:engine/view/position~Position|module:engine/view/range~Range} positionOrRange Position where to break attribute elements.
  74. * @returns {module:engine/view/position~Position|module:engine/view/range~Range} New position or range, after breaking the attribute
  75. * elements.
  76. */
  77. export function breakAttributes( positionOrRange ) {
  78. if ( positionOrRange instanceof Position ) {
  79. return _breakAttributes( positionOrRange );
  80. } else {
  81. return _breakAttributesRange( positionOrRange );
  82. }
  83. }
  84. /**
  85. * Breaks {@link module:engine/view/containerelement~ContainerElement container view element} into two, at the given position. Position
  86. * has to be directly inside container element and cannot be in root. Does not break if position is at the beginning
  87. * or at the end of it's parent element.
  88. *
  89. * <p>foo^bar</p> -> <p>foo</p><p>bar</p>
  90. * <div><p>foo</p>^<p>bar</p></div> -> <div><p>foo</p></div><div><p>bar</p></div>
  91. * <p>^foobar</p> -> ^<p>foobar</p>
  92. * <p>foobar^</p> -> <p>foobar</p>^
  93. *
  94. * **Note:** Difference between {@link module:engine/view/writer~writer.breakAttributes breakAttributes} and
  95. * {@link module:engine/view/writer~writer.breakContainer breakContainer} is that `breakAttributes` breaks all
  96. * {@link module:engine/view/attributeelement~AttributeElement attribute elements} that are ancestors of given `position`, up to the first
  97. * encountered {@link module:engine/view/containerelement~ContainerElement container element}. `breakContainer` assumes that given
  98. * `position`
  99. * is directly in container element and breaks that container element.
  100. *
  101. * @see module:engine/view/attributeelement~AttributeElement
  102. * @see module:engine/view/containerelement~ContainerElement
  103. * @see module:engine/view/writer~writer.breakAttributes
  104. * @function module:engine/view/writer~writer.breakContainer
  105. * @param {module:engine/view/position~Position} position Position where to break element.
  106. * @returns {module:engine/view/position~Position} Position between broken elements. If element has not been broken, the returned position
  107. * is placed either before it or after it.
  108. */
  109. export function breakContainer( position ) {
  110. const element = position.parent;
  111. if ( !( element.is( 'containerElement' ) ) ) {
  112. /**
  113. * Trying to break an element which is not a container element.
  114. *
  115. * @error view-writer-break-non-container-element
  116. */
  117. throw new CKEditorError( 'view-writer-break-non-container-element: Trying to break an element which is not a container element.' );
  118. }
  119. if ( !element.parent ) {
  120. /**
  121. * Trying to break root element.
  122. *
  123. * @error view-writer-break-root
  124. */
  125. throw new CKEditorError( 'view-writer-break-root: Trying to break root element.' );
  126. }
  127. if ( position.isAtStart ) {
  128. return Position.createBefore( element );
  129. } else if ( !position.isAtEnd ) {
  130. const newElement = element.clone( false );
  131. insert( Position.createAfter( element ), newElement );
  132. const sourceRange = new Range( position, Position.createAt( element, 'end' ) );
  133. const targetPosition = new Position( newElement, 0 );
  134. move( sourceRange, targetPosition );
  135. }
  136. return Position.createAfter( element );
  137. }
  138. /**
  139. * Merges {@link module:engine/view/attributeelement~AttributeElement attribute elements}. It also merges text nodes if needed.
  140. * Only {@link module:engine/view/attributeelement~AttributeElement#isSimilar similar} attribute elements can be merged.
  141. *
  142. * In following examples `<p>` is a container and `<b>` is an attribute element:
  143. *
  144. * <p>foo[]bar</p> -> <p>foo{}bar</p>
  145. * <p><b>foo</b>[]<b>bar</b></p> -> <p><b>foo{}bar</b></p>
  146. * <p><b foo="bar">a</b>[]<b foo="baz">b</b></p> -> <p><b foo="bar">a</b>[]<b foo="baz">b</b></p>
  147. *
  148. * It will also take care about empty attributes when merging:
  149. *
  150. * <p><b>[]</b></p> -> <p>[]</p>
  151. * <p><b>foo</b><i>[]</i><b>bar</b></p> -> <p><b>foo{}bar</b></p>
  152. *
  153. * **Note:** Difference between {@link module:engine/view/writer~writer.mergeAttributes mergeAttributes} and
  154. * {@link module:engine/view/writer~writer.mergeContainers mergeContainers} is that `mergeAttributes` merges two
  155. * {@link module:engine/view/attributeelement~AttributeElement attribute elements} or {@link module:engine/view/text~Text text nodes}
  156. * while `mergeContainer` merges two {@link module:engine/view/containerelement~ContainerElement container elements}.
  157. *
  158. * @see module:engine/view/attributeelement~AttributeElement
  159. * @see module:engine/view/containerelement~ContainerElement
  160. * @see module:engine/view/writer~writer.mergeContainers
  161. * @function module:engine/view/writer~writer.mergeAttributes
  162. * @param {module:engine/view/position~Position} position Merge position.
  163. * @returns {module:engine/view/position~Position} Position after merge.
  164. */
  165. export function mergeAttributes( position ) {
  166. const positionOffset = position.offset;
  167. const positionParent = position.parent;
  168. // When inside text node - nothing to merge.
  169. if ( positionParent.is( 'text' ) ) {
  170. return position;
  171. }
  172. // When inside empty attribute - remove it.
  173. if ( positionParent.is( 'attributeElement' ) && positionParent.childCount === 0 ) {
  174. const parent = positionParent.parent;
  175. const offset = positionParent.index;
  176. positionParent.remove();
  177. return mergeAttributes( new Position( parent, offset ) );
  178. }
  179. const nodeBefore = positionParent.getChild( positionOffset - 1 );
  180. const nodeAfter = positionParent.getChild( positionOffset );
  181. // Position should be placed between two nodes.
  182. if ( !nodeBefore || !nodeAfter ) {
  183. return position;
  184. }
  185. // When position is between two text nodes.
  186. if ( nodeBefore.is( 'text' ) && nodeAfter.is( 'text' ) ) {
  187. return mergeTextNodes( nodeBefore, nodeAfter );
  188. }
  189. // When selection is between two same attribute elements.
  190. else if ( nodeBefore.is( 'attributeElement' ) && nodeAfter.is( 'attributeElement' ) && nodeBefore.isSimilar( nodeAfter ) ) {
  191. // Move all children nodes from node placed after selection and remove that node.
  192. const count = nodeBefore.childCount;
  193. nodeBefore.appendChildren( nodeAfter.getChildren() );
  194. nodeAfter.remove();
  195. // New position is located inside the first node, before new nodes.
  196. // Call this method recursively to merge again if needed.
  197. return mergeAttributes( new Position( nodeBefore, count ) );
  198. }
  199. return position;
  200. }
  201. /**
  202. * Merges two {@link module:engine/view/containerelement~ContainerElement container elements} that are before and after given position.
  203. * Precisely, the element after the position is removed and it's contents are moved to element before the position.
  204. *
  205. * <p>foo</p>^<p>bar</p> -> <p>foo^bar</p>
  206. * <div>foo</div>^<p>bar</p> -> <div>foo^bar</div>
  207. *
  208. * **Note:** Difference between {@link module:engine/view/writer~writer.mergeAttributes mergeAttributes} and
  209. * {@link module:engine/view/writer~writer.mergeContainers mergeContainers} is that `mergeAttributes` merges two
  210. * {@link module:engine/view/attributeelement~AttributeElement attribute elements} or {@link module:engine/view/text~Text text nodes}
  211. * while `mergeContainer` merges two {@link module:engine/view/containerelement~ContainerElement container elements}.
  212. *
  213. * @see module:engine/view/attributeelement~AttributeElement
  214. * @see module:engine/view/containerelement~ContainerElement
  215. * @see module:engine/view/writer~writer.mergeAttributes
  216. * @function module:engine/view/writer~writer.mergeContainers
  217. * @param {module:engine/view/position~Position} position Merge position.
  218. * @returns {module:engine/view/position~Position} Position after merge.
  219. */
  220. export function mergeContainers( position ) {
  221. const prev = position.nodeBefore;
  222. const next = position.nodeAfter;
  223. if ( !prev || !next || !prev.is( 'containerElement' ) || !next.is( 'containerElement' ) ) {
  224. /**
  225. * Element before and after given position cannot be merged.
  226. *
  227. * @error view-writer-merge-containers-invalid-position
  228. */
  229. throw new CKEditorError( 'view-writer-merge-containers-invalid-position: ' +
  230. 'Element before and after given position cannot be merged.' );
  231. }
  232. const lastChild = prev.getChild( prev.childCount - 1 );
  233. const newPosition = lastChild instanceof Text ? Position.createAt( lastChild, 'end' ) : Position.createAt( prev, 'end' );
  234. move( Range.createIn( next ), Position.createAt( prev, 'end' ) );
  235. remove( Range.createOn( next ) );
  236. return newPosition;
  237. }
  238. /**
  239. * Insert node or nodes at specified position. Takes care about breaking attributes before insertion
  240. * and merging them afterwards.
  241. *
  242. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-insert-invalid-node` when nodes to insert
  243. * contains instances that are not {@link module:engine/view/text~Text Texts},
  244. * {@link module:engine/view/attributeelement~AttributeElement AttributeElements},
  245. * {@link module:engine/view/containerelement~ContainerElement ContainerElements},
  246. * {@link module:engine/view/emptyelement~EmptyElement EmptyElements} or
  247. * {@link module:engine/view/uielement~UIElement UIElements}.
  248. *
  249. * @function insert
  250. * @param {module:engine/view/position~Position} position Insertion position.
  251. * @param {module:engine/view/text~Text|module:engine/view/attributeelement~AttributeElement|
  252. * module:engine/view/containerelement~ContainerElement|module:engine/view/emptyelement~EmptyElement|
  253. * module:engine/view/uielement~UIElement|Iterable.<module:engine/view/text~Text|
  254. * module:engine/view/attributeelement~AttributeElement|module:engine/view/containerelement~ContainerElement|
  255. * module:engine/view/emptyelement~EmptyElement|module:engine/view/uielement~UIElement>} nodes Node or nodes to insert.
  256. * @returns {module:engine/view/range~Range} Range around inserted nodes.
  257. */
  258. export function insert( position, nodes ) {
  259. nodes = isIterable( nodes ) ? [ ...nodes ] : [ nodes ];
  260. // Check if nodes to insert are instances of AttributeElements, ContainerElements, EmptyElements, UIElements or Text.
  261. validateNodesToInsert( nodes );
  262. const container = getParentContainer( position );
  263. if ( !container ) {
  264. /**
  265. * Position's parent container cannot be found.
  266. *
  267. * @error view-writer-invalid-position-container
  268. */
  269. throw new CKEditorError( 'view-writer-invalid-position-container' );
  270. }
  271. const insertionPosition = _breakAttributes( position, true );
  272. const length = container.insertChildren( insertionPosition.offset, nodes );
  273. const endPosition = insertionPosition.getShiftedBy( length );
  274. const start = mergeAttributes( insertionPosition );
  275. // When no nodes were inserted - return collapsed range.
  276. if ( length === 0 ) {
  277. return new Range( start, start );
  278. } else {
  279. // If start position was merged - move end position.
  280. if ( !start.isEqual( insertionPosition ) ) {
  281. endPosition.offset--;
  282. }
  283. const end = mergeAttributes( endPosition );
  284. return new Range( start, end );
  285. }
  286. }
  287. /**
  288. * Removes provided range from the container.
  289. *
  290. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  291. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
  292. * same parent container.
  293. *
  294. * @function module:engine/view/writer~writer.remove
  295. * @param {module:engine/view/range~Range} range Range to remove from container. After removing, it will be updated
  296. * to a collapsed range showing the new position.
  297. * @returns {module:engine/view/documentfragment~DocumentFragment} Document fragment containing removed nodes.
  298. */
  299. export function remove( range ) {
  300. validateRangeContainer( range );
  301. // If range is collapsed - nothing to remove.
  302. if ( range.isCollapsed ) {
  303. return new DocumentFragment();
  304. }
  305. // Break attributes at range start and end.
  306. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  307. const parentContainer = breakStart.parent;
  308. const count = breakEnd.offset - breakStart.offset;
  309. // Remove nodes in range.
  310. const removed = parentContainer.removeChildren( breakStart.offset, count );
  311. // Merge after removing.
  312. const mergePosition = mergeAttributes( breakStart );
  313. range.start = mergePosition;
  314. range.end = Position.createFromPosition( mergePosition );
  315. // Return removed nodes.
  316. return new DocumentFragment( removed );
  317. }
  318. /**
  319. * Removes matching elements from given range.
  320. *
  321. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  322. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
  323. * same parent container.
  324. *
  325. * @function module:engine/view/writer~writer.clear
  326. * @param {module:engine/view/range~Range} range Range to clear.
  327. * @param {module:engine/view/element~Element} element Element to remove.
  328. */
  329. export function clear( range, element ) {
  330. validateRangeContainer( range );
  331. // Create walker on given range.
  332. // We walk backward because when we remove element during walk it modifies range end position.
  333. const walker = range.getWalker( {
  334. direction: 'backward',
  335. ignoreElementEnd: true
  336. } );
  337. // Let's walk.
  338. for ( const current of walker ) {
  339. const item = current.item;
  340. let rangeToRemove;
  341. // When current item matches to the given element.
  342. if ( item.is( 'element' ) && element.isSimilar( item ) ) {
  343. // Create range on this element.
  344. rangeToRemove = Range.createOn( item );
  345. // When range starts inside Text or TextProxy element.
  346. } else if ( !current.nextPosition.isAfter( range.start ) && item.is( 'textProxy' ) ) {
  347. // We need to check if parent of this text matches to given element.
  348. const parentElement = item.getAncestors().find( ancestor => {
  349. return ancestor.is( 'element' ) && element.isSimilar( ancestor );
  350. } );
  351. // If it is then create range inside this element.
  352. if ( parentElement ) {
  353. rangeToRemove = Range.createIn( parentElement );
  354. }
  355. }
  356. // If we have found element to remove.
  357. if ( rangeToRemove ) {
  358. // We need to check if element range stick out of the given range and truncate if it is.
  359. if ( rangeToRemove.end.isAfter( range.end ) ) {
  360. rangeToRemove.end = range.end;
  361. }
  362. if ( rangeToRemove.start.isBefore( range.start ) ) {
  363. rangeToRemove.start = range.start;
  364. }
  365. // At the end we remove range with found element.
  366. remove( rangeToRemove );
  367. }
  368. }
  369. }
  370. /**
  371. * Moves nodes from provided range to target position.
  372. *
  373. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  374. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
  375. * same parent container.
  376. *
  377. * @function module:engine/view/writer~writer.move
  378. * @param {module:engine/view/range~Range} sourceRange Range containing nodes to move.
  379. * @param {module:engine/view/position~Position} targetPosition Position to insert.
  380. * @returns {module:engine/view/range~Range} Range in target container. Inserted nodes are placed between
  381. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions.
  382. */
  383. export function move( sourceRange, targetPosition ) {
  384. let nodes;
  385. if ( targetPosition.isAfter( sourceRange.end ) ) {
  386. targetPosition = _breakAttributes( targetPosition, true );
  387. const parent = targetPosition.parent;
  388. const countBefore = parent.childCount;
  389. sourceRange = _breakAttributesRange( sourceRange, true );
  390. nodes = remove( sourceRange );
  391. targetPosition.offset += ( parent.childCount - countBefore );
  392. } else {
  393. nodes = remove( sourceRange );
  394. }
  395. return insert( targetPosition, nodes );
  396. }
  397. /**
  398. * Wraps elements within range with provided {@link module:engine/view/attributeelement~AttributeElement AttributeElement}.
  399. *
  400. * If `viewSelection` was set and a collapsed range was passed, if the range is same as selection, the selection
  401. * will be moved to the inside of the wrapped attribute element.
  402. *
  403. * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-invalid-range-container`
  404. * when {@link module:engine/view/range~Range#start}
  405. * and {@link module:engine/view/range~Range#end} positions are not placed inside same parent container.
  406. *
  407. * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
  408. * an instance of {module:engine/view/attributeelement~AttributeElement AttributeElement}.
  409. *
  410. * @function module:engine/view/writer~writer.wrap
  411. * @param {module:engine/view/range~Range} range Range to wrap.
  412. * @param {module:engine/view/attributeelement~AttributeElement} attribute Attribute element to use as wrapper.
  413. * @param {module:engine/view/selection~Selection} [viewSelection=null] View selection to change, required when
  414. * wrapping collapsed range.
  415. * @returns {module:engine/view/range~Range} range Range after wrapping, spanning over wrapping attribute element.
  416. */
  417. export function wrap( range, attribute, viewSelection = null ) {
  418. if ( !( attribute instanceof AttributeElement ) ) {
  419. throw new CKEditorError( 'view-writer-wrap-invalid-attribute' );
  420. }
  421. validateRangeContainer( range );
  422. if ( !range.isCollapsed ) {
  423. // Non-collapsed range. Wrap it with the attribute element.
  424. return _wrapRange( range, attribute );
  425. } else {
  426. // Collapsed range. Wrap position.
  427. let position = range.start;
  428. if ( position.parent.is( 'element' ) && !_hasNonUiChildren( position.parent ) ) {
  429. position = position.getLastMatchingPosition( value => value.item.is( 'uiElement' ) );
  430. }
  431. position = _wrapPosition( position, attribute );
  432. // If wrapping position is equal to view selection, move view selection inside wrapping attribute element.
  433. if ( viewSelection && viewSelection.isCollapsed && viewSelection.getFirstPosition().isEqual( range.start ) ) {
  434. viewSelection.setTo( position );
  435. }
  436. return new Range( position );
  437. }
  438. }
  439. // Helper function for `view.writer.wrap`. Wraps range with provided attribute element.
  440. // This method will also merge newly added attribute element with its siblings whenever possible.
  441. //
  442. // Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
  443. // an instance of {module:engine/view/attributeelement~AttributeElement AttributeElement}.
  444. //
  445. // @param {module:engine/view/range~Range} range
  446. // @param {module:engine/view/attributeelement~AttributeElement} attribute
  447. // @returns {module:engine/view/range~Range} New range after wrapping, spanning over wrapping attribute element.
  448. function _wrapRange( range, attribute ) {
  449. // Range is inside single attribute and spans on all children.
  450. if ( rangeSpansOnAllChildren( range ) && wrapAttributeElement( attribute, range.start.parent ) ) {
  451. const parent = range.start.parent;
  452. const end = mergeAttributes( Position.createAfter( parent ) );
  453. const start = mergeAttributes( Position.createBefore( parent ) );
  454. return new Range( start, end );
  455. }
  456. // Break attributes at range start and end.
  457. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  458. // Range around one element.
  459. if ( breakEnd.isEqual( breakStart.getShiftedBy( 1 ) ) ) {
  460. const node = breakStart.nodeAfter;
  461. if ( node instanceof AttributeElement && wrapAttributeElement( attribute, node ) ) {
  462. const start = mergeAttributes( breakStart );
  463. if ( !start.isEqual( breakStart ) ) {
  464. breakEnd.offset--;
  465. }
  466. const end = mergeAttributes( breakEnd );
  467. return new Range( start, end );
  468. }
  469. }
  470. const parentContainer = breakStart.parent;
  471. // Unwrap children located between break points.
  472. const unwrappedRange = unwrapChildren( parentContainer, breakStart.offset, breakEnd.offset, attribute );
  473. // Wrap all children with attribute.
  474. const newRange = wrapChildren( parentContainer, unwrappedRange.start.offset, unwrappedRange.end.offset, attribute );
  475. // Merge attributes at the both ends and return a new range.
  476. const start = mergeAttributes( newRange.start );
  477. // If start position was merged - move end position back.
  478. if ( !start.isEqual( newRange.start ) ) {
  479. newRange.end.offset--;
  480. }
  481. const end = mergeAttributes( newRange.end );
  482. return new Range( start, end );
  483. }
  484. // Helper function for `view.writer.wrap`. Wraps position with provided attribute element.
  485. // This method will also merge newly added attribute element with its siblings whenever possible.
  486. //
  487. // Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
  488. // an instance of {module:engine/view/attributeelement~AttributeElement AttributeElement}.
  489. //
  490. // @param {module:engine/view/position~Position} position
  491. // @param {module:engine/view/attributeelement~AttributeElement} attribute
  492. // @returns {module:engine/view/position~Position} New position after wrapping.
  493. function _wrapPosition( position, attribute ) {
  494. // Return same position when trying to wrap with attribute similar to position parent.
  495. if ( attribute.isSimilar( position.parent ) ) {
  496. return movePositionToTextNode( Position.createFromPosition( position ) );
  497. }
  498. // When position is inside text node - break it and place new position between two text nodes.
  499. if ( position.parent.is( 'text' ) ) {
  500. position = breakTextNode( position );
  501. }
  502. // Create fake element that will represent position, and will not be merged with other attributes.
  503. const fakePosition = new AttributeElement();
  504. fakePosition.priority = Number.POSITIVE_INFINITY;
  505. fakePosition.isSimilar = () => false;
  506. // Insert fake element in position location.
  507. position.parent.insertChildren( position.offset, fakePosition );
  508. // Range around inserted fake attribute element.
  509. const wrapRange = new Range( position, position.getShiftedBy( 1 ) );
  510. // Wrap fake element with attribute (it will also merge if possible).
  511. wrap( wrapRange, attribute );
  512. // Remove fake element and place new position there.
  513. const newPosition = new Position( fakePosition.parent, fakePosition.index );
  514. fakePosition.remove();
  515. // If position is placed between text nodes - merge them and return position inside.
  516. const nodeBefore = newPosition.nodeBefore;
  517. const nodeAfter = newPosition.nodeAfter;
  518. if ( nodeBefore instanceof Text && nodeAfter instanceof Text ) {
  519. return mergeTextNodes( nodeBefore, nodeAfter );
  520. }
  521. // If position is next to text node - move position inside.
  522. return movePositionToTextNode( newPosition );
  523. }
  524. // Helper function for `view.writer.wrap`. Checks if given element has any children that are not ui elements.
  525. function _hasNonUiChildren( parent ) {
  526. return Array.from( parent.getChildren() ).some( child => !child.is( 'uiElement' ) );
  527. }
  528. /**
  529. * Unwraps nodes within provided range from attribute element.
  530. *
  531. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  532. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
  533. * same parent container.
  534. *
  535. * @param {module:engine/view/range~Range} range
  536. * @param {module:engine/view/attributeelement~AttributeElement} attribute
  537. */
  538. export function unwrap( range, attribute ) {
  539. if ( !( attribute instanceof AttributeElement ) ) {
  540. /**
  541. * Attribute element need to be instance of attribute element.
  542. *
  543. * @error view-writer-unwrap-invalid-attribute
  544. */
  545. throw new CKEditorError( 'view-writer-unwrap-invalid-attribute' );
  546. }
  547. validateRangeContainer( range );
  548. // If range is collapsed - nothing to unwrap.
  549. if ( range.isCollapsed ) {
  550. return range;
  551. }
  552. // Break attributes at range start and end.
  553. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  554. // Range around one element - check if AttributeElement can be unwrapped partially when it's not similar.
  555. // For example:
  556. // <b class="foo bar" title="baz"></b> unwrap with: <b class="foo"></p> result: <b class"bar" title="baz"></b>
  557. if ( breakEnd.isEqual( breakStart.getShiftedBy( 1 ) ) ) {
  558. const node = breakStart.nodeAfter;
  559. // Unwrap single attribute element.
  560. if ( !attribute.isSimilar( node ) && node instanceof AttributeElement && unwrapAttributeElement( attribute, node ) ) {
  561. const start = mergeAttributes( breakStart );
  562. if ( !start.isEqual( breakStart ) ) {
  563. breakEnd.offset--;
  564. }
  565. const end = mergeAttributes( breakEnd );
  566. return new Range( start, end );
  567. }
  568. }
  569. const parentContainer = breakStart.parent;
  570. // Unwrap children located between break points.
  571. const newRange = unwrapChildren( parentContainer, breakStart.offset, breakEnd.offset, attribute );
  572. // Merge attributes at the both ends and return a new range.
  573. const start = mergeAttributes( newRange.start );
  574. // If start position was merged - move end position back.
  575. if ( !start.isEqual( newRange.start ) ) {
  576. newRange.end.offset--;
  577. }
  578. const end = mergeAttributes( newRange.end );
  579. return new Range( start, end );
  580. }
  581. /**
  582. * Renames element by creating a copy of renamed element but with changed name and then moving contents of the
  583. * old element to the new one. Keep in mind that this will invalidate all {@link module:engine/view/position~Position positions} which
  584. * has renamed element as {@link module:engine/view/position~Position#parent a parent}.
  585. *
  586. * New element has to be created because `Element#tagName` property in DOM is readonly.
  587. *
  588. * Since this function creates a new element and removes the given one, the new element is returned to keep reference.
  589. *
  590. * @param {module:engine/view/containerelement~ContainerElement} viewElement Element to be renamed.
  591. * @param {String} newName New name for element.
  592. */
  593. export function rename( viewElement, newName ) {
  594. const newElement = new ContainerElement( newName, viewElement.getAttributes() );
  595. insert( Position.createAfter( viewElement ), newElement );
  596. move( Range.createIn( viewElement ), Position.createAt( newElement ) );
  597. remove( Range.createOn( viewElement ) );
  598. return newElement;
  599. }
  600. /**
  601. * Attribute element need to be instance of attribute element.
  602. *
  603. * @error view-writer-wrap-invalid-attribute
  604. */
  605. // Returns first parent container of specified {@link module:engine/view/position~Position Position}.
  606. // Position's parent node is checked as first, then next parents are checked.
  607. // Note that {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment} is treated like a container.
  608. //
  609. // @param {module:engine/view/position~Position} position Position used as a start point to locate parent container.
  610. // @returns {module:engine/view/containerelement~ContainerElement|module:engine/view/documentfragment~DocumentFragment|undefined}
  611. // Parent container element or `undefined` if container is not found.
  612. function getParentContainer( position ) {
  613. let parent = position.parent;
  614. while ( !isContainerOrFragment( parent ) ) {
  615. if ( !parent ) {
  616. return undefined;
  617. }
  618. parent = parent.parent;
  619. }
  620. return parent;
  621. }
  622. // Function used by both public breakAttributes (without splitting text nodes) and by other methods (with
  623. // splitting text nodes).
  624. //
  625. // @param {module:engine/view/range~Range} range Range which `start` and `end` positions will be used to break attributes.
  626. // @param {Boolean} [forceSplitText = false] If set to `true`, will break text nodes even if they are directly in
  627. // container element. This behavior will result in incorrect view state, but is needed by other view writing methods
  628. // which then fixes view state. Defaults to `false`.
  629. // @returns {module:engine/view/range~Range} New range with located at break positions.
  630. function _breakAttributesRange( range, forceSplitText = false ) {
  631. const rangeStart = range.start;
  632. const rangeEnd = range.end;
  633. validateRangeContainer( range );
  634. // Break at the collapsed position. Return new collapsed range.
  635. if ( range.isCollapsed ) {
  636. const position = _breakAttributes( range.start, forceSplitText );
  637. return new Range( position, position );
  638. }
  639. const breakEnd = _breakAttributes( rangeEnd, forceSplitText );
  640. const count = breakEnd.parent.childCount;
  641. const breakStart = _breakAttributes( rangeStart, forceSplitText );
  642. // Calculate new break end offset.
  643. breakEnd.offset += breakEnd.parent.childCount - count;
  644. return new Range( breakStart, breakEnd );
  645. }
  646. // Function used by public breakAttributes (without splitting text nodes) and by other methods (with
  647. // splitting text nodes).
  648. //
  649. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-empty-element` when break position
  650. // is placed inside {@link module:engine/view/emptyelement~EmptyElement EmptyElement}.
  651. //
  652. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-ui-element` when break position
  653. // is placed inside {@link module:engine/view/uielement~UIElement UIElement}.
  654. //
  655. // @param {module:engine/view/position~Position} position Position where to break attributes.
  656. // @param {Boolean} [forceSplitText = false] If set to `true`, will break text nodes even if they are directly in
  657. // container element. This behavior will result in incorrect view state, but is needed by other view writing methods
  658. // which then fixes view state. Defaults to `false`.
  659. // @returns {module:engine/view/position~Position} New position after breaking the attributes.
  660. function _breakAttributes( position, forceSplitText = false ) {
  661. const positionOffset = position.offset;
  662. const positionParent = position.parent;
  663. // If position is placed inside EmptyElement - throw an exception as we cannot break inside.
  664. if ( position.parent.is( 'emptyElement' ) ) {
  665. /**
  666. * Cannot break inside EmptyElement instance.
  667. *
  668. * @error view-writer-cannot-break-empty-element
  669. */
  670. throw new CKEditorError( 'view-writer-cannot-break-empty-element' );
  671. }
  672. // If position is placed inside UIElement - throw an exception as we cannot break inside.
  673. if ( position.parent.is( 'uiElement' ) ) {
  674. /**
  675. * Cannot break inside UIElement instance.
  676. *
  677. * @error view-writer-cannot-break-ui-element
  678. */
  679. throw new CKEditorError( 'view-writer-cannot-break-ui-element' );
  680. }
  681. // There are no attributes to break and text nodes breaking is not forced.
  682. if ( !forceSplitText && positionParent.is( 'text' ) && isContainerOrFragment( positionParent.parent ) ) {
  683. return Position.createFromPosition( position );
  684. }
  685. // Position's parent is container, so no attributes to break.
  686. if ( isContainerOrFragment( positionParent ) ) {
  687. return Position.createFromPosition( position );
  688. }
  689. // Break text and start again in new position.
  690. if ( positionParent.is( 'text' ) ) {
  691. return _breakAttributes( breakTextNode( position ), forceSplitText );
  692. }
  693. const length = positionParent.childCount;
  694. // <p>foo<b><u>bar{}</u></b></p>
  695. // <p>foo<b><u>bar</u>[]</b></p>
  696. // <p>foo<b><u>bar</u></b>[]</p>
  697. if ( positionOffset == length ) {
  698. const newPosition = new Position( positionParent.parent, positionParent.index + 1 );
  699. return _breakAttributes( newPosition, forceSplitText );
  700. } else
  701. // <p>foo<b><u>{}bar</u></b></p>
  702. // <p>foo<b>[]<u>bar</u></b></p>
  703. // <p>foo{}<b><u>bar</u></b></p>
  704. if ( positionOffset === 0 ) {
  705. const newPosition = new Position( positionParent.parent, positionParent.index );
  706. return _breakAttributes( newPosition, forceSplitText );
  707. }
  708. // <p>foo<b><u>b{}ar</u></b></p>
  709. // <p>foo<b><u>b[]ar</u></b></p>
  710. // <p>foo<b><u>b</u>[]<u>ar</u></b></p>
  711. // <p>foo<b><u>b</u></b>[]<b><u>ar</u></b></p>
  712. else {
  713. const offsetAfter = positionParent.index + 1;
  714. // Break element.
  715. const clonedNode = positionParent.clone();
  716. // Insert cloned node to position's parent node.
  717. positionParent.parent.insertChildren( offsetAfter, clonedNode );
  718. // Get nodes to move.
  719. const count = positionParent.childCount - positionOffset;
  720. const nodesToMove = positionParent.removeChildren( positionOffset, count );
  721. // Move nodes to cloned node.
  722. clonedNode.appendChildren( nodesToMove );
  723. // Create new position to work on.
  724. const newPosition = new Position( positionParent.parent, offsetAfter );
  725. return _breakAttributes( newPosition, forceSplitText );
  726. }
  727. }
  728. // Unwraps children from provided `attribute`. Only children contained in `parent` element between
  729. // `startOffset` and `endOffset` will be unwrapped.
  730. //
  731. // @param {module:engine/view/element~Element} parent
  732. // @param {Number} startOffset
  733. // @param {Number} endOffset
  734. // @param {module:engine/view/element~Element} attribute
  735. function unwrapChildren( parent, startOffset, endOffset, attribute ) {
  736. let i = startOffset;
  737. const unwrapPositions = [];
  738. // Iterate over each element between provided offsets inside parent.
  739. while ( i < endOffset ) {
  740. const child = parent.getChild( i );
  741. // If attributes are the similar, then unwrap.
  742. if ( child.isSimilar( attribute ) ) {
  743. const unwrapped = child.getChildren();
  744. const count = child.childCount;
  745. // Replace wrapper element with its children
  746. child.remove();
  747. parent.insertChildren( i, unwrapped );
  748. // Save start and end position of moved items.
  749. unwrapPositions.push(
  750. new Position( parent, i ),
  751. new Position( parent, i + count )
  752. );
  753. // Skip elements that were unwrapped. Assuming that there won't be another element to unwrap in child
  754. // elements.
  755. i += count;
  756. endOffset += count - 1;
  757. } else {
  758. // If other nested attribute is found start unwrapping there.
  759. if ( child.is( 'attributeElement' ) ) {
  760. unwrapChildren( child, 0, child.childCount, attribute );
  761. }
  762. i++;
  763. }
  764. }
  765. // Merge at each unwrap.
  766. let offsetChange = 0;
  767. for ( const position of unwrapPositions ) {
  768. position.offset -= offsetChange;
  769. // Do not merge with elements outside selected children.
  770. if ( position.offset == startOffset || position.offset == endOffset ) {
  771. continue;
  772. }
  773. const newPosition = mergeAttributes( position );
  774. // If nodes were merged - other merge offsets will change.
  775. if ( !newPosition.isEqual( position ) ) {
  776. offsetChange++;
  777. endOffset--;
  778. }
  779. }
  780. return Range.createFromParentsAndOffsets( parent, startOffset, parent, endOffset );
  781. }
  782. // Wraps children with provided `attribute`. Only children contained in `parent` element between
  783. // `startOffset` and `endOffset` will be wrapped.
  784. //
  785. // @param {module:engine/view/element~Element} parent
  786. // @param {Number} startOffset
  787. // @param {Number} endOffset
  788. // @param {module:engine/view/element~Element} attribute
  789. function wrapChildren( parent, startOffset, endOffset, attribute ) {
  790. let i = startOffset;
  791. const wrapPositions = [];
  792. while ( i < endOffset ) {
  793. const child = parent.getChild( i );
  794. const isText = child.is( 'text' );
  795. const isAttribute = child.is( 'attributeElement' );
  796. const isEmpty = child.is( 'emptyElement' );
  797. const isUI = child.is( 'uiElement' );
  798. // Wrap text, empty elements, ui elements or attributes with higher or equal priority.
  799. if ( isText || isEmpty || isUI || ( isAttribute && shouldABeOutsideB( attribute, child ) ) ) {
  800. // Clone attribute.
  801. const newAttribute = attribute.clone();
  802. // Wrap current node with new attribute;
  803. child.remove();
  804. newAttribute.appendChildren( child );
  805. parent.insertChildren( i, newAttribute );
  806. wrapPositions.push( new Position( parent, i ) );
  807. }
  808. // If other nested attribute is found start wrapping there.
  809. else if ( isAttribute ) {
  810. wrapChildren( child, 0, child.childCount, attribute );
  811. }
  812. i++;
  813. }
  814. // Merge at each wrap.
  815. let offsetChange = 0;
  816. for ( const position of wrapPositions ) {
  817. position.offset -= offsetChange;
  818. // Do not merge with elements outside selected children.
  819. if ( position.offset == startOffset ) {
  820. continue;
  821. }
  822. const newPosition = mergeAttributes( position );
  823. // If nodes were merged - other merge offsets will change.
  824. if ( !newPosition.isEqual( position ) ) {
  825. offsetChange++;
  826. endOffset--;
  827. }
  828. }
  829. return Range.createFromParentsAndOffsets( parent, startOffset, parent, endOffset );
  830. }
  831. // Checks if first {@link module:engine/view/attributeelement~AttributeElement AttributeElement} provided to the function
  832. // can be wrapped otuside second element. It is done by comparing elements'
  833. // {@link module:engine/view/attributeelement~AttributeElement#priority priorities}, if both have same priority
  834. // {@link module:engine/view/element~Element#getIdentity identities} are compared.
  835. //
  836. // @param {module:engine/view/attributeelement~AttributeElement} a
  837. // @param {module:engine/view/attributeelement~AttributeElement} b
  838. // @returns {Boolean}
  839. function shouldABeOutsideB( a, b ) {
  840. if ( a.priority < b.priority ) {
  841. return true;
  842. } else if ( a.priority > b.priority ) {
  843. return false;
  844. }
  845. // When priorities are equal and names are different - use identities.
  846. return a.getIdentity() < b.getIdentity();
  847. }
  848. // Returns new position that is moved to near text node. Returns same position if there is no text node before of after
  849. // specified position.
  850. //
  851. // <p>foo[]</p> -> <p>foo{}</p>
  852. // <p>[]foo</p> -> <p>{}foo</p>
  853. //
  854. // @param {module:engine/view/position~Position} position
  855. // @returns {module:engine/view/position~Position} Position located inside text node or same position if there is no text nodes
  856. // before or after position location.
  857. function movePositionToTextNode( position ) {
  858. const nodeBefore = position.nodeBefore;
  859. if ( nodeBefore && nodeBefore.is( 'text' ) ) {
  860. return new Position( nodeBefore, nodeBefore.data.length );
  861. }
  862. const nodeAfter = position.nodeAfter;
  863. if ( nodeAfter && nodeAfter.is( 'text' ) ) {
  864. return new Position( nodeAfter, 0 );
  865. }
  866. return position;
  867. }
  868. // Breaks text node into two text nodes when possible.
  869. //
  870. // <p>foo{}bar</p> -> <p>foo[]bar</p>
  871. // <p>{}foobar</p> -> <p>[]foobar</p>
  872. // <p>foobar{}</p> -> <p>foobar[]</p>
  873. //
  874. // @param {module:engine/view/position~Position} position Position that need to be placed inside text node.
  875. // @returns {module:engine/view/position~Position} New position after breaking text node.
  876. function breakTextNode( position ) {
  877. if ( position.offset == position.parent.data.length ) {
  878. return new Position( position.parent.parent, position.parent.index + 1 );
  879. }
  880. if ( position.offset === 0 ) {
  881. return new Position( position.parent.parent, position.parent.index );
  882. }
  883. // Get part of the text that need to be moved.
  884. const textToMove = position.parent.data.slice( position.offset );
  885. // Leave rest of the text in position's parent.
  886. position.parent.data = position.parent.data.slice( 0, position.offset );
  887. // Insert new text node after position's parent text node.
  888. position.parent.parent.insertChildren( position.parent.index + 1, new Text( textToMove ) );
  889. // Return new position between two newly created text nodes.
  890. return new Position( position.parent.parent, position.parent.index + 1 );
  891. }
  892. // Merges two text nodes into first node. Removes second node and returns merge position.
  893. //
  894. // @param {module:engine/view/text~Text} t1 First text node to merge. Data from second text node will be moved at the end of
  895. // this text node.
  896. // @param {module:engine/view/text~Text} t2 Second text node to merge. This node will be removed after merging.
  897. // @returns {module:engine/view/position~Position} Position after merging text nodes.
  898. function mergeTextNodes( t1, t2 ) {
  899. // Merge text data into first text node and remove second one.
  900. const nodeBeforeLength = t1.data.length;
  901. t1.data += t2.data;
  902. t2.remove();
  903. return new Position( t1, nodeBeforeLength );
  904. }
  905. // Wraps one {@link module:engine/view/attributeelement~AttributeElement AttributeElement} into another by merging them if possible.
  906. // When merging is possible - all attributes, styles and classes are moved from wrapper element to element being
  907. // wrapped.
  908. //
  909. // @param {module:engine/view/attributeelement~AttributeElement} wrapper Wrapper AttributeElement.
  910. // @param {module:engine/view/attributeelement~AttributeElement} toWrap AttributeElement to wrap using wrapper element.
  911. // @returns {Boolean} Returns `true` if elements are merged.
  912. function wrapAttributeElement( wrapper, toWrap ) {
  913. // Can't merge if name or priority differs.
  914. if ( wrapper.name !== toWrap.name || wrapper.priority !== toWrap.priority ) {
  915. return false;
  916. }
  917. // Check if attributes can be merged.
  918. for ( const key of wrapper.getAttributeKeys() ) {
  919. // Classes and styles should be checked separately.
  920. if ( key === 'class' || key === 'style' ) {
  921. continue;
  922. }
  923. // If some attributes are different we cannot wrap.
  924. if ( toWrap.hasAttribute( key ) && toWrap.getAttribute( key ) !== wrapper.getAttribute( key ) ) {
  925. return false;
  926. }
  927. }
  928. // Check if styles can be merged.
  929. for ( const key of wrapper.getStyleNames() ) {
  930. if ( toWrap.hasStyle( key ) && toWrap.getStyle( key ) !== wrapper.getStyle( key ) ) {
  931. return false;
  932. }
  933. }
  934. // Move all attributes/classes/styles from wrapper to wrapped AttributeElement.
  935. for ( const key of wrapper.getAttributeKeys() ) {
  936. // Classes and styles should be checked separately.
  937. if ( key === 'class' || key === 'style' ) {
  938. continue;
  939. }
  940. // Move only these attributes that are not present - other are similar.
  941. if ( !toWrap.hasAttribute( key ) ) {
  942. toWrap.setAttribute( key, wrapper.getAttribute( key ) );
  943. }
  944. }
  945. for ( const key of wrapper.getStyleNames() ) {
  946. if ( !toWrap.hasStyle( key ) ) {
  947. toWrap.setStyle( key, wrapper.getStyle( key ) );
  948. }
  949. }
  950. for ( const key of wrapper.getClassNames() ) {
  951. if ( !toWrap.hasClass( key ) ) {
  952. toWrap.addClass( key );
  953. }
  954. }
  955. return true;
  956. }
  957. // Unwraps {@link module:engine/view/attributeelement~AttributeElement AttributeElement} from another by removing corresponding attributes,
  958. // classes and styles. All attributes, classes and styles from wrapper should be present inside element being unwrapped.
  959. //
  960. // @param {module:engine/view/attributeelement~AttributeElement} wrapper Wrapper AttributeElement.
  961. // @param {module:engine/view/attributeelement~AttributeElement} toUnwrap AttributeElement to unwrap using wrapper element.
  962. // @returns {Boolean} Returns `true` if elements are unwrapped.
  963. function unwrapAttributeElement( wrapper, toUnwrap ) {
  964. // Can't unwrap if name or priority differs.
  965. if ( wrapper.name !== toUnwrap.name || wrapper.priority !== toUnwrap.priority ) {
  966. return false;
  967. }
  968. // Check if AttributeElement has all wrapper attributes.
  969. for ( const key of wrapper.getAttributeKeys() ) {
  970. // Classes and styles should be checked separately.
  971. if ( key === 'class' || key === 'style' ) {
  972. continue;
  973. }
  974. // If some attributes are missing or different we cannot unwrap.
  975. if ( !toUnwrap.hasAttribute( key ) || toUnwrap.getAttribute( key ) !== wrapper.getAttribute( key ) ) {
  976. return false;
  977. }
  978. }
  979. // Check if AttributeElement has all wrapper classes.
  980. if ( !toUnwrap.hasClass( ...wrapper.getClassNames() ) ) {
  981. return false;
  982. }
  983. // Check if AttributeElement has all wrapper styles.
  984. for ( const key of wrapper.getStyleNames() ) {
  985. // If some styles are missing or different we cannot unwrap.
  986. if ( !toUnwrap.hasStyle( key ) || toUnwrap.getStyle( key ) !== wrapper.getStyle( key ) ) {
  987. return false;
  988. }
  989. }
  990. // Remove all wrapper's attributes from unwrapped element.
  991. for ( const key of wrapper.getAttributeKeys() ) {
  992. // Classes and styles should be checked separately.
  993. if ( key === 'class' || key === 'style' ) {
  994. continue;
  995. }
  996. toUnwrap.removeAttribute( key );
  997. }
  998. // Remove all wrapper's classes from unwrapped element.
  999. toUnwrap.removeClass( ...wrapper.getClassNames() );
  1000. // Remove all wrapper's styles from unwrapped element.
  1001. toUnwrap.removeStyle( ...wrapper.getStyleNames() );
  1002. return true;
  1003. }
  1004. // Returns `true` if range is located in same {@link module:engine/view/attributeelement~AttributeElement AttributeElement}
  1005. // (`start` and `end` positions are located inside same {@link module:engine/view/attributeelement~AttributeElement AttributeElement}),
  1006. // starts on 0 offset and ends after last child node.
  1007. //
  1008. // @param {module:engine/view/range~Range} Range
  1009. // @returns {Boolean}
  1010. function rangeSpansOnAllChildren( range ) {
  1011. return range.start.parent == range.end.parent && range.start.parent.is( 'attributeElement' ) &&
  1012. range.start.offset === 0 && range.end.offset === range.start.parent.childCount;
  1013. }
  1014. // Checks if provided nodes are valid to insert. Checks if each node is an instance of
  1015. // {@link module:engine/view/text~Text Text} or {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
  1016. // {@link module:engine/view/containerelement~ContainerElement ContainerElement},
  1017. // {@link module:engine/view/emptyelement~EmptyElement EmptyElement} or
  1018. // {@link module:engine/view/uielement~UIElement UIElement}.
  1019. //
  1020. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-insert-invalid-node` when nodes to insert
  1021. // contains instances that are not {@link module:engine/view/text~Text Texts},
  1022. // {@link module:engine/view/emptyelement~EmptyElement EmptyElements},
  1023. // {@link module:engine/view/uielement~UIElement UIElements},
  1024. // {@link module:engine/view/attributeelement~AttributeElement AttributeElements} or
  1025. // {@link module:engine/view/containerelement~ContainerElement ContainerElements}.
  1026. //
  1027. // @param Iterable.<module:engine/view/text~Text|module:engine/view/attributeelement~AttributeElement
  1028. // |module:engine/view/containerelement~ContainerElement> nodes
  1029. function validateNodesToInsert( nodes ) {
  1030. for ( const node of nodes ) {
  1031. if ( !validNodesToInsert.some( ( validNode => node instanceof validNode ) ) ) { // eslint-disable-line no-use-before-define
  1032. /**
  1033. * Inserted nodes should be valid to insert. of {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
  1034. * {@link module:engine/view/containerelement~ContainerElement ContainerElement},
  1035. * {@link module:engine/view/emptyelement~EmptyElement EmptyElement},
  1036. * {@link module:engine/view/uielement~UIElement UIElement}, {@link module:engine/view/text~Text Text}.
  1037. *
  1038. * @error view-writer-insert-invalid-node
  1039. */
  1040. throw new CKEditorError( 'view-writer-insert-invalid-node' );
  1041. }
  1042. if ( !node.is( 'text' ) ) {
  1043. validateNodesToInsert( node.getChildren() );
  1044. }
  1045. }
  1046. }
  1047. const validNodesToInsert = [ Text, AttributeElement, ContainerElement, EmptyElement, UIElement ];
  1048. // Checks if node is ContainerElement or DocumentFragment, because in most cases they should be treated the same way.
  1049. //
  1050. // @param {module:engine/view/node~Node} node
  1051. // @returns {Boolean} Returns `true` if node is instance of ContainerElement or DocumentFragment.
  1052. function isContainerOrFragment( node ) {
  1053. return node && ( node.is( 'containerElement' ) || node.is( 'documentFragment' ) );
  1054. }
  1055. // Checks if {@link module:engine/view/range~Range#start range start} and {@link module:engine/view/range~Range#end range end} are placed
  1056. // inside same {@link module:engine/view/containerelement~ContainerElement container element}.
  1057. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when validation fails.
  1058. //
  1059. // @param {module:engine/view/range~Range} range
  1060. function validateRangeContainer( range ) {
  1061. const startContainer = getParentContainer( range.start );
  1062. const endContainer = getParentContainer( range.end );
  1063. if ( !startContainer || !endContainer || startContainer !== endContainer ) {
  1064. /**
  1065. * Range container is invalid. This can happen if {@link module:engine/view/range~Range#start range start} and
  1066. * {@link module:engine/view/range~Range#end range end} positions are not placed inside same container or
  1067. * parent container for these positions cannot be found.
  1068. *
  1069. * @error view-writer-invalid-range-container
  1070. */
  1071. throw new CKEditorError( 'view-writer-invalid-range-container' );
  1072. }
  1073. }