writer.js 54 KB

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