writer.js 48 KB

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