8
0

writer.js 60 KB

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