8
0

downcastwriter.js 73 KB

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