model.js 36 KB

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