writer.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/writer
  7. */
  8. import AttributeOperation from './operation/attributeoperation';
  9. import DetachOperation from './operation/detachoperation';
  10. import InsertOperation from './operation/insertoperation';
  11. import MarkerOperation from './operation/markeroperation';
  12. import MoveOperation from './operation/moveoperation';
  13. import RenameOperation from './operation/renameoperation';
  14. import RootAttributeOperation from './operation/rootattributeoperation';
  15. import SplitOperation from './operation/splitoperation';
  16. import MergeOperation from './operation/mergeoperation';
  17. import DocumentFragment from './documentfragment';
  18. import Text from './text';
  19. import Element from './element';
  20. import RootElement from './rootelement';
  21. import Position from './position';
  22. import Range from './range.js';
  23. import DocumentSelection from './documentselection';
  24. import toMap from '@ckeditor/ckeditor5-utils/src/tomap';
  25. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  26. /**
  27. * The model can only be modified by using the writer. It should be used whenever you want to create a node, modify
  28. * child nodes, attributes or text, set the selection's position and its attributes.
  29. *
  30. * The instance of the writer is only available in the {@link module:engine/model/model~Model#change `change()`} or
  31. * {@link module:engine/model/model~Model#enqueueChange `enqueueChange()`}.
  32. *
  33. * model.change( writer => {
  34. * writer.insertText( 'foo', paragraph, 'end' );
  35. * } );
  36. *
  37. * Note that the writer should never be stored and used outside of the `change()` and
  38. * `enqueueChange()` blocks.
  39. *
  40. * Note that writer's methods do not check the {@link module:engine/model/schema~Schema}. It is possible
  41. * to create incorrect model structures by using the writer. Read more about in
  42. * {@glink framework/guides/deep-dive/schema#who-checks-the-schema "Who checks the schema?"}.
  43. *
  44. * @see module:engine/model/model~Model#change
  45. * @see module:engine/model/model~Model#enqueueChange
  46. */
  47. export default class Writer {
  48. /**
  49. * Creates a writer instance.
  50. *
  51. * **Note:** It is not recommended to use it directly. Use {@link module:engine/model/model~Model#change `Model#change()`} or
  52. * {@link module:engine/model/model~Model#enqueueChange `Model#enqueueChange()`} instead.
  53. *
  54. * @protected
  55. * @param {module:engine/model/model~Model} model
  56. * @param {module:engine/model/batch~Batch} batch
  57. */
  58. constructor( model, batch ) {
  59. /**
  60. * Instance of the model on which this writer operates.
  61. *
  62. * @readonly
  63. * @type {module:engine/model/model~Model}
  64. */
  65. this.model = model;
  66. /**
  67. * The batch to which this writer will add changes.
  68. *
  69. * @readonly
  70. * @type {module:engine/model/batch~Batch}
  71. */
  72. this.batch = batch;
  73. }
  74. /**
  75. * Creates a new {@link module:engine/model/text~Text text node}.
  76. *
  77. * writer.createText( 'foo' );
  78. * writer.createText( 'foo', { bold: true } );
  79. *
  80. * @param {String} data Text data.
  81. * @param {Object} [attributes] Text attributes.
  82. * @returns {module:engine/model/text~Text} Created text node.
  83. */
  84. createText( data, attributes ) {
  85. return new Text( data, attributes );
  86. }
  87. /**
  88. * Creates a new {@link module:engine/model/element~Element element}.
  89. *
  90. * writer.createElement( 'paragraph' );
  91. * writer.createElement( 'paragraph', { alignment: 'center' } );
  92. *
  93. * @param {String} name Name of the element.
  94. * @param {Object} [attributes] Elements attributes.
  95. * @returns {module:engine/model/element~Element} Created element.
  96. */
  97. createElement( name, attributes ) {
  98. return new Element( name, attributes );
  99. }
  100. /**
  101. * Creates a new {@link module:engine/model/documentfragment~DocumentFragment document fragment}.
  102. *
  103. * @returns {module:engine/model/documentfragment~DocumentFragment} Created document fragment.
  104. */
  105. createDocumentFragment() {
  106. return new DocumentFragment();
  107. }
  108. /**
  109. * Inserts item on given position.
  110. *
  111. * const paragraph = writer.createElement( 'paragraph' );
  112. * writer.insert( paragraph, position );
  113. *
  114. * Instead of using position you can use parent and offset:
  115. *
  116. * const text = writer.createText( 'foo' );
  117. * writer.insert( text, paragraph, 5 );
  118. *
  119. * You can also use `end` instead of the offset to insert at the end:
  120. *
  121. * const text = writer.createText( 'foo' );
  122. * writer.insert( text, paragraph, 'end' );
  123. *
  124. * Or insert before or after another element:
  125. *
  126. * const paragraph = writer.createElement( 'paragraph' );
  127. * writer.insert( paragraph, anotherParagraph, 'after' );
  128. *
  129. * These parameters works the same way as {@link module:engine/model/position~Position.createAt `Position.createAt()`}.
  130. *
  131. * Note that if the item already has parent it will be removed from the previous parent.
  132. *
  133. * Note that you cannot re-insert a node from a document to a different document or a document fragment. In this case,
  134. * `model-writer-insert-forbidden-move` is thrown.
  135. *
  136. * If you want to move {@link module:engine/model/range~Range range} instead of an
  137. * {@link module:engine/model/item~Item item} use {@link module:engine/model/writer~Writer#move `Writer#move()`}.
  138. *
  139. * **Note:** For a paste-like content insertion mechanism see
  140. * {@link module:engine/model/model~Model#insertContent `model.insertContent()`}.
  141. *
  142. * @param {module:engine/model/item~Item|module:engine/model/documentfragment~DocumentFragment} item Item or document
  143. * fragment to insert.
  144. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  145. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  146. * second parameter is a {@link module:engine/model/item~Item model item}.
  147. */
  148. insert( item, itemOrPosition, offset ) {
  149. this._assertWriterUsedCorrectly();
  150. const position = Position.createAt( itemOrPosition, offset );
  151. // If item has a parent already.
  152. if ( item.parent ) {
  153. // We need to check if item is going to be inserted within the same document.
  154. if ( isSameTree( item.root, position.root ) ) {
  155. // If it's we just need to move it.
  156. this.move( Range.createOn( item ), position );
  157. return;
  158. }
  159. // If it isn't the same root.
  160. else {
  161. if ( item.root.document ) {
  162. // It is forbidden to move a node that was already in a document outside of it.
  163. throw new Error( 'model-writer-insert-forbidden-move: Cannot move a node from a document to a different tree.' );
  164. } else {
  165. // Move between two different document fragments or from document fragment to a document is possible.
  166. // In that case, remove the item from it's original parent.
  167. this.remove( item );
  168. }
  169. }
  170. }
  171. const version = position.root.document ? position.root.document.version : null;
  172. const insert = new InsertOperation( position, item, version );
  173. if ( item instanceof Text ) {
  174. insert.shouldReceiveAttributes = true;
  175. }
  176. this.batch.addOperation( insert );
  177. this.model.applyOperation( insert );
  178. // When element is a DocumentFragment we need to move its markers to Document#markers.
  179. if ( item instanceof DocumentFragment ) {
  180. for ( const [ markerName, markerRange ] of item.markers ) {
  181. // We need to migrate marker range from DocumentFragment to Document.
  182. const rangeRootPosition = Position.createAt( markerRange.root );
  183. const range = new Range(
  184. markerRange.start._getCombined( rangeRootPosition, position ),
  185. markerRange.end._getCombined( rangeRootPosition, position )
  186. );
  187. this.addMarker( markerName, { range, usingOperation: true } );
  188. }
  189. }
  190. }
  191. /**
  192. * Creates and inserts text on given position. You can optionally set text attributes:
  193. *
  194. * writer.insertText( 'foo', position );
  195. * writer.insertText( 'foo', { bold: true }, position );
  196. *
  197. * Instead of using position you can use parent and offset or define that text should be inserted at the end
  198. * or before or after other node:
  199. *
  200. * // Inserts 'foo' in paragraph, at offset 5:
  201. * writer.insertText( 'foo', paragraph, 5 );
  202. * // Inserts 'foo' at the end of a paragraph:
  203. * writer.insertText( 'foo', paragraph, 'end' );
  204. * // Inserts 'foo' after an image:
  205. * writer.insertText( 'foo', image, 'after' );
  206. *
  207. * These parameters work in the same way as {@link module:engine/model/position~Position.createAt `Position.createAt()`}.
  208. *
  209. * @param {String} data Text data.
  210. * @param {Object} [attributes] Text attributes.
  211. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  212. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  213. * third parameter is a {@link module:engine/model/item~Item model item}.
  214. */
  215. insertText( text, attributes, itemOrPosition, offset ) {
  216. if ( attributes instanceof DocumentFragment || attributes instanceof Element || attributes instanceof Position ) {
  217. this.insert( this.createText( text ), attributes, itemOrPosition );
  218. } else {
  219. this.insert( this.createText( text, attributes ), itemOrPosition, offset );
  220. }
  221. }
  222. /**
  223. * Creates and inserts element on given position. You can optionally set attributes:
  224. *
  225. * writer.insertElement( 'paragraph', position );
  226. * writer.insertElement( 'paragraph', { alignment: 'center' }, position );
  227. *
  228. * Instead of using position you can use parent and offset or define that text should be inserted at the end
  229. * or before or after other node:
  230. *
  231. * // Inserts paragraph in the root at offset 5:
  232. * writer.insertElement( 'paragraph', root, 5 );
  233. * // Inserts paragraph at the end of a blockquote:
  234. * writer.insertElement( 'paragraph', blockquote, 'end' );
  235. * // Inserts after an image:
  236. * writer.insertElement( 'paragraph', image, 'after' );
  237. *
  238. * These parameters works the same way as {@link module:engine/model/position~Position.createAt `Position.createAt()`}.
  239. *
  240. * @param {String} name Name of the element.
  241. * @param {Object} [attributes] Elements attributes.
  242. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  243. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  244. * third parameter is a {@link module:engine/model/item~Item model item}.
  245. */
  246. insertElement( name, attributes, itemOrPosition, offset ) {
  247. if ( attributes instanceof DocumentFragment || attributes instanceof Element || attributes instanceof Position ) {
  248. this.insert( this.createElement( name ), attributes, itemOrPosition );
  249. } else {
  250. this.insert( this.createElement( name, attributes ), itemOrPosition, offset );
  251. }
  252. }
  253. /**
  254. * Inserts item at the end of the given parent.
  255. *
  256. * const paragraph = writer.createElement( 'paragraph' );
  257. * writer.append( paragraph, root );
  258. *
  259. * Note that if the item already has parent it will be removed from the previous parent.
  260. *
  261. * If you want to move {@link module:engine/model/range~Range range} instead of an
  262. * {@link module:engine/model/item~Item item} use {@link module:engine/model/writer~Writer#move `Writer#move()`}.
  263. *
  264. * @param {module:engine/model/item~Item|module:engine/model/documentfragment~DocumentFragment}
  265. * item Item or document fragment to insert.
  266. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} parent
  267. */
  268. append( item, parent ) {
  269. this.insert( item, parent, 'end' );
  270. }
  271. /**
  272. * Creates text node and inserts it at the end of the parent. You can optionally set text attributes:
  273. *
  274. * writer.appendText( 'foo', paragraph );
  275. * writer.appendText( 'foo', { bold: true }, paragraph );
  276. *
  277. * @param {String} text Text data.
  278. * @param {Object} [attributes] Text attributes.
  279. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} parent
  280. */
  281. appendText( text, attributes, parent ) {
  282. if ( attributes instanceof DocumentFragment || attributes instanceof Element ) {
  283. this.insert( this.createText( text ), attributes, 'end' );
  284. } else {
  285. this.insert( this.createText( text, attributes ), parent, 'end' );
  286. }
  287. }
  288. /**
  289. * Creates element and inserts it at the end of the parent. You can optionally set attributes:
  290. *
  291. * writer.appendElement( 'paragraph', root );
  292. * writer.appendElement( 'paragraph', { alignment: 'center' }, root );
  293. *
  294. * @param {String} name Name of the element.
  295. * @param {Object} [attributes] Elements attributes.
  296. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} parent
  297. */
  298. appendElement( name, attributes, parent ) {
  299. if ( attributes instanceof DocumentFragment || attributes instanceof Element ) {
  300. this.insert( this.createElement( name ), attributes, 'end' );
  301. } else {
  302. this.insert( this.createElement( name, attributes ), parent, 'end' );
  303. }
  304. }
  305. /**
  306. * Sets value of the attribute with given key on a {@link module:engine/model/item~Item model item}
  307. * or on a {@link module:engine/model/range~Range range}.
  308. *
  309. * @param {String} key Attribute key.
  310. * @param {*} value Attribute new value.
  311. * @param {module:engine/model/item~Item|module:engine/model/range~Range} itemOrRange
  312. * Model item or range on which the attribute will be set.
  313. */
  314. setAttribute( key, value, itemOrRange ) {
  315. this._assertWriterUsedCorrectly();
  316. if ( itemOrRange instanceof Range ) {
  317. const ranges = itemOrRange.getMinimalFlatRanges();
  318. for ( const range of ranges ) {
  319. setAttributeOnRange( this, key, value, range );
  320. }
  321. } else {
  322. setAttributeOnItem( this, key, value, itemOrRange );
  323. }
  324. }
  325. /**
  326. * Sets values of attributes on a {@link module:engine/model/item~Item model item}
  327. * or on a {@link module:engine/model/range~Range range}.
  328. *
  329. * writer.setAttributes( {
  330. * bold: true,
  331. * italic: true
  332. * }, range );
  333. *
  334. * @param {Object} attributes Attributes keys and values.
  335. * @param {module:engine/model/item~Item|module:engine/model/range~Range} itemOrRange
  336. * Model item or range on which the attributes will be set.
  337. */
  338. setAttributes( attributes, itemOrRange ) {
  339. for ( const [ key, val ] of toMap( attributes ) ) {
  340. this.setAttribute( key, val, itemOrRange );
  341. }
  342. }
  343. /**
  344. * Removes an attribute with given key from a {@link module:engine/model/item~Item model item}
  345. * or from a {@link module:engine/model/range~Range range}.
  346. *
  347. * @param {String} key Attribute key.
  348. * @param {module:engine/model/item~Item|module:engine/model/range~Range} itemOrRange
  349. * Model item or range from which the attribute will be removed.
  350. */
  351. removeAttribute( key, itemOrRange ) {
  352. this._assertWriterUsedCorrectly();
  353. if ( itemOrRange instanceof Range ) {
  354. const ranges = itemOrRange.getMinimalFlatRanges();
  355. for ( const range of ranges ) {
  356. setAttributeOnRange( this, key, null, range );
  357. }
  358. } else {
  359. setAttributeOnItem( this, key, null, itemOrRange );
  360. }
  361. }
  362. /**
  363. * Removes all attributes from all elements in the range or from the given item.
  364. *
  365. * @param {module:engine/model/item~Item|module:engine/model/range~Range} itemOrRange
  366. * Model item or range from which all attributes will be removed.
  367. */
  368. clearAttributes( itemOrRange ) {
  369. this._assertWriterUsedCorrectly();
  370. const removeAttributesFromItem = item => {
  371. for ( const attribute of item.getAttributeKeys() ) {
  372. this.removeAttribute( attribute, item );
  373. }
  374. };
  375. if ( !( itemOrRange instanceof Range ) ) {
  376. removeAttributesFromItem( itemOrRange );
  377. } else {
  378. for ( const item of itemOrRange.getItems() ) {
  379. removeAttributesFromItem( item );
  380. }
  381. }
  382. }
  383. /**
  384. * Moves all items in the source range to the target position.
  385. *
  386. * writer.move( sourceRange, targetPosition );
  387. *
  388. * Instead of the target position you can use parent and offset or define that range should be moved to the end
  389. * or before or after chosen item:
  390. *
  391. * // Moves all items in the range to the paragraph at offset 5:
  392. * writer.move( sourceRange, paragraph, 5 );
  393. * // Moves all items in the range to the end of a blockquote:
  394. * writer.move( sourceRange, blockquote, 'end' );
  395. * // Moves all items in the range to a position after an image:
  396. * writer.move( sourceRange, image, 'after' );
  397. *
  398. * These parameters works the same way as {@link module:engine/model/position~Position.createAt `Position.createAt()`}.
  399. *
  400. * Note that items can be moved only within the same tree. It means that you can move items within the same root
  401. * (element or document fragment) or between {@link module:engine/model/document~Document#roots documents roots},
  402. * but you can not move items from document fragment to the document or from one detached element to another. Use
  403. * {@link module:engine/model/writer~Writer#insert} in such cases.
  404. *
  405. * @param {module:engine/model/range~Range} range Source range.
  406. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  407. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  408. * second parameter is a {@link module:engine/model/item~Item model item}.
  409. */
  410. move( range, itemOrPosition, offset ) {
  411. this._assertWriterUsedCorrectly();
  412. if ( !( range instanceof Range ) ) {
  413. /**
  414. * Invalid range to move.
  415. *
  416. * @error writer-move-invalid-range
  417. */
  418. throw new CKEditorError( 'writer-move-invalid-range: Invalid range to move.' );
  419. }
  420. if ( !range.isFlat ) {
  421. /**
  422. * Range to move is not flat.
  423. *
  424. * @error writer-move-range-not-flat
  425. */
  426. throw new CKEditorError( 'writer-move-range-not-flat: Range to move is not flat.' );
  427. }
  428. const position = Position.createAt( itemOrPosition, offset );
  429. if ( !isSameTree( range.root, position.root ) ) {
  430. /**
  431. * Range is going to be moved within not the same document. Please use
  432. * {@link module:engine/model/writer~Writer#insert insert} instead.
  433. *
  434. * @error writer-move-different-document
  435. */
  436. throw new CKEditorError( 'writer-move-different-document: Range is going to be moved between different documents.' );
  437. }
  438. const version = range.root.document ? range.root.document.version : null;
  439. const operation = new MoveOperation( range.start, range.end.offset - range.start.offset, position, version );
  440. this.batch.addOperation( operation );
  441. this.model.applyOperation( operation );
  442. }
  443. /**
  444. * Removes given model {@link module:engine/model/item~Item item} or {@link module:engine/model/range~Range range}.
  445. *
  446. * @param {module:engine/model/item~Item|module:engine/model/range~Range} itemOrRange Model item or range to remove.
  447. */
  448. remove( itemOrRange ) {
  449. this._assertWriterUsedCorrectly();
  450. if ( itemOrRange instanceof Range ) {
  451. // The array is reversed, so the ranges to remove are in correct order and do not have to be updated.
  452. const ranges = itemOrRange.getMinimalFlatRanges().reverse();
  453. for ( const flat of ranges ) {
  454. applyRemoveOperation( flat.start, flat.end.offset - flat.start.offset, this.batch, this.model );
  455. }
  456. } else {
  457. const howMany = itemOrRange.is( 'text' ) ? itemOrRange.offsetSize : 1;
  458. applyRemoveOperation( Position.createBefore( itemOrRange ), howMany, this.batch, this.model );
  459. }
  460. }
  461. /**
  462. * Merges two siblings at the given position.
  463. *
  464. * Node before and after the position have to be an element. Otherwise `writer-merge-no-element-before` or
  465. * `writer-merge-no-element-after` error will be thrown.
  466. *
  467. * @param {module:engine/model/position~Position} position Position between merged elements.
  468. */
  469. merge( position ) {
  470. this._assertWriterUsedCorrectly();
  471. const nodeBefore = position.nodeBefore;
  472. const nodeAfter = position.nodeAfter;
  473. if ( !( nodeBefore instanceof Element ) ) {
  474. /**
  475. * Node before merge position must be an element.
  476. *
  477. * @error writer-merge-no-element-before
  478. */
  479. throw new CKEditorError( 'writer-merge-no-element-before: Node before merge position must be an element.' );
  480. }
  481. if ( !( nodeAfter instanceof Element ) ) {
  482. /**
  483. * Node after merge position must be an element.
  484. *
  485. * @error writer-merge-no-element-after
  486. */
  487. throw new CKEditorError( 'writer-merge-no-element-after: Node after merge position must be an element.' );
  488. }
  489. if ( !position.root.document ) {
  490. this._mergeDetached( position );
  491. } else {
  492. this._merge( position );
  493. }
  494. }
  495. /**
  496. * Performs merge action in a detached tree.
  497. *
  498. * @private
  499. * @param {module:engine/model/position~Position} position Position between merged elements.
  500. */
  501. _mergeDetached( position ) {
  502. const nodeBefore = position.nodeBefore;
  503. const nodeAfter = position.nodeAfter;
  504. this.move( Range.createIn( nodeAfter ), Position.createAt( nodeBefore, 'end' ) );
  505. this.remove( nodeAfter );
  506. }
  507. /**
  508. * Performs merge action in a non-detached tree.
  509. *
  510. * @private
  511. * @param {module:engine/model/position~Position} position Position between merged elements.
  512. */
  513. _merge( position ) {
  514. const targetPosition = Position.createAt( position.nodeBefore, 'end' );
  515. const sourcePosition = Position.createAt( position.nodeAfter, 0 );
  516. const graveyard = position.root.document.graveyard;
  517. const graveyardPosition = new Position( graveyard, [ 0 ] );
  518. const version = position.root.document.version;
  519. const merge = new MergeOperation( sourcePosition, position.nodeAfter.maxOffset, targetPosition, graveyardPosition, version );
  520. this.batch.addOperation( merge );
  521. this.model.applyOperation( merge );
  522. }
  523. /**
  524. * Renames the given element.
  525. *
  526. * @param {module:engine/model/element~Element} element The element to rename.
  527. * @param {String} newName New element name.
  528. */
  529. rename( element, newName ) {
  530. this._assertWriterUsedCorrectly();
  531. if ( !( element instanceof Element ) ) {
  532. /**
  533. * Trying to rename an object which is not an instance of Element.
  534. *
  535. * @error writer-rename-not-element-instance
  536. */
  537. throw new CKEditorError(
  538. 'writer-rename-not-element-instance: Trying to rename an object which is not an instance of Element.'
  539. );
  540. }
  541. const version = element.root.document ? element.root.document.version : null;
  542. const renameOperation = new RenameOperation( Position.createBefore( element ), element.name, newName, version );
  543. this.batch.addOperation( renameOperation );
  544. this.model.applyOperation( renameOperation );
  545. }
  546. /**
  547. * Splits elements starting from the given position and going to the top of the model tree as long as given
  548. * `limitElement` is reached. When `limitElement` is not defined then only the parent of the given position will be split.
  549. *
  550. * The element needs to have a parent. It cannot be a root element nor a document fragment.
  551. * The `writer-split-element-no-parent` error will be thrown if you try to split an element with no parent.
  552. *
  553. * @param {module:engine/model/position~Position} position Position of split.
  554. * @param {module:engine/model/node~Node} [limitElement] Stop splitting when this element will be reached.
  555. * @returns {Object} result Split result.
  556. * @returns {module:engine/model/position~Position} result.position between split elements.
  557. * @returns {module:engine/model/range~Range} result.range Range that stars from the end of the first split element and ands
  558. * at the beginning of the first copy element.
  559. */
  560. split( position, limitElement ) {
  561. this._assertWriterUsedCorrectly();
  562. let splitElement = position.parent;
  563. if ( !splitElement.parent ) {
  564. /**
  565. * Element with no parent can not be split.
  566. *
  567. * @error writer-split-element-no-parent
  568. */
  569. throw new CKEditorError( 'writer-split-element-no-parent: Element with no parent can not be split.' );
  570. }
  571. // When limit element is not defined lets set splitElement parent as limit.
  572. if ( !limitElement ) {
  573. limitElement = splitElement.parent;
  574. }
  575. if ( !position.parent.getAncestors( { includeSelf: true } ).includes( limitElement ) ) {
  576. throw new CKEditorError( 'writer-split-invalid-limit-element: Limit element is not a position ancestor.' );
  577. }
  578. // We need to cache elements that will be created as a result of the first split because
  579. // we need to create a range from the end of the first split element to the beginning of the
  580. // first copy element. This should be handled by LiveRange but it doesn't work on detached nodes.
  581. let firstSplitElement, firstCopyElement;
  582. do {
  583. const version = splitElement.root.document ? splitElement.root.document.version : null;
  584. const howMany = splitElement.maxOffset - position.offset;
  585. const split = new SplitOperation( position, howMany, null, version );
  586. this.batch.addOperation( split );
  587. this.model.applyOperation( split );
  588. // Cache result of the first split.
  589. if ( !firstSplitElement && !firstCopyElement ) {
  590. firstSplitElement = splitElement;
  591. firstCopyElement = position.parent.nextSibling;
  592. }
  593. position = Position.createAfter( position.parent );
  594. splitElement = position.parent;
  595. } while ( splitElement !== limitElement );
  596. return {
  597. position,
  598. range: new Range( Position.createAt( firstSplitElement, 'end' ), Position.createAt( firstCopyElement ) )
  599. };
  600. }
  601. /**
  602. * Wraps the given range with the given element or with a new element (if a string was passed).
  603. *
  604. * **Note:** range to wrap should be a "flat range" (see {@link module:engine/model/range~Range#isFlat `Range#isFlat`}).
  605. * If not, an error will be thrown.
  606. *
  607. * @param {module:engine/model/range~Range} range Range to wrap.
  608. * @param {module:engine/model/element~Element|String} elementOrString Element or name of element to wrap the range with.
  609. */
  610. wrap( range, elementOrString ) {
  611. this._assertWriterUsedCorrectly();
  612. if ( !range.isFlat ) {
  613. /**
  614. * Range to wrap is not flat.
  615. *
  616. * @error writer-wrap-range-not-flat
  617. */
  618. throw new CKEditorError( 'writer-wrap-range-not-flat: Range to wrap is not flat.' );
  619. }
  620. const element = elementOrString instanceof Element ? elementOrString : new Element( elementOrString );
  621. if ( element.childCount > 0 ) {
  622. /**
  623. * Element to wrap with is not empty.
  624. *
  625. * @error writer-wrap-element-not-empty
  626. */
  627. throw new CKEditorError( 'writer-wrap-element-not-empty: Element to wrap with is not empty.' );
  628. }
  629. if ( element.parent !== null ) {
  630. /**
  631. * Element to wrap with is already attached to a tree model.
  632. *
  633. * @error writer-wrap-element-attached
  634. */
  635. throw new CKEditorError( 'writer-wrap-element-attached: Element to wrap with is already attached to tree model.' );
  636. }
  637. const version = range.root.document ? range.root.document.version : null;
  638. // Has to be `range.start` not `range.end` for better transformations.
  639. const insert = new InsertOperation( range.start, element, version );
  640. this.batch.addOperation( insert );
  641. this.model.applyOperation( insert );
  642. const move = new MoveOperation(
  643. range.start.getShiftedBy( 1 ),
  644. range.end.offset - range.start.offset,
  645. Position.createAt( element, 0 ),
  646. version === null ? null : version + 1
  647. );
  648. this.batch.addOperation( move );
  649. this.model.applyOperation( move );
  650. }
  651. /**
  652. * Unwraps children of the given element – all its children are moved before it and then the element is removed.
  653. * Throws error if you try to unwrap an element which does not have a parent.
  654. *
  655. * @param {module:engine/model/element~Element} element Element to unwrap.
  656. */
  657. unwrap( element ) {
  658. this._assertWriterUsedCorrectly();
  659. if ( element.parent === null ) {
  660. /**
  661. * Trying to unwrap an element which has no parent.
  662. *
  663. * @error writer-unwrap-element-no-parent
  664. */
  665. throw new CKEditorError( 'writer-unwrap-element-no-parent: Trying to unwrap an element which has no parent.' );
  666. }
  667. this.move( Range.createIn( element ), Position.createAfter( element ) );
  668. this.remove( element );
  669. }
  670. /**
  671. * Adds a {@link module:engine/model/markercollection~Marker marker}. Marker is a named range, which tracks
  672. * changes in the document and updates its range automatically, when model tree changes.
  673. *
  674. * As the first parameter you can set marker name.
  675. *
  676. * The required `options.usingOperation` parameter lets you decide if the marker should be managed by operations or not. See
  677. * {@link module:engine/model/markercollection~Marker marker class description} to learn about the difference between
  678. * markers managed by operations and not-managed by operations.
  679. *
  680. * The `options.affectsData` parameter, which defaults to `false`, allows you to define if a marker affects the data. It should be
  681. * `true` when the marker change changes the data returned by the
  682. * {@link module:core/editor/utils/dataapimixin~DataApi#getData `editor.getData()`} method.
  683. * When set to `true` it fires the {@link module:engine/model/document~Document#event:change:data `change:data`} event.
  684. * When set to `false` it fires the {@link module:engine/model/document~Document#event:change `change`} event.
  685. *
  686. * Create marker directly base on marker's name:
  687. *
  688. * addMarker( markerName, { range, usingOperation: false } );
  689. *
  690. * Create marker using operation:
  691. *
  692. * addMarker( markerName, { range, usingOperation: true } );
  693. *
  694. * Create marker that affects the editor data:
  695. *
  696. * addMarker( markerName, { range, usingOperation: false, affectsData: true } );
  697. *
  698. * Note: For efficiency reasons, it's best to create and keep as little markers as possible.
  699. *
  700. * @see module:engine/model/markercollection~Marker
  701. * @param {String} name Name of a marker to create - must be unique.
  702. * @param {Object} options
  703. * @param {Boolean} options.usingOperation Flag indicating that the marker should be added by MarkerOperation.
  704. * See {@link module:engine/model/markercollection~Marker#managedUsingOperations}.
  705. * @param {module:engine/model/range~Range} options.range Marker range.
  706. * @param {Boolean} [options.affectsData=false] Flag indicating that the marker changes the editor data.
  707. * @returns {module:engine/model/markercollection~Marker} Marker that was set.
  708. */
  709. addMarker( name, options ) {
  710. this._assertWriterUsedCorrectly();
  711. if ( !options || typeof options.usingOperation != 'boolean' ) {
  712. /**
  713. * The `options.usingOperations` parameter is required when adding a new marker.
  714. *
  715. * @error writer-addMarker-no-usingOperations
  716. */
  717. throw new CKEditorError(
  718. 'writer-addMarker-no-usingOperations: The options.usingOperations parameter is required when adding a new marker.'
  719. );
  720. }
  721. const usingOperation = options.usingOperation;
  722. const range = options.range;
  723. const affectsData = options.affectsData === undefined ? false : options.affectsData;
  724. if ( this.model.markers.has( name ) ) {
  725. /**
  726. * Marker with provided name already exists.
  727. *
  728. * @error writer-addMarker-marker-exists
  729. */
  730. throw new CKEditorError( 'writer-addMarker-marker-exists: Marker with provided name already exists.' );
  731. }
  732. if ( !range ) {
  733. /**
  734. * Range parameter is required when adding a new marker.
  735. *
  736. * @error writer-addMarker-no-range
  737. */
  738. throw new CKEditorError( 'writer-addMarker-no-range: Range parameter is required when adding a new marker.' );
  739. }
  740. if ( !usingOperation ) {
  741. return this.model.markers._set( name, range, usingOperation, affectsData );
  742. }
  743. applyMarkerOperation( this, name, null, range, affectsData );
  744. return this.model.markers.get( name );
  745. }
  746. /**
  747. * Adds or updates a {@link module:engine/model/markercollection~Marker marker}. Marker is a named range, which tracks
  748. * changes in the document and updates its range automatically, when model tree changes. Still, it is possible to change the
  749. * marker's range directly using this method.
  750. *
  751. * As the first parameter you can set marker name or instance. If none of them is provided, new marker, with a unique
  752. * name is created and returned.
  753. *
  754. * The `options.usingOperation` parameter lets you change if the marker should be managed by operations or not. See
  755. * {@link module:engine/model/markercollection~Marker marker class description} to learn about the difference between
  756. * markers managed by operations and not-managed by operations. It is possible to change this option for an existing marker.
  757. *
  758. * The `options.affectsData` parameter, which defaults to `false`, allows you to define if a marker affects the data. It should be
  759. * `true` when the marker change changes the data returned by
  760. * the {@link module:core/editor/utils/dataapimixin~DataApi#getData `editor.getData()`} method.
  761. * When set to `true` it fires the {@link module:engine/model/document~Document#event:change:data `change:data`} event.
  762. * When set to `false` it fires the {@link module:engine/model/document~Document#event:change `change`} event.
  763. *
  764. * Update marker directly base on marker's name:
  765. *
  766. * updateMarker( markerName, { range } );
  767. *
  768. * Update marker using operation:
  769. *
  770. * updateMarker( marker, { range, usingOperation: true } );
  771. * updateMarker( markerName, { range, usingOperation: true } );
  772. *
  773. * Change marker's option (start using operations to manage it):
  774. *
  775. * updateMarker( marker, { usingOperation: true } );
  776. *
  777. * Change marker's option (inform the engine, that the marker does not affect the data anymore):
  778. *
  779. * updateMarker( markerName, { affectsData: false } );
  780. *
  781. * @see module:engine/model/markercollection~Marker
  782. * @param {String} markerOrName Name of a marker to update, or a marker instance.
  783. * @param {Object} options
  784. * @param {module:engine/model/range~Range} [options.range] Marker range to update.
  785. * @param {Boolean} [options.usingOperation] Flag indicated whether the marker should be added by MarkerOperation.
  786. * See {@link module:engine/model/markercollection~Marker#managedUsingOperations}.
  787. * @param {Boolean} [options.affectsData] Flag indicating that the marker changes the editor data.
  788. */
  789. updateMarker( markerOrName, options = {} ) {
  790. this._assertWriterUsedCorrectly();
  791. const markerName = typeof markerOrName == 'string' ? markerOrName : markerOrName.name;
  792. const currentMarker = this.model.markers.get( markerName );
  793. if ( !currentMarker ) {
  794. /**
  795. * Marker with provided name does not exists.
  796. *
  797. * @error writer-updateMarker-marker-not-exists
  798. */
  799. throw new CKEditorError( 'writer-updateMarker-marker-not-exists: Marker with provided name does not exists.' );
  800. }
  801. const hasUsingOperationDefined = typeof options.usingOperation == 'boolean';
  802. const affectsDataDefined = typeof options.affectsData == 'boolean';
  803. // Use previously defined marker's affectsData if the property is not provided.
  804. const affectsData = affectsDataDefined ? options.affectsData : currentMarker.affectsData;
  805. if ( !hasUsingOperationDefined && !options.range && !affectsDataDefined ) {
  806. /**
  807. * One of the options is required - provide range, usingOperations or affectsData.
  808. *
  809. * @error writer-updateMarker-wrong-options
  810. */
  811. throw new CKEditorError(
  812. 'writer-updateMarker-wrong-options: One of the options is required - provide range, usingOperations or affectsData.'
  813. );
  814. }
  815. const currentRange = currentMarker.getRange();
  816. const updatedRange = options.range ? options.range : currentRange;
  817. if ( hasUsingOperationDefined && options.usingOperation !== currentMarker.managedUsingOperations ) {
  818. // The marker type is changed so it's necessary to create proper operations.
  819. if ( options.usingOperation ) {
  820. // If marker changes to a managed one treat this as synchronizing existing marker.
  821. // Create `MarkerOperation` with `oldRange` set to `null`, so reverse operation will remove the marker.
  822. applyMarkerOperation( this, markerName, null, updatedRange, affectsData );
  823. } else {
  824. // If marker changes to a marker that do not use operations then we need to create additional operation
  825. // that removes that marker first.
  826. applyMarkerOperation( this, markerName, currentRange, null, affectsData );
  827. // Although not managed the marker itself should stay in model and its range should be preserver or changed to passed range.
  828. this.model.markers._set( markerName, updatedRange, undefined, affectsData );
  829. }
  830. return;
  831. }
  832. // Marker's type doesn't change so update it accordingly.
  833. if ( currentMarker.managedUsingOperations ) {
  834. applyMarkerOperation( this, markerName, currentRange, updatedRange, affectsData );
  835. } else {
  836. this.model.markers._set( markerName, updatedRange, undefined, affectsData );
  837. }
  838. }
  839. /**
  840. * Removes given {@link module:engine/model/markercollection~Marker marker} or marker with given name.
  841. * The marker is removed accordingly to how it has been created, so if the marker was created using operation,
  842. * it will be destroyed using operation.
  843. *
  844. * @param {module:engine/model/markercollection~Marker|String} markerOrName Marker or marker name to remove.
  845. */
  846. removeMarker( markerOrName ) {
  847. this._assertWriterUsedCorrectly();
  848. const name = typeof markerOrName == 'string' ? markerOrName : markerOrName.name;
  849. if ( !this.model.markers.has( name ) ) {
  850. /**
  851. * Trying to remove marker which does not exist.
  852. *
  853. * @error writer-removeMarker-no-marker
  854. */
  855. throw new CKEditorError( 'writer-removeMarker-no-marker: Trying to remove marker which does not exist.' );
  856. }
  857. const marker = this.model.markers.get( name );
  858. if ( !marker.managedUsingOperations ) {
  859. this.model.markers._remove( name );
  860. return;
  861. }
  862. const oldRange = marker.getRange();
  863. applyMarkerOperation( this, name, oldRange, null, marker.affectsData );
  864. }
  865. /**
  866. * Sets this selection's ranges and direction to the specified location based on the given
  867. * {@link module:engine/model/selection~Selection selection}, {@link module:engine/model/position~Position position},
  868. * {@link module:engine/model/node~Node node}, {@link module:engine/model/position~Position position},
  869. * {@link module:engine/model/range~Range range}, an iterable of {@link module:engine/model/range~Range ranges} or null.
  870. *
  871. * // Sets selection to the given range.
  872. * const range = new Range( start, end );
  873. * writer.setSelection( range );
  874. *
  875. * // Sets selection to given ranges.
  876. * const ranges = [ new Range( start1, end2 ), new Range( star2, end2 ) ];
  877. * writer.setSelection( range );
  878. *
  879. * // Sets selection to other selection.
  880. * const otherSelection = new Selection();
  881. * writer.setSelection( otherSelection );
  882. *
  883. * // Sets selection to the given document selection.
  884. * const documentSelection = new DocumentSelection( doc );
  885. * writer.setSelection( documentSelection );
  886. *
  887. * // Sets collapsed selection at the given position.
  888. * const position = new Position( root, path );
  889. * writer.setSelection( position );
  890. *
  891. * // Sets collapsed selection at the position of the given node and an offset.
  892. * writer.setSelection( paragraph, offset );
  893. *
  894. * Creates a range inside an {@link module:engine/model/element~Element element} which starts before the first child of
  895. * that element and ends after the last child of that element.
  896. *
  897. * writer.setSelection( paragraph, 'in' );
  898. *
  899. * Creates a range on an {@link module:engine/model/item~Item item} which starts before the item and ends just after the item.
  900. *
  901. * writer.setSelection( paragraph, 'on' );
  902. *
  903. * // Removes all selection's ranges.
  904. * writer.setSelection( null );
  905. *
  906. * `Writer#setSelection()` allow passing additional options (`backward`) as the last argument.
  907. *
  908. * // Sets selection as backward.
  909. * writer.setSelection( range, { backward: true } );
  910. *
  911. * Throws `writer-incorrect-use` error when the writer is used outside the `change()` block.
  912. *
  913. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection|
  914. * module:engine/model/position~Position|module:engine/model/node~Node|
  915. * Iterable.<module:engine/model/range~Range>|module:engine/model/range~Range|null} selectable
  916. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
  917. * @param {Object} [options]
  918. * @param {Boolean} [options.backward] Sets this selection instance to be backward.
  919. */
  920. setSelection( selectable, placeOrOffset, options ) {
  921. this._assertWriterUsedCorrectly();
  922. this.model.document.selection._setTo( selectable, placeOrOffset, options );
  923. }
  924. /**
  925. * Moves {@link module:engine/model/documentselection~DocumentSelection#focus} to the specified location.
  926. *
  927. * The location can be specified in the same form as
  928. * {@link module:engine/model/position~Position.createAt `Position.createAt()`} parameters.
  929. *
  930. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  931. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  932. * first parameter is a {@link module:engine/model/item~Item model item}.
  933. */
  934. setSelectionFocus( itemOrPosition, offset ) {
  935. this._assertWriterUsedCorrectly();
  936. this.model.document.selection._setFocus( itemOrPosition, offset );
  937. }
  938. /**
  939. * Sets attribute(s) on the selection. If attribute with the same key already is set, it's value is overwritten.
  940. *
  941. * Using key and value pair:
  942. *
  943. * writer.setSelectionAttribute( 'italic', true );
  944. *
  945. * Using key-value object:
  946. *
  947. * writer.setSelectionAttribute( { italic: true, bold: false } );
  948. *
  949. * Using iterable object:
  950. *
  951. * writer.setSelectionAttribute( new Map( [ [ 'italic', true ] ] ) );
  952. *
  953. * @param {String|Object|Iterable.<*>} keyOrObjectOrIterable Key of the attribute to set
  954. * or object / iterable of key => value attribute pairs.
  955. * @param {*} [value] Attribute value.
  956. */
  957. setSelectionAttribute( keyOrObjectOrIterable, value ) {
  958. this._assertWriterUsedCorrectly();
  959. if ( typeof keyOrObjectOrIterable === 'string' ) {
  960. this._setSelectionAttribute( keyOrObjectOrIterable, value );
  961. } else {
  962. for ( const [ key, value ] of toMap( keyOrObjectOrIterable ) ) {
  963. this._setSelectionAttribute( key, value );
  964. }
  965. }
  966. }
  967. /**
  968. * Removes attribute(s) with given key(s) from the selection.
  969. *
  970. * Remove one attribute:
  971. *
  972. * writer.removeSelectionAttribute( 'italic' );
  973. *
  974. * Remove multiple attributes:
  975. *
  976. * writer.removeSelectionAttribute( [ 'italic', 'bold' ] );
  977. *
  978. * @param {String|Iterable.<String>} keyOrIterableOfKeys Key of the attribute to remove or an iterable of attribute keys to remove.
  979. */
  980. removeSelectionAttribute( keyOrIterableOfKeys ) {
  981. this._assertWriterUsedCorrectly();
  982. if ( typeof keyOrIterableOfKeys === 'string' ) {
  983. this._removeSelectionAttribute( keyOrIterableOfKeys );
  984. } else {
  985. for ( const key of keyOrIterableOfKeys ) {
  986. this._removeSelectionAttribute( key );
  987. }
  988. }
  989. }
  990. /**
  991. * Temporarily changes the {@link module:engine/model/documentselection~DocumentSelection#isGravityOverridden gravity}
  992. * of the selection from left to right.
  993. *
  994. * The gravity defines from which direction the selection inherits its attributes. If it's the default left gravity,
  995. * then the selection (after being moved by the user) inherits attributes from its left-hand side.
  996. * This method allows to temporarily override this behavior by forcing the gravity to the right.
  997. *
  998. * For the following model fragment:
  999. *
  1000. * <$text bold="true" linkHref="url">bar[]</$text><$text bold="true">biz</$text>
  1001. *
  1002. * * Default gravity: selection will have the `bold` and `linkHref` attributes.
  1003. * * Overridden gravity: selection will have `bold` attribute.
  1004. *
  1005. * **Note**: It returns an unique identifier which is required to restore the gravity. It guarantees the symmetry
  1006. * of the process.
  1007. *
  1008. * @returns {String} The unique id which allows restoring the gravity.
  1009. */
  1010. overrideSelectionGravity() {
  1011. return this.model.document.selection._overrideGravity();
  1012. }
  1013. /**
  1014. * Restores {@link ~Writer#overrideSelectionGravity} gravity to default.
  1015. *
  1016. * Restoring the gravity is only possible using the unique identifier returned by
  1017. * {@link ~Writer#overrideSelectionGravity}. Note that the gravity remains overridden as long as won't be restored
  1018. * the same number of times it was overridden.
  1019. *
  1020. * @param {String} uid The unique id returned by {@link ~Writer#overrideSelectionGravity}.
  1021. */
  1022. restoreSelectionGravity( uid ) {
  1023. this.model.document.selection._restoreGravity( uid );
  1024. }
  1025. /**
  1026. * @private
  1027. * @param {String} key Key of the attribute to remove.
  1028. * @param {*} value Attribute value.
  1029. */
  1030. _setSelectionAttribute( key, value ) {
  1031. const selection = this.model.document.selection;
  1032. // Store attribute in parent element if the selection is collapsed in an empty node.
  1033. if ( selection.isCollapsed && selection.anchor.parent.isEmpty ) {
  1034. const storeKey = DocumentSelection._getStoreAttributeKey( key );
  1035. this.setAttribute( storeKey, value, selection.anchor.parent );
  1036. }
  1037. selection._setAttribute( key, value );
  1038. }
  1039. /**
  1040. * @private
  1041. * @param {String} key Key of the attribute to remove.
  1042. */
  1043. _removeSelectionAttribute( key ) {
  1044. const selection = this.model.document.selection;
  1045. // Remove stored attribute from parent element if the selection is collapsed in an empty node.
  1046. if ( selection.isCollapsed && selection.anchor.parent.isEmpty ) {
  1047. const storeKey = DocumentSelection._getStoreAttributeKey( key );
  1048. this.removeAttribute( storeKey, selection.anchor.parent );
  1049. }
  1050. selection._removeAttribute( key );
  1051. }
  1052. /**
  1053. * Throws `writer-detached-writer-tries-to-modify-model` error when the writer is used outside of the `change()` block.
  1054. *
  1055. * @private
  1056. */
  1057. _assertWriterUsedCorrectly() {
  1058. /**
  1059. * Trying to use a writer outside a {@link module:engine/model/model~Model#change `change()` or
  1060. * {@link module:engine/model/model~Model#enqueueChange `enqueueChange()`} blocks.
  1061. *
  1062. * The writer can only be used inside these blocks which ensures that the model
  1063. * can only be changed during such "sessions".
  1064. *
  1065. * @error writer-incorrect-use
  1066. */
  1067. if ( this.model._currentWriter !== this ) {
  1068. throw new CKEditorError( 'writer-incorrect-use: Trying to use a writer outside the change() block.' );
  1069. }
  1070. }
  1071. }
  1072. // Sets given attribute to each node in given range. When attribute value is null then attribute will be removed.
  1073. //
  1074. // Because attribute operation needs to have the same attribute value on the whole range, this function splits
  1075. // the range into smaller parts.
  1076. //
  1077. // Given `range` must be flat.
  1078. //
  1079. // @private
  1080. // @param {module:engine/model/writer~Writer} writer
  1081. // @param {String} key Attribute key.
  1082. // @param {*} value Attribute new value.
  1083. // @param {module:engine/model/range~Range} range Model range on which the attribute will be set.
  1084. function setAttributeOnRange( writer, key, value, range ) {
  1085. const model = writer.model;
  1086. const doc = model.document;
  1087. // Position of the last split, the beginning of the new range.
  1088. let lastSplitPosition = range.start;
  1089. // Currently position in the scanning range. Because we need value after the position, it is not a current
  1090. // position of the iterator but the previous one (we need to iterate one more time to get the value after).
  1091. let position;
  1092. // Value before the currently position.
  1093. let valueBefore;
  1094. // Value after the currently position.
  1095. let valueAfter;
  1096. for ( const val of range.getWalker( { shallow: true } ) ) {
  1097. valueAfter = val.item.getAttribute( key );
  1098. // At the first run of the iterator the position in undefined. We also do not have a valueBefore, but
  1099. // because valueAfter may be null, valueBefore may be equal valueAfter ( undefined == null ).
  1100. if ( position && valueBefore != valueAfter ) {
  1101. // if valueBefore == value there is nothing to change, so we add operation only if these values are different.
  1102. if ( valueBefore != value ) {
  1103. addOperation();
  1104. }
  1105. lastSplitPosition = position;
  1106. }
  1107. position = val.nextPosition;
  1108. valueBefore = valueAfter;
  1109. }
  1110. // Because position in the loop is not the iterator position (see let position comment), the last position in
  1111. // the while loop will be last but one position in the range. We need to check the last position manually.
  1112. if ( position instanceof Position && position != lastSplitPosition && valueBefore != value ) {
  1113. addOperation();
  1114. }
  1115. function addOperation() {
  1116. const range = new Range( lastSplitPosition, position );
  1117. const version = range.root.document ? doc.version : null;
  1118. const operation = new AttributeOperation( range, key, valueBefore, value, version );
  1119. writer.batch.addOperation( operation );
  1120. model.applyOperation( operation );
  1121. }
  1122. }
  1123. // Sets given attribute to the given node. When attribute value is null then attribute will be removed.
  1124. //
  1125. // @private
  1126. // @param {module:engine/model/writer~Writer} writer
  1127. // @param {String} key Attribute key.
  1128. // @param {*} value Attribute new value.
  1129. // @param {module:engine/model/item~Item} item Model item on which the attribute will be set.
  1130. function setAttributeOnItem( writer, key, value, item ) {
  1131. const model = writer.model;
  1132. const doc = model.document;
  1133. const previousValue = item.getAttribute( key );
  1134. let range, operation;
  1135. if ( previousValue != value ) {
  1136. const isRootChanged = item.root === item;
  1137. if ( isRootChanged ) {
  1138. // If we change attributes of root element, we have to use `RootAttributeOperation`.
  1139. const version = item.document ? doc.version : null;
  1140. operation = new RootAttributeOperation( item, key, previousValue, value, version );
  1141. } else {
  1142. range = new Range( Position.createBefore( item ), Position.createAfter( item ) );
  1143. const version = range.root.document ? doc.version : null;
  1144. operation = new AttributeOperation( range, key, previousValue, value, version );
  1145. }
  1146. writer.batch.addOperation( operation );
  1147. model.applyOperation( operation );
  1148. }
  1149. }
  1150. // Creates and applies marker operation to {@link module:engine/model/operation/operation~Operation operation}.
  1151. //
  1152. // @private
  1153. // @param {module:engine/model/writer~Writer} writer
  1154. // @param {String} name Marker name.
  1155. // @param {module:engine/model/range~Range} oldRange Marker range before the change.
  1156. // @param {module:engine/model/range~Range} newRange Marker range after the change.
  1157. // @param {Boolean} affectsData
  1158. function applyMarkerOperation( writer, name, oldRange, newRange, affectsData ) {
  1159. const model = writer.model;
  1160. const doc = model.document;
  1161. const operation = new MarkerOperation( name, oldRange, newRange, model.markers, affectsData, doc.version );
  1162. writer.batch.addOperation( operation );
  1163. model.applyOperation( operation );
  1164. }
  1165. // Creates `MoveOperation` or `DetachOperation` that removes `howMany` nodes starting from `position`.
  1166. // The operation will be applied on given model instance and added to given operation instance.
  1167. //
  1168. // @private
  1169. // @param {module:engine/model/position~Position} position Position from which nodes are removed.
  1170. // @param {Number} howMany Number of nodes to remove.
  1171. // @param {Batch} batch Batch to which the operation will be added.
  1172. // @param {module:engine/model/model~Model} model Model instance on which operation will be applied.
  1173. function applyRemoveOperation( position, howMany, batch, model ) {
  1174. let operation;
  1175. if ( position.root.document ) {
  1176. const doc = model.document;
  1177. const graveyardPosition = new Position( doc.graveyard, [ 0 ] );
  1178. operation = new MoveOperation( position, howMany, graveyardPosition, doc.version );
  1179. } else {
  1180. operation = new DetachOperation( position, howMany );
  1181. }
  1182. batch.addOperation( operation );
  1183. model.applyOperation( operation );
  1184. }
  1185. // Returns `true` if both root elements are the same element or both are documents root elements.
  1186. //
  1187. // Elements in the same tree can be moved (for instance you can move element form one documents root to another, or
  1188. // within the same document fragment), but when element supposed to be moved from document fragment to the document, or
  1189. // to another document it should be removed and inserted to avoid problems with OT. This is because features like undo or
  1190. // collaboration may track changes on the document but ignore changes on detached fragments and should not get
  1191. // unexpected `move` operation.
  1192. function isSameTree( rootA, rootB ) {
  1193. // If it is the same root this is the same tree.
  1194. if ( rootA === rootB ) {
  1195. return true;
  1196. }
  1197. // If both roots are documents root it is operation within the document what we still treat as the same tree.
  1198. if ( rootA instanceof RootElement && rootB instanceof RootElement ) {
  1199. return true;
  1200. }
  1201. return false;
  1202. }