8
0

writer.js 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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. const 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.offset--;
  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( '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.offset += ( 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 is inside single attribute and spans on all children.
  421. if ( rangeSpansOnAllChildren( range ) && wrapAttributeElement( attribute, range.start.parent ) ) {
  422. const parent = range.start.parent;
  423. const end = mergeAttributes( Position.createAfter( parent ) );
  424. const start = mergeAttributes( Position.createBefore( parent ) );
  425. return new Range( start, end );
  426. }
  427. // Break attributes at range start and end.
  428. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  429. // Range around one element.
  430. if ( breakEnd.isEqual( breakStart.getShiftedBy( 1 ) ) ) {
  431. const node = breakStart.nodeAfter;
  432. if ( node instanceof AttributeElement && wrapAttributeElement( attribute, node ) ) {
  433. const start = mergeAttributes( breakStart );
  434. if ( !start.isEqual( breakStart ) ) {
  435. breakEnd.offset--;
  436. }
  437. const end = mergeAttributes( breakEnd );
  438. return new Range( start, end );
  439. }
  440. }
  441. const parentContainer = breakStart.parent;
  442. // Unwrap children located between break points.
  443. const unwrappedRange = unwrapChildren( parentContainer, breakStart.offset, breakEnd.offset, attribute );
  444. // Wrap all children with attribute.
  445. const newRange = wrapChildren( parentContainer, unwrappedRange.start.offset, unwrappedRange.end.offset, attribute );
  446. // Merge attributes at the both ends and return a new range.
  447. const start = mergeAttributes( newRange.start );
  448. // If start position was merged - move end position back.
  449. if ( !start.isEqual( newRange.start ) ) {
  450. newRange.end.offset--;
  451. }
  452. const end = mergeAttributes( newRange.end );
  453. return new Range( start, end );
  454. }
  455. /**
  456. * Wraps position with provided attribute. Returns new position after wrapping. This method will also merge newly
  457. * added attribute with its siblings whenever possible.
  458. *
  459. * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not
  460. * an instance of {module:engine/view/attributeelement~AttributeElement AttributeElement}.
  461. *
  462. * @param {module:engine/view/position~Position} position
  463. * @param {module:engine/view/attributeelement~AttributeElement} attribute
  464. * @returns {module:engine/view/position~Position} New position after wrapping.
  465. */
  466. export function wrapPosition( position, attribute ) {
  467. if ( !( attribute instanceof AttributeElement ) ) {
  468. throw new CKEditorError( 'view-writer-wrap-invalid-attribute' );
  469. }
  470. // Return same position when trying to wrap with attribute similar to position parent.
  471. if ( attribute.isSimilar( position.parent ) ) {
  472. return movePositionToTextNode( Position.createFromPosition( position ) );
  473. }
  474. // When position is inside text node - break it and place new position between two text nodes.
  475. if ( position.parent.is( 'text' ) ) {
  476. position = breakTextNode( position );
  477. }
  478. // Create fake element that will represent position, and will not be merged with other attributes.
  479. const fakePosition = new AttributeElement();
  480. fakePosition.priority = Number.POSITIVE_INFINITY;
  481. fakePosition.isSimilar = () => false;
  482. // Insert fake element in position location.
  483. position.parent.insertChildren( position.offset, fakePosition );
  484. // Range around inserted fake attribute element.
  485. const wrapRange = new Range( position, position.getShiftedBy( 1 ) );
  486. // Wrap fake element with attribute (it will also merge if possible).
  487. wrap( wrapRange, attribute );
  488. // Remove fake element and place new position there.
  489. const newPosition = new Position( fakePosition.parent, fakePosition.index );
  490. fakePosition.remove();
  491. // If position is placed between text nodes - merge them and return position inside.
  492. const nodeBefore = newPosition.nodeBefore;
  493. const nodeAfter = newPosition.nodeAfter;
  494. if ( nodeBefore instanceof Text && nodeAfter instanceof Text ) {
  495. return mergeTextNodes( nodeBefore, nodeAfter );
  496. }
  497. // If position is next to text node - move position inside.
  498. return movePositionToTextNode( newPosition );
  499. }
  500. /**
  501. * Unwraps nodes within provided range from attribute element.
  502. *
  503. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when
  504. * {@link module:engine/view/range~Range#start start} and {@link module:engine/view/range~Range#end end} positions are not placed inside
  505. * same parent container.
  506. *
  507. * @param {module:engine/view/range~Range} range
  508. * @param {module:engine/view/attributeelement~AttributeElement} attribute
  509. */
  510. export function unwrap( range, attribute ) {
  511. if ( !( attribute instanceof AttributeElement ) ) {
  512. /**
  513. * Attribute element need to be instance of attribute element.
  514. *
  515. * @error view-writer-unwrap-invalid-attribute
  516. */
  517. throw new CKEditorError( 'view-writer-unwrap-invalid-attribute' );
  518. }
  519. validateRangeContainer( range );
  520. // If range is collapsed - nothing to unwrap.
  521. if ( range.isCollapsed ) {
  522. return range;
  523. }
  524. // Break attributes at range start and end.
  525. const { start: breakStart, end: breakEnd } = _breakAttributesRange( range, true );
  526. // Range around one element - check if AttributeElement can be unwrapped partially when it's not similar.
  527. // For example:
  528. // <b class="foo bar" title="baz"></b> unwrap with: <b class="foo"></p> result: <b class"bar" title="baz"></b>
  529. if ( breakEnd.isEqual( breakStart.getShiftedBy( 1 ) ) ) {
  530. const node = breakStart.nodeAfter;
  531. // Unwrap single attribute element.
  532. if ( !attribute.isSimilar( node ) && node instanceof AttributeElement && unwrapAttributeElement( attribute, node ) ) {
  533. const start = mergeAttributes( breakStart );
  534. if ( !start.isEqual( breakStart ) ) {
  535. breakEnd.offset--;
  536. }
  537. const end = mergeAttributes( breakEnd );
  538. return new Range( start, end );
  539. }
  540. }
  541. const parentContainer = breakStart.parent;
  542. // Unwrap children located between break points.
  543. const newRange = unwrapChildren( parentContainer, breakStart.offset, breakEnd.offset, attribute );
  544. // Merge attributes at the both ends and return a new range.
  545. const start = mergeAttributes( newRange.start );
  546. // If start position was merged - move end position back.
  547. if ( !start.isEqual( newRange.start ) ) {
  548. newRange.end.offset--;
  549. }
  550. const end = mergeAttributes( newRange.end );
  551. return new Range( start, end );
  552. }
  553. /**
  554. * Renames element by creating a copy of renamed element but with changed name and then moving contents of the
  555. * old element to the new one. Keep in mind that this will invalidate all {@link module:engine/view/position~Position positions} which
  556. * has renamed element as {@link module:engine/view/position~Position#parent a parent}.
  557. *
  558. * New element has to be created because `Element#tagName` property in DOM is readonly.
  559. *
  560. * Since this function creates a new element and removes the given one, the new element is returned to keep reference.
  561. *
  562. * @param {module:engine/view/containerelement~ContainerElement} viewElement Element to be renamed.
  563. * @param {String} newName New name for element.
  564. */
  565. export function rename( viewElement, newName ) {
  566. const newElement = new ContainerElement( newName, viewElement.getAttributes() );
  567. insert( Position.createAfter( viewElement ), newElement );
  568. move( Range.createIn( viewElement ), Position.createAt( newElement ) );
  569. remove( Range.createOn( viewElement ) );
  570. return newElement;
  571. }
  572. /**
  573. * Attribute element need to be instance of attribute element.
  574. *
  575. * @error view-writer-wrap-invalid-attribute
  576. */
  577. // Returns first parent container of specified {@link module:engine/view/position~Position Position}.
  578. // Position's parent node is checked as first, then next parents are checked.
  579. // Note that {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment} is treated like a container.
  580. //
  581. // @param {module:engine/view/position~Position} position Position used as a start point to locate parent container.
  582. // @returns {module:engine/view/containerelement~ContainerElement|module:engine/view/documentfragment~DocumentFragment|undefined}
  583. // Parent container element or `undefined` if container is not found.
  584. function getParentContainer( position ) {
  585. let parent = position.parent;
  586. while ( !isContainerOrFragment( parent ) ) {
  587. if ( !parent ) {
  588. return undefined;
  589. }
  590. parent = parent.parent;
  591. }
  592. return parent;
  593. }
  594. // Function used by both public breakAttributes (without splitting text nodes) and by other methods (with
  595. // splitting text nodes).
  596. //
  597. // @param {module:engine/view/range~Range} range Range which `start` and `end` positions will be used to break attributes.
  598. // @param {Boolean} [forceSplitText = false] If set to `true`, will break text nodes even if they are directly in
  599. // container element. This behavior will result in incorrect view state, but is needed by other view writing methods
  600. // which then fixes view state. Defaults to `false`.
  601. // @returns {module:engine/view/range~Range} New range with located at break positions.
  602. function _breakAttributesRange( range, forceSplitText = false ) {
  603. const rangeStart = range.start;
  604. const rangeEnd = range.end;
  605. validateRangeContainer( range );
  606. // Break at the collapsed position. Return new collapsed range.
  607. if ( range.isCollapsed ) {
  608. const position = _breakAttributes( range.start, forceSplitText );
  609. return new Range( position, position );
  610. }
  611. const breakEnd = _breakAttributes( rangeEnd, forceSplitText );
  612. const count = breakEnd.parent.childCount;
  613. const breakStart = _breakAttributes( rangeStart, forceSplitText );
  614. // Calculate new break end offset.
  615. breakEnd.offset += breakEnd.parent.childCount - count;
  616. return new Range( breakStart, breakEnd );
  617. }
  618. // Function used by public breakAttributes (without splitting text nodes) and by other methods (with
  619. // splitting text nodes).
  620. //
  621. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-empty-element` when break position
  622. // is placed inside {@link module:engine/view/emptyelement~EmptyElement EmptyElement}.
  623. //
  624. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-ui-element` when break position
  625. // is placed inside {@link module:engine/view/uielement~UIElement UIElement}.
  626. //
  627. // @param {module:engine/view/position~Position} position Position where to break attributes.
  628. // @param {Boolean} [forceSplitText = false] If set to `true`, will break text nodes even if they are directly in
  629. // container element. This behavior will result in incorrect view state, but is needed by other view writing methods
  630. // which then fixes view state. Defaults to `false`.
  631. // @returns {module:engine/view/position~Position} New position after breaking the attributes.
  632. function _breakAttributes( position, forceSplitText = false ) {
  633. const positionOffset = position.offset;
  634. const positionParent = position.parent;
  635. // If position is placed inside EmptyElement - throw an exception as we cannot break inside.
  636. if ( position.parent.is( 'emptyElement' ) ) {
  637. /**
  638. * Cannot break inside EmptyElement instance.
  639. *
  640. * @error view-writer-cannot-break-empty-element
  641. */
  642. throw new CKEditorError( 'view-writer-cannot-break-empty-element' );
  643. }
  644. // If position is placed inside UIElement - throw an exception as we cannot break inside.
  645. if ( position.parent.is( 'uiElement' ) ) {
  646. /**
  647. * Cannot break inside UIElement instance.
  648. *
  649. * @error view-writer-cannot-break-ui-element
  650. */
  651. throw new CKEditorError( 'view-writer-cannot-break-ui-element' );
  652. }
  653. // There are no attributes to break and text nodes breaking is not forced.
  654. if ( !forceSplitText && positionParent.is( 'text' ) && isContainerOrFragment( positionParent.parent ) ) {
  655. return Position.createFromPosition( position );
  656. }
  657. // Position's parent is container, so no attributes to break.
  658. if ( isContainerOrFragment( positionParent ) ) {
  659. return Position.createFromPosition( position );
  660. }
  661. // Break text and start again in new position.
  662. if ( positionParent.is( 'text' ) ) {
  663. return _breakAttributes( breakTextNode( position ), forceSplitText );
  664. }
  665. const length = positionParent.childCount;
  666. // <p>foo<b><u>bar{}</u></b></p>
  667. // <p>foo<b><u>bar</u>[]</b></p>
  668. // <p>foo<b><u>bar</u></b>[]</p>
  669. if ( positionOffset == length ) {
  670. const newPosition = new Position( positionParent.parent, positionParent.index + 1 );
  671. return _breakAttributes( newPosition, forceSplitText );
  672. } else
  673. // <p>foo<b><u>{}bar</u></b></p>
  674. // <p>foo<b>[]<u>bar</u></b></p>
  675. // <p>foo{}<b><u>bar</u></b></p>
  676. if ( positionOffset === 0 ) {
  677. const newPosition = new Position( positionParent.parent, positionParent.index );
  678. return _breakAttributes( newPosition, forceSplitText );
  679. }
  680. // <p>foo<b><u>b{}ar</u></b></p>
  681. // <p>foo<b><u>b[]ar</u></b></p>
  682. // <p>foo<b><u>b</u>[]<u>ar</u></b></p>
  683. // <p>foo<b><u>b</u></b>[]<b><u>ar</u></b></p>
  684. else {
  685. const offsetAfter = positionParent.index + 1;
  686. // Break element.
  687. const clonedNode = positionParent.clone();
  688. // Insert cloned node to position's parent node.
  689. positionParent.parent.insertChildren( offsetAfter, clonedNode );
  690. // Get nodes to move.
  691. const count = positionParent.childCount - positionOffset;
  692. const nodesToMove = positionParent.removeChildren( positionOffset, count );
  693. // Move nodes to cloned node.
  694. clonedNode.appendChildren( nodesToMove );
  695. // Create new position to work on.
  696. const newPosition = new Position( positionParent.parent, offsetAfter );
  697. return _breakAttributes( newPosition, forceSplitText );
  698. }
  699. }
  700. // Unwraps children from provided `attribute`. Only children contained in `parent` element between
  701. // `startOffset` and `endOffset` will be unwrapped.
  702. //
  703. // @param {module:engine/view/element~Element} parent
  704. // @param {Number} startOffset
  705. // @param {Number} endOffset
  706. // @param {module:engine/view/element~Element} attribute
  707. function unwrapChildren( parent, startOffset, endOffset, attribute ) {
  708. let i = startOffset;
  709. const unwrapPositions = [];
  710. // Iterate over each element between provided offsets inside parent.
  711. while ( i < endOffset ) {
  712. const child = parent.getChild( i );
  713. // If attributes are the similar, then unwrap.
  714. if ( child.isSimilar( attribute ) ) {
  715. const unwrapped = child.getChildren();
  716. const count = child.childCount;
  717. // Replace wrapper element with its children
  718. child.remove();
  719. parent.insertChildren( i, unwrapped );
  720. // Save start and end position of moved items.
  721. unwrapPositions.push(
  722. new Position( parent, i ),
  723. new Position( parent, i + count )
  724. );
  725. // Skip elements that were unwrapped. Assuming that there won't be another element to unwrap in child
  726. // elements.
  727. i += count;
  728. endOffset += count - 1;
  729. } else {
  730. // If other nested attribute is found start unwrapping there.
  731. if ( child.is( 'attributeElement' ) ) {
  732. unwrapChildren( child, 0, child.childCount, attribute );
  733. }
  734. i++;
  735. }
  736. }
  737. // Merge at each unwrap.
  738. let offsetChange = 0;
  739. for ( const position of unwrapPositions ) {
  740. position.offset -= offsetChange;
  741. // Do not merge with elements outside selected children.
  742. if ( position.offset == startOffset || position.offset == endOffset ) {
  743. continue;
  744. }
  745. const newPosition = mergeAttributes( position );
  746. // If nodes were merged - other merge offsets will change.
  747. if ( !newPosition.isEqual( position ) ) {
  748. offsetChange++;
  749. endOffset--;
  750. }
  751. }
  752. return Range.createFromParentsAndOffsets( parent, startOffset, parent, endOffset );
  753. }
  754. // Wraps children with provided `attribute`. Only children contained in `parent` element between
  755. // `startOffset` and `endOffset` will be wrapped.
  756. //
  757. // @param {module:engine/view/element~Element} parent
  758. // @param {Number} startOffset
  759. // @param {Number} endOffset
  760. // @param {module:engine/view/element~Element} attribute
  761. function wrapChildren( parent, startOffset, endOffset, attribute ) {
  762. let i = startOffset;
  763. const wrapPositions = [];
  764. while ( i < endOffset ) {
  765. const child = parent.getChild( i );
  766. const isText = child.is( 'text' );
  767. const isAttribute = child.is( 'attributeElement' );
  768. const isEmpty = child.is( 'emptyElement' );
  769. const isUI = child.is( 'uiElement' );
  770. // Wrap text, empty elements, ui elements or attributes with higher or equal priority.
  771. if ( isText || isEmpty || isUI || ( isAttribute && shouldABeOutsideB( attribute, child ) ) ) {
  772. // Clone attribute.
  773. const newAttribute = attribute.clone();
  774. // Wrap current node with new attribute;
  775. child.remove();
  776. newAttribute.appendChildren( child );
  777. parent.insertChildren( i, newAttribute );
  778. wrapPositions.push( new Position( parent, i ) );
  779. }
  780. // If other nested attribute is found start wrapping there.
  781. else if ( isAttribute ) {
  782. wrapChildren( child, 0, child.childCount, attribute );
  783. }
  784. i++;
  785. }
  786. // Merge at each wrap.
  787. let offsetChange = 0;
  788. for ( const position of wrapPositions ) {
  789. position.offset -= offsetChange;
  790. // Do not merge with elements outside selected children.
  791. if ( position.offset == startOffset ) {
  792. continue;
  793. }
  794. const newPosition = mergeAttributes( position );
  795. // If nodes were merged - other merge offsets will change.
  796. if ( !newPosition.isEqual( position ) ) {
  797. offsetChange++;
  798. endOffset--;
  799. }
  800. }
  801. return Range.createFromParentsAndOffsets( parent, startOffset, parent, endOffset );
  802. }
  803. // Checks if first {@link module:engine/view/attributeelement~AttributeElement AttributeElement} provided to the function
  804. // can be wrapped otuside second element. It is done by comparing elements'
  805. // {@link module:engine/view/attributeelement~AttributeElement#priority priorities}, if both have same priority
  806. // {@link module:engine/view/element~Element#getIdentity identities} are compared.
  807. //
  808. // @param {module:engine/view/attributeelement~AttributeElement} a
  809. // @param {module:engine/view/attributeelement~AttributeElement} b
  810. // @returns {Boolean}
  811. function shouldABeOutsideB( a, b ) {
  812. if ( a.priority < b.priority ) {
  813. return true;
  814. } else if ( a.priority > b.priority ) {
  815. return false;
  816. }
  817. // When priorities are equal and names are different - use identities.
  818. return a.getIdentity() < b.getIdentity();
  819. }
  820. // Returns new position that is moved to near text node. Returns same position if there is no text node before of after
  821. // specified position.
  822. //
  823. // <p>foo[]</p> -> <p>foo{}</p>
  824. // <p>[]foo</p> -> <p>{}foo</p>
  825. //
  826. // @param {module:engine/view/position~Position} position
  827. // @returns {module:engine/view/position~Position} Position located inside text node or same position if there is no text nodes
  828. // before or after position location.
  829. function movePositionToTextNode( position ) {
  830. const nodeBefore = position.nodeBefore;
  831. if ( nodeBefore && nodeBefore.is( 'text' ) ) {
  832. return new Position( nodeBefore, nodeBefore.data.length );
  833. }
  834. const nodeAfter = position.nodeAfter;
  835. if ( nodeAfter && nodeAfter.is( 'text' ) ) {
  836. return new Position( nodeAfter, 0 );
  837. }
  838. return position;
  839. }
  840. // Breaks text node into two text nodes when possible.
  841. //
  842. // <p>foo{}bar</p> -> <p>foo[]bar</p>
  843. // <p>{}foobar</p> -> <p>[]foobar</p>
  844. // <p>foobar{}</p> -> <p>foobar[]</p>
  845. //
  846. // @param {module:engine/view/position~Position} position Position that need to be placed inside text node.
  847. // @returns {module:engine/view/position~Position} New position after breaking text node.
  848. function breakTextNode( position ) {
  849. if ( position.offset == position.parent.data.length ) {
  850. return new Position( position.parent.parent, position.parent.index + 1 );
  851. }
  852. if ( position.offset === 0 ) {
  853. return new Position( position.parent.parent, position.parent.index );
  854. }
  855. // Get part of the text that need to be moved.
  856. const textToMove = position.parent.data.slice( position.offset );
  857. // Leave rest of the text in position's parent.
  858. position.parent.data = position.parent.data.slice( 0, position.offset );
  859. // Insert new text node after position's parent text node.
  860. position.parent.parent.insertChildren( position.parent.index + 1, new Text( textToMove ) );
  861. // Return new position between two newly created text nodes.
  862. return new Position( position.parent.parent, position.parent.index + 1 );
  863. }
  864. // Merges two text nodes into first node. Removes second node and returns merge position.
  865. //
  866. // @param {module:engine/view/text~Text} t1 First text node to merge. Data from second text node will be moved at the end of
  867. // this text node.
  868. // @param {module:engine/view/text~Text} t2 Second text node to merge. This node will be removed after merging.
  869. // @returns {module:engine/view/position~Position} Position after merging text nodes.
  870. function mergeTextNodes( t1, t2 ) {
  871. // Merge text data into first text node and remove second one.
  872. const nodeBeforeLength = t1.data.length;
  873. t1.data += t2.data;
  874. t2.remove();
  875. return new Position( t1, nodeBeforeLength );
  876. }
  877. // Wraps one {@link module:engine/view/attributeelement~AttributeElement AttributeElement} into another by merging them if possible.
  878. // When merging is possible - all attributes, styles and classes are moved from wrapper element to element being
  879. // wrapped.
  880. //
  881. // @param {module:engine/view/attributeelement~AttributeElement} wrapper Wrapper AttributeElement.
  882. // @param {module:engine/view/attributeelement~AttributeElement} toWrap AttributeElement to wrap using wrapper element.
  883. // @returns {Boolean} Returns `true` if elements are merged.
  884. function wrapAttributeElement( wrapper, toWrap ) {
  885. // Can't merge if name or priority differs.
  886. if ( wrapper.name !== toWrap.name || wrapper.priority !== toWrap.priority ) {
  887. return false;
  888. }
  889. // Check if attributes can be merged.
  890. for ( const key of wrapper.getAttributeKeys() ) {
  891. // Classes and styles should be checked separately.
  892. if ( key === 'class' || key === 'style' ) {
  893. continue;
  894. }
  895. // If some attributes are different we cannot wrap.
  896. if ( toWrap.hasAttribute( key ) && toWrap.getAttribute( key ) !== wrapper.getAttribute( key ) ) {
  897. return false;
  898. }
  899. }
  900. // Check if styles can be merged.
  901. for ( const key of wrapper.getStyleNames() ) {
  902. if ( toWrap.hasStyle( key ) && toWrap.getStyle( key ) !== wrapper.getStyle( key ) ) {
  903. return false;
  904. }
  905. }
  906. // Move all attributes/classes/styles from wrapper to wrapped AttributeElement.
  907. for ( const key of wrapper.getAttributeKeys() ) {
  908. // Classes and styles should be checked separately.
  909. if ( key === 'class' || key === 'style' ) {
  910. continue;
  911. }
  912. // Move only these attributes that are not present - other are similar.
  913. if ( !toWrap.hasAttribute( key ) ) {
  914. toWrap.setAttribute( key, wrapper.getAttribute( key ) );
  915. }
  916. }
  917. for ( const key of wrapper.getStyleNames() ) {
  918. if ( !toWrap.hasStyle( key ) ) {
  919. toWrap.setStyle( key, wrapper.getStyle( key ) );
  920. }
  921. }
  922. for ( const key of wrapper.getClassNames() ) {
  923. if ( !toWrap.hasClass( key ) ) {
  924. toWrap.addClass( key );
  925. }
  926. }
  927. return true;
  928. }
  929. // Unwraps {@link module:engine/view/attributeelement~AttributeElement AttributeElement} from another by removing corresponding attributes,
  930. // classes and styles. All attributes, classes and styles from wrapper should be present inside element being unwrapped.
  931. //
  932. // @param {module:engine/view/attributeelement~AttributeElement} wrapper Wrapper AttributeElement.
  933. // @param {module:engine/view/attributeelement~AttributeElement} toUnwrap AttributeElement to unwrap using wrapper element.
  934. // @returns {Boolean} Returns `true` if elements are unwrapped.
  935. function unwrapAttributeElement( wrapper, toUnwrap ) {
  936. // Can't unwrap if name or priority differs.
  937. if ( wrapper.name !== toUnwrap.name || wrapper.priority !== toUnwrap.priority ) {
  938. return false;
  939. }
  940. // Check if AttributeElement has all wrapper attributes.
  941. for ( const key of wrapper.getAttributeKeys() ) {
  942. // Classes and styles should be checked separately.
  943. if ( key === 'class' || key === 'style' ) {
  944. continue;
  945. }
  946. // If some attributes are missing or different we cannot unwrap.
  947. if ( !toUnwrap.hasAttribute( key ) || toUnwrap.getAttribute( key ) !== wrapper.getAttribute( key ) ) {
  948. return false;
  949. }
  950. }
  951. // Check if AttributeElement has all wrapper classes.
  952. if ( !toUnwrap.hasClass( ...wrapper.getClassNames() ) ) {
  953. return false;
  954. }
  955. // Check if AttributeElement has all wrapper styles.
  956. for ( const key of wrapper.getStyleNames() ) {
  957. // If some styles are missing or different we cannot unwrap.
  958. if ( !toUnwrap.hasStyle( key ) || toUnwrap.getStyle( key ) !== wrapper.getStyle( key ) ) {
  959. return false;
  960. }
  961. }
  962. // Remove all wrapper's attributes from unwrapped element.
  963. for ( const key of wrapper.getAttributeKeys() ) {
  964. // Classes and styles should be checked separately.
  965. if ( key === 'class' || key === 'style' ) {
  966. continue;
  967. }
  968. toUnwrap.removeAttribute( key );
  969. }
  970. // Remove all wrapper's classes from unwrapped element.
  971. toUnwrap.removeClass( ...wrapper.getClassNames() );
  972. // Remove all wrapper's styles from unwrapped element.
  973. toUnwrap.removeStyle( ...wrapper.getStyleNames() );
  974. return true;
  975. }
  976. // Returns `true` if range is located in same {@link module:engine/view/attributeelement~AttributeElement AttributeElement}
  977. // (`start` and `end` positions are located inside same {@link module:engine/view/attributeelement~AttributeElement AttributeElement}),
  978. // starts on 0 offset and ends after last child node.
  979. //
  980. // @param {module:engine/view/range~Range} Range
  981. // @returns {Boolean}
  982. function rangeSpansOnAllChildren( range ) {
  983. return range.start.parent == range.end.parent && range.start.parent.is( 'attributeElement' ) &&
  984. range.start.offset === 0 && range.end.offset === range.start.parent.childCount;
  985. }
  986. // Checks if provided nodes are valid to insert. Checks if each node is an instance of
  987. // {@link module:engine/view/text~Text Text} or {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
  988. // {@link module:engine/view/containerelement~ContainerElement ContainerElement},
  989. // {@link module:engine/view/emptyelement~EmptyElement EmptyElement} or
  990. // {@link module:engine/view/uielement~UIElement UIElement}.
  991. //
  992. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-insert-invalid-node` when nodes to insert
  993. // contains instances that are not {@link module:engine/view/text~Text Texts},
  994. // {@link module:engine/view/emptyelement~EmptyElement EmptyElements},
  995. // {@link module:engine/view/uielement~UIElement UIElements},
  996. // {@link module:engine/view/attributeelement~AttributeElement AttributeElements} or
  997. // {@link module:engine/view/containerelement~ContainerElement ContainerElements}.
  998. //
  999. // @param Iterable.<module:engine/view/text~Text|module:engine/view/attributeelement~AttributeElement
  1000. // |module:engine/view/containerelement~ContainerElement> nodes
  1001. function validateNodesToInsert( nodes ) {
  1002. for ( const node of nodes ) {
  1003. if ( !validNodesToInsert.some( ( validNode => node instanceof validNode ) ) ) { // eslint-disable-line no-use-before-define
  1004. /**
  1005. * Inserted nodes should be valid to insert. of {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
  1006. * {@link module:engine/view/containerelement~ContainerElement ContainerElement},
  1007. * {@link module:engine/view/emptyelement~EmptyElement EmptyElement},
  1008. * {@link module:engine/view/uielement~UIElement UIElement}, {@link module:engine/view/text~Text Text}.
  1009. *
  1010. * @error view-writer-insert-invalid-node
  1011. */
  1012. throw new CKEditorError( 'view-writer-insert-invalid-node' );
  1013. }
  1014. if ( !node.is( 'text' ) ) {
  1015. validateNodesToInsert( node.getChildren() );
  1016. }
  1017. }
  1018. }
  1019. const validNodesToInsert = [ Text, AttributeElement, ContainerElement, EmptyElement, UIElement ];
  1020. // Checks if node is ContainerElement or DocumentFragment, because in most cases they should be treated the same way.
  1021. //
  1022. // @param {module:engine/view/node~Node} node
  1023. // @returns {Boolean} Returns `true` if node is instance of ContainerElement or DocumentFragment.
  1024. function isContainerOrFragment( node ) {
  1025. return node && ( node.is( 'containerElement' ) || node.is( 'documentFragment' ) );
  1026. }
  1027. // Checks if {@link module:engine/view/range~Range#start range start} and {@link module:engine/view/range~Range#end range end} are placed
  1028. // inside same {@link module:engine/view/containerelement~ContainerElement container element}.
  1029. // Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when validation fails.
  1030. //
  1031. // @param {module:engine/view/range~Range} range
  1032. function validateRangeContainer( range ) {
  1033. const startContainer = getParentContainer( range.start );
  1034. const endContainer = getParentContainer( range.end );
  1035. if ( !startContainer || !endContainer || startContainer !== endContainer ) {
  1036. /**
  1037. * Range container is invalid. This can happen if {@link module:engine/view/range~Range#start range start} and
  1038. * {@link module:engine/view/range~Range#end range end} positions are not placed inside same container or
  1039. * parent container for these positions cannot be found.
  1040. *
  1041. * @error view-writer-invalid-range-container
  1042. */
  1043. throw new CKEditorError( 'view-writer-invalid-range-container' );
  1044. }
  1045. }