writer.js 66 KB

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