model.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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/model
  7. */
  8. import Batch from './batch';
  9. import Writer from './writer';
  10. import Schema from './schema';
  11. import Document from './document';
  12. import MarkerCollection from './markercollection';
  13. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  14. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  15. import ModelElement from './element';
  16. import ModelRange from './range';
  17. import ModelPosition from './position';
  18. import ModelSelection from './selection';
  19. import OperationFactory from './operation/operationfactory';
  20. import insertContent from './utils/insertcontent';
  21. import deleteContent from './utils/deletecontent';
  22. import modifySelection from './utils/modifyselection';
  23. import getSelectedContent from './utils/getselectedcontent';
  24. import { injectSelectionPostFixer } from './utils/selection-post-fixer';
  25. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  26. // @if CK_DEBUG_ENGINE // const { dumpTrees } = require( '../dev-utils/utils' );
  27. // @if CK_DEBUG_ENGINE // const { OperationReplayer } = require( '../dev-utils/operationreplayer' ).default;
  28. /**
  29. * Editor's data model. Read about the model in the
  30. * {@glink framework/guides/architecture/editing-engine engine architecture guide}.
  31. *
  32. * @mixes module:utils/observablemixin~ObservableMixin
  33. */
  34. export default class Model {
  35. constructor() {
  36. /**
  37. * Model's marker collection.
  38. *
  39. * @readonly
  40. * @member {module:engine/model/markercollection~MarkerCollection}
  41. */
  42. this.markers = new MarkerCollection();
  43. /**
  44. * Model's document.
  45. *
  46. * @readonly
  47. * @member {module:engine/model/document~Document}
  48. */
  49. this.document = new Document( this );
  50. /**
  51. * Model's schema.
  52. *
  53. * @readonly
  54. * @member {module:engine/model/schema~Schema}
  55. */
  56. this.schema = new Schema();
  57. /**
  58. * All callbacks added by {@link module:engine/model/model~Model#change} or
  59. * {@link module:engine/model/model~Model#enqueueChange} methods waiting to be executed.
  60. *
  61. * @private
  62. * @type {Array.<Function>}
  63. */
  64. this._pendingChanges = [];
  65. /**
  66. * The last created and currently used writer instance.
  67. *
  68. * @private
  69. * @member {module:engine/model/writer~Writer}
  70. */
  71. this._currentWriter = null;
  72. [ 'insertContent', 'deleteContent', 'modifySelection', 'getSelectedContent', 'applyOperation' ]
  73. .forEach( methodName => this.decorate( methodName ) );
  74. // Adding operation validation with `highest` priority, so it is called before any other feature would like
  75. // to do anything with the operation. If the operation has incorrect parameters it should throw on the earliest occasion.
  76. this.on( 'applyOperation', ( evt, args ) => {
  77. const operation = args[ 0 ];
  78. operation._validate();
  79. }, { priority: 'highest' } );
  80. // Register some default abstract entities.
  81. this.schema.register( '$root', {
  82. isLimit: true
  83. } );
  84. this.schema.register( '$block', {
  85. allowIn: '$root',
  86. isBlock: true
  87. } );
  88. this.schema.register( '$text', {
  89. allowIn: '$block',
  90. isInline: true,
  91. isContent: true
  92. } );
  93. this.schema.register( '$clipboardHolder', {
  94. allowContentOf: '$root',
  95. isLimit: true
  96. } );
  97. this.schema.extend( '$text', { allowIn: '$clipboardHolder' } );
  98. // An element needed by the `upcastElementToMarker` converter.
  99. // This element temporarily represents a marker boundary during the conversion process and is removed
  100. // at the end of the conversion. `UpcastDispatcher` or at least `Conversion` class looks like a
  101. // better place for this registration but both know nothing about `Schema`.
  102. this.schema.register( '$marker' );
  103. this.schema.addChildCheck( ( context, childDefinition ) => {
  104. if ( childDefinition.name === '$marker' ) {
  105. return true;
  106. }
  107. } );
  108. injectSelectionPostFixer( this );
  109. // @if CK_DEBUG_ENGINE // this.on( 'applyOperation', () => {
  110. // @if CK_DEBUG_ENGINE // dumpTrees( this.document, this.document.version );
  111. // @if CK_DEBUG_ENGINE // }, { priority: 'lowest' } );
  112. }
  113. /**
  114. * The `change()` method is the primary way of changing the model. You should use it to modify all document nodes
  115. * (including detached nodes – i.e. nodes not added to the {@link module:engine/model/model~Model#document model document}),
  116. * the {@link module:engine/model/document~Document#selection document's selection}, and
  117. * {@link module:engine/model/model~Model#markers model markers}.
  118. *
  119. * model.change( writer => {
  120. * writer.insertText( 'foo', paragraph, 'end' );
  121. * } );
  122. *
  123. * All changes inside the change block use the same {@link module:engine/model/batch~Batch} so they are combined
  124. * into a single undo step.
  125. *
  126. * model.change( writer => {
  127. * writer.insertText( 'foo', paragraph, 'end' ); // foo.
  128. *
  129. * model.change( writer => {
  130. * writer.insertText( 'bar', paragraph, 'end' ); // foobar.
  131. * } );
  132. *
  133. * writer.insertText( 'bom', paragraph, 'end' ); // foobarbom.
  134. * } );
  135. *
  136. * The callback of the `change()` block is executed synchronously.
  137. *
  138. * You can also return a value from the change block.
  139. *
  140. * const img = model.change( writer => {
  141. * return writer.createElement( 'img' );
  142. * } );
  143. *
  144. * @see #enqueueChange
  145. * @param {Function} callback Callback function which may modify the model.
  146. * @returns {*} Value returned by the callback.
  147. */
  148. change( callback ) {
  149. try {
  150. if ( this._pendingChanges.length === 0 ) {
  151. // If this is the outermost block, create a new batch and start `_runPendingChanges` execution flow.
  152. this._pendingChanges.push( { batch: new Batch(), callback } );
  153. return this._runPendingChanges()[ 0 ];
  154. } else {
  155. // If this is not the outermost block, just execute the callback.
  156. return callback( this._currentWriter );
  157. }
  158. } catch ( err ) {
  159. // @if CK_DEBUG // throw err;
  160. /* istanbul ignore next */
  161. CKEditorError.rethrowUnexpectedError( err, this );
  162. }
  163. }
  164. /**
  165. * The `enqueueChange()` method performs similar task as the {@link #change `change()` method}, with two major differences.
  166. *
  167. * First, the callback of `enqueueChange()` is executed when all other enqueued changes are done. It might be executed
  168. * immediately if it is not nested in any other change block, but if it is nested in another (enqueue)change block,
  169. * it will be delayed and executed after the outermost block.
  170. *
  171. * model.change( writer => {
  172. * console.log( 1 );
  173. *
  174. * model.enqueueChange( writer => {
  175. * console.log( 2 );
  176. * } );
  177. *
  178. * console.log( 3 );
  179. * } ); // Will log: 1, 3, 2.
  180. *
  181. * In addition to that, the changes enqueued with `enqueueChange()` will be converted separately from the changes
  182. * done in the outer `change()` block.
  183. *
  184. * Second, it lets you define the {@link module:engine/model/batch~Batch} into which you want to add your changes.
  185. * By default, a new batch is created. In the sample above, `change` and `enqueueChange` blocks use a different
  186. * batch (and different {@link module:engine/model/writer~Writer} since each of them operates on the separate batch).
  187. *
  188. * When using the `enqueueChange()` block you can also add some changes to the batch you used before.
  189. *
  190. * model.enqueueChange( batch, writer => {
  191. * writer.insertText( 'foo', paragraph, 'end' );
  192. * } );
  193. *
  194. * In order to make a nested `enqueueChange()` create a single undo step together with the changes done in the outer `change()`
  195. * block, you can obtain the batch instance from the {@link module:engine/model/writer~Writer#batch writer} of the outer block.
  196. *
  197. * @param {module:engine/model/batch~Batch|'transparent'|'default'} batchOrType Batch or batch type should be used in the callback.
  198. * If not defined, a new batch will be created.
  199. * @param {Function} callback Callback function which may modify the model.
  200. */
  201. enqueueChange( batchOrType, callback ) {
  202. try {
  203. if ( typeof batchOrType === 'string' ) {
  204. batchOrType = new Batch( batchOrType );
  205. } else if ( typeof batchOrType == 'function' ) {
  206. callback = batchOrType;
  207. batchOrType = new Batch();
  208. }
  209. this._pendingChanges.push( { batch: batchOrType, callback } );
  210. if ( this._pendingChanges.length == 1 ) {
  211. this._runPendingChanges();
  212. }
  213. } catch ( err ) {
  214. // @if CK_DEBUG // throw err;
  215. /* istanbul ignore next */
  216. CKEditorError.rethrowUnexpectedError( err, this );
  217. }
  218. }
  219. /**
  220. * {@link module:utils/observablemixin~ObservableMixin#decorate Decorated} function for applying
  221. * {@link module:engine/model/operation/operation~Operation operations} to the model.
  222. *
  223. * This is a low-level way of changing the model. It is exposed for very specific use cases (like the undo feature).
  224. * Normally, to modify the model, you will want to use {@link module:engine/model/writer~Writer `Writer`}.
  225. * See also {@glink framework/guides/architecture/editing-engine#changing-the-model Changing the model} section
  226. * of the {@glink framework/guides/architecture/editing-engine Editing architecture} guide.
  227. *
  228. * @param {module:engine/model/operation/operation~Operation} operation The operation to apply.
  229. */
  230. applyOperation( operation ) {
  231. // @if CK_DEBUG_ENGINE // console.log( 'Applying ' + operation );
  232. // @if CK_DEBUG_ENGINE // if ( !this._operationLogs ) {
  233. // @if CK_DEBUG_ENGINE // this._operationLogs = [];
  234. // @if CK_DEBUG_ENGINE // }
  235. // @if CK_DEBUG_ENGINE // this._operationLogs.push( JSON.stringify( operation ) );
  236. // @if CK_DEBUG_ENGINE //if ( !this._appliedOperations ) {
  237. // @if CK_DEBUG_ENGINE // this._appliedOperations = [];
  238. // @if CK_DEBUG_ENGINE //}
  239. // @if CK_DEBUG_ENGINE //this._appliedOperations.push( operation );
  240. operation._execute();
  241. }
  242. // @if CK_DEBUG_ENGINE // getAppliedOperation() {
  243. // @if CK_DEBUG_ENGINE // if ( !this._appliedOperations ) {
  244. // @if CK_DEBUG_ENGINE // return '';
  245. // @if CK_DEBUG_ENGINE // }
  246. // @if CK_DEBUG_ENGINE // return this._appliedOperations.map( JSON.stringify ).join( '-------' );
  247. // @if CK_DEBUG_ENGINE // }
  248. // @if CK_DEBUG_ENGINE // createReplayer( stringifiedOperations ) {
  249. // @if CK_DEBUG_ENGINE // return new OperationReplayer( this, '-------', stringifiedOperations );
  250. // @if CK_DEBUG_ENGINE // }
  251. /**
  252. * Inserts content at the position in the editor specified by the selection, as one would expect the paste
  253. * functionality to work.
  254. *
  255. * This is a high-level method. It takes the {@link #schema schema} into consideration when inserting
  256. * the content, clears the given selection's content before inserting nodes and moves the selection
  257. * to its target position at the end of the process.
  258. * It can split elements, merge them, wrap bare text nodes with paragraphs, etc. &mdash; just like the
  259. * pasting feature should do.
  260. *
  261. * For lower-level methods see {@link module:engine/model/writer~Writer `Writer`}.
  262. *
  263. * This method, unlike {@link module:engine/model/writer~Writer `Writer`}'s methods, does not have to be used
  264. * inside a {@link #change `change()` block}.
  265. *
  266. * # Conversion and schema
  267. *
  268. * Inserting elements and text nodes into the model is not enough to make CKEditor 5 render that content
  269. * to the user. CKEditor 5 implements a model-view-controller architecture and what `model.insertContent()` does
  270. * is only adding nodes to the model. Additionally, you need to define
  271. * {@glink framework/guides/architecture/editing-engine#conversion converters} between the model and view
  272. * and define those nodes in the {@glink framework/guides/architecture/editing-engine#schema schema}.
  273. *
  274. * So, while this method may seem similar to CKEditor 4 `editor.insertHtml()` (in fact, both methods
  275. * are used for paste-like content insertion), the CKEditor 5 method cannot be use to insert arbitrary HTML
  276. * unless converters are defined for all elements and attributes in that HTML.
  277. *
  278. * # Examples
  279. *
  280. * Using `insertContent()` with a manually created model structure:
  281. *
  282. * // Let's create a document fragment containing such content as:
  283. * //
  284. * // <paragraph>foo</paragraph>
  285. * // <blockQuote>
  286. * // <paragraph>bar</paragraph>
  287. * // </blockQuote>
  288. * const docFrag = editor.model.change( writer => {
  289. * const p1 = writer.createElement( 'paragraph' );
  290. * const p2 = writer.createElement( 'paragraph' );
  291. * const blockQuote = writer.createElement( 'blockQuote' );
  292. * const docFrag = writer.createDocumentFragment();
  293. *
  294. * writer.append( p1, docFrag );
  295. * writer.append( blockQuote, docFrag );
  296. * writer.append( p2, blockQuote );
  297. * writer.insertText( 'foo', p1 );
  298. * writer.insertText( 'bar', p2 );
  299. *
  300. * return docFrag;
  301. * } );
  302. *
  303. * // insertContent() does not have to be used in a change() block. It can, though,
  304. * // so this code could be moved to the callback defined above.
  305. * editor.model.insertContent( docFrag );
  306. *
  307. * Using `insertContent()` with an HTML string converted to a model document fragment (similar to the pasting mechanism):
  308. *
  309. * // You can create your own HtmlDataProcessor instance or use editor.data.processor
  310. * // if you have not overridden the default one (which is the HtmlDataProcessor instance).
  311. * const htmlDP = new HtmlDataProcessor( viewDocument );
  312. *
  313. * // Convert an HTML string to a view document fragment:
  314. * const viewFragment = htmlDP.toView( htmlString );
  315. *
  316. * // Convert the view document fragment to a model document fragment
  317. * // in the context of $root. This conversion takes the schema into
  318. * // account so if, for example, the view document fragment contained a bare text node,
  319. * // this text node cannot be a child of $root, so it will be automatically
  320. * // wrapped with a <paragraph>. You can define the context yourself (in the second parameter),
  321. * // and e.g. convert the content like it would happen in a <paragraph>.
  322. * // Note: The clipboard feature uses a custom context called $clipboardHolder
  323. * // which has a loosened schema.
  324. * const modelFragment = editor.data.toModel( viewFragment );
  325. *
  326. * editor.model.insertContent( modelFragment );
  327. *
  328. * By default this method will use the document selection but it can also be used with a position, range or selection instance.
  329. *
  330. * // Insert text at the current document selection position.
  331. * editor.model.change( writer => {
  332. * editor.model.insertContent( writer.createText( 'x' ) );
  333. * } );
  334. *
  335. * // Insert text at a given position - the document selection will not be modified.
  336. * editor.model.change( writer => {
  337. * editor.model.insertContent( writer.createText( 'x' ), doc.getRoot(), 2 );
  338. *
  339. * // Which is a shorthand for:
  340. * editor.model.insertContent( writer.createText( 'x' ), writer.createPositionAt( doc.getRoot(), 2 ) );
  341. * } );
  342. *
  343. * If you want the document selection to be moved to the inserted content, use the
  344. * {@link module:engine/model/writer~Writer#setSelection `setSelection()`} method of the writer after inserting
  345. * the content:
  346. *
  347. * editor.model.change( writer => {
  348. * const paragraph = writer.createElement( 'paragraph' );
  349. *
  350. * // Insert an empty paragraph at the beginning of the root.
  351. * editor.model.insertContent( paragraph, writer.createPositionAt( editor.model.document.getRoot(), 0 ) );
  352. *
  353. * // Move the document selection to the inserted paragraph.
  354. * writer.setSelection( paragraph, 'in' );
  355. * } );
  356. *
  357. * If an instance of the {@link module:engine/model/selection~Selection model selection} is passed as `selectable`,
  358. * the new content will be inserted at the passed selection (instead of document selection):
  359. *
  360. * editor.model.change( writer => {
  361. * // Create a selection in a paragraph that will be used as a place of insertion.
  362. * const selection = writer.createSelection( paragraph, 'in' );
  363. *
  364. * // Insert the new text at the created selection.
  365. * editor.model.insertContent( writer.createText( 'x' ), selection );
  366. *
  367. * // insertContent() modifies the passed selection instance so it can be used to set the document selection.
  368. * // Note: This is not necessary when you passed the document selection to insertContent().
  369. * writer.setSelection( selection );
  370. * } );
  371. *
  372. * @fires insertContent
  373. * @param {module:engine/model/documentfragment~DocumentFragment|module:engine/model/item~Item} content The content to insert.
  374. * @param {module:engine/model/selection~Selectable} [selectable=model.document.selection]
  375. * The selection into which the content should be inserted. If not provided the current model document selection will be used.
  376. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] To be used when a model item was passed as `selectable`.
  377. * This param defines a position in relation to that item.
  378. * @returns {module:engine/model/range~Range} Range which contains all the performed changes. This is a range that, if removed,
  379. * would return the model to the state before the insertion. If no changes were preformed by `insertContent`, returns a range collapsed
  380. * at the insertion position.
  381. */
  382. insertContent( content, selectable, placeOrOffset ) {
  383. return insertContent( this, content, selectable, placeOrOffset );
  384. }
  385. /**
  386. * Deletes content of the selection and merge siblings. The resulting selection is always collapsed.
  387. *
  388. * **Note:** For the sake of predictability, the resulting selection should always be collapsed.
  389. * In cases where a feature wants to modify deleting behavior so selection isn't collapsed
  390. * (e.g. a table feature may want to keep row selection after pressing <kbd>Backspace</kbd>),
  391. * then that behavior should be implemented in the view's listener. At the same time, the table feature
  392. * will need to modify this method's behavior too, e.g. to "delete contents and then collapse
  393. * the selection inside the last selected cell" or "delete the row and collapse selection somewhere near".
  394. * That needs to be done in order to ensure that other features which use `deleteContent()` will work well with tables.
  395. *
  396. * @fires deleteContent
  397. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  398. * Selection of which the content should be deleted.
  399. * @param {Object} [options]
  400. * @param {Boolean} [options.leaveUnmerged=false] Whether to merge elements after removing the content of the selection.
  401. *
  402. * For example `<heading1>x[x</heading1><paragraph>y]y</paragraph>` will become:
  403. *
  404. * * `<heading1>x^y</heading1>` with the option disabled (`leaveUnmerged == false`)
  405. * * `<heading1>x^</heading1><paragraph>y</paragraph>` with enabled (`leaveUnmerged == true`).
  406. *
  407. * Note: {@link module:engine/model/schema~Schema#isObject object} and {@link module:engine/model/schema~Schema#isLimit limit}
  408. * elements will not be merged.
  409. *
  410. * @param {Boolean} [options.doNotResetEntireContent=false] Whether to skip replacing the entire content with a
  411. * paragraph when the entire content was selected.
  412. *
  413. * For example `<heading1>[x</heading1><paragraph>y]</paragraph>` will become:
  414. *
  415. * * `<paragraph>^</paragraph>` with the option disabled (`doNotResetEntireContent == false`)
  416. * * `<heading1>^</heading1>` with enabled (`doNotResetEntireContent == true`)
  417. *
  418. * @param {Boolean} [options.doNotAutoparagraph=false] Whether to create a paragraph if after content deletion selection is moved
  419. * to a place where text cannot be inserted.
  420. *
  421. * For example `<paragraph>x</paragraph>[<image src="foo.jpg"></image>]` will become:
  422. *
  423. * * `<paragraph>x</paragraph><paragraph>[]</paragraph>` with the option disabled (`doNotAutoparagraph == false`)
  424. * * `<paragraph>x[]</paragraph>` with the option enabled (`doNotAutoparagraph == true`).
  425. *
  426. * **Note:** if there is no valid position for the selection, the paragraph will always be created:
  427. *
  428. * `[<image src="foo.jpg"></image>]` -> `<paragraph>[]</paragraph>`.
  429. *
  430. * @param {'forward'|'backward'} [options.direction='backward'] The direction in which the content is being consumed.
  431. * Deleting backward corresponds to using the <kbd>Backspace</kbd> key, while deleting content forward corresponds to
  432. * the <kbd>Shift</kbd>+<kbd>Backspace</kbd> keystroke.
  433. */
  434. deleteContent( selection, options ) {
  435. deleteContent( this, selection, options );
  436. }
  437. /**
  438. * Modifies the selection. Currently, the supported modifications are:
  439. *
  440. * * Extending. The selection focus is moved in the specified `options.direction` with a step specified in `options.unit`.
  441. * Possible values for `unit` are:
  442. * * `'character'` (default) - moves selection by one user-perceived character. In most cases this means moving by one
  443. * character in `String` sense. However, unicode also defines "combing marks". These are special symbols, that combines
  444. * with a symbol before it ("base character") to create one user-perceived character. For example, `q̣̇` is a normal
  445. * letter `q` with two "combining marks": upper dot (`Ux0307`) and lower dot (`Ux0323`). For most actions, i.e. extending
  446. * selection by one position, it is correct to include both "base character" and all of it's "combining marks". That is
  447. * why `'character'` value is most natural and common method of modifying selection.
  448. * * `'codePoint'` - moves selection by one unicode code point. In contrary to, `'character'` unit, this will insert
  449. * selection between "base character" and "combining mark", because "combining marks" have their own unicode code points.
  450. * However, for technical reasons, unicode code points with values above `UxFFFF` are represented in native `String` by
  451. * two characters, called "surrogate pairs". Halves of "surrogate pairs" have a meaning only when placed next to each other.
  452. * For example `𨭎` is represented in `String` by `\uD862\uDF4E`. Both `\uD862` and `\uDF4E` do not have any meaning
  453. * outside the pair (are rendered as ? when alone). Position between them would be incorrect. In this case, selection
  454. * extension will include whole "surrogate pair".
  455. * * `'word'` - moves selection by a whole word.
  456. *
  457. * **Note:** if you extend a forward selection in a backward direction you will in fact shrink it.
  458. *
  459. * @fires modifySelection
  460. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  461. * The selection to modify.
  462. * @param {Object} [options]
  463. * @param {'forward'|'backward'} [options.direction='forward'] The direction in which the selection should be modified.
  464. * @param {'character'|'codePoint'|'word'} [options.unit='character'] The unit by which selection should be modified.
  465. */
  466. modifySelection( selection, options ) {
  467. modifySelection( this, selection, options );
  468. }
  469. /**
  470. * Gets a clone of the selected content.
  471. *
  472. * For example, for the following selection:
  473. *
  474. * ```html
  475. * <paragraph>x</paragraph>
  476. * <blockQuote>
  477. * <paragraph>y</paragraph>
  478. * <heading1>fir[st</heading1>
  479. * </blockQuote>
  480. * <paragraph>se]cond</paragraph>
  481. * <paragraph>z</paragraph>
  482. * ```
  483. *
  484. * It will return a document fragment with such a content:
  485. *
  486. * ```html
  487. * <blockQuote>
  488. * <heading1>st</heading1>
  489. * </blockQuote>
  490. * <paragraph>se</paragraph>
  491. * ```
  492. *
  493. * @fires getSelectedContent
  494. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  495. * The selection of which content will be returned.
  496. * @returns {module:engine/model/documentfragment~DocumentFragment}
  497. */
  498. getSelectedContent( selection ) {
  499. return getSelectedContent( this, selection );
  500. }
  501. /**
  502. * Checks whether the given {@link module:engine/model/range~Range range} or
  503. * {@link module:engine/model/element~Element element} has any meaningful content.
  504. *
  505. * Meaningful content is:
  506. *
  507. * * any text node (`options.ignoreWhitespaces` allows controlling whether this text node must also contain
  508. * any non-whitespace characters),
  509. * * or any {@link module:engine/model/schema~Schema#isContent content element},
  510. * * or any {@link module:engine/model/markercollection~Marker marker} which
  511. * {@link module:engine/model/markercollection~Marker#_affectsData affects data}.
  512. *
  513. * This means that a range containing an empty `<paragraph></paragraph>` is not considered to have a meaningful content.
  514. * However, a range containing an `<image></image>` (which would normally be marked in the schema as an object element)
  515. * is considered non-empty.
  516. *
  517. * @param {module:engine/model/range~Range|module:engine/model/element~Element} rangeOrElement Range or element to check.
  518. * @param {Object} [options]
  519. * @param {Boolean} [options.ignoreWhitespaces] Whether text node with whitespaces only should be considered empty.
  520. * @param {Boolean} [options.ignoreMarkers] Whether markers should be ignored.
  521. * @returns {Boolean}
  522. */
  523. hasContent( rangeOrElement, options = {} ) {
  524. const range = rangeOrElement instanceof ModelElement ? ModelRange._createIn( rangeOrElement ) : rangeOrElement;
  525. if ( range.isCollapsed ) {
  526. return false;
  527. }
  528. const { ignoreWhitespaces = false, ignoreMarkers = false } = options;
  529. // Check if there are any markers which affects data in this given range.
  530. if ( !ignoreMarkers ) {
  531. for ( const intersectingMarker of this.markers.getMarkersIntersectingRange( range ) ) {
  532. if ( intersectingMarker.affectsData ) {
  533. return true;
  534. }
  535. }
  536. }
  537. for ( const item of range.getItems() ) {
  538. if ( this.schema.isContent( item ) ) {
  539. if ( item.is( '$textProxy' ) ) {
  540. if ( !ignoreWhitespaces ) {
  541. return true;
  542. } else if ( item.data.search( /\S/ ) !== -1 ) {
  543. return true;
  544. }
  545. } else {
  546. return true;
  547. }
  548. }
  549. }
  550. return false;
  551. }
  552. /**
  553. * Creates a position from the given root and path in that root.
  554. *
  555. * Note: This method is also available as
  556. * {@link module:engine/model/writer~Writer#createPositionFromPath `Writer#createPositionFromPath()`}.
  557. *
  558. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} root Root of the position.
  559. * @param {Array.<Number>} path Position path. See {@link module:engine/model/position~Position#path}.
  560. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
  561. * See {@link module:engine/model/position~PositionStickiness}.
  562. * @returns {module:engine/model/position~Position}
  563. */
  564. createPositionFromPath( root, path, stickiness ) {
  565. return new ModelPosition( root, path, stickiness );
  566. }
  567. /**
  568. * Creates position at the given location. The location can be specified as:
  569. *
  570. * * a {@link module:engine/model/position~Position position},
  571. * * a parent element and offset in that element,
  572. * * a parent element and `'end'` (the position will be set at the end of that element),
  573. * * a {@link module:engine/model/item~Item model item} and `'before'` or `'after'`
  574. * (the position will be set before or after the given model item).
  575. *
  576. * This method is a shortcut to other factory methods such as:
  577. *
  578. * * {@link module:engine/model/model~Model#createPositionBefore `createPositionBefore()`},
  579. * * {@link module:engine/model/model~Model#createPositionAfter `createPositionAfter()`}.
  580. *
  581. * Note: This method is also available as
  582. * {@link module:engine/model/writer~Writer#createPositionAt `Writer#createPositionAt()`},
  583. *
  584. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  585. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
  586. * first parameter is a {@link module:engine/model/item~Item model item}.
  587. */
  588. createPositionAt( itemOrPosition, offset ) {
  589. return ModelPosition._createAt( itemOrPosition, offset );
  590. }
  591. /**
  592. * Creates a new position after the given {@link module:engine/model/item~Item model item}.
  593. *
  594. * Note: This method is also available as
  595. * {@link module:engine/model/writer~Writer#createPositionAfter `Writer#createPositionAfter()`}.
  596. *
  597. * @param {module:engine/model/item~Item} item Item after which the position should be placed.
  598. * @returns {module:engine/model/position~Position}
  599. */
  600. createPositionAfter( item ) {
  601. return ModelPosition._createAfter( item );
  602. }
  603. /**
  604. * Creates a new position before the given {@link module:engine/model/item~Item model item}.
  605. *
  606. * Note: This method is also available as
  607. * {@link module:engine/model/writer~Writer#createPositionBefore `Writer#createPositionBefore()`}.
  608. *
  609. * @param {module:engine/model/item~Item} item Item before which the position should be placed.
  610. * @returns {module:engine/model/position~Position}
  611. */
  612. createPositionBefore( item ) {
  613. return ModelPosition._createBefore( item );
  614. }
  615. /**
  616. * Creates a range spanning from the `start` position to the `end` position.
  617. *
  618. * Note: This method is also available as
  619. * {@link module:engine/model/writer~Writer#createRange `Writer#createRange()`}:
  620. *
  621. * model.change( writer => {
  622. * const range = writer.createRange( start, end );
  623. * } );
  624. *
  625. * @param {module:engine/model/position~Position} start Start position.
  626. * @param {module:engine/model/position~Position} [end] End position. If not set, the range will be collapsed
  627. * to the `start` position.
  628. * @returns {module:engine/model/range~Range}
  629. */
  630. createRange( start, end ) {
  631. return new ModelRange( start, end );
  632. }
  633. /**
  634. * Creates a range inside the given element which starts before the first child of
  635. * that element and ends after the last child of that element.
  636. *
  637. * Note: This method is also available as
  638. * {@link module:engine/model/writer~Writer#createRangeIn `Writer#createRangeIn()`}:
  639. *
  640. * model.change( writer => {
  641. * const range = writer.createRangeIn( paragraph );
  642. * } );
  643. *
  644. * @param {module:engine/model/element~Element} element Element which is a parent for the range.
  645. * @returns {module:engine/model/range~Range}
  646. */
  647. createRangeIn( element ) {
  648. return ModelRange._createIn( element );
  649. }
  650. /**
  651. * Creates a range that starts before the given {@link module:engine/model/item~Item model item} and ends after it.
  652. *
  653. * Note: This method is also available on `writer` instance as
  654. * {@link module:engine/model/writer~Writer#createRangeOn `Writer.createRangeOn()`}:
  655. *
  656. * model.change( writer => {
  657. * const range = writer.createRangeOn( paragraph );
  658. * } );
  659. *
  660. * @param {module:engine/model/item~Item} item
  661. * @returns {module:engine/model/range~Range}
  662. */
  663. createRangeOn( item ) {
  664. return ModelRange._createOn( item );
  665. }
  666. /**
  667. * Creates a new selection instance based on the given {@link module:engine/model/selection~Selectable selectable}
  668. * or creates an empty selection if no arguments were passed.
  669. *
  670. * Note: This method is also available as
  671. * {@link module:engine/model/writer~Writer#createSelection `Writer#createSelection()`}.
  672. *
  673. * // Creates empty selection without ranges.
  674. * const selection = writer.createSelection();
  675. *
  676. * // Creates selection at the given range.
  677. * const range = writer.createRange( start, end );
  678. * const selection = writer.createSelection( range );
  679. *
  680. * // Creates selection at the given ranges
  681. * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
  682. * const selection = writer.createSelection( ranges );
  683. *
  684. * // Creates selection from the other selection.
  685. * // Note: It doesn't copies selection attributes.
  686. * const otherSelection = writer.createSelection();
  687. * const selection = writer.createSelection( otherSelection );
  688. *
  689. * // Creates selection from the given document selection.
  690. * // Note: It doesn't copies selection attributes.
  691. * const documentSelection = model.document.selection;
  692. * const selection = writer.createSelection( documentSelection );
  693. *
  694. * // Creates selection at the given position.
  695. * const position = writer.createPositionFromPath( root, path );
  696. * const selection = writer.createSelection( position );
  697. *
  698. * // Creates selection at the given offset in the given element.
  699. * const paragraph = writer.createElement( 'paragraph' );
  700. * const selection = writer.createSelection( paragraph, offset );
  701. *
  702. * // Creates a range inside an {@link module:engine/model/element~Element element} which starts before the
  703. * // first child of that element and ends after the last child of that element.
  704. * const selection = writer.createSelection( paragraph, 'in' );
  705. *
  706. * // Creates a range on an {@link module:engine/model/item~Item item} which starts before the item and ends
  707. * // just after the item.
  708. * const selection = writer.createSelection( paragraph, 'on' );
  709. *
  710. * // Additional options (`'backward'`) can be specified as the last argument.
  711. *
  712. * // Creates backward selection.
  713. * const selection = writer.createSelection( range, { backward: true } );
  714. *
  715. * @param {module:engine/model/selection~Selectable} selectable
  716. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
  717. * @param {Object} [options]
  718. * @param {Boolean} [options.backward] Sets this selection instance to be backward.
  719. * @returns {module:engine/model/selection~Selection}
  720. */
  721. createSelection( selectable, placeOrOffset, options ) {
  722. return new ModelSelection( selectable, placeOrOffset, options );
  723. }
  724. /**
  725. * Creates a {@link module:engine/model/batch~Batch} instance.
  726. *
  727. * **Note:** In most cases creating a batch instance is not necessary as they are created when using:
  728. *
  729. * * {@link #change `change()`},
  730. * * {@link #enqueueChange `enqueueChange()`}.
  731. *
  732. * @param {'transparent'|'default'} [type='default'] The type of the batch.
  733. * @returns {module:engine/model/batch~Batch}
  734. */
  735. createBatch( type ) {
  736. return new Batch( type );
  737. }
  738. /**
  739. * Creates an operation instance from a JSON object (parsed JSON string).
  740. *
  741. * This is an alias for {@link module:engine/model/operation/operationfactory~OperationFactory.fromJSON `OperationFactory.fromJSON()`}.
  742. *
  743. * @param {Object} json Deserialized JSON object.
  744. * @returns {module:engine/model/operation/operation~Operation}
  745. */
  746. createOperationFromJSON( json ) {
  747. return OperationFactory.fromJSON( json, this.document );
  748. }
  749. /**
  750. * Removes all events listeners set by model instance and destroys {@link module:engine/model/document~Document}.
  751. */
  752. destroy() {
  753. this.document.destroy();
  754. this.stopListening();
  755. }
  756. /**
  757. * Common part of {@link module:engine/model/model~Model#change} and {@link module:engine/model/model~Model#enqueueChange}
  758. * which calls callbacks and returns array of values returned by these callbacks.
  759. *
  760. * @private
  761. * @returns {Array.<*>} Array of values returned by callbacks.
  762. */
  763. _runPendingChanges() {
  764. const ret = [];
  765. this.fire( '_beforeChanges' );
  766. while ( this._pendingChanges.length ) {
  767. // Create a new writer using batch instance created for this chain of changes.
  768. const currentBatch = this._pendingChanges[ 0 ].batch;
  769. this._currentWriter = new Writer( this, currentBatch );
  770. // Execute changes callback and gather the returned value.
  771. const callbackReturnValue = this._pendingChanges[ 0 ].callback( this._currentWriter );
  772. ret.push( callbackReturnValue );
  773. this.document._handleChangeBlock( this._currentWriter );
  774. this._pendingChanges.shift();
  775. this._currentWriter = null;
  776. }
  777. this.fire( '_afterChanges' );
  778. return ret;
  779. }
  780. /**
  781. * Fired when entering the outermost {@link module:engine/model/model~Model#enqueueChange} or
  782. * {@link module:engine/model/model~Model#change} block.
  783. *
  784. * @protected
  785. * @event _beforeChanges
  786. */
  787. /**
  788. * Fired when leaving the outermost {@link module:engine/model/model~Model#enqueueChange} or
  789. * {@link module:engine/model/model~Model#change} block.
  790. *
  791. * @protected
  792. * @event _afterChanges
  793. */
  794. /**
  795. * Fired every time any {@link module:engine/model/operation/operation~Operation operation} is applied on the model
  796. * using {@link #applyOperation}.
  797. *
  798. * Note that this event is suitable only for very specific use-cases. Use it if you need to listen to every single operation
  799. * applied on the document. However, in most cases {@link module:engine/model/document~Document#event:change} should
  800. * be used.
  801. *
  802. * A few callbacks are already added to this event by engine internal classes:
  803. *
  804. * * with `highest` priority operation is validated,
  805. * * with `normal` priority operation is executed,
  806. * * with `low` priority the {@link module:engine/model/document~Document} updates its version,
  807. * * with `low` priority {@link module:engine/model/liveposition~LivePosition} and {@link module:engine/model/liverange~LiveRange}
  808. * update themselves.
  809. *
  810. * @event applyOperation
  811. * @param {Array} args Arguments of the `applyOperation` which is an array with a single element - applied
  812. * {@link module:engine/model/operation/operation~Operation operation}.
  813. */
  814. /**
  815. * Event fired when {@link #insertContent} method is called.
  816. *
  817. * The {@link #insertContent default action of that method} is implemented as a
  818. * listener to this event so it can be fully customized by the features.
  819. *
  820. * **Note** The `selectable` parameter for the {@link #insertContent} is optional. When `undefined` value is passed the method uses
  821. * `model.document.selection`.
  822. *
  823. * @event insertContent
  824. * @param {Array} args The arguments passed to the original method.
  825. */
  826. /**
  827. * Event fired when {@link #deleteContent} method is called.
  828. *
  829. * The {@link #deleteContent default action of that method} is implemented as a
  830. * listener to this event so it can be fully customized by the features.
  831. *
  832. * @event deleteContent
  833. * @param {Array} args The arguments passed to the original method.
  834. */
  835. /**
  836. * Event fired when {@link #modifySelection} method is called.
  837. *
  838. * The {@link #modifySelection default action of that method} is implemented as a
  839. * listener to this event so it can be fully customized by the features.
  840. *
  841. * @event modifySelection
  842. * @param {Array} args The arguments passed to the original method.
  843. */
  844. /**
  845. * Event fired when {@link #getSelectedContent} method is called.
  846. *
  847. * The {@link #getSelectedContent default action of that method} is implemented as a
  848. * listener to this event so it can be fully customized by the features.
  849. *
  850. * @event getSelectedContent
  851. * @param {Array} args The arguments passed to the original method.
  852. */
  853. }
  854. mix( Model, ObservableMixin );