enableenginedebug.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/dev-utils/enableenginedebug
  7. */
  8. /* global console */
  9. import DeltaReplayer from './deltareplayer';
  10. import ModelPosition from '../model/position';
  11. import ModelRange from '../model/range';
  12. import ModelText from '../model/text';
  13. import ModelTextProxy from '../model/textproxy';
  14. import ModelElement from '../model/element';
  15. import Operation from '../model/operation/operation';
  16. import AttributeOperation from '../model/operation/attributeoperation';
  17. import DetachOperation from '../model/operation/detachoperation';
  18. import InsertOperation from '../model/operation/insertoperation';
  19. import MarkerOperation from '../model/operation/markeroperation';
  20. import MoveOperation from '../model/operation/moveoperation';
  21. import NoOperation from '../model/operation/nooperation';
  22. import RenameOperation from '../model/operation/renameoperation';
  23. import RootAttributeOperation from '../model/operation/rootattributeoperation';
  24. import Delta from '../model/delta/delta';
  25. import AttributeDelta from '../model/delta/attributedelta';
  26. import InsertDelta from '../model/delta/insertdelta';
  27. import MarkerDelta from '../model/delta/markerdelta';
  28. import MergeDelta from '../model/delta/mergedelta';
  29. import MoveDelta from '../model/delta/movedelta';
  30. import RenameDelta from '../model/delta/renamedelta';
  31. import RootAttributeDelta from '../model/delta/rootattributedelta';
  32. import SplitDelta from '../model/delta/splitdelta';
  33. import UnwrapDelta from '../model/delta/unwrapdelta';
  34. import WrapDelta from '../model/delta/wrapdelta';
  35. import deltaTransform from '../model/delta/transform';
  36. import ModelDocument from '../model/document';
  37. import ModelDocumentFragment from '../model/documentfragment';
  38. import ModelRootElement from '../model/rootelement';
  39. import ViewDocument from '../view/document';
  40. import ViewElement from '../view/element';
  41. import ViewText from '../view/text';
  42. import ViewTextProxy from '../view/textproxy';
  43. import ViewDocumentFragment from '../view/documentfragment';
  44. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  45. import Editor from '@ckeditor/ckeditor5-core/src/editor/editor';
  46. import clone from '@ckeditor/ckeditor5-utils/src/lib/lodash/clone';
  47. // Sandbox class allows creating mocks of the functions and restoring these mocks to the original values.
  48. class Sandbox {
  49. constructor() {
  50. // An array that contains functions which restore the original values of mocked objects.
  51. // @private
  52. // @type {Array.<Function>}
  53. this._restores = [];
  54. }
  55. // Creates a new mock.
  56. //
  57. // @param {Object} object Object to mock.
  58. // @param {String} methodName Function to mock.
  59. // @param {Function} fakeMethod Function that will be executed.
  60. mock( object, methodName, fakeMethod ) {
  61. const originalMethod = object[ methodName ];
  62. object[ methodName ] = fakeMethod;
  63. this._restores.unshift( () => {
  64. if ( originalMethod ) {
  65. object[ methodName ] = originalMethod;
  66. } else {
  67. delete object[ methodName ];
  68. }
  69. } );
  70. }
  71. // Restores all mocked functions.
  72. restore() {
  73. for ( const restore of this._restores ) {
  74. restore();
  75. }
  76. this._restores = [];
  77. }
  78. }
  79. const sandbox = new Sandbox();
  80. const treeDump = Symbol( '_treeDump' );
  81. // Maximum number of stored states of model and view document.
  82. const maxTreeDumpLength = 20;
  83. // Separator used to separate stringified deltas
  84. const LOG_SEPARATOR = '-------';
  85. // Specified whether debug tools were already enabled.
  86. let enabled = false;
  87. // Logging function used to log debug messages.
  88. let logger = console;
  89. /**
  90. * Enhances model classes with logging methods. Returns a plugin that should be loaded in the editor to
  91. * enable debugging features.
  92. *
  93. * Every operation applied on {@link module:engine/model/document~Document model.Document} is logged.
  94. *
  95. * Following classes are expanded with `log` and meaningful `toString` methods:
  96. * * {@link module:engine/model/position~Position model.Position},
  97. * * {@link module:engine/model/range~Range model.Range},
  98. * * {@link module:engine/model/text~Text model.Text},
  99. * * {@link module:engine/model/element~Element model.Element},
  100. * * {@link module:engine/model/rootelement~RootElement model.RootElement},
  101. * * {@link module:engine/model/documentfragment~DocumentFragment model.DocumentFragment},
  102. * * {@link module:engine/model/document~Document model.Document},
  103. * * all {@link module:engine/model/operation/operation~Operation operations}
  104. * * all {@link module:engine/model/delta/delta~Delta deltas},
  105. * * {@link module:engine/view/element~Element view.Element},
  106. * * {@link module:engine/view/documentfragment~DocumentFragment view.DocumentFragment},
  107. * * {@link module:engine/view/document~Document view.Document}.
  108. *
  109. * Additionally, following logging utility methods are added:
  110. * * {@link module:engine/model/text~Text model.Text} `logExtended`,
  111. * * {@link module:engine/model/element~Element model.Element} `logExtended`,
  112. * * {@link module:engine/model/element~Element model.Element} `logAll`,
  113. * * {@link module:engine/model/delta/delta~Delta model.Delta} `logAll`.
  114. *
  115. * Additionally, following classes are expanded with `logTree` and `printTree` methods:
  116. * * {@link module:engine/model/element~Element model.Element},
  117. * * {@link module:engine/model/documentfragment~DocumentFragment model.DocumentFragment},
  118. * * {@link module:engine/view/element~Element view.Element},
  119. * * {@link module:engine/view/documentfragment~DocumentFragment view.DocumentFragment}.
  120. *
  121. * Finally, following methods are added to {@link module:core/editor/editor~Editor}: `logModel`, `logView`, `logDocuments`.
  122. * All those methods take one parameter, which is a version of {@link module:engine/model/document~Document model document}
  123. * for which model or view document state should be logged.
  124. *
  125. * @param {Object} [_logger] Object with functions used to log messages and errors. By default messages are logged to console.
  126. * If specified, it is expected to have `log()` and `error()` methods.
  127. * @returns {module:engine/dev-utils/enableenginedebug~DebugPlugin} Plugin to be loaded in the editor.
  128. */
  129. export default function enableEngineDebug( _logger = console ) {
  130. logger = _logger;
  131. if ( !enabled ) {
  132. enabled = true;
  133. enableLoggingTools();
  134. enableDocumentTools();
  135. enableReplayerTools();
  136. }
  137. return DebugPlugin;
  138. }
  139. /**
  140. * Restores all methods that have been overwritten.
  141. */
  142. export function disableEngineDebug() {
  143. sandbox.restore();
  144. enabled = false;
  145. }
  146. function enableLoggingTools() {
  147. sandbox.mock( ModelPosition.prototype, 'toString', function() {
  148. return `${ this.root } [ ${ this.path.join( ', ' ) } ]`;
  149. } );
  150. sandbox.mock( ModelPosition.prototype, 'log', function() {
  151. logger.log( 'ModelPosition: ' + this );
  152. } );
  153. sandbox.mock( ModelRange.prototype, 'toString', function() {
  154. return `${ this.root } [ ${ this.start.path.join( ', ' ) } ] - [ ${ this.end.path.join( ', ' ) } ]`;
  155. } );
  156. sandbox.mock( ModelRange.prototype, 'log', function() {
  157. logger.log( 'ModelRange: ' + this );
  158. } );
  159. sandbox.mock( ModelText.prototype, 'toString', function() {
  160. return `#${ this.data }`;
  161. } );
  162. sandbox.mock( ModelText.prototype, 'logExtended', function() {
  163. logger.log( `ModelText: ${ this }, attrs: ${ mapString( this.getAttributes() ) }` );
  164. } );
  165. sandbox.mock( ModelText.prototype, 'log', function() {
  166. logger.log( 'ModelText: ' + this );
  167. } );
  168. sandbox.mock( ModelTextProxy.prototype, 'toString', function() {
  169. return `#${ this.data }`;
  170. } );
  171. sandbox.mock( ModelTextProxy.prototype, 'logExtended', function() {
  172. logger.log( `ModelTextProxy: ${ this }, attrs: ${ mapString( this.getAttributes() ) }` );
  173. } );
  174. sandbox.mock( ModelTextProxy.prototype, 'log', function() {
  175. logger.log( 'ModelTextProxy: ' + this );
  176. } );
  177. sandbox.mock( ModelElement.prototype, 'toString', function() {
  178. return `<${ this.rootName || this.name }>`;
  179. } );
  180. sandbox.mock( ModelElement.prototype, 'log', function() {
  181. logger.log( 'ModelElement: ' + this );
  182. } );
  183. sandbox.mock( ModelElement.prototype, 'logExtended', function() {
  184. logger.log( `ModelElement: ${ this }, ${ this.childCount } children, attrs: ${ mapString( this.getAttributes() ) }` );
  185. } );
  186. sandbox.mock( ModelElement.prototype, 'logAll', function() {
  187. logger.log( '--------------------' );
  188. this.logExtended();
  189. logger.log( 'List of children:' );
  190. for ( const child of this.getChildren() ) {
  191. child.log();
  192. }
  193. } );
  194. sandbox.mock( ModelElement.prototype, 'printTree', function( level = 0 ) {
  195. let string = '';
  196. string += '\t'.repeat( level ) + `<${ this.rootName || this.name }${ mapToTags( this.getAttributes() ) }>`;
  197. for ( const child of this.getChildren() ) {
  198. string += '\n';
  199. if ( child.is( 'text' ) ) {
  200. const textAttrs = mapToTags( child._attrs );
  201. string += '\t'.repeat( level + 1 );
  202. if ( textAttrs !== '' ) {
  203. string += `<$text${ textAttrs }>` + child.data + '</$text>';
  204. } else {
  205. string += child.data;
  206. }
  207. } else {
  208. string += child.printTree( level + 1 );
  209. }
  210. }
  211. if ( this.childCount ) {
  212. string += '\n' + '\t'.repeat( level );
  213. }
  214. string += `</${ this.rootName || this.name }>`;
  215. return string;
  216. } );
  217. sandbox.mock( ModelElement.prototype, 'logTree', function() {
  218. logger.log( this.printTree() );
  219. } );
  220. sandbox.mock( ModelRootElement.prototype, 'toString', function() {
  221. return this.rootName;
  222. } );
  223. sandbox.mock( ModelRootElement.prototype, 'log', function() {
  224. logger.log( 'ModelRootElement: ' + this );
  225. } );
  226. sandbox.mock( ModelDocumentFragment.prototype, 'toString', function() {
  227. return 'documentFragment';
  228. } );
  229. sandbox.mock( ModelDocumentFragment.prototype, 'log', function() {
  230. logger.log( 'ModelDocumentFragment: ' + this );
  231. } );
  232. sandbox.mock( ModelDocumentFragment.prototype, 'printTree', function() {
  233. let string = 'ModelDocumentFragment: [';
  234. for ( const child of this.getChildren() ) {
  235. string += '\n';
  236. if ( child.is( 'text' ) ) {
  237. const textAttrs = mapToTags( child._attrs );
  238. string += '\t'.repeat( 1 );
  239. if ( textAttrs !== '' ) {
  240. string += `<$text${ textAttrs }>` + child.data + '</$text>';
  241. } else {
  242. string += child.data;
  243. }
  244. } else {
  245. string += child.printTree( 1 );
  246. }
  247. }
  248. string += '\n]';
  249. return string;
  250. } );
  251. sandbox.mock( ModelDocumentFragment.prototype, 'logTree', function() {
  252. logger.log( this.printTree() );
  253. } );
  254. sandbox.mock( Operation.prototype, 'log', function() {
  255. logger.log( this.toString() );
  256. } );
  257. sandbox.mock( AttributeOperation.prototype, 'toString', function() {
  258. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  259. `"${ this.key }": ${ JSON.stringify( this.oldValue ) } -> ${ JSON.stringify( this.newValue ) }, ${ this.range }`;
  260. } );
  261. sandbox.mock( DetachOperation.prototype, 'toString', function() {
  262. const range = ModelRange.createFromPositionAndShift( this.sourcePosition, this.howMany );
  263. const nodes = Array.from( range.getItems() );
  264. const nodeString = nodes.length > 1 ? `[ ${ nodes.length } ]` : nodes[ 0 ];
  265. return getClassName( this ) + `( ${ this.baseVersion } ): ${ nodeString } -> ${ range }`;
  266. } );
  267. sandbox.mock( InsertOperation.prototype, 'toString', function() {
  268. const nodeString = this.nodes.length > 1 ? `[ ${ this.nodes.length } ]` : this.nodes.getNode( 0 );
  269. return getClassName( this ) + `( ${ this.baseVersion } ): ${ nodeString } -> ${ this.position }`;
  270. } );
  271. sandbox.mock( MarkerOperation.prototype, 'toString', function() {
  272. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  273. `"${ this.name }": ${ this.oldRange } -> ${ this.newRange }`;
  274. } );
  275. sandbox.mock( MoveOperation.prototype, 'toString', function() {
  276. const range = ModelRange.createFromPositionAndShift( this.sourcePosition, this.howMany );
  277. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  278. `${ range } -> ${ this.targetPosition }${ this.isSticky ? ' (sticky)' : '' }`;
  279. } );
  280. sandbox.mock( NoOperation.prototype, 'toString', function() {
  281. return `NoOperation( ${ this.baseVersion } )`;
  282. } );
  283. sandbox.mock( RenameOperation.prototype, 'toString', function() {
  284. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  285. `${ this.position }: "${ this.oldName }" -> "${ this.newName }"`;
  286. } );
  287. sandbox.mock( RootAttributeOperation.prototype, 'toString', function() {
  288. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  289. `"${ this.key }": ${ JSON.stringify( this.oldValue ) } -> ${ JSON.stringify( this.newValue ) }, ${ this.root.rootName }`;
  290. } );
  291. sandbox.mock( Delta.prototype, 'log', function() {
  292. logger.log( this.toString() );
  293. } );
  294. sandbox.mock( Delta.prototype, 'logAll', function() {
  295. logger.log( '--------------------' );
  296. this.log();
  297. for ( const op of this.operations ) {
  298. op.log();
  299. }
  300. } );
  301. sandbox.mock( Delta.prototype, '_saveHistory', function( itemToSave ) {
  302. const history = itemToSave.before.history ? itemToSave.before.history : [];
  303. itemToSave.before = clone( itemToSave.before );
  304. delete itemToSave.before.history;
  305. itemToSave.before = JSON.stringify( itemToSave.before );
  306. itemToSave.transformedBy = clone( itemToSave.transformedBy );
  307. delete itemToSave.transformedBy.history;
  308. itemToSave.transformedBy = JSON.stringify( itemToSave.transformedBy );
  309. this.history = history.concat( itemToSave );
  310. } );
  311. const _deltaTransformTransform = deltaTransform.transform;
  312. sandbox.mock( deltaTransform, 'transform', function( a, b, context ) {
  313. let results;
  314. try {
  315. results = _deltaTransformTransform( a, b, context );
  316. } catch ( e ) {
  317. logger.error( 'Error during delta transformation!' );
  318. logger.error( a.toString() + ( context.isStrong ? ' (important)' : '' ) );
  319. logger.error( b.toString() + ( context.isStrong ? '' : ' (important)' ) );
  320. throw e;
  321. }
  322. for ( let i = 0; i < results.length; i++ ) {
  323. results[ i ]._saveHistory( {
  324. before: a,
  325. transformedBy: b,
  326. wasImportant: !!context.isStrong,
  327. resultIndex: i,
  328. resultsTotal: results.length
  329. } );
  330. }
  331. return results;
  332. } );
  333. sandbox.mock( AttributeDelta.prototype, 'toString', function() {
  334. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  335. `"${ this.key }": -> ${ JSON.stringify( this.value ) }, ${ this.range }, ${ this.operations.length } ops`;
  336. } );
  337. sandbox.mock( InsertDelta.prototype, 'toString', function() {
  338. const op = this._insertOperation;
  339. const nodeString = op.nodes.length > 1 ? `[ ${ op.nodes.length } ]` : op.nodes.getNode( 0 );
  340. return getClassName( this ) + `( ${ this.baseVersion } ): ${ nodeString } -> ${ op.position }`;
  341. } );
  342. sandbox.mock( MarkerDelta.prototype, 'toString', function() {
  343. const op = this.operations[ 0 ];
  344. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  345. `"${ op.name }": ${ op.oldRange } -> ${ op.newRange }`;
  346. } );
  347. sandbox.mock( MergeDelta.prototype, 'toString', function() {
  348. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  349. ( this.position ?
  350. this.position.toString() :
  351. `(move from ${ this.operations[ 0 ].sourcePosition })`
  352. );
  353. } );
  354. sandbox.mock( MoveDelta.prototype, 'toString', function() {
  355. const opStrings = [];
  356. for ( const op of this.operations ) {
  357. const range = ModelRange.createFromPositionAndShift( op.sourcePosition, op.howMany );
  358. opStrings.push( `${ range } -> ${ op.targetPosition }` );
  359. }
  360. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  361. opStrings.join( '; ' );
  362. } );
  363. sandbox.mock( RenameDelta.prototype, 'toString', function() {
  364. const op = this.operations[ 0 ];
  365. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  366. `${ op.position }: "${ op.oldName }" -> "${ op.newName }"`;
  367. } );
  368. sandbox.mock( RootAttributeDelta.prototype, 'toString', function() {
  369. const op = this.operations[ 0 ];
  370. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  371. `"${ op.key }": ${ JSON.stringify( op.oldValue ) } -> ${ JSON.stringify( op.newValue ) }, ${ op.root.rootName }`;
  372. } );
  373. sandbox.mock( SplitDelta.prototype, 'toString', function() {
  374. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  375. ( this.position ?
  376. this.position.toString() :
  377. `(clone to ${ this._cloneOperation.position || this._cloneOperation.targetPosition })`
  378. );
  379. } );
  380. sandbox.mock( UnwrapDelta.prototype, 'toString', function() {
  381. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  382. this.position.toString();
  383. } );
  384. sandbox.mock( WrapDelta.prototype, 'toString', function() {
  385. const wrapElement = this._insertOperation.nodes.getNode( 0 );
  386. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  387. `${ this.range } -> ${ wrapElement }`;
  388. } );
  389. sandbox.mock( ViewText.prototype, 'toString', function() {
  390. return `#${ this.data }`;
  391. } );
  392. sandbox.mock( ViewText.prototype, 'logExtended', function() {
  393. logger.log( 'ViewText: ' + this );
  394. } );
  395. sandbox.mock( ViewText.prototype, 'log', function() {
  396. logger.log( 'ViewText: ' + this );
  397. } );
  398. sandbox.mock( ViewTextProxy.prototype, 'toString', function() {
  399. return `#${ this.data }`;
  400. } );
  401. sandbox.mock( ViewTextProxy.prototype, 'logExtended', function() {
  402. logger.log( 'ViewTextProxy: ' + this );
  403. } );
  404. sandbox.mock( ViewTextProxy.prototype, 'log', function() {
  405. logger.log( 'ViewTextProxy: ' + this );
  406. } );
  407. sandbox.mock( ViewElement.prototype, 'printTree', function( level = 0 ) {
  408. let string = '';
  409. string += '\t'.repeat( level ) + `<${ this.name }${ mapToTags( this.getAttributes() ) }>`;
  410. for ( const child of this.getChildren() ) {
  411. if ( child.is( 'text' ) ) {
  412. string += '\n' + '\t'.repeat( level + 1 ) + child.data;
  413. } else {
  414. string += '\n' + child.printTree( level + 1 );
  415. }
  416. }
  417. if ( this.childCount ) {
  418. string += '\n' + '\t'.repeat( level );
  419. }
  420. string += `</${ this.name }>`;
  421. return string;
  422. } );
  423. sandbox.mock( ViewElement.prototype, 'logTree', function() {
  424. logger.log( this.printTree() );
  425. } );
  426. sandbox.mock( ViewDocumentFragment.prototype, 'printTree', function() {
  427. let string = 'ViewDocumentFragment: [';
  428. for ( const child of this.getChildren() ) {
  429. if ( child.is( 'text' ) ) {
  430. string += '\n' + '\t'.repeat( 1 ) + child.data;
  431. } else {
  432. string += '\n' + child.printTree( 1 );
  433. }
  434. }
  435. string += '\n]';
  436. return string;
  437. } );
  438. sandbox.mock( ViewDocumentFragment.prototype, 'logTree', function() {
  439. logger.log( this.printTree() );
  440. } );
  441. }
  442. function enableReplayerTools() {
  443. const _modelDocumentApplyOperation = ModelDocument.prototype.applyOperation;
  444. sandbox.mock( ModelDocument.prototype, 'applyOperation', function( operation ) {
  445. if ( !this._lastDelta ) {
  446. this._appliedDeltas = [];
  447. } else if ( this._lastDelta !== operation.delta ) {
  448. this._appliedDeltas.push( this._lastDelta.toJSON() );
  449. }
  450. this._lastDelta = operation.delta;
  451. _modelDocumentApplyOperation.call( this, operation );
  452. } );
  453. sandbox.mock( ModelDocument.prototype, 'getAppliedDeltas', function() {
  454. // No deltas has been applied yet, return empty string.
  455. if ( !this._lastDelta ) {
  456. return '';
  457. }
  458. const appliedDeltas = this._appliedDeltas.concat( this._lastDelta );
  459. return appliedDeltas.map( JSON.stringify ).join( LOG_SEPARATOR );
  460. } );
  461. sandbox.mock( ModelDocument.prototype, 'createReplayer', function( stringifiedDeltas ) {
  462. return new DeltaReplayer( this, LOG_SEPARATOR, stringifiedDeltas );
  463. } );
  464. }
  465. function enableDocumentTools() {
  466. const _modelDocumentApplyOperation = ModelDocument.prototype.applyOperation;
  467. sandbox.mock( ModelDocument.prototype, 'applyOperation', function( operation ) {
  468. logger.log( 'Applying ' + operation );
  469. if ( !this._operationLogs ) {
  470. this._operationLogs = [];
  471. }
  472. this._operationLogs.push( JSON.stringify( operation.toJSON() ) );
  473. _modelDocumentApplyOperation.call( this, operation );
  474. } );
  475. sandbox.mock( ModelDocument.prototype, 'log', function( version = null ) {
  476. version = version === null ? this.version : version;
  477. logDocument( this, version );
  478. } );
  479. sandbox.mock( ViewDocument.prototype, 'log', function( version ) {
  480. logDocument( this, version );
  481. } );
  482. sandbox.mock( Editor.prototype, 'logModel', function( version = null ) {
  483. version = version === null ? this.document.version : version;
  484. this.document.log( version );
  485. } );
  486. sandbox.mock( Editor.prototype, 'logView', function( version ) {
  487. this.editing.view.log( version );
  488. } );
  489. sandbox.mock( Editor.prototype, 'logDocuments', function( version = null ) {
  490. version = version === null ? this.document.version : version;
  491. this.logModel( version );
  492. this.logView( version );
  493. } );
  494. function logDocument( document, version ) {
  495. logger.log( '--------------------' );
  496. if ( document[ treeDump ][ version ] ) {
  497. logger.log( document[ treeDump ][ version ] );
  498. } else {
  499. logger.log( 'Tree log unavailable for given version: ' + version );
  500. }
  501. }
  502. }
  503. /**
  504. * Plugin that enables debugging features on the editor's model and view documents.
  505. */
  506. class DebugPlugin extends Plugin {
  507. constructor( editor ) {
  508. super( editor );
  509. const modelDocument = this.editor.document;
  510. const viewDocument = this.editor.editing.view;
  511. modelDocument[ treeDump ] = [];
  512. viewDocument[ treeDump ] = [];
  513. dumpTrees( modelDocument, modelDocument.version );
  514. dumpTrees( viewDocument, modelDocument.version );
  515. modelDocument.on( 'change', () => {
  516. dumpTrees( modelDocument, modelDocument.version );
  517. dumpTrees( viewDocument, modelDocument.version );
  518. }, { priority: 'lowest' } );
  519. }
  520. }
  521. // Helper function, stores `document` state for given `version` as a string in private property.
  522. function dumpTrees( document, version ) {
  523. let string = '';
  524. for ( const root of document.roots.values() ) {
  525. string += root.printTree() + '\n';
  526. }
  527. document[ treeDump ][ version ] = string.substr( 0, string.length - 1 ); // Remove the last "\n".
  528. const overflow = document[ treeDump ].length - maxTreeDumpLength;
  529. if ( overflow > 0 ) {
  530. document[ treeDump ][ overflow - 1 ] = null;
  531. }
  532. }
  533. // Helper function, returns class name of given `Delta` or `Operation`.
  534. // @param {module:engine/model/delta/delta~Delta|module:engine/model/operation/operation~Operation}
  535. // @returns {String} Class name.
  536. function getClassName( obj ) {
  537. const path = obj.constructor.className.split( '.' );
  538. return path[ path.length - 1 ];
  539. }
  540. // Helper function, converts map to {"key1":"value1","key2":"value2"} format.
  541. // @param {Map} map Map to convert.
  542. // @returns {String} Converted map.
  543. function mapString( map ) {
  544. const obj = {};
  545. for ( const entry of map ) {
  546. obj[ entry[ 0 ] ] = entry[ 1 ];
  547. }
  548. return JSON.stringify( obj );
  549. }
  550. // Helper function, converts map to key1="value1" key2="value1" format.
  551. // @param {Map} map Map to convert.
  552. // @returns {String} Converted map.
  553. function mapToTags( map ) {
  554. let string = '';
  555. for ( const entry of map ) {
  556. string += ` ${ entry[ 0 ] }=${ JSON.stringify( entry[ 1 ] ) }`;
  557. }
  558. return string;
  559. }