utils.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. import ModelTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/modeltesteditor';
  6. import ListEditing from '@ckeditor/ckeditor5-list/src/listediting';
  7. import BoldEditing from '@ckeditor/ckeditor5-basic-styles/src/bold/boldediting';
  8. import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
  9. import Typing from '@ckeditor/ckeditor5-typing/src/typing';
  10. import UndoEditing from '@ckeditor/ckeditor5-undo/src/undoediting';
  11. import BlockQuoteEditing from '@ckeditor/ckeditor5-block-quote/src/blockquoteediting';
  12. import HeadingEditing from '@ckeditor/ckeditor5-heading/src/headingediting';
  13. import TableEditing from '@ckeditor/ckeditor5-table/src/tableediting';
  14. import { getData, parse } from '../../../../src/dev-utils/model';
  15. import { transformSets } from '../../../../src/model/operation/transform';
  16. import Position from '../../../../src/model/position';
  17. import Range from '../../../../src/model/range';
  18. import OperationFactory from '../../../../src/model/operation/operationfactory';
  19. const clients = new Set();
  20. const bufferedOperations = new Set();
  21. export class Client {
  22. constructor( name ) {
  23. this.editor = null;
  24. this.document = null;
  25. this.syncedVersion = 0;
  26. this.orderNumber = null;
  27. this.name = name;
  28. }
  29. init() {
  30. return ModelTestEditor.create( {
  31. // Typing is needed for delete command.
  32. // UndoEditing is needed for undo command.
  33. // Block plugins are needed for proper data serializing.
  34. // BoldEditing is needed for bold command.
  35. plugins: [ Typing, Paragraph, ListEditing, UndoEditing, BlockQuoteEditing, HeadingEditing, BoldEditing, TableEditing ]
  36. } ).then( editor => {
  37. this.editor = editor;
  38. this.document = editor.model.document;
  39. return this;
  40. } );
  41. }
  42. setData( initModelString ) {
  43. const model = this.editor.model;
  44. const modelRoot = model.document.getRoot();
  45. // Parse data string to model.
  46. const parsedResult = parse( initModelString, model.schema, { context: [ modelRoot.name ] } );
  47. // Retrieve DocumentFragment and Selection from parsed model.
  48. const modelDocumentFragment = parsedResult.model;
  49. const selection = parsedResult.selection;
  50. model.change( writer => {
  51. // Replace existing model in document by new one.
  52. writer.remove( writer.createRangeIn( modelRoot ) );
  53. writer.insert( modelDocumentFragment, modelRoot );
  54. } );
  55. const ranges = [];
  56. for ( const range of selection.getRanges() ) {
  57. const start = new Position( modelRoot, range.start.path );
  58. const end = new Position( modelRoot, range.end.path );
  59. ranges.push( new Range( start, end ) );
  60. }
  61. model.document.selection._setTo( ranges );
  62. // Purify graveyard so there are no artifact nodes there remaining after setting new data.
  63. // Because of those old nodes some tests may pass even though they fail in real scenarios (those tests
  64. // involve bringing back elements from graveyard, like wrap or split).
  65. model.document.graveyard._removeChildren( 0, model.document.graveyard.childCount );
  66. this.syncedVersion = this.document.version;
  67. }
  68. setSelection( start, end ) {
  69. if ( !end ) {
  70. end = start.slice();
  71. }
  72. const startPos = this._getPosition( start );
  73. const endPos = this._getPosition( end );
  74. this.editor.model.document.selection._setTo( new Range( startPos, endPos ) );
  75. }
  76. insert( itemString, path ) {
  77. const item = parse( itemString, this.editor.model.schema );
  78. const position = this._getPosition( path, 'start' );
  79. this._processAction( 'insert', item, position );
  80. }
  81. type( text, attributes, path ) {
  82. const position = this._getPosition( path, 'start' );
  83. this._processAction( 'insertText', text, attributes, position );
  84. }
  85. remove( start, end ) {
  86. const startPos = this._getPosition( start, 'start' );
  87. const endPos = this._getPosition( end, 'end' );
  88. this._processAction( 'remove', new Range( startPos, endPos ) );
  89. }
  90. delete() {
  91. this._processExecute( 'delete' );
  92. }
  93. move( target, start, end ) {
  94. const targetPos = this._getPosition( target );
  95. const startPos = this._getPosition( start, 'start' );
  96. const endPos = this._getPosition( end, 'end' );
  97. this._processAction( 'move', new Range( startPos, endPos ), targetPos );
  98. }
  99. rename( newName, path ) {
  100. const pos = this._getPosition( path, 'beforeParent' );
  101. const element = pos.nodeAfter;
  102. this._processAction( 'rename', element, newName );
  103. }
  104. setAttribute( key, value, start, end ) {
  105. const startPos = this._getPosition( start, 'start' );
  106. const endPos = this._getPosition( end, 'end' );
  107. this._processAction( 'setAttribute', key, value, new Range( startPos, endPos ) );
  108. }
  109. removeAttribute( key, start, end ) {
  110. const startPos = this._getPosition( start, 'start' );
  111. const endPos = this._getPosition( end, 'end' );
  112. this._processAction( 'removeAttribute', key, new Range( startPos, endPos ) );
  113. }
  114. setMarker( name, start, end ) {
  115. let actionName;
  116. const startPos = this._getPosition( start, 'start' );
  117. const endPos = this._getPosition( end, 'end' );
  118. if ( this.editor.model.markers.has( name ) ) {
  119. actionName = 'updateMarker';
  120. } else {
  121. actionName = 'addMarker';
  122. }
  123. const range = new Range( startPos, endPos );
  124. this._processAction( actionName, name, { range, usingOperation: true } );
  125. }
  126. removeMarker( name ) {
  127. this._processAction( 'removeMarker', name );
  128. }
  129. wrap( elementName, start, end ) {
  130. const startPos = this._getPosition( start, 'start' );
  131. const endPos = this._getPosition( end, 'end' );
  132. this._processAction( 'wrap', new Range( startPos, endPos ), elementName );
  133. }
  134. unwrap( path ) {
  135. const pos = this._getPosition( path, 'beforeParent' );
  136. const element = pos.nodeAfter;
  137. this._processAction( 'unwrap', element );
  138. }
  139. merge( path ) {
  140. const pos = this._getPosition( path, 'start' );
  141. this._processAction( 'merge', pos );
  142. }
  143. split( path ) {
  144. const pos = this._getPosition( path, 'start' );
  145. this._processAction( 'split', pos );
  146. }
  147. undo() {
  148. this._processExecute( 'undo' );
  149. }
  150. redo() {
  151. this._processExecute( 'redo' );
  152. }
  153. _processExecute( commandName, commandArgs ) {
  154. const oldVersion = this.document.version;
  155. this.editor.execute( commandName, commandArgs );
  156. const operations = this.document.history.getOperations( oldVersion );
  157. bufferOperations( Array.from( operations ), this );
  158. }
  159. _getPosition( path, type ) {
  160. if ( !path ) {
  161. return this._getPositionFromSelection( type );
  162. }
  163. return new Position( this.document.getRoot(), path );
  164. }
  165. _getPositionFromSelection( type ) {
  166. const selRange = this.editor.model.document.selection.getFirstRange();
  167. switch ( type ) {
  168. default:
  169. case 'start':
  170. return selRange.start.clone();
  171. case 'end':
  172. return selRange.end.clone();
  173. case 'beforeParent':
  174. return Position._createBefore( selRange.start.parent );
  175. }
  176. }
  177. getModelString() {
  178. return getData( this.editor.model, { withoutSelection: true, convertMarkers: true } );
  179. }
  180. destroy() {
  181. clients.delete( this );
  182. return this.editor.destroy();
  183. }
  184. _processAction( name, ...args ) {
  185. const oldVersion = this.document.version;
  186. this.editor.model.change( writer => {
  187. writer[ name ]( ...args );
  188. } );
  189. const operations = Array.from( this.document.history.getOperations( oldVersion ) );
  190. bufferOperations( operations, this );
  191. }
  192. static get( clientName ) {
  193. const client = new Client( clientName );
  194. client.orderNumber = clients.size;
  195. clients.add( client );
  196. return client.init();
  197. }
  198. }
  199. function bufferOperations( operations, client ) {
  200. bufferedOperations.add( { operations, client } );
  201. }
  202. export function syncClients() {
  203. const clientsOperations = {};
  204. // For each client, flatten all buffered operations into one set.
  205. for ( const item of bufferedOperations ) {
  206. const name = item.client.name;
  207. if ( !clientsOperations[ name ] ) {
  208. clientsOperations[ name ] = [];
  209. }
  210. clientsOperations[ name ].push( ...item.operations );
  211. }
  212. for ( const localClient of clients ) {
  213. for ( const remoteClient of clients ) {
  214. if ( remoteClient == localClient ) {
  215. continue;
  216. }
  217. if ( !clientsOperations[ remoteClient.name ] ) {
  218. continue;
  219. }
  220. // Stringify and rebuild operations to simulate sending operations. Set `wasUndone`.
  221. const remoteOperationsJson = clientsOperations[ remoteClient.name ].map( operation => {
  222. operation.wasUndone = remoteClient.document.history.isUndoneOperation( operation );
  223. const json = JSON.stringify( operation );
  224. delete operation.wasUndone;
  225. return json;
  226. } );
  227. const remoteOperations = remoteOperationsJson.map( json => {
  228. const parsedJson = JSON.parse( json );
  229. const operation = OperationFactory.fromJSON( parsedJson, localClient.document );
  230. if ( parsedJson.wasUndone ) {
  231. operation.wasUndone = true;
  232. }
  233. return operation;
  234. } );
  235. const localOperations = Array.from( localClient.document.history.getOperations( localClient.syncedVersion ) );
  236. let remoteOperationsTransformed = null;
  237. const options = {
  238. document: localClient.document,
  239. useRelations: false,
  240. padWithNoOps: true
  241. };
  242. if ( localClient.orderNumber < remoteClient.orderNumber ) {
  243. remoteOperationsTransformed = transformSets( localOperations, remoteOperations, options ).operationsB;
  244. } else {
  245. remoteOperationsTransformed = transformSets( remoteOperations, localOperations, options ).operationsA;
  246. }
  247. localClient.editor.model.enqueueChange( 'transparent', writer => {
  248. for ( const operation of remoteOperationsTransformed ) {
  249. writer.batch.addOperation( operation );
  250. localClient.editor.model.applyOperation( operation );
  251. }
  252. } );
  253. }
  254. localClient.syncedVersion = localClient.document.version;
  255. }
  256. bufferedOperations.clear();
  257. }
  258. export function expectClients( expectedModelString ) {
  259. for ( const client of clients ) {
  260. expect( client.getModelString(), client.name + ' content' ).to.equal( expectedModelString );
  261. }
  262. let syncedVersion = null;
  263. for ( const client of clients ) {
  264. if ( syncedVersion === null ) {
  265. syncedVersion = client.syncedVersion;
  266. continue;
  267. }
  268. expect( client.syncedVersion, client.name + ' version' ).to.equal( syncedVersion );
  269. }
  270. }
  271. export function clearBuffer() {
  272. bufferedOperations.clear();
  273. }