8
0

downcastwriter.js 73 KB

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