downcastwriter.js 75 KB

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