writer.js 65 KB

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