8
0

model.js 38 KB

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