writer.js 47 KB

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