writer.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  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. After removing, it will be updated
  297. * to a collapsed range showing the new position.
  298. * @returns {module:engine/view/documentfragment~DocumentFragment} Document fragment containing removed nodes.
  299. */
  300. export function remove( range ) {
  301. validateRangeContainer( range );
  302. // If range is collapsed - nothing to remove.
  303. if ( range.isCollapsed ) {
  304. return new DocumentFragment();
  305. }
  306. // Break attributes at range start and end.
  307. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  308. const parentContainer = breakStart.parent;
  309. const count = breakEnd.offset - breakStart.offset;
  310. // Remove nodes in range.
  311. const removed = parentContainer.removeChildren( breakStart.offset, count );
  312. // Merge after removing.
  313. const mergePosition = mergeAttributes( breakStart );
  314. range.start = mergePosition;
  315. range.end = Position.createFromPosition( mergePosition );
  316. // Return removed nodes.
  317. return new DocumentFragment( removed );
  318. }
  319. /**
  320. * Removes matching elements from given range.
  321. *
  322. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  323. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
  324. * same parent container.
  325. *
  326. * @function module:engine/view/writer~writer.clear
  327. * @param {module:engine/view/range~Range} range Range to clear.
  328. * @param {module:engine/view/element~Element} element Element to remove.
  329. */
  330. export function clear( range, element ) {
  331. validateRangeContainer( range );
  332. // Create walker on given range.
  333. // We walk backward because when we remove element during walk it modifies range end position.
  334. const walker = range.getWalker( {
  335. direction: 'backward',
  336. ignoreElementEnd: true
  337. } );
  338. // Let's walk.
  339. for ( const current of walker ) {
  340. const item = current.item;
  341. let rangeToRemove;
  342. // When current item matches to the given element.
  343. if ( item.is( 'element' ) && element.isSimilar( item ) ) {
  344. // Create range on this element.
  345. rangeToRemove = Range.createOn( item );
  346. // When range starts inside Text or TextProxy element.
  347. } else if ( !current.nextPosition.isAfter( range.start ) && ( item.is( 'text' ) || item.is( 'textProxy' ) ) ) {
  348. // We need to check if parent of this text matches to given element.
  349. const parentElement = item.getAncestors().find( ancestor => {
  350. return ancestor.is( 'element' ) && element.isSimilar( ancestor );
  351. } );
  352. // If it is then create range inside this element.
  353. if ( parentElement ) {
  354. rangeToRemove = Range.createIn( parentElement );
  355. }
  356. }
  357. // If we have found element to remove.
  358. if ( rangeToRemove ) {
  359. // We need to check if element range stick out of the given range and truncate if it is.
  360. if ( rangeToRemove.end.isAfter( range.end ) ) {
  361. rangeToRemove.end = range.end;
  362. }
  363. if ( rangeToRemove.start.isBefore( range.start ) ) {
  364. rangeToRemove.start = range.start;
  365. }
  366. // At the end we remove range with found element.
  367. remove( rangeToRemove );
  368. }
  369. }
  370. }
  371. /**
  372. * Moves nodes from provided range to target position.
  373. *
  374. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  375. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
  376. * same parent container.
  377. *
  378. * @function module:engine/view/writer~writer.move
  379. * @param {module:engine/view/range~Range} sourceRange Range containing nodes to move.
  380. * @param {module:engine/view/position~Position} targetPosition Position to insert.
  381. * @returns {module:engine/view/range~Range} Range in target container. Inserted nodes are placed between
  382. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions.
  383. */
  384. export function move( sourceRange, targetPosition ) {
  385. let nodes;
  386. if ( targetPosition.isAfter( sourceRange.end ) ) {
  387. targetPosition = _breakAttributes( targetPosition, true );
  388. const parent = targetPosition.parent;
  389. const countBefore = parent.childCount;
  390. sourceRange = _breakAttributesRange( sourceRange, true );
  391. nodes = remove( sourceRange );
  392. targetPosition = targetPosition.getShiftedBy( parent.childCount - countBefore );
  393. } else {
  394. nodes = remove( sourceRange );
  395. }
  396. return insert( targetPosition, nodes );
  397. }
  398. /**
  399. * Wraps elements within range with provided {@link module:engine/view/attributeelement~AttributeElement AttributeElement}.
  400. *
  401. * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-invalid-range-container`
  402. * when {@link module:engine/view/range~Range#start}
  403. * and {@link module:engine/view/range~Range#end} positions are not placed inside same parent container.
  404. * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
  405. * an instance of {module:engine/view/attributeelement~AttributeElement AttributeElement}.
  406. *
  407. * @function module:engine/view/writer~writer.wrap
  408. * @param {module:engine/view/range~Range} range Range to wrap.
  409. * @param {module:engine/view/attributeelement~AttributeElement} attribute Attribute element to use as wrapper.
  410. */
  411. export function wrap( range, attribute ) {
  412. if ( !( attribute instanceof AttributeElement ) ) {
  413. throw new CKEditorError( 'view-writer-wrap-invalid-attribute' );
  414. }
  415. validateRangeContainer( range );
  416. // If range is collapsed - nothing to wrap.
  417. if ( range.isCollapsed ) {
  418. return range;
  419. }
  420. // Range around one element.
  421. if ( range.end.isEqual( range.start.getShiftedBy( 1 ) ) ) {
  422. const node = range.start.nodeAfter;
  423. if ( node instanceof AttributeElement && wrapAttributeElement( attribute, node ) ) {
  424. return range;
  425. }
  426. }
  427. // Range is inside single attribute and spans on all children.
  428. if ( rangeSpansOnAllChildren( range ) && wrapAttributeElement( attribute, range.start.parent ) ) {
  429. const parent = range.start.parent.parent;
  430. const index = range.start.parent.index;
  431. return Range.createFromParentsAndOffsets( parent, index, parent, index + 1 );
  432. }
  433. // Break attributes at range start and end.
  434. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  435. const parentContainer = breakStart.parent;
  436. // Unwrap children located between break points.
  437. const unwrappedRange = unwrapChildren( parentContainer, breakStart.offset, breakEnd.offset, attribute );
  438. // Wrap all children with attribute.
  439. const newRange = wrapChildren( parentContainer, unwrappedRange.start.offset, unwrappedRange.end.offset, attribute );
  440. // Merge attributes at the both ends and return a new range.
  441. const start = mergeAttributes( newRange.start );
  442. // If start position was merged - move end position back.
  443. if ( !start.isEqual( newRange.start ) ) {
  444. newRange.end = newRange.end.getShiftedBy( -1 );
  445. }
  446. const end = mergeAttributes( newRange.end );
  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.createFromPosition( 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. if ( !start.isEqual( newRange.start ) ) {
  537. newRange.end = newRange.end.getShiftedBy( -1 );
  538. }
  539. const end = mergeAttributes( newRange.end );
  540. return new Range( start, end );
  541. }
  542. /**
  543. * Renames element by creating a copy of renamed element but with changed name and then moving contents of the
  544. * old element to the new one. Keep in mind that this will invalidate all {@link module:engine/view/position~Position positions} which
  545. * has renamed element as {@link module:engine/view/position~Position#parent a parent}.
  546. *
  547. * New element has to be created because `Element#tagName` property in DOM is readonly.
  548. *
  549. * Since this function creates a new element and removes the given one, the new element is returned to keep reference.
  550. *
  551. * @param {module:engine/view/containerelement~ContainerElement} viewElement Element to be renamed.
  552. * @param {String} newName New name for element.
  553. */
  554. export function rename( viewElement, newName ) {
  555. const newElement = new ContainerElement( newName, viewElement.getAttributes() );
  556. insert( Position.createAfter( viewElement ), newElement );
  557. move( Range.createIn( viewElement ), Position.createAt( newElement ) );
  558. remove( Range.createOn( viewElement ) );
  559. return newElement;
  560. }
  561. /**
  562. * Attribute element need to be instance of attribute element.
  563. *
  564. * @error view-writer-wrap-invalid-attribute
  565. */
  566. // Returns first parent container of specified {@link module:engine/view/position~Position Position}.
  567. // Position's parent node is checked as first, then next parents are checked.
  568. // Note that {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment} is treated like a container.
  569. //
  570. // @param {module:engine/view/position~Position} position Position used as a start point to locate parent container.
  571. // @returns {module:engine/view/containerelement~ContainerElement|module:engine/view/documentfragment~DocumentFragment|undefined}
  572. // Parent container element or `undefined` if container is not found.
  573. function getParentContainer( position ) {
  574. let parent = position.parent;
  575. while ( !isContainerOrFragment( parent ) ) {
  576. if ( !parent ) {
  577. return undefined;
  578. }
  579. parent = parent.parent;
  580. }
  581. return parent;
  582. }
  583. // Function used by both public breakAttributes (without splitting text nodes) and by other methods (with
  584. // splitting text nodes).
  585. //
  586. // @param {module:engine/view/range~Range} range Range which `start` and `end` positions will be used to break attributes.
  587. // @param {Boolean} [forceSplitText = false] If set to `true`, will break text nodes even if they are directly in
  588. // container element. This behavior will result in incorrect view state, but is needed by other view writing methods
  589. // which then fixes view state. Defaults to `false`.
  590. // @returns {module:engine/view/range~Range} New range with located at break positions.
  591. function _breakAttributesRange( range, forceSplitText = false ) {
  592. const rangeStart = range.start;
  593. const rangeEnd = range.end;
  594. validateRangeContainer( range );
  595. // Break at the collapsed position. Return new collapsed range.
  596. if ( range.isCollapsed ) {
  597. const position = _breakAttributes( range.start, forceSplitText );
  598. return new Range( position, position );
  599. }
  600. let breakEnd = _breakAttributes( rangeEnd, forceSplitText );
  601. const count = breakEnd.parent.childCount;
  602. const breakStart = _breakAttributes( rangeStart, forceSplitText );
  603. // Calculate new break end offset.
  604. breakEnd = breakEnd.getShiftedBy( breakEnd.parent.childCount - count );
  605. return new Range( breakStart, breakEnd );
  606. }
  607. // Function used by public breakAttributes (without splitting text nodes) and by other methods (with
  608. // splitting text nodes).
  609. //
  610. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-empty-element` when break position
  611. // is placed inside {@link module:engine/view/emptyelement~EmptyElement EmptyElement}.
  612. //
  613. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-ui-element` when break position
  614. // is placed inside {@link module:engine/view/uielement~UIElement UIElement}.
  615. //
  616. // @param {module:engine/view/position~Position} position Position where to break attributes.
  617. // @param {Boolean} [forceSplitText = false] If set to `true`, will break text nodes even if they are directly in
  618. // container element. This behavior will result in incorrect view state, but is needed by other view writing methods
  619. // which then fixes view state. Defaults to `false`.
  620. // @returns {module:engine/view/position~Position} New position after breaking the attributes.
  621. function _breakAttributes( position, forceSplitText = false ) {
  622. const positionOffset = position.offset;
  623. const positionParent = position.parent;
  624. // If position is placed inside EmptyElement - throw an exception as we cannot break inside.
  625. if ( position.parent.is( 'emptyElement' ) ) {
  626. /**
  627. * Cannot break inside EmptyElement instance.
  628. *
  629. * @error view-writer-cannot-break-empty-element
  630. */
  631. throw new CKEditorError( 'view-writer-cannot-break-empty-element' );
  632. }
  633. // If position is placed inside UIElement - throw an exception as we cannot break inside.
  634. if ( position.parent.is( 'uiElement' ) ) {
  635. /**
  636. * Cannot break inside UIElement instance.
  637. *
  638. * @error view-writer-cannot-break-ui-element
  639. */
  640. throw new CKEditorError( 'view-writer-cannot-break-ui-element' );
  641. }
  642. // There are no attributes to break and text nodes breaking is not forced.
  643. if ( !forceSplitText && positionParent.is( 'text' ) && isContainerOrFragment( positionParent.parent ) ) {
  644. return Position.createFromPosition( position );
  645. }
  646. // Position's parent is container, so no attributes to break.
  647. if ( isContainerOrFragment( positionParent ) ) {
  648. return Position.createFromPosition( position );
  649. }
  650. // Break text and start again in new position.
  651. if ( positionParent.is( 'text' ) ) {
  652. return _breakAttributes( breakTextNode( position ), forceSplitText );
  653. }
  654. const length = positionParent.childCount;
  655. // <p>foo<b><u>bar{}</u></b></p>
  656. // <p>foo<b><u>bar</u>[]</b></p>
  657. // <p>foo<b><u>bar</u></b>[]</p>
  658. if ( positionOffset == length ) {
  659. const newPosition = new Position( positionParent.parent, positionParent.index + 1 );
  660. return _breakAttributes( newPosition, forceSplitText );
  661. } else
  662. // <p>foo<b><u>{}bar</u></b></p>
  663. // <p>foo<b>[]<u>bar</u></b></p>
  664. // <p>foo{}<b><u>bar</u></b></p>
  665. if ( positionOffset === 0 ) {
  666. const newPosition = new Position( positionParent.parent, positionParent.index );
  667. return _breakAttributes( newPosition, forceSplitText );
  668. }
  669. // <p>foo<b><u>b{}ar</u></b></p>
  670. // <p>foo<b><u>b[]ar</u></b></p>
  671. // <p>foo<b><u>b</u>[]<u>ar</u></b></p>
  672. // <p>foo<b><u>b</u></b>[]<b><u>ar</u></b></p>
  673. else {
  674. const offsetAfter = positionParent.index + 1;
  675. // Break element.
  676. const clonedNode = positionParent.clone();
  677. // Insert cloned node to position's parent node.
  678. positionParent.parent.insertChildren( offsetAfter, clonedNode );
  679. // Get nodes to move.
  680. const count = positionParent.childCount - positionOffset;
  681. const nodesToMove = positionParent.removeChildren( positionOffset, count );
  682. // Move nodes to cloned node.
  683. clonedNode.appendChildren( nodesToMove );
  684. // Create new position to work on.
  685. const newPosition = new Position( positionParent.parent, offsetAfter );
  686. return _breakAttributes( newPosition, forceSplitText );
  687. }
  688. }
  689. // Unwraps children from provided `attribute`. Only children contained in `parent` element between
  690. // `startOffset` and `endOffset` will be unwrapped.
  691. //
  692. // @param {module:engine/view/element~Element} parent
  693. // @param {Number} startOffset
  694. // @param {Number} endOffset
  695. // @param {module:engine/view/element~Element} attribute
  696. function unwrapChildren( parent, startOffset, endOffset, attribute ) {
  697. let i = startOffset;
  698. const unwrapPositions = [];
  699. // Iterate over each element between provided offsets inside parent.
  700. while ( i < endOffset ) {
  701. const child = parent.getChild( i );
  702. // If attributes are the similar, then unwrap.
  703. if ( child.isSimilar( attribute ) ) {
  704. const unwrapped = child.getChildren();
  705. const count = child.childCount;
  706. // Replace wrapper element with its children
  707. child.remove();
  708. parent.insertChildren( i, unwrapped );
  709. // Save start and end position of moved items.
  710. unwrapPositions.push(
  711. new Position( parent, i ),
  712. new Position( parent, i + count )
  713. );
  714. // Skip elements that were unwrapped. Assuming that there won't be another element to unwrap in child
  715. // elements.
  716. i += count;
  717. endOffset += count - 1;
  718. } else {
  719. // If other nested attribute is found start unwrapping there.
  720. if ( child.is( 'attributeElement' ) ) {
  721. unwrapChildren( child, 0, child.childCount, attribute );
  722. }
  723. i++;
  724. }
  725. }
  726. // Merge at each unwrap.
  727. let offsetChange = 0;
  728. for ( let position of unwrapPositions ) {
  729. position = position.getShiftedBy( -offsetChange );
  730. // Do not merge with elements outside selected children.
  731. if ( position.offset == startOffset || position.offset == endOffset ) {
  732. continue;
  733. }
  734. const newPosition = mergeAttributes( position );
  735. // If nodes were merged - other merge offsets will change.
  736. if ( !newPosition.isEqual( position ) ) {
  737. offsetChange++;
  738. endOffset--;
  739. }
  740. }
  741. return Range.createFromParentsAndOffsets( parent, startOffset, parent, endOffset );
  742. }
  743. // Wraps children with provided `attribute`. Only children contained in `parent` element between
  744. // `startOffset` and `endOffset` will be wrapped.
  745. //
  746. // @param {module:engine/view/element~Element} parent
  747. // @param {Number} startOffset
  748. // @param {Number} endOffset
  749. // @param {module:engine/view/element~Element} attribute
  750. function wrapChildren( parent, startOffset, endOffset, attribute ) {
  751. let i = startOffset;
  752. const wrapPositions = [];
  753. while ( i < endOffset ) {
  754. const child = parent.getChild( i );
  755. const isText = child.is( 'text' );
  756. const isAttribute = child.is( 'attributeElement' );
  757. const isEmpty = child.is( 'emptyElement' );
  758. const isUI = child.is( 'uiElement' );
  759. // Wrap text, empty elements, ui elements or attributes with higher or equal priority.
  760. if ( isText || isEmpty || isUI || ( isAttribute && shouldABeOutsideB( attribute, child ) ) ) {
  761. // Clone attribute.
  762. const newAttribute = attribute.clone();
  763. // Wrap current node with new attribute;
  764. child.remove();
  765. newAttribute.appendChildren( child );
  766. parent.insertChildren( i, newAttribute );
  767. wrapPositions.push( new Position( parent, i ) );
  768. }
  769. // If other nested attribute is found start wrapping there.
  770. else if ( isAttribute ) {
  771. wrapChildren( child, 0, child.childCount, attribute );
  772. }
  773. i++;
  774. }
  775. // Merge at each wrap.
  776. let offsetChange = 0;
  777. for ( let position of wrapPositions ) {
  778. position = position.getShiftedBy( -offsetChange );
  779. // Do not merge with elements outside selected children.
  780. if ( position.offset == startOffset ) {
  781. continue;
  782. }
  783. const newPosition = mergeAttributes( position );
  784. // If nodes were merged - other merge offsets will change.
  785. if ( !newPosition.isEqual( position ) ) {
  786. offsetChange++;
  787. endOffset--;
  788. }
  789. }
  790. return Range.createFromParentsAndOffsets( parent, startOffset, parent, endOffset );
  791. }
  792. // Checks if first {@link module:engine/view/attributeelement~AttributeElement AttributeElement} provided to the function
  793. // can be wrapped otuside second element. It is done by comparing elements'
  794. // {@link module:engine/view/attributeelement~AttributeElement#priority priorities}, if both have same priority
  795. // {@link module:engine/view/element~Element#getIdentity identities} are compared.
  796. //
  797. // @param {module:engine/view/attributeelement~AttributeElement} a
  798. // @param {module:engine/view/attributeelement~AttributeElement} b
  799. // @returns {Boolean}
  800. function shouldABeOutsideB( a, b ) {
  801. if ( a.priority < b.priority ) {
  802. return true;
  803. } else if ( a.priority > b.priority ) {
  804. return false;
  805. }
  806. // When priorities are equal and names are different - use identities.
  807. return a.getIdentity() < b.getIdentity();
  808. }
  809. // Returns new position that is moved to near text node. Returns same position if there is no text node before of after
  810. // specified position.
  811. //
  812. // <p>foo[]</p> -> <p>foo{}</p>
  813. // <p>[]foo</p> -> <p>{}foo</p>
  814. //
  815. // @param {module:engine/view/position~Position} position
  816. // @returns {module:engine/view/position~Position} Position located inside text node or same position if there is no text nodes
  817. // before or after position location.
  818. function movePositionToTextNode( position ) {
  819. const nodeBefore = position.nodeBefore;
  820. if ( nodeBefore && nodeBefore.is( 'text' ) ) {
  821. return new Position( nodeBefore, nodeBefore.data.length );
  822. }
  823. const nodeAfter = position.nodeAfter;
  824. if ( nodeAfter && nodeAfter.is( 'text' ) ) {
  825. return new Position( nodeAfter, 0 );
  826. }
  827. return position;
  828. }
  829. // Breaks text node into two text nodes when possible.
  830. //
  831. // <p>foo{}bar</p> -> <p>foo[]bar</p>
  832. // <p>{}foobar</p> -> <p>[]foobar</p>
  833. // <p>foobar{}</p> -> <p>foobar[]</p>
  834. //
  835. // @param {module:engine/view/position~Position} position Position that need to be placed inside text node.
  836. // @returns {module:engine/view/position~Position} New position after breaking text node.
  837. function breakTextNode( position ) {
  838. if ( position.offset == position.parent.data.length ) {
  839. return new Position( position.parent.parent, position.parent.index + 1 );
  840. }
  841. if ( position.offset === 0 ) {
  842. return new Position( position.parent.parent, position.parent.index );
  843. }
  844. // Get part of the text that need to be moved.
  845. const textToMove = position.parent.data.slice( position.offset );
  846. // Leave rest of the text in position's parent.
  847. position.parent.data = position.parent.data.slice( 0, position.offset );
  848. // Insert new text node after position's parent text node.
  849. position.parent.parent.insertChildren( position.parent.index + 1, new Text( textToMove ) );
  850. // Return new position between two newly created text nodes.
  851. return new Position( position.parent.parent, position.parent.index + 1 );
  852. }
  853. // Merges two text nodes into first node. Removes second node and returns merge position.
  854. //
  855. // @param {module:engine/view/text~Text} t1 First text node to merge. Data from second text node will be moved at the end of
  856. // this text node.
  857. // @param {module:engine/view/text~Text} t2 Second text node to merge. This node will be removed after merging.
  858. // @returns {module:engine/view/position~Position} Position after merging text nodes.
  859. function mergeTextNodes( t1, t2 ) {
  860. // Merge text data into first text node and remove second one.
  861. const nodeBeforeLength = t1.data.length;
  862. t1.data += t2.data;
  863. t2.remove();
  864. return new Position( t1, nodeBeforeLength );
  865. }
  866. // Wraps one {@link module:engine/view/attributeelement~AttributeElement AttributeElement} into another by merging them if possible.
  867. // When merging is possible - all attributes, styles and classes are moved from wrapper element to element being
  868. // wrapped.
  869. //
  870. // @param {module:engine/view/attributeelement~AttributeElement} wrapper Wrapper AttributeElement.
  871. // @param {module:engine/view/attributeelement~AttributeElement} toWrap AttributeElement to wrap using wrapper element.
  872. // @returns {Boolean} Returns `true` if elements are merged.
  873. function wrapAttributeElement( wrapper, toWrap ) {
  874. // Can't merge if name or priority differs.
  875. if ( wrapper.name !== toWrap.name || wrapper.priority !== toWrap.priority ) {
  876. return false;
  877. }
  878. // Check if attributes can be merged.
  879. for ( const key of wrapper.getAttributeKeys() ) {
  880. // Classes and styles should be checked separately.
  881. if ( key === 'class' || key === 'style' ) {
  882. continue;
  883. }
  884. // If some attributes are different we cannot wrap.
  885. if ( toWrap.hasAttribute( key ) && toWrap.getAttribute( key ) !== wrapper.getAttribute( key ) ) {
  886. return false;
  887. }
  888. }
  889. // Check if styles can be merged.
  890. for ( const key of wrapper.getStyleNames() ) {
  891. if ( toWrap.hasStyle( key ) && toWrap.getStyle( key ) !== wrapper.getStyle( key ) ) {
  892. return false;
  893. }
  894. }
  895. // Move all attributes/classes/styles from wrapper to wrapped AttributeElement.
  896. for ( const key of wrapper.getAttributeKeys() ) {
  897. // Classes and styles should be checked separately.
  898. if ( key === 'class' || key === 'style' ) {
  899. continue;
  900. }
  901. // Move only these attributes that are not present - other are similar.
  902. if ( !toWrap.hasAttribute( key ) ) {
  903. toWrap.setAttribute( key, wrapper.getAttribute( key ) );
  904. }
  905. }
  906. for ( const key of wrapper.getStyleNames() ) {
  907. if ( !toWrap.hasStyle( key ) ) {
  908. toWrap.setStyle( key, wrapper.getStyle( key ) );
  909. }
  910. }
  911. for ( const key of wrapper.getClassNames() ) {
  912. if ( !toWrap.hasClass( key ) ) {
  913. toWrap.addClass( key );
  914. }
  915. }
  916. return true;
  917. }
  918. // Unwraps {@link module:engine/view/attributeelement~AttributeElement AttributeElement} from another by removing corresponding attributes,
  919. // classes and styles. All attributes, classes and styles from wrapper should be present inside element being unwrapped.
  920. //
  921. // @param {module:engine/view/attributeelement~AttributeElement} wrapper Wrapper AttributeElement.
  922. // @param {module:engine/view/attributeelement~AttributeElement} toUnwrap AttributeElement to unwrap using wrapper element.
  923. // @returns {Boolean} Returns `true` if elements are unwrapped.
  924. function unwrapAttributeElement( wrapper, toUnwrap ) {
  925. // Can't unwrap if name or priority differs.
  926. if ( wrapper.name !== toUnwrap.name || wrapper.priority !== toUnwrap.priority ) {
  927. return false;
  928. }
  929. // Check if AttributeElement has all wrapper attributes.
  930. for ( const key of wrapper.getAttributeKeys() ) {
  931. // Classes and styles should be checked separately.
  932. if ( key === 'class' || key === 'style' ) {
  933. continue;
  934. }
  935. // If some attributes are missing or different we cannot unwrap.
  936. if ( !toUnwrap.hasAttribute( key ) || toUnwrap.getAttribute( key ) !== wrapper.getAttribute( key ) ) {
  937. return false;
  938. }
  939. }
  940. // Check if AttributeElement has all wrapper classes.
  941. if ( !toUnwrap.hasClass( ...wrapper.getClassNames() ) ) {
  942. return false;
  943. }
  944. // Check if AttributeElement has all wrapper styles.
  945. for ( const key of wrapper.getStyleNames() ) {
  946. // If some styles are missing or different we cannot unwrap.
  947. if ( !toUnwrap.hasStyle( key ) || toUnwrap.getStyle( key ) !== wrapper.getStyle( key ) ) {
  948. return false;
  949. }
  950. }
  951. // Remove all wrapper's attributes from unwrapped element.
  952. for ( const key of wrapper.getAttributeKeys() ) {
  953. // Classes and styles should be checked separately.
  954. if ( key === 'class' || key === 'style' ) {
  955. continue;
  956. }
  957. toUnwrap.removeAttribute( key );
  958. }
  959. // Remove all wrapper's classes from unwrapped element.
  960. toUnwrap.removeClass( ...wrapper.getClassNames() );
  961. // Remove all wrapper's styles from unwrapped element.
  962. toUnwrap.removeStyle( ...wrapper.getStyleNames() );
  963. return true;
  964. }
  965. // Returns `true` if range is located in same {@link module:engine/view/attributeelement~AttributeElement AttributeElement}
  966. // (`start` and `end` positions are located inside same {@link module:engine/view/attributeelement~AttributeElement AttributeElement}),
  967. // starts on 0 offset and ends after last child node.
  968. //
  969. // @param {module:engine/view/range~Range} Range
  970. // @returns {Boolean}
  971. function rangeSpansOnAllChildren( range ) {
  972. return range.start.parent == range.end.parent && range.start.parent.is( 'attributeElement' ) &&
  973. range.start.offset === 0 && range.end.offset === range.start.parent.childCount;
  974. }
  975. // Checks if provided nodes are valid to insert. Checks if each node is an instance of
  976. // {@link module:engine/view/text~Text Text} or {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
  977. // {@link module:engine/view/containerelement~ContainerElement ContainerElement},
  978. // {@link module:engine/view/emptyelement~EmptyElement EmptyElement} or
  979. // {@link module:engine/view/uielement~UIElement UIElement}.
  980. //
  981. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-insert-invalid-node` when nodes to insert
  982. // contains instances that are not {@link module:engine/view/text~Text Texts},
  983. // {@link module:engine/view/emptyelement~EmptyElement EmptyElements},
  984. // {@link module:engine/view/uielement~UIElement UIElements},
  985. // {@link module:engine/view/attributeelement~AttributeElement AttributeElements} or
  986. // {@link module:engine/view/containerelement~ContainerElement ContainerElements}.
  987. //
  988. // @param Iterable.<module:engine/view/text~Text|module:engine/view/attributeelement~AttributeElement
  989. // |module:engine/view/containerelement~ContainerElement> nodes
  990. function validateNodesToInsert( nodes ) {
  991. for ( const node of nodes ) {
  992. if ( !validNodesToInsert.some( ( validNode => node instanceof validNode ) ) ) { // eslint-disable-line no-use-before-define
  993. /**
  994. * Inserted nodes should be valid to insert. of {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
  995. * {@link module:engine/view/containerelement~ContainerElement ContainerElement},
  996. * {@link module:engine/view/emptyelement~EmptyElement EmptyElement},
  997. * {@link module:engine/view/uielement~UIElement UIElement}, {@link module:engine/view/text~Text Text}.
  998. *
  999. * @error view-writer-insert-invalid-node
  1000. */
  1001. throw new CKEditorError( 'view-writer-insert-invalid-node' );
  1002. }
  1003. if ( !node.is( 'text' ) ) {
  1004. validateNodesToInsert( node.getChildren() );
  1005. }
  1006. }
  1007. }
  1008. const validNodesToInsert = [ Text, AttributeElement, ContainerElement, EmptyElement, UIElement ];
  1009. // Checks if node is ContainerElement or DocumentFragment, because in most cases they should be treated the same way.
  1010. //
  1011. // @param {module:engine/view/node~Node} node
  1012. // @returns {Boolean} Returns `true` if node is instance of ContainerElement or DocumentFragment.
  1013. function isContainerOrFragment( node ) {
  1014. return node && ( node.is( 'containerElement' ) || node.is( 'documentFragment' ) );
  1015. }
  1016. // Checks if {@link module:engine/view/range~Range#start range start} and {@link module:engine/view/range~Range#end range end} are placed
  1017. // inside same {@link module:engine/view/containerelement~ContainerElement container element}.
  1018. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when validation fails.
  1019. //
  1020. // @param {module:engine/view/range~Range} range
  1021. function validateRangeContainer( range ) {
  1022. const startContainer = getParentContainer( range.start );
  1023. const endContainer = getParentContainer( range.end );
  1024. if ( !startContainer || !endContainer || startContainer !== endContainer ) {
  1025. /**
  1026. * Range container is invalid. This can happen if {@link module:engine/view/range~Range#start range start} and
  1027. * {@link module:engine/view/range~Range#end range end} positions are not placed inside same container or
  1028. * parent container for these positions cannot be found.
  1029. *
  1030. * @error view-writer-invalid-range-container
  1031. */
  1032. throw new CKEditorError( 'view-writer-invalid-range-container' );
  1033. }
  1034. }