writer.js 66 KB

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