writer.js 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  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 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 #createPositionAt `writer.createPositionAt()`}.
  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] 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 = 0 ) {
  149. this._assertWriterUsedCorrectly();
  150. if ( item instanceof Text && item.data == '' ) {
  151. return;
  152. }
  153. const position = Position._createAt( itemOrPosition, offset );
  154. // If item has a parent already.
  155. if ( item.parent ) {
  156. // We need to check if item is going to be inserted within the same document.
  157. if ( isSameTree( item.root, position.root ) ) {
  158. // If it's we just need to move it.
  159. this.move( Range._createOn( item ), position );
  160. return;
  161. }
  162. // If it isn't the same root.
  163. else {
  164. if ( item.root.document ) {
  165. /**
  166. * Cannot move a node from a document to a different tree.
  167. * It is forbidden to move a node that was already in a document outside of it.
  168. *
  169. * @error model-writer-insert-forbidden-move
  170. */
  171. throw new CKEditorError(
  172. 'model-writer-insert-forbidden-move: ' +
  173. 'Cannot move a node from a document to a different tree. ' +
  174. 'It is forbidden to move a node that was already in a document outside of it.',
  175. this
  176. );
  177. } else {
  178. // Move between two different document fragments or from document fragment to a document is possible.
  179. // In that case, remove the item from it's original parent.
  180. this.remove( item );
  181. }
  182. }
  183. }
  184. const version = position.root.document ? position.root.document.version : null;
  185. const insert = new InsertOperation( position, item, version );
  186. if ( item instanceof Text ) {
  187. insert.shouldReceiveAttributes = true;
  188. }
  189. this.batch.addOperation( insert );
  190. this.model.applyOperation( insert );
  191. // When element is a DocumentFragment we need to move its markers to Document#markers.
  192. if ( item instanceof DocumentFragment ) {
  193. for ( const [ markerName, markerRange ] of item.markers ) {
  194. // We need to migrate marker range from DocumentFragment to Document.
  195. const rangeRootPosition = Position._createAt( markerRange.root, 0 );
  196. const range = new Range(
  197. markerRange.start._getCombined( rangeRootPosition, position ),
  198. markerRange.end._getCombined( rangeRootPosition, position )
  199. );
  200. const options = { range, usingOperation: true, affectsData: true };
  201. if ( this.model.markers.has( markerName ) ) {
  202. this.updateMarker( markerName, options );
  203. } else {
  204. this.addMarker( markerName, options );
  205. }
  206. }
  207. }
  208. }
  209. /**
  210. * Creates and inserts text on given position. You can optionally set text attributes:
  211. *
  212. * writer.insertText( 'foo', position );
  213. * writer.insertText( 'foo', { bold: true }, position );
  214. *
  215. * Instead of using position you can use parent and offset or define that text should be inserted at the end
  216. * or before or after other node:
  217. *
  218. * // Inserts 'foo' in paragraph, at offset 5:
  219. * writer.insertText( 'foo', paragraph, 5 );
  220. * // Inserts 'foo' at the end of a paragraph:
  221. * writer.insertText( 'foo', paragraph, 'end' );
  222. * // Inserts 'foo' after an image:
  223. * writer.insertText( 'foo', image, 'after' );
  224. *
  225. * These parameters work in the same way as {@link #createPositionAt `writer.createPositionAt()`}.
  226. *
  227. * @param {String} data Text data.
  228. * @param {Object} [attributes] Text attributes.
  229. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  230. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
  231. * third parameter is a {@link module:engine/model/item~Item model item}.
  232. */
  233. insertText( text, attributes, itemOrPosition, offset ) {
  234. if ( attributes instanceof DocumentFragment || attributes instanceof Element || attributes instanceof Position ) {
  235. this.insert( this.createText( text ), attributes, itemOrPosition );
  236. } else {
  237. this.insert( this.createText( text, attributes ), itemOrPosition, offset );
  238. }
  239. }
  240. /**
  241. * Creates and inserts element on given position. You can optionally set attributes:
  242. *
  243. * writer.insertElement( 'paragraph', position );
  244. * writer.insertElement( 'paragraph', { alignment: 'center' }, position );
  245. *
  246. * Instead of using position you can use parent and offset or define that text should be inserted at the end
  247. * or before or after other node:
  248. *
  249. * // Inserts paragraph in the root at offset 5:
  250. * writer.insertElement( 'paragraph', root, 5 );
  251. * // Inserts paragraph at the end of a blockquote:
  252. * writer.insertElement( 'paragraph', blockquote, 'end' );
  253. * // Inserts after an image:
  254. * writer.insertElement( 'paragraph', image, 'after' );
  255. *
  256. * These parameters works the same way as {@link #createPositionAt `writer.createPositionAt()`}.
  257. *
  258. * @param {String} name Name of the element.
  259. * @param {Object} [attributes] Elements attributes.
  260. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  261. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
  262. * third parameter is a {@link module:engine/model/item~Item model item}.
  263. */
  264. insertElement( name, attributes, itemOrPosition, offset ) {
  265. if ( attributes instanceof DocumentFragment || attributes instanceof Element || attributes instanceof Position ) {
  266. this.insert( this.createElement( name ), attributes, itemOrPosition );
  267. } else {
  268. this.insert( this.createElement( name, attributes ), itemOrPosition, offset );
  269. }
  270. }
  271. /**
  272. * Inserts item at the end of the given parent.
  273. *
  274. * const paragraph = writer.createElement( 'paragraph' );
  275. * writer.append( paragraph, root );
  276. *
  277. * Note that if the item already has parent it will be removed from the previous parent.
  278. *
  279. * If you want to move {@link module:engine/model/range~Range range} instead of an
  280. * {@link module:engine/model/item~Item item} use {@link module:engine/model/writer~Writer#move `Writer#move()`}.
  281. *
  282. * @param {module:engine/model/item~Item|module:engine/model/documentfragment~DocumentFragment}
  283. * item Item or document fragment to insert.
  284. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} parent
  285. */
  286. append( item, parent ) {
  287. this.insert( item, parent, 'end' );
  288. }
  289. /**
  290. * Creates text node and inserts it at the end of the parent. You can optionally set text attributes:
  291. *
  292. * writer.appendText( 'foo', paragraph );
  293. * writer.appendText( 'foo', { bold: true }, paragraph );
  294. *
  295. * @param {String} text Text data.
  296. * @param {Object} [attributes] Text attributes.
  297. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} parent
  298. */
  299. appendText( text, attributes, parent ) {
  300. if ( attributes instanceof DocumentFragment || attributes instanceof Element ) {
  301. this.insert( this.createText( text ), attributes, 'end' );
  302. } else {
  303. this.insert( this.createText( text, attributes ), parent, 'end' );
  304. }
  305. }
  306. /**
  307. * Creates element and inserts it at the end of the parent. You can optionally set attributes:
  308. *
  309. * writer.appendElement( 'paragraph', root );
  310. * writer.appendElement( 'paragraph', { alignment: 'center' }, root );
  311. *
  312. * @param {String} name Name of the element.
  313. * @param {Object} [attributes] Elements attributes.
  314. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} parent
  315. */
  316. appendElement( name, attributes, parent ) {
  317. if ( attributes instanceof DocumentFragment || attributes instanceof Element ) {
  318. this.insert( this.createElement( name ), attributes, 'end' );
  319. } else {
  320. this.insert( this.createElement( name, attributes ), parent, 'end' );
  321. }
  322. }
  323. /**
  324. * Sets value of the attribute with given key on a {@link module:engine/model/item~Item model item}
  325. * or on a {@link module:engine/model/range~Range range}.
  326. *
  327. * @param {String} key Attribute key.
  328. * @param {*} value Attribute new value.
  329. * @param {module:engine/model/item~Item|module:engine/model/range~Range} itemOrRange
  330. * Model item or range on which the attribute will be set.
  331. */
  332. setAttribute( key, value, itemOrRange ) {
  333. this._assertWriterUsedCorrectly();
  334. if ( itemOrRange instanceof Range ) {
  335. const ranges = itemOrRange.getMinimalFlatRanges();
  336. for ( const range of ranges ) {
  337. setAttributeOnRange( this, key, value, range );
  338. }
  339. } else {
  340. setAttributeOnItem( this, key, value, itemOrRange );
  341. }
  342. }
  343. /**
  344. * Sets values of attributes on a {@link module:engine/model/item~Item model item}
  345. * or on a {@link module:engine/model/range~Range range}.
  346. *
  347. * writer.setAttributes( {
  348. * bold: true,
  349. * italic: true
  350. * }, range );
  351. *
  352. * @param {Object} attributes Attributes keys and values.
  353. * @param {module:engine/model/item~Item|module:engine/model/range~Range} itemOrRange
  354. * Model item or range on which the attributes will be set.
  355. */
  356. setAttributes( attributes, itemOrRange ) {
  357. for ( const [ key, val ] of toMap( attributes ) ) {
  358. this.setAttribute( key, val, itemOrRange );
  359. }
  360. }
  361. /**
  362. * Removes an attribute with given key from a {@link module:engine/model/item~Item model item}
  363. * or from a {@link module:engine/model/range~Range range}.
  364. *
  365. * @param {String} key Attribute key.
  366. * @param {module:engine/model/item~Item|module:engine/model/range~Range} itemOrRange
  367. * Model item or range from which the attribute will be removed.
  368. */
  369. removeAttribute( key, itemOrRange ) {
  370. this._assertWriterUsedCorrectly();
  371. if ( itemOrRange instanceof Range ) {
  372. const ranges = itemOrRange.getMinimalFlatRanges();
  373. for ( const range of ranges ) {
  374. setAttributeOnRange( this, key, null, range );
  375. }
  376. } else {
  377. setAttributeOnItem( this, key, null, itemOrRange );
  378. }
  379. }
  380. /**
  381. * Removes all attributes from all elements in the range or from the given item.
  382. *
  383. * @param {module:engine/model/item~Item|module:engine/model/range~Range} itemOrRange
  384. * Model item or range from which all attributes will be removed.
  385. */
  386. clearAttributes( itemOrRange ) {
  387. this._assertWriterUsedCorrectly();
  388. const removeAttributesFromItem = item => {
  389. for ( const attribute of item.getAttributeKeys() ) {
  390. this.removeAttribute( attribute, item );
  391. }
  392. };
  393. if ( !( itemOrRange instanceof Range ) ) {
  394. removeAttributesFromItem( itemOrRange );
  395. } else {
  396. for ( const item of itemOrRange.getItems() ) {
  397. removeAttributesFromItem( item );
  398. }
  399. }
  400. }
  401. /**
  402. * Moves all items in the source range to the target position.
  403. *
  404. * writer.move( sourceRange, targetPosition );
  405. *
  406. * Instead of the target position you can use parent and offset or define that range should be moved to the end
  407. * or before or after chosen item:
  408. *
  409. * // Moves all items in the range to the paragraph at offset 5:
  410. * writer.move( sourceRange, paragraph, 5 );
  411. * // Moves all items in the range to the end of a blockquote:
  412. * writer.move( sourceRange, blockquote, 'end' );
  413. * // Moves all items in the range to a position after an image:
  414. * writer.move( sourceRange, image, 'after' );
  415. *
  416. * These parameters works the same way as {@link #createPositionAt `writer.createPositionAt()`}.
  417. *
  418. * Note that items can be moved only within the same tree. It means that you can move items within the same root
  419. * (element or document fragment) or between {@link module:engine/model/document~Document#roots documents roots},
  420. * but you can not move items from document fragment to the document or from one detached element to another. Use
  421. * {@link module:engine/model/writer~Writer#insert} in such cases.
  422. *
  423. * @param {module:engine/model/range~Range} range Source range.
  424. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  425. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
  426. * second parameter is a {@link module:engine/model/item~Item model item}.
  427. */
  428. move( range, itemOrPosition, offset ) {
  429. this._assertWriterUsedCorrectly();
  430. if ( !( range instanceof Range ) ) {
  431. /**
  432. * Invalid range to move.
  433. *
  434. * @error writer-move-invalid-range
  435. */
  436. throw new CKEditorError( 'writer-move-invalid-range: Invalid range to move.', this );
  437. }
  438. if ( !range.isFlat ) {
  439. /**
  440. * Range to move is not flat.
  441. *
  442. * @error writer-move-range-not-flat
  443. */
  444. throw new CKEditorError( 'writer-move-range-not-flat: Range to move is not flat.', this );
  445. }
  446. const position = Position._createAt( itemOrPosition, offset );
  447. // Do not move anything if the move target is same as moved range start.
  448. if ( position.isEqual( range.start ) ) {
  449. return;
  450. }
  451. // If part of the marker is removed, create additional marker operation for undo purposes.
  452. this._addOperationForAffectedMarkers( 'move', range );
  453. if ( !isSameTree( range.root, position.root ) ) {
  454. /**
  455. * Range is going to be moved within not the same document. Please use
  456. * {@link module:engine/model/writer~Writer#insert insert} instead.
  457. *
  458. * @error writer-move-different-document
  459. */
  460. throw new CKEditorError( 'writer-move-different-document: Range is going to be moved between different documents.', this );
  461. }
  462. const version = range.root.document ? range.root.document.version : null;
  463. const operation = new MoveOperation( range.start, range.end.offset - range.start.offset, position, version );
  464. this.batch.addOperation( operation );
  465. this.model.applyOperation( operation );
  466. }
  467. /**
  468. * Removes given model {@link module:engine/model/item~Item item} or {@link module:engine/model/range~Range range}.
  469. *
  470. * @param {module:engine/model/item~Item|module:engine/model/range~Range} itemOrRange Model item or range to remove.
  471. */
  472. remove( itemOrRange ) {
  473. this._assertWriterUsedCorrectly();
  474. const rangeToRemove = itemOrRange instanceof Range ? itemOrRange : Range._createOn( itemOrRange );
  475. const ranges = rangeToRemove.getMinimalFlatRanges().reverse();
  476. for ( const flat of ranges ) {
  477. // If part of the marker is removed, create additional marker operation for undo purposes.
  478. this._addOperationForAffectedMarkers( 'move', flat );
  479. applyRemoveOperation( flat.start, flat.end.offset - flat.start.offset, this.batch, this.model );
  480. }
  481. }
  482. /**
  483. * Merges two siblings at the given position.
  484. *
  485. * Node before and after the position have to be an element. Otherwise `writer-merge-no-element-before` or
  486. * `writer-merge-no-element-after` error will be thrown.
  487. *
  488. * @param {module:engine/model/position~Position} position Position between merged elements.
  489. */
  490. merge( position ) {
  491. this._assertWriterUsedCorrectly();
  492. const nodeBefore = position.nodeBefore;
  493. const nodeAfter = position.nodeAfter;
  494. // If part of the marker is removed, create additional marker operation for undo purposes.
  495. this._addOperationForAffectedMarkers( 'merge', position );
  496. if ( !( nodeBefore instanceof Element ) ) {
  497. /**
  498. * Node before merge position must be an element.
  499. *
  500. * @error writer-merge-no-element-before
  501. */
  502. throw new CKEditorError( 'writer-merge-no-element-before: Node before merge position must be an element.', this );
  503. }
  504. if ( !( nodeAfter instanceof Element ) ) {
  505. /**
  506. * Node after merge position must be an element.
  507. *
  508. * @error writer-merge-no-element-after
  509. */
  510. throw new CKEditorError( 'writer-merge-no-element-after: Node after merge position must be an element.', this );
  511. }
  512. if ( !position.root.document ) {
  513. this._mergeDetached( position );
  514. } else {
  515. this._merge( position );
  516. }
  517. }
  518. /**
  519. * Shortcut for {@link module:engine/model/model~Model#createPositionFromPath `Model#createPositionFromPath()`}.
  520. *
  521. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} root Root of the position.
  522. * @param {Array.<Number>} path Position path. See {@link module:engine/model/position~Position#path}.
  523. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
  524. * See {@link module:engine/model/position~PositionStickiness}.
  525. * @returns {module:engine/model/position~Position}
  526. */
  527. createPositionFromPath( root, path, stickiness ) {
  528. return this.model.createPositionFromPath( root, path, stickiness );
  529. }
  530. /**
  531. * Shortcut for {@link module:engine/model/model~Model#createPositionAt `Model#createPositionAt()`}.
  532. *
  533. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  534. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
  535. * first parameter is a {@link module:engine/model/item~Item model item}.
  536. * @returns {module:engine/model/position~Position}
  537. */
  538. createPositionAt( itemOrPosition, offset ) {
  539. return this.model.createPositionAt( itemOrPosition, offset );
  540. }
  541. /**
  542. * Shortcut for {@link module:engine/model/model~Model#createPositionAfter `Model#createPositionAfter()`}.
  543. *
  544. * @param {module:engine/model/item~Item} item Item after which the position should be placed.
  545. * @returns {module:engine/model/position~Position}
  546. */
  547. createPositionAfter( item ) {
  548. return this.model.createPositionAfter( item );
  549. }
  550. /**
  551. * Shortcut for {@link module:engine/model/model~Model#createPositionBefore `Model#createPositionBefore()`}.
  552. *
  553. * @param {module:engine/model/item~Item} item Item after which the position should be placed.
  554. * @returns {module:engine/model/position~Position}
  555. */
  556. createPositionBefore( item ) {
  557. return this.model.createPositionBefore( item );
  558. }
  559. /**
  560. * Shortcut for {@link module:engine/model/model~Model#createRange `Model#createRange()`}.
  561. *
  562. * @param {module:engine/model/position~Position} start Start position.
  563. * @param {module:engine/model/position~Position} [end] End position. If not set, range will be collapsed at `start` position.
  564. * @returns {module:engine/model/range~Range}
  565. */
  566. createRange( start, end ) {
  567. return this.model.createRange( start, end );
  568. }
  569. /**
  570. * Shortcut for {@link module:engine/model/model~Model#createRangeIn `Model#createRangeIn()`}.
  571. *
  572. * @param {module:engine/model/element~Element} element Element which is a parent for the range.
  573. * @returns {module:engine/model/range~Range}
  574. */
  575. createRangeIn( element ) {
  576. return this.model.createRangeIn( element );
  577. }
  578. /**
  579. * Shortcut for {@link module:engine/model/model~Model#createRangeOn `Model#createRangeOn()`}.
  580. *
  581. * @param {module:engine/model/element~Element} element Element which is a parent for the range.
  582. * @returns {module:engine/model/range~Range}
  583. */
  584. createRangeOn( element ) {
  585. return this.model.createRangeOn( element );
  586. }
  587. /**
  588. * Shortcut for {@link module:engine/model/model~Model#createSelection `Model#createSelection()`}.
  589. *
  590. * @param {module:engine/model/selection~Selectable} selectable
  591. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
  592. * @param {Object} [options]
  593. * @param {Boolean} [options.backward] Sets this selection instance to be backward.
  594. * @returns {module:engine/model/selection~Selection}
  595. */
  596. createSelection( selectable, placeOrOffset, options ) {
  597. return this.model.createSelection( selectable, placeOrOffset, options );
  598. }
  599. /**
  600. * Performs merge action in a detached tree.
  601. *
  602. * @private
  603. * @param {module:engine/model/position~Position} position Position between merged elements.
  604. */
  605. _mergeDetached( position ) {
  606. const nodeBefore = position.nodeBefore;
  607. const nodeAfter = position.nodeAfter;
  608. this.move( Range._createIn( nodeAfter ), Position._createAt( nodeBefore, 'end' ) );
  609. this.remove( nodeAfter );
  610. }
  611. /**
  612. * Performs merge action in a non-detached tree.
  613. *
  614. * @private
  615. * @param {module:engine/model/position~Position} position Position between merged elements.
  616. */
  617. _merge( position ) {
  618. const targetPosition = Position._createAt( position.nodeBefore, 'end' );
  619. const sourcePosition = Position._createAt( position.nodeAfter, 0 );
  620. const graveyard = position.root.document.graveyard;
  621. const graveyardPosition = new Position( graveyard, [ 0 ] );
  622. const version = position.root.document.version;
  623. const merge = new MergeOperation( sourcePosition, position.nodeAfter.maxOffset, targetPosition, graveyardPosition, version );
  624. this.batch.addOperation( merge );
  625. this.model.applyOperation( merge );
  626. }
  627. /**
  628. * Renames the given element.
  629. *
  630. * @param {module:engine/model/element~Element} element The element to rename.
  631. * @param {String} newName New element name.
  632. */
  633. rename( element, newName ) {
  634. this._assertWriterUsedCorrectly();
  635. if ( !( element instanceof Element ) ) {
  636. /**
  637. * Trying to rename an object which is not an instance of Element.
  638. *
  639. * @error writer-rename-not-element-instance
  640. */
  641. throw new CKEditorError(
  642. 'writer-rename-not-element-instance: Trying to rename an object which is not an instance of Element.',
  643. this
  644. );
  645. }
  646. const version = element.root.document ? element.root.document.version : null;
  647. const renameOperation = new RenameOperation( Position._createBefore( element ), element.name, newName, version );
  648. this.batch.addOperation( renameOperation );
  649. this.model.applyOperation( renameOperation );
  650. }
  651. /**
  652. * Splits elements starting from the given position and going to the top of the model tree as long as given
  653. * `limitElement` is reached. When `limitElement` is not defined then only the parent of the given position will be split.
  654. *
  655. * The element needs to have a parent. It cannot be a root element nor a document fragment.
  656. * The `writer-split-element-no-parent` error will be thrown if you try to split an element with no parent.
  657. *
  658. * @param {module:engine/model/position~Position} position Position of split.
  659. * @param {module:engine/model/node~Node} [limitElement] Stop splitting when this element will be reached.
  660. * @returns {Object} result Split result.
  661. * @returns {module:engine/model/position~Position} result.position Position between split elements.
  662. * @returns {module:engine/model/range~Range} result.range Range that stars from the end of the first split element and ends
  663. * at the beginning of the first copy element.
  664. */
  665. split( position, limitElement ) {
  666. this._assertWriterUsedCorrectly();
  667. let splitElement = position.parent;
  668. if ( !splitElement.parent ) {
  669. /**
  670. * Element with no parent can not be split.
  671. *
  672. * @error writer-split-element-no-parent
  673. */
  674. throw new CKEditorError( 'writer-split-element-no-parent: Element with no parent can not be split.', this );
  675. }
  676. // When limit element is not defined lets set splitElement parent as limit.
  677. if ( !limitElement ) {
  678. limitElement = splitElement.parent;
  679. }
  680. if ( !position.parent.getAncestors( { includeSelf: true } ).includes( limitElement ) ) {
  681. throw new CKEditorError( 'writer-split-invalid-limit-element: Limit element is not a position ancestor.', this );
  682. }
  683. // We need to cache elements that will be created as a result of the first split because
  684. // we need to create a range from the end of the first split element to the beginning of the
  685. // first copy element. This should be handled by LiveRange but it doesn't work on detached nodes.
  686. let firstSplitElement, firstCopyElement;
  687. do {
  688. const version = splitElement.root.document ? splitElement.root.document.version : null;
  689. const howMany = splitElement.maxOffset - position.offset;
  690. const split = new SplitOperation( position, howMany, null, version );
  691. this.batch.addOperation( split );
  692. this.model.applyOperation( split );
  693. // Cache result of the first split.
  694. if ( !firstSplitElement && !firstCopyElement ) {
  695. firstSplitElement = splitElement;
  696. firstCopyElement = position.parent.nextSibling;
  697. }
  698. position = this.createPositionAfter( position.parent );
  699. splitElement = position.parent;
  700. } while ( splitElement !== limitElement );
  701. return {
  702. position,
  703. range: new Range( Position._createAt( firstSplitElement, 'end' ), Position._createAt( firstCopyElement, 0 ) )
  704. };
  705. }
  706. /**
  707. * Wraps the given range with the given element or with a new element (if a string was passed).
  708. *
  709. * **Note:** range to wrap should be a "flat range" (see {@link module:engine/model/range~Range#isFlat `Range#isFlat`}).
  710. * If not, an error will be thrown.
  711. *
  712. * @param {module:engine/model/range~Range} range Range to wrap.
  713. * @param {module:engine/model/element~Element|String} elementOrString Element or name of element to wrap the range with.
  714. */
  715. wrap( range, elementOrString ) {
  716. this._assertWriterUsedCorrectly();
  717. if ( !range.isFlat ) {
  718. /**
  719. * Range to wrap is not flat.
  720. *
  721. * @error writer-wrap-range-not-flat
  722. */
  723. throw new CKEditorError( 'writer-wrap-range-not-flat: Range to wrap is not flat.', this );
  724. }
  725. const element = elementOrString instanceof Element ? elementOrString : new Element( elementOrString );
  726. if ( element.childCount > 0 ) {
  727. /**
  728. * Element to wrap with is not empty.
  729. *
  730. * @error writer-wrap-element-not-empty
  731. */
  732. throw new CKEditorError( 'writer-wrap-element-not-empty: Element to wrap with is not empty.', this );
  733. }
  734. if ( element.parent !== null ) {
  735. /**
  736. * Element to wrap with is already attached to a tree model.
  737. *
  738. * @error writer-wrap-element-attached
  739. */
  740. throw new CKEditorError( 'writer-wrap-element-attached: Element to wrap with is already attached to tree model.', this );
  741. }
  742. this.insert( element, range.start );
  743. // Shift the range-to-wrap because we just inserted an element before that range.
  744. const shiftedRange = new Range( range.start.getShiftedBy( 1 ), range.end.getShiftedBy( 1 ) );
  745. this.move( shiftedRange, Position._createAt( element, 0 ) );
  746. }
  747. /**
  748. * Unwraps children of the given element – all its children are moved before it and then the element is removed.
  749. * Throws error if you try to unwrap an element which does not have a parent.
  750. *
  751. * @param {module:engine/model/element~Element} element Element to unwrap.
  752. */
  753. unwrap( element ) {
  754. this._assertWriterUsedCorrectly();
  755. if ( element.parent === null ) {
  756. /**
  757. * Trying to unwrap an element which has no parent.
  758. *
  759. * @error writer-unwrap-element-no-parent
  760. */
  761. throw new CKEditorError( 'writer-unwrap-element-no-parent: Trying to unwrap an element which has no parent.', this );
  762. }
  763. this.move( Range._createIn( element ), this.createPositionAfter( element ) );
  764. this.remove( element );
  765. }
  766. /**
  767. * Adds a {@link module:engine/model/markercollection~Marker marker}. Marker is a named range, which tracks
  768. * changes in the document and updates its range automatically, when model tree changes.
  769. *
  770. * As the first parameter you can set marker name.
  771. *
  772. * The required `options.usingOperation` parameter lets you decide if the marker should be managed by operations or not. See
  773. * {@link module:engine/model/markercollection~Marker marker class description} to learn about the difference between
  774. * markers managed by operations and not-managed by operations.
  775. *
  776. * The `options.affectsData` parameter, which defaults to `false`, allows you to define if a marker affects the data. It should be
  777. * `true` when the marker change changes the data returned by the
  778. * {@link module:core/editor/utils/dataapimixin~DataApi#getData `editor.getData()`} method.
  779. * When set to `true` it fires the {@link module:engine/model/document~Document#event:change:data `change:data`} event.
  780. * When set to `false` it fires the {@link module:engine/model/document~Document#event:change `change`} event.
  781. *
  782. * Create marker directly base on marker's name:
  783. *
  784. * addMarker( markerName, { range, usingOperation: false } );
  785. *
  786. * Create marker using operation:
  787. *
  788. * addMarker( markerName, { range, usingOperation: true } );
  789. *
  790. * Create marker that affects the editor data:
  791. *
  792. * addMarker( markerName, { range, usingOperation: false, affectsData: true } );
  793. *
  794. * Note: For efficiency reasons, it's best to create and keep as little markers as possible.
  795. *
  796. * @see module:engine/model/markercollection~Marker
  797. * @param {String} name Name of a marker to create - must be unique.
  798. * @param {Object} options
  799. * @param {Boolean} options.usingOperation Flag indicating that the marker should be added by MarkerOperation.
  800. * See {@link module:engine/model/markercollection~Marker#managedUsingOperations}.
  801. * @param {module:engine/model/range~Range} options.range Marker range.
  802. * @param {Boolean} [options.affectsData=false] Flag indicating that the marker changes the editor data.
  803. * @returns {module:engine/model/markercollection~Marker} Marker that was set.
  804. */
  805. addMarker( name, options ) {
  806. this._assertWriterUsedCorrectly();
  807. if ( !options || typeof options.usingOperation != 'boolean' ) {
  808. /**
  809. * The `options.usingOperation` parameter is required when adding a new marker.
  810. *
  811. * @error writer-addMarker-no-usingOperation
  812. */
  813. throw new CKEditorError(
  814. 'writer-addMarker-no-usingOperation: The options.usingOperation parameter is required when adding a new marker.',
  815. this
  816. );
  817. }
  818. const usingOperation = options.usingOperation;
  819. const range = options.range;
  820. const affectsData = options.affectsData === undefined ? false : options.affectsData;
  821. if ( this.model.markers.has( name ) ) {
  822. /**
  823. * Marker with provided name already exists.
  824. *
  825. * @error writer-addMarker-marker-exists
  826. */
  827. throw new CKEditorError( 'writer-addMarker-marker-exists: Marker with provided name already exists.', this );
  828. }
  829. if ( !range ) {
  830. /**
  831. * Range parameter is required when adding a new marker.
  832. *
  833. * @error writer-addMarker-no-range
  834. */
  835. throw new CKEditorError(
  836. 'writer-addMarker-no-range: Range parameter is required when adding a new marker.',
  837. this
  838. );
  839. }
  840. if ( !usingOperation ) {
  841. return this.model.markers._set( name, range, usingOperation, affectsData );
  842. }
  843. applyMarkerOperation( this, name, null, range, affectsData );
  844. return this.model.markers.get( name );
  845. }
  846. /**
  847. * Adds, updates or refreshes a {@link module:engine/model/markercollection~Marker marker}. Marker is a named range, which tracks
  848. * changes in the document and updates its range automatically, when model tree changes. Still, it is possible to change the
  849. * marker's range directly using this method.
  850. *
  851. * As the first parameter you can set marker name or instance. If none of them is provided, new marker, with a unique
  852. * name is created and returned.
  853. *
  854. * As the second parameter you can set the new marker data or leave this parameter as empty which will just refresh
  855. * the marker by triggering downcast conversion for it. Refreshing the marker is useful when you want to change
  856. * the marker {@link module:engine/view/element~Element view element} without changing any marker data.
  857. *
  858. * let isCommentActive = false;
  859. *
  860. * model.conversion.markerToHighlight( {
  861. * model: 'comment',
  862. * view: data => {
  863. * const classes = [ 'comment-marker' ];
  864. *
  865. * if ( isCommentActive ) {
  866. * classes.push( 'comment-marker--active' );
  867. * }
  868. *
  869. * return { classes };
  870. * }
  871. * } );
  872. *
  873. * // Change the property that indicates if marker is displayed as active or not.
  874. * isCommentActive = true;
  875. *
  876. * // And refresh the marker to convert it with additional class.
  877. * model.change( writer => writer.updateMarker( 'comment' ) );
  878. *
  879. * The `options.usingOperation` parameter lets you change if the marker should be managed by operations or not. See
  880. * {@link module:engine/model/markercollection~Marker marker class description} to learn about the difference between
  881. * markers managed by operations and not-managed by operations. It is possible to change this option for an existing marker.
  882. *
  883. * The `options.affectsData` parameter, which defaults to `false`, allows you to define if a marker affects the data. It should be
  884. * `true` when the marker change changes the data returned by
  885. * the {@link module:core/editor/utils/dataapimixin~DataApi#getData `editor.getData()`} method.
  886. * When set to `true` it fires the {@link module:engine/model/document~Document#event:change:data `change:data`} event.
  887. * When set to `false` it fires the {@link module:engine/model/document~Document#event:change `change`} event.
  888. *
  889. * Update marker directly base on marker's name:
  890. *
  891. * updateMarker( markerName, { range } );
  892. *
  893. * Update marker using operation:
  894. *
  895. * updateMarker( marker, { range, usingOperation: true } );
  896. * updateMarker( markerName, { range, usingOperation: true } );
  897. *
  898. * Change marker's option (start using operations to manage it):
  899. *
  900. * updateMarker( marker, { usingOperation: true } );
  901. *
  902. * Change marker's option (inform the engine, that the marker does not affect the data anymore):
  903. *
  904. * updateMarker( markerName, { affectsData: false } );
  905. *
  906. * @see module:engine/model/markercollection~Marker
  907. * @param {String|module:engine/model/markercollection~Marker} markerOrName Name of a marker to update, or a marker instance.
  908. * @param {Object} [options] If options object is not defined then marker will be refreshed by triggering
  909. * downcast conversion for this marker with the same data.
  910. * @param {module:engine/model/range~Range} [options.range] Marker range to update.
  911. * @param {Boolean} [options.usingOperation] Flag indicated whether the marker should be added by MarkerOperation.
  912. * See {@link module:engine/model/markercollection~Marker#managedUsingOperations}.
  913. * @param {Boolean} [options.affectsData] Flag indicating that the marker changes the editor data.
  914. */
  915. updateMarker( markerOrName, options ) {
  916. this._assertWriterUsedCorrectly();
  917. const markerName = typeof markerOrName == 'string' ? markerOrName : markerOrName.name;
  918. const currentMarker = this.model.markers.get( markerName );
  919. if ( !currentMarker ) {
  920. /**
  921. * Marker with provided name does not exists.
  922. *
  923. * @error writer-updateMarker-marker-not-exists
  924. */
  925. throw new CKEditorError( 'writer-updateMarker-marker-not-exists: Marker with provided name does not exists.', this );
  926. }
  927. if ( !options ) {
  928. this.model.markers._refresh( currentMarker );
  929. return;
  930. }
  931. const hasUsingOperationDefined = typeof options.usingOperation == 'boolean';
  932. const affectsDataDefined = typeof options.affectsData == 'boolean';
  933. // Use previously defined marker's affectsData if the property is not provided.
  934. const affectsData = affectsDataDefined ? options.affectsData : currentMarker.affectsData;
  935. if ( !hasUsingOperationDefined && !options.range && !affectsDataDefined ) {
  936. /**
  937. * One of the options is required - provide range, usingOperations or affectsData.
  938. *
  939. * @error writer-updateMarker-wrong-options
  940. */
  941. throw new CKEditorError(
  942. 'writer-updateMarker-wrong-options: One of the options is required - provide range, usingOperations or affectsData.',
  943. this
  944. );
  945. }
  946. const currentRange = currentMarker.getRange();
  947. const updatedRange = options.range ? options.range : currentRange;
  948. if ( hasUsingOperationDefined && options.usingOperation !== currentMarker.managedUsingOperations ) {
  949. // The marker type is changed so it's necessary to create proper operations.
  950. if ( options.usingOperation ) {
  951. // If marker changes to a managed one treat this as synchronizing existing marker.
  952. // Create `MarkerOperation` with `oldRange` set to `null`, so reverse operation will remove the marker.
  953. applyMarkerOperation( this, markerName, null, updatedRange, affectsData );
  954. } else {
  955. // If marker changes to a marker that do not use operations then we need to create additional operation
  956. // that removes that marker first.
  957. applyMarkerOperation( this, markerName, currentRange, null, affectsData );
  958. // Although not managed the marker itself should stay in model and its range should be preserver or changed to passed range.
  959. this.model.markers._set( markerName, updatedRange, undefined, affectsData );
  960. }
  961. return;
  962. }
  963. // Marker's type doesn't change so update it accordingly.
  964. if ( currentMarker.managedUsingOperations ) {
  965. applyMarkerOperation( this, markerName, currentRange, updatedRange, affectsData );
  966. } else {
  967. this.model.markers._set( markerName, updatedRange, undefined, affectsData );
  968. }
  969. }
  970. /**
  971. * Removes given {@link module:engine/model/markercollection~Marker marker} or marker with given name.
  972. * The marker is removed accordingly to how it has been created, so if the marker was created using operation,
  973. * it will be destroyed using operation.
  974. *
  975. * @param {module:engine/model/markercollection~Marker|String} markerOrName Marker or marker name to remove.
  976. */
  977. removeMarker( markerOrName ) {
  978. this._assertWriterUsedCorrectly();
  979. const name = typeof markerOrName == 'string' ? markerOrName : markerOrName.name;
  980. if ( !this.model.markers.has( name ) ) {
  981. /**
  982. * Trying to remove marker which does not exist.
  983. *
  984. * @error writer-removeMarker-no-marker
  985. */
  986. throw new CKEditorError( 'writer-removeMarker-no-marker: Trying to remove marker which does not exist.', this );
  987. }
  988. const marker = this.model.markers.get( name );
  989. if ( !marker.managedUsingOperations ) {
  990. this.model.markers._remove( name );
  991. return;
  992. }
  993. const oldRange = marker.getRange();
  994. applyMarkerOperation( this, name, oldRange, null, marker.affectsData );
  995. }
  996. /**
  997. * Sets the document's selection (ranges and direction) to the specified location based on the given
  998. * {@link module:engine/model/selection~Selectable selectable} or creates an empty selection if no arguments were passed.
  999. *
  1000. * // Sets selection to the given range.
  1001. * const range = writer.createRange( start, end );
  1002. * writer.setSelection( range );
  1003. *
  1004. * // Sets selection to given ranges.
  1005. * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
  1006. * writer.setSelection( range );
  1007. *
  1008. * // Sets selection to other selection.
  1009. * const otherSelection = writer.createSelection();
  1010. * writer.setSelection( otherSelection );
  1011. *
  1012. * // Sets selection to the given document selection.
  1013. * const documentSelection = model.document.selection;
  1014. * writer.setSelection( documentSelection );
  1015. *
  1016. * // Sets collapsed selection at the given position.
  1017. * const position = writer.createPosition( root, path );
  1018. * writer.setSelection( position );
  1019. *
  1020. * // Sets collapsed selection at the position of the given node and an offset.
  1021. * writer.setSelection( paragraph, offset );
  1022. *
  1023. * Creates a range inside an {@link module:engine/model/element~Element element} which starts before the first child of
  1024. * that element and ends after the last child of that element.
  1025. *
  1026. * writer.setSelection( paragraph, 'in' );
  1027. *
  1028. * Creates a range on an {@link module:engine/model/item~Item item} which starts before the item and ends just after the item.
  1029. *
  1030. * writer.setSelection( paragraph, 'on' );
  1031. *
  1032. * // Removes all selection's ranges.
  1033. * writer.setSelection( null );
  1034. *
  1035. * `Writer#setSelection()` allow passing additional options (`backward`) as the last argument.
  1036. *
  1037. * // Sets selection as backward.
  1038. * writer.setSelection( range, { backward: true } );
  1039. *
  1040. * Throws `writer-incorrect-use` error when the writer is used outside the `change()` block.
  1041. *
  1042. * @param {module:engine/model/selection~Selectable} selectable
  1043. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
  1044. * @param {Object} [options]
  1045. * @param {Boolean} [options.backward] Sets this selection instance to be backward.
  1046. */
  1047. setSelection( selectable, placeOrOffset, options ) {
  1048. this._assertWriterUsedCorrectly();
  1049. this.model.document.selection._setTo( selectable, placeOrOffset, options );
  1050. }
  1051. /**
  1052. * Moves {@link module:engine/model/documentselection~DocumentSelection#focus} to the specified location.
  1053. *
  1054. * The location can be specified in the same form as
  1055. * {@link #createPositionAt `writer.createPositionAt()`} parameters.
  1056. *
  1057. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  1058. * @param {Number|'end'|'before'|'after'} [offset=0] Offset or one of the flags. Used only when
  1059. * first parameter is a {@link module:engine/model/item~Item model item}.
  1060. */
  1061. setSelectionFocus( itemOrPosition, offset ) {
  1062. this._assertWriterUsedCorrectly();
  1063. this.model.document.selection._setFocus( itemOrPosition, offset );
  1064. }
  1065. /**
  1066. * Sets attribute(s) on the selection. If attribute with the same key already is set, it's value is overwritten.
  1067. *
  1068. * Using key and value pair:
  1069. *
  1070. * writer.setSelectionAttribute( 'italic', true );
  1071. *
  1072. * Using key-value object:
  1073. *
  1074. * writer.setSelectionAttribute( { italic: true, bold: false } );
  1075. *
  1076. * Using iterable object:
  1077. *
  1078. * writer.setSelectionAttribute( new Map( [ [ 'italic', true ] ] ) );
  1079. *
  1080. * @param {String|Object|Iterable.<*>} keyOrObjectOrIterable Key of the attribute to set
  1081. * or object / iterable of key => value attribute pairs.
  1082. * @param {*} [value] Attribute value.
  1083. */
  1084. setSelectionAttribute( keyOrObjectOrIterable, value ) {
  1085. this._assertWriterUsedCorrectly();
  1086. if ( typeof keyOrObjectOrIterable === 'string' ) {
  1087. this._setSelectionAttribute( keyOrObjectOrIterable, value );
  1088. } else {
  1089. for ( const [ key, value ] of toMap( keyOrObjectOrIterable ) ) {
  1090. this._setSelectionAttribute( key, value );
  1091. }
  1092. }
  1093. }
  1094. /**
  1095. * Removes attribute(s) with given key(s) from the selection.
  1096. *
  1097. * Remove one attribute:
  1098. *
  1099. * writer.removeSelectionAttribute( 'italic' );
  1100. *
  1101. * Remove multiple attributes:
  1102. *
  1103. * writer.removeSelectionAttribute( [ 'italic', 'bold' ] );
  1104. *
  1105. * @param {String|Iterable.<String>} keyOrIterableOfKeys Key of the attribute to remove or an iterable of attribute keys to remove.
  1106. */
  1107. removeSelectionAttribute( keyOrIterableOfKeys ) {
  1108. this._assertWriterUsedCorrectly();
  1109. if ( typeof keyOrIterableOfKeys === 'string' ) {
  1110. this._removeSelectionAttribute( keyOrIterableOfKeys );
  1111. } else {
  1112. for ( const key of keyOrIterableOfKeys ) {
  1113. this._removeSelectionAttribute( key );
  1114. }
  1115. }
  1116. }
  1117. /**
  1118. * Temporarily changes the {@link module:engine/model/documentselection~DocumentSelection#isGravityOverridden gravity}
  1119. * of the selection from left to right.
  1120. *
  1121. * The gravity defines from which direction the selection inherits its attributes. If it's the default left gravity,
  1122. * then the selection (after being moved by the user) inherits attributes from its left-hand side.
  1123. * This method allows to temporarily override this behavior by forcing the gravity to the right.
  1124. *
  1125. * For the following model fragment:
  1126. *
  1127. * <$text bold="true" linkHref="url">bar[]</$text><$text bold="true">biz</$text>
  1128. *
  1129. * * Default gravity: selection will have the `bold` and `linkHref` attributes.
  1130. * * Overridden gravity: selection will have `bold` attribute.
  1131. *
  1132. * **Note**: It returns an unique identifier which is required to restore the gravity. It guarantees the symmetry
  1133. * of the process.
  1134. *
  1135. * @returns {String} The unique id which allows restoring the gravity.
  1136. */
  1137. overrideSelectionGravity() {
  1138. return this.model.document.selection._overrideGravity();
  1139. }
  1140. /**
  1141. * Restores {@link ~Writer#overrideSelectionGravity} gravity to default.
  1142. *
  1143. * Restoring the gravity is only possible using the unique identifier returned by
  1144. * {@link ~Writer#overrideSelectionGravity}. Note that the gravity remains overridden as long as won't be restored
  1145. * the same number of times it was overridden.
  1146. *
  1147. * @param {String} uid The unique id returned by {@link ~Writer#overrideSelectionGravity}.
  1148. */
  1149. restoreSelectionGravity( uid ) {
  1150. this.model.document.selection._restoreGravity( uid );
  1151. }
  1152. /**
  1153. * @private
  1154. * @param {String} key Key of the attribute to remove.
  1155. * @param {*} value Attribute value.
  1156. */
  1157. _setSelectionAttribute( key, value ) {
  1158. const selection = this.model.document.selection;
  1159. // Store attribute in parent element if the selection is collapsed in an empty node.
  1160. if ( selection.isCollapsed && selection.anchor.parent.isEmpty ) {
  1161. const storeKey = DocumentSelection._getStoreAttributeKey( key );
  1162. this.setAttribute( storeKey, value, selection.anchor.parent );
  1163. }
  1164. selection._setAttribute( key, value );
  1165. }
  1166. /**
  1167. * @private
  1168. * @param {String} key Key of the attribute to remove.
  1169. */
  1170. _removeSelectionAttribute( key ) {
  1171. const selection = this.model.document.selection;
  1172. // Remove stored attribute from parent element if the selection is collapsed in an empty node.
  1173. if ( selection.isCollapsed && selection.anchor.parent.isEmpty ) {
  1174. const storeKey = DocumentSelection._getStoreAttributeKey( key );
  1175. this.removeAttribute( storeKey, selection.anchor.parent );
  1176. }
  1177. selection._removeAttribute( key );
  1178. }
  1179. /**
  1180. * Throws `writer-detached-writer-tries-to-modify-model` error when the writer is used outside of the `change()` block.
  1181. *
  1182. * @private
  1183. */
  1184. _assertWriterUsedCorrectly() {
  1185. /**
  1186. * Trying to use a writer outside a {@link module:engine/model/model~Model#change `change()`} or
  1187. * {@link module:engine/model/model~Model#enqueueChange `enqueueChange()`} blocks.
  1188. *
  1189. * The writer can only be used inside these blocks which ensures that the model
  1190. * can only be changed during such "sessions".
  1191. *
  1192. * @error writer-incorrect-use
  1193. */
  1194. if ( this.model._currentWriter !== this ) {
  1195. throw new CKEditorError( 'writer-incorrect-use: Trying to use a writer outside the change() block.', this );
  1196. }
  1197. }
  1198. /**
  1199. * For given action `type` and `positionOrRange` where the action happens, this function finds all affected markers
  1200. * and applies a marker operation with the new marker range equal to the current range. Thanks to this, the marker range
  1201. * can be later correctly processed during undo.
  1202. *
  1203. * @private
  1204. * @param {'move'|'merge'} type Writer action type.
  1205. * @param {module:engine/model/position~Position|module:engine/model/range~Range} positionOrRange Position or range
  1206. * where the writer action happens.
  1207. */
  1208. _addOperationForAffectedMarkers( type, positionOrRange ) {
  1209. for ( const marker of this.model.markers ) {
  1210. if ( !marker.managedUsingOperations ) {
  1211. continue;
  1212. }
  1213. const markerRange = marker.getRange();
  1214. let isAffected = false;
  1215. if ( type == 'move' ) {
  1216. isAffected =
  1217. positionOrRange.containsPosition( markerRange.start ) ||
  1218. positionOrRange.start.isEqual( markerRange.start ) ||
  1219. positionOrRange.containsPosition( markerRange.end ) ||
  1220. positionOrRange.end.isEqual( markerRange.end );
  1221. } else {
  1222. // if type == 'merge'.
  1223. const elementBefore = positionOrRange.nodeBefore;
  1224. const elementAfter = positionOrRange.nodeAfter;
  1225. // Start: <p>Foo[</p><p>Bar]</p>
  1226. // After merge: <p>Foo[Bar]</p>
  1227. // After undoing split: <p>Foo</p><p>[Bar]</p> <-- incorrect, needs remembering for undo.
  1228. //
  1229. const affectedInLeftElement = markerRange.start.parent == elementBefore && markerRange.start.isAtEnd;
  1230. // Start: <p>[Foo</p><p>]Bar</p>
  1231. // After merge: <p>[Foo]Bar</p>
  1232. // After undoing split: <p>[Foo]</p><p>Bar</p> <-- incorrect, needs remembering for undo.
  1233. //
  1234. const affectedInRightElement = markerRange.end.parent == elementAfter && markerRange.end.offset == 0;
  1235. // Start: <p>[Foo</p>]<p>Bar</p>
  1236. // After merge: <p>[Foo]Bar</p>
  1237. // After undoing split: <p>[Foo]</p><p>Bar</p> <-- incorrect, needs remembering for undo.
  1238. //
  1239. const affectedAfterLeftElement = markerRange.end.nodeAfter == elementAfter;
  1240. // Start: <p>Foo</p>[<p>Bar]</p>
  1241. // After merge: <p>Foo[Bar]</p>
  1242. // After undoing split: <p>Foo</p><p>[Bar]</p> <-- incorrect, needs remembering for undo.
  1243. //
  1244. const affectedBeforeRightElement = markerRange.start.nodeAfter == elementAfter;
  1245. isAffected = affectedInLeftElement || affectedInRightElement || affectedAfterLeftElement || affectedBeforeRightElement;
  1246. }
  1247. if ( isAffected ) {
  1248. this.updateMarker( marker.name, { range: markerRange } );
  1249. }
  1250. }
  1251. }
  1252. }
  1253. // Sets given attribute to each node in given range. When attribute value is null then attribute will be removed.
  1254. //
  1255. // Because attribute operation needs to have the same attribute value on the whole range, this function splits
  1256. // the range into smaller parts.
  1257. //
  1258. // Given `range` must be flat.
  1259. //
  1260. // @private
  1261. // @param {module:engine/model/writer~Writer} writer
  1262. // @param {String} key Attribute key.
  1263. // @param {*} value Attribute new value.
  1264. // @param {module:engine/model/range~Range} range Model range on which the attribute will be set.
  1265. function setAttributeOnRange( writer, key, value, range ) {
  1266. const model = writer.model;
  1267. const doc = model.document;
  1268. // Position of the last split, the beginning of the new range.
  1269. let lastSplitPosition = range.start;
  1270. // Currently position in the scanning range. Because we need value after the position, it is not a current
  1271. // position of the iterator but the previous one (we need to iterate one more time to get the value after).
  1272. let position;
  1273. // Value before the currently position.
  1274. let valueBefore;
  1275. // Value after the currently position.
  1276. let valueAfter;
  1277. for ( const val of range.getWalker( { shallow: true } ) ) {
  1278. valueAfter = val.item.getAttribute( key );
  1279. // At the first run of the iterator the position in undefined. We also do not have a valueBefore, but
  1280. // because valueAfter may be null, valueBefore may be equal valueAfter ( undefined == null ).
  1281. if ( position && valueBefore != valueAfter ) {
  1282. // if valueBefore == value there is nothing to change, so we add operation only if these values are different.
  1283. if ( valueBefore != value ) {
  1284. addOperation();
  1285. }
  1286. lastSplitPosition = position;
  1287. }
  1288. position = val.nextPosition;
  1289. valueBefore = valueAfter;
  1290. }
  1291. // Because position in the loop is not the iterator position (see let position comment), the last position in
  1292. // the while loop will be last but one position in the range. We need to check the last position manually.
  1293. if ( position instanceof Position && position != lastSplitPosition && valueBefore != value ) {
  1294. addOperation();
  1295. }
  1296. function addOperation() {
  1297. const range = new Range( lastSplitPosition, position );
  1298. const version = range.root.document ? doc.version : null;
  1299. const operation = new AttributeOperation( range, key, valueBefore, value, version );
  1300. writer.batch.addOperation( operation );
  1301. model.applyOperation( operation );
  1302. }
  1303. }
  1304. // Sets given attribute to the given node. When attribute value is null then attribute will be removed.
  1305. //
  1306. // @private
  1307. // @param {module:engine/model/writer~Writer} writer
  1308. // @param {String} key Attribute key.
  1309. // @param {*} value Attribute new value.
  1310. // @param {module:engine/model/item~Item} item Model item on which the attribute will be set.
  1311. function setAttributeOnItem( writer, key, value, item ) {
  1312. const model = writer.model;
  1313. const doc = model.document;
  1314. const previousValue = item.getAttribute( key );
  1315. let range, operation;
  1316. if ( previousValue != value ) {
  1317. const isRootChanged = item.root === item;
  1318. if ( isRootChanged ) {
  1319. // If we change attributes of root element, we have to use `RootAttributeOperation`.
  1320. const version = item.document ? doc.version : null;
  1321. operation = new RootAttributeOperation( item, key, previousValue, value, version );
  1322. } else {
  1323. range = new Range( Position._createBefore( item ), writer.createPositionAfter( item ) );
  1324. const version = range.root.document ? doc.version : null;
  1325. operation = new AttributeOperation( range, key, previousValue, value, version );
  1326. }
  1327. writer.batch.addOperation( operation );
  1328. model.applyOperation( operation );
  1329. }
  1330. }
  1331. // Creates and applies marker operation to {@link module:engine/model/operation/operation~Operation operation}.
  1332. //
  1333. // @private
  1334. // @param {module:engine/model/writer~Writer} writer
  1335. // @param {String} name Marker name.
  1336. // @param {module:engine/model/range~Range} oldRange Marker range before the change.
  1337. // @param {module:engine/model/range~Range} newRange Marker range after the change.
  1338. // @param {Boolean} affectsData
  1339. function applyMarkerOperation( writer, name, oldRange, newRange, affectsData ) {
  1340. const model = writer.model;
  1341. const doc = model.document;
  1342. const operation = new MarkerOperation( name, oldRange, newRange, model.markers, affectsData, doc.version );
  1343. writer.batch.addOperation( operation );
  1344. model.applyOperation( operation );
  1345. }
  1346. // Creates `MoveOperation` or `DetachOperation` that removes `howMany` nodes starting from `position`.
  1347. // The operation will be applied on given model instance and added to given operation instance.
  1348. //
  1349. // @private
  1350. // @param {module:engine/model/position~Position} position Position from which nodes are removed.
  1351. // @param {Number} howMany Number of nodes to remove.
  1352. // @param {Batch} batch Batch to which the operation will be added.
  1353. // @param {module:engine/model/model~Model} model Model instance on which operation will be applied.
  1354. function applyRemoveOperation( position, howMany, batch, model ) {
  1355. let operation;
  1356. if ( position.root.document ) {
  1357. const doc = model.document;
  1358. const graveyardPosition = new Position( doc.graveyard, [ 0 ] );
  1359. operation = new MoveOperation( position, howMany, graveyardPosition, doc.version );
  1360. } else {
  1361. operation = new DetachOperation( position, howMany );
  1362. }
  1363. batch.addOperation( operation );
  1364. model.applyOperation( operation );
  1365. }
  1366. // Returns `true` if both root elements are the same element or both are documents root elements.
  1367. //
  1368. // Elements in the same tree can be moved (for instance you can move element form one documents root to another, or
  1369. // within the same document fragment), but when element supposed to be moved from document fragment to the document, or
  1370. // to another document it should be removed and inserted to avoid problems with OT. This is because features like undo or
  1371. // collaboration may track changes on the document but ignore changes on detached fragments and should not get
  1372. // unexpected `move` operation.
  1373. function isSameTree( rootA, rootB ) {
  1374. // If it is the same root this is the same tree.
  1375. if ( rootA === rootB ) {
  1376. return true;
  1377. }
  1378. // If both roots are documents root it is operation within the document what we still treat as the same tree.
  1379. if ( rootA instanceof RootElement && rootB instanceof RootElement ) {
  1380. return true;
  1381. }
  1382. return false;
  1383. }