8
0

enableenginedebug.js 19 KB

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