writer.js 58 KB

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