downcastwriter.js 76 KB

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