enableenginedebug.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. /**
  2. * @license Copyright (c) 2003-2018, 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 OperationReplayer from './operationreplayer';
  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 Model from '../model/model';
  25. import ModelDocument from '../model/document';
  26. import ModelDocumentFragment from '../model/documentfragment';
  27. import ModelRootElement from '../model/rootelement';
  28. import ViewDocument from '../view/document';
  29. import ViewElement from '../view/element';
  30. import ViewText from '../view/text';
  31. import ViewTextProxy from '../view/textproxy';
  32. import ViewDocumentFragment from '../view/documentfragment';
  33. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  34. import Editor from '@ckeditor/ckeditor5-core/src/editor/editor';
  35. // Sandbox class allows creating mocks of the functions and restoring these mocks to the original values.
  36. class Sandbox {
  37. constructor() {
  38. // An array that contains functions which restore the original values of mocked objects.
  39. // @private
  40. // @type {Array.<Function>}
  41. this._restores = [];
  42. }
  43. // Creates a new mock.
  44. //
  45. // @param {Object} object Object to mock.
  46. // @param {String} methodName Function to mock.
  47. // @param {Function} fakeMethod Function that will be executed.
  48. mock( object, methodName, fakeMethod ) {
  49. const originalMethod = object[ methodName ];
  50. object[ methodName ] = fakeMethod;
  51. this._restores.unshift( () => {
  52. if ( originalMethod ) {
  53. object[ methodName ] = originalMethod;
  54. } else {
  55. delete object[ methodName ];
  56. }
  57. } );
  58. }
  59. // Restores all mocked functions.
  60. restore() {
  61. for ( const restore of this._restores ) {
  62. restore();
  63. }
  64. this._restores = [];
  65. }
  66. }
  67. const sandbox = new Sandbox();
  68. const treeDump = Symbol( '_treeDump' );
  69. // Maximum number of stored states of model and view document.
  70. const maxTreeDumpLength = 20;
  71. // Separator used to separate stringified operations
  72. const LOG_SEPARATOR = '-------';
  73. // Specified whether debug tools were already enabled.
  74. let enabled = false;
  75. // Logging function used to log debug messages.
  76. let logger = console;
  77. /**
  78. * Enhances model classes with logging methods. Returns a plugin that should be loaded in the editor to
  79. * enable debugging features.
  80. *
  81. * Every operation applied on {@link module:engine/model/document~Document model.Document} is logged.
  82. *
  83. * The following classes are expanded with `log` and meaningful `toString` methods:
  84. * * {@link module:engine/model/position~Position model.Position},
  85. * * {@link module:engine/model/range~Range model.Range},
  86. * * {@link module:engine/model/text~Text model.Text},
  87. * * {@link module:engine/model/element~Element model.Element},
  88. * * {@link module:engine/model/rootelement~RootElement model.RootElement},
  89. * * {@link module:engine/model/documentfragment~DocumentFragment model.DocumentFragment},
  90. * * {@link module:engine/model/document~Document model.Document},
  91. * * all {@link module:engine/model/operation/operation~Operation operations}
  92. * * {@link module:engine/view/element~Element view.Element},
  93. * * {@link module:engine/view/documentfragment~DocumentFragment view.DocumentFragment},
  94. * * {@link module:engine/view/document~Document view.Document}.
  95. *
  96. * Additionally, the following logging utility methods are added:
  97. * * {@link module:engine/model/text~Text model.Text} `logExtended`,
  98. * * {@link module:engine/model/element~Element model.Element} `logExtended`,
  99. * * {@link module:engine/model/element~Element model.Element} `logAll`.
  100. *
  101. * Additionally, the following classes are expanded with `logTree` and `printTree` methods:
  102. * * {@link module:engine/model/element~Element model.Element},
  103. * * {@link module:engine/model/documentfragment~DocumentFragment model.DocumentFragment},
  104. * * {@link module:engine/view/element~Element view.Element},
  105. * * {@link module:engine/view/documentfragment~DocumentFragment view.DocumentFragment}.
  106. *
  107. * Finally, the following methods are added to {@link module:core/editor/editor~Editor}: `logModel`, `logView`, `logDocuments`.
  108. * All those methods take one parameter, which is the version of the {@link module:engine/model/document~Document model document}
  109. * for which the model or view document state should be logged.
  110. *
  111. * @param {Object} [_logger] An object with functions used to log messages and errors. By default messages are logged to the console.
  112. * If specified, it is expected to have `log()` and `error()` methods.
  113. * @returns {module:engine/dev-utils/enableenginedebug~DebugPlugin} The plugin to be loaded into the editor.
  114. */
  115. export default function enableEngineDebug( _logger = console ) {
  116. logger = _logger;
  117. if ( !enabled ) {
  118. enabled = true;
  119. enableLoggingTools();
  120. enableDocumentTools();
  121. enableReplayerTools();
  122. }
  123. return DebugPlugin;
  124. }
  125. /**
  126. * Restores all methods that have been overwritten.
  127. */
  128. export function disableEngineDebug() {
  129. sandbox.restore();
  130. enabled = false;
  131. }
  132. function enableLoggingTools() {
  133. sandbox.mock( ModelPosition.prototype, 'toString', function() {
  134. return `${ this.root } [ ${ this.path.join( ', ' ) } ]`;
  135. } );
  136. sandbox.mock( ModelPosition.prototype, 'log', function() {
  137. logger.log( 'ModelPosition: ' + this );
  138. } );
  139. sandbox.mock( ModelRange.prototype, 'toString', function() {
  140. return `${ this.root } [ ${ this.start.path.join( ', ' ) } ] - [ ${ this.end.path.join( ', ' ) } ]`;
  141. } );
  142. sandbox.mock( ModelRange.prototype, 'log', function() {
  143. logger.log( 'ModelRange: ' + this );
  144. } );
  145. sandbox.mock( ModelText.prototype, 'toString', function() {
  146. return `#${ this.data }`;
  147. } );
  148. sandbox.mock( ModelText.prototype, 'logExtended', function() {
  149. logger.log( `ModelText: ${ this }, attrs: ${ mapString( this.getAttributes() ) }` );
  150. } );
  151. sandbox.mock( ModelText.prototype, 'log', function() {
  152. logger.log( 'ModelText: ' + this );
  153. } );
  154. sandbox.mock( ModelTextProxy.prototype, 'toString', function() {
  155. return `#${ this.data }`;
  156. } );
  157. sandbox.mock( ModelTextProxy.prototype, 'logExtended', function() {
  158. logger.log( `ModelTextProxy: ${ this }, attrs: ${ mapString( this.getAttributes() ) }` );
  159. } );
  160. sandbox.mock( ModelTextProxy.prototype, 'log', function() {
  161. logger.log( 'ModelTextProxy: ' + this );
  162. } );
  163. sandbox.mock( ModelElement.prototype, 'toString', function() {
  164. return `<${ this.rootName || this.name }>`;
  165. } );
  166. sandbox.mock( ModelElement.prototype, 'log', function() {
  167. logger.log( 'ModelElement: ' + this );
  168. } );
  169. sandbox.mock( ModelElement.prototype, 'logExtended', function() {
  170. logger.log( `ModelElement: ${ this }, ${ this.childCount } children, attrs: ${ mapString( this.getAttributes() ) }` );
  171. } );
  172. sandbox.mock( ModelElement.prototype, 'logAll', function() {
  173. logger.log( '--------------------' );
  174. this.logExtended();
  175. logger.log( 'List of children:' );
  176. for ( const child of this.getChildren() ) {
  177. child.log();
  178. }
  179. } );
  180. sandbox.mock( ModelElement.prototype, 'printTree', function( level = 0 ) {
  181. let string = '';
  182. string += '\t'.repeat( level ) + `<${ this.rootName || this.name }${ mapToTags( this.getAttributes() ) }>`;
  183. for ( const child of this.getChildren() ) {
  184. string += '\n';
  185. if ( child.is( 'text' ) ) {
  186. const textAttrs = mapToTags( child._attrs );
  187. string += '\t'.repeat( level + 1 );
  188. if ( textAttrs !== '' ) {
  189. string += `<$text${ textAttrs }>` + child.data + '</$text>';
  190. } else {
  191. string += child.data;
  192. }
  193. } else {
  194. string += child.printTree( level + 1 );
  195. }
  196. }
  197. if ( this.childCount ) {
  198. string += '\n' + '\t'.repeat( level );
  199. }
  200. string += `</${ this.rootName || this.name }>`;
  201. return string;
  202. } );
  203. sandbox.mock( ModelElement.prototype, 'logTree', function() {
  204. logger.log( this.printTree() );
  205. } );
  206. sandbox.mock( ModelRootElement.prototype, 'toString', function() {
  207. return this.rootName;
  208. } );
  209. sandbox.mock( ModelRootElement.prototype, 'log', function() {
  210. logger.log( 'ModelRootElement: ' + this );
  211. } );
  212. sandbox.mock( ModelDocumentFragment.prototype, 'toString', function() {
  213. return 'documentFragment';
  214. } );
  215. sandbox.mock( ModelDocumentFragment.prototype, 'log', function() {
  216. logger.log( 'ModelDocumentFragment: ' + this );
  217. } );
  218. sandbox.mock( ModelDocumentFragment.prototype, 'printTree', function() {
  219. let string = 'ModelDocumentFragment: [';
  220. for ( const child of this.getChildren() ) {
  221. string += '\n';
  222. if ( child.is( 'text' ) ) {
  223. const textAttrs = mapToTags( child._attrs );
  224. string += '\t'.repeat( 1 );
  225. if ( textAttrs !== '' ) {
  226. string += `<$text${ textAttrs }>` + child.data + '</$text>';
  227. } else {
  228. string += child.data;
  229. }
  230. } else {
  231. string += child.printTree( 1 );
  232. }
  233. }
  234. string += '\n]';
  235. return string;
  236. } );
  237. sandbox.mock( ModelDocumentFragment.prototype, 'logTree', function() {
  238. logger.log( this.printTree() );
  239. } );
  240. sandbox.mock( Operation.prototype, 'log', function() {
  241. logger.log( this.toString() );
  242. } );
  243. sandbox.mock( AttributeOperation.prototype, 'toString', function() {
  244. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  245. `"${ this.key }": ${ JSON.stringify( this.oldValue ) } -> ${ JSON.stringify( this.newValue ) }, ${ this.range }`;
  246. } );
  247. sandbox.mock( DetachOperation.prototype, 'toString', function() {
  248. const range = ModelRange.createFromPositionAndShift( this.sourcePosition, this.howMany );
  249. const nodes = Array.from( range.getItems() );
  250. const nodeString = nodes.length > 1 ? `[ ${ nodes.length } ]` : nodes[ 0 ];
  251. return getClassName( this ) + `( ${ this.baseVersion } ): ${ nodeString } -> ${ range }`;
  252. } );
  253. sandbox.mock( InsertOperation.prototype, 'toString', function() {
  254. const nodeString = this.nodes.length > 1 ? `[ ${ this.nodes.length } ]` : this.nodes.getNode( 0 );
  255. return getClassName( this ) + `( ${ this.baseVersion } ): ${ nodeString } -> ${ this.position }`;
  256. } );
  257. sandbox.mock( MarkerOperation.prototype, 'toString', function() {
  258. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  259. `"${ this.name }": ${ this.oldRange } -> ${ this.newRange }`;
  260. } );
  261. sandbox.mock( MoveOperation.prototype, 'toString', function() {
  262. const range = ModelRange.createFromPositionAndShift( this.sourcePosition, this.howMany );
  263. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  264. `${ range } -> ${ this.targetPosition }${ this.isSticky ? ' (sticky)' : '' }`;
  265. } );
  266. sandbox.mock( NoOperation.prototype, 'toString', function() {
  267. return `NoOperation( ${ this.baseVersion } )`;
  268. } );
  269. sandbox.mock( RenameOperation.prototype, 'toString', function() {
  270. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  271. `${ this.position }: "${ this.oldName }" -> "${ this.newName }"`;
  272. } );
  273. sandbox.mock( RootAttributeOperation.prototype, 'toString', function() {
  274. return getClassName( this ) + `( ${ this.baseVersion } ): ` +
  275. `"${ this.key }": ${ JSON.stringify( this.oldValue ) } -> ${ JSON.stringify( this.newValue ) }, ${ this.root.rootName }`;
  276. } );
  277. sandbox.mock( ViewText.prototype, 'toString', function() {
  278. return `#${ this.data }`;
  279. } );
  280. sandbox.mock( ViewText.prototype, 'logExtended', function() {
  281. logger.log( 'ViewText: ' + this );
  282. } );
  283. sandbox.mock( ViewText.prototype, 'log', function() {
  284. logger.log( 'ViewText: ' + this );
  285. } );
  286. sandbox.mock( ViewTextProxy.prototype, 'toString', function() {
  287. return `#${ this.data }`;
  288. } );
  289. sandbox.mock( ViewTextProxy.prototype, 'logExtended', function() {
  290. logger.log( 'ViewTextProxy: ' + this );
  291. } );
  292. sandbox.mock( ViewTextProxy.prototype, 'log', function() {
  293. logger.log( 'ViewTextProxy: ' + this );
  294. } );
  295. sandbox.mock( ViewElement.prototype, 'printTree', function( level = 0 ) {
  296. let string = '';
  297. string += '\t'.repeat( level ) + `<${ this.name }${ mapToTags( this.getAttributes() ) }>`;
  298. for ( const child of this.getChildren() ) {
  299. if ( child.is( 'text' ) ) {
  300. string += '\n' + '\t'.repeat( level + 1 ) + child.data;
  301. } else {
  302. string += '\n' + child.printTree( level + 1 );
  303. }
  304. }
  305. if ( this.childCount ) {
  306. string += '\n' + '\t'.repeat( level );
  307. }
  308. string += `</${ this.name }>`;
  309. return string;
  310. } );
  311. sandbox.mock( ViewElement.prototype, 'logTree', function() {
  312. logger.log( this.printTree() );
  313. } );
  314. sandbox.mock( ViewDocumentFragment.prototype, 'printTree', function() {
  315. let string = 'ViewDocumentFragment: [';
  316. for ( const child of this.getChildren() ) {
  317. if ( child.is( 'text' ) ) {
  318. string += '\n' + '\t'.repeat( 1 ) + child.data;
  319. } else {
  320. string += '\n' + child.printTree( 1 );
  321. }
  322. }
  323. string += '\n]';
  324. return string;
  325. } );
  326. sandbox.mock( ViewDocumentFragment.prototype, 'logTree', function() {
  327. logger.log( this.printTree() );
  328. } );
  329. }
  330. function enableReplayerTools() {
  331. const _modelApplyOperation = Model.prototype.applyOperation;
  332. sandbox.mock( Model.prototype, 'applyOperation', function( operation ) {
  333. if ( !this._appliedOperations ) {
  334. this._appliedOperations = [];
  335. }
  336. this._appliedOperations.push( operation );
  337. return _modelApplyOperation.call( this, operation );
  338. } );
  339. sandbox.mock( Model.prototype, 'getAppliedOperations', function() {
  340. if ( !this._appliedOperations ) {
  341. return '';
  342. }
  343. return this._appliedOperations.map( JSON.stringify ).join( LOG_SEPARATOR );
  344. } );
  345. sandbox.mock( Model.prototype, 'createReplayer', function( stringifiedOperations ) {
  346. return new OperationReplayer( this, LOG_SEPARATOR, stringifiedOperations );
  347. } );
  348. }
  349. function enableDocumentTools() {
  350. const _modelApplyOperation = Model.prototype.applyOperation;
  351. sandbox.mock( Model.prototype, 'applyOperation', function( operation ) {
  352. logger.log( 'Applying ' + operation );
  353. if ( !this._operationLogs ) {
  354. this._operationLogs = [];
  355. }
  356. this._operationLogs.push( JSON.stringify( operation ) );
  357. return _modelApplyOperation.call( this, operation );
  358. } );
  359. sandbox.mock( ModelDocument.prototype, 'log', function( version = null ) {
  360. version = version === null ? this.version : version;
  361. logDocument( this, version );
  362. } );
  363. sandbox.mock( ViewDocument.prototype, 'log', function( version ) {
  364. logDocument( this, version );
  365. } );
  366. sandbox.mock( Editor.prototype, 'logModel', function( version = null ) {
  367. version = version === null ? this.model.document.version : version;
  368. this.model.document.log( version );
  369. } );
  370. sandbox.mock( Editor.prototype, 'logView', function( version ) {
  371. this.editing.view.document.log( version );
  372. } );
  373. sandbox.mock( Editor.prototype, 'logDocuments', function( version = null ) {
  374. version = version === null ? this.model.document.version : version;
  375. this.logModel( version );
  376. this.logView( version );
  377. } );
  378. function logDocument( document, version ) {
  379. logger.log( '--------------------' );
  380. if ( document[ treeDump ][ version ] ) {
  381. logger.log( document[ treeDump ][ version ] );
  382. } else {
  383. logger.log( 'Tree log unavailable for given version: ' + version );
  384. }
  385. }
  386. }
  387. /**
  388. * Plugin that enables debugging features on the editor's model and view documents.
  389. */
  390. class DebugPlugin extends Plugin {
  391. constructor( editor ) {
  392. super( editor );
  393. const model = this.editor.model;
  394. const modelDocument = model.document;
  395. const view = this.editor.editing.view;
  396. const viewDocument = view.document;
  397. modelDocument[ treeDump ] = [];
  398. viewDocument[ treeDump ] = [];
  399. dumpTrees( modelDocument, modelDocument.version );
  400. dumpTrees( viewDocument, modelDocument.version );
  401. model.on( 'applyOperation', () => {
  402. dumpTrees( modelDocument, modelDocument.version );
  403. }, { priority: 'lowest' } );
  404. model.document.on( 'change', () => {
  405. dumpTrees( viewDocument, modelDocument.version );
  406. }, { priority: 'lowest' } );
  407. }
  408. }
  409. // Helper function, stores the `document` state for a given `version` as a string in a private property.
  410. function dumpTrees( document, version ) {
  411. let string = '';
  412. for ( const root of document.roots ) {
  413. string += root.printTree() + '\n';
  414. }
  415. document[ treeDump ][ version ] = string.substr( 0, string.length - 1 ); // Remove the last "\n".
  416. const overflow = document[ treeDump ].length - maxTreeDumpLength;
  417. if ( overflow > 0 ) {
  418. document[ treeDump ][ overflow - 1 ] = null;
  419. }
  420. }
  421. // Helper function, returns the class name of a given `Operation`.
  422. // @param {module:engine/model/operation/operation~Operation}
  423. // @returns {String} Class name.
  424. function getClassName( obj ) {
  425. const path = obj.constructor.className.split( '.' );
  426. return path[ path.length - 1 ];
  427. }
  428. // Helper function, converts a map to the {"key1":"value1","key2":"value2"} format.
  429. // @param {Map} map Map to convert.
  430. // @returns {String} Converted map.
  431. function mapString( map ) {
  432. const obj = {};
  433. for ( const entry of map ) {
  434. obj[ entry[ 0 ] ] = entry[ 1 ];
  435. }
  436. return JSON.stringify( obj );
  437. }
  438. // Helper function, converts a map to the key1="value1" key2="value1" format.
  439. // @param {Map} map Map to convert.
  440. // @returns {String} Converted map.
  441. function mapToTags( map ) {
  442. let string = '';
  443. for ( const entry of map ) {
  444. string += ` ${ entry[ 0 ] }=${ JSON.stringify( entry[ 1 ] ) }`;
  445. }
  446. return string;
  447. }