8
0

downcastwriter.js 74 KB

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