| 1 | /*! |
| 2 | * VisualEditor DataModel TransactionProcessor class. |
| 3 | * |
| 4 | * @copyright See AUTHORS.txt |
| 5 | */ |
| 6 | |
| 7 | /** |
| 8 | * DataModel transaction processor. |
| 9 | * |
| 10 | * This class reads operations from a transaction and applies them one by one. It's not intended |
| 11 | * to be used directly; use {ve.dm.Document#commit} instead. |
| 12 | * |
| 13 | * NOTE: Instances of this class are not recyclable: you can only call .process() on them once. |
| 14 | * |
| 15 | * @class |
| 16 | * @param {ve.dm.Document} doc |
| 17 | * @param {ve.dm.Transaction} transaction |
| 18 | * @param {boolean} isStaging Transaction is being applied in staging mode |
| 19 | * @constructor |
| 20 | */ |
| 21 | ve.dm.TransactionProcessor = function VeDmTransactionProcessor( doc, transaction, isStaging ) { |
| 22 | // Properties |
| 23 | this.document = doc; |
| 24 | this.transaction = transaction; |
| 25 | this.operations = transaction.getOperations(); |
| 26 | this.isStaging = isStaging; |
| 27 | this.modificationQueue = []; |
| 28 | this.rollbackQueue = []; |
| 29 | this.eventQueue = []; |
| 30 | // Linear model offset that we're currently at. Operations in the transaction are ordered, so |
| 31 | // the cursor only ever moves forward. |
| 32 | this.cursor = 0; |
| 33 | // Adjustment that needs to be added to linear model offsets in the original linear model |
| 34 | // to get offsets in the half-updated linear model. Arguments to queued modifications all use |
| 35 | // unadjusted offsets; this is needed to adjust those offsets after other modifications have been |
| 36 | // made to the linear model that have caused offsets to shift. |
| 37 | this.adjustment = 0; |
| 38 | // State tracking for unbalanced replace operations |
| 39 | this.replaceRemoveLevel = 0; |
| 40 | this.replaceInsertLevel = 0; |
| 41 | this.replaceMinInsertLevel = 0; |
| 42 | this.retainDepth = 0; |
| 43 | this.balanced = true; |
| 44 | }; |
| 45 | |
| 46 | /* Static members */ |
| 47 | |
| 48 | /* See ve.dm.TransactionProcessor.modifiers */ |
| 49 | ve.dm.TransactionProcessor.modifiers = {}; |
| 50 | |
| 51 | /* See ve.dm.TransactionProcessor.processors */ |
| 52 | ve.dm.TransactionProcessor.processors = {}; |
| 53 | |
| 54 | /* Methods */ |
| 55 | |
| 56 | /** |
| 57 | * Execute an operation. |
| 58 | * |
| 59 | * @private |
| 60 | * @param {Object} op Operation object to execute |
| 61 | * @throws {Error} Operation type is not supported |
| 62 | */ |
| 63 | ve.dm.TransactionProcessor.prototype.executeOperation = function ( op ) { |
| 64 | if ( Object.prototype.hasOwnProperty.call( ve.dm.TransactionProcessor.processors, op.type ) ) { |
| 65 | ve.dm.TransactionProcessor.processors[ op.type ].call( this, op ); |
| 66 | } else { |
| 67 | throw new Error( 'Invalid operation error. Operation type is not supported: ' + op.type ); |
| 68 | } |
| 69 | }; |
| 70 | |
| 71 | /** |
| 72 | * Process all operations. |
| 73 | * |
| 74 | * When all operations are done being processed, the document will be synchronized. |
| 75 | * |
| 76 | * @private |
| 77 | */ |
| 78 | ve.dm.TransactionProcessor.prototype.process = function () { |
| 79 | // Warning: some of this is vestigial. Before TreeModifier, things worked as follows: |
| 80 | // 1) executeOperation ran on each operation. This built a list of modifications, |
| 81 | // .modificationQueue, consisting of linear splices and attribute/annotation changes. |
| 82 | // 2) applyModifications processed .modificationQueue. In particular it executed the |
| 83 | // linear splices (invalidating the DM tree). |
| 84 | // 3) rebuildTree rebuilt the part of the DM tree invalidated by the linear splices. |
| 85 | // |
| 86 | // Since then, we removed annotation changes completely. And TreeModifier handles |
| 87 | // replacements. So for replacements: |
| 88 | // 1) executeOperation does very little (just a balancedness check) |
| 89 | // 2) applyModifications queues linear splices for rollback on error |
| 90 | // 3) rebuildTree is only called in the rollback case |
| 91 | |
| 92 | // Ensure the pre-modification document tree has been generated |
| 93 | this.document.getDocumentNode(); |
| 94 | |
| 95 | // First process each operation to gather modifications in the modification queue. |
| 96 | // If an exception occurs during this stage, we don't need to do anything to recover, |
| 97 | // because no modifications were made yet. |
| 98 | for ( let i = 0; i < this.operations.length; i++ ) { |
| 99 | this.executeOperation( this.operations[ i ] ); |
| 100 | } |
| 101 | if ( !this.balanced ) { |
| 102 | throw new Error( 'Unbalanced set of replace operations found' ); |
| 103 | } |
| 104 | |
| 105 | let completed; |
| 106 | // Apply the queued modifications |
| 107 | try { |
| 108 | completed = false; |
| 109 | this.applyModifications(); |
| 110 | ve.dm.treeModifier.process( this.document, this.transaction ); |
| 111 | completed = true; |
| 112 | } finally { |
| 113 | // Don't catch and re-throw errors so that they are reported properly |
| 114 | if ( !completed ) { |
| 115 | // Restore the linear model to its original state |
| 116 | if ( this.treeModifier ) { |
| 117 | this.treeModifier.undoLinearSplices(); |
| 118 | } |
| 119 | this.rollbackModifications(); |
| 120 | // The tree may have been left in some sort of half-baked state, so rebuild it |
| 121 | // from scratch |
| 122 | this.document.rebuildTree(); |
| 123 | } |
| 124 | } |
| 125 | // Mark the transaction as committed |
| 126 | this.transaction.markAsApplied(); |
| 127 | // Emit events in the queue |
| 128 | this.emitQueuedEvents(); |
| 129 | }; |
| 130 | |
| 131 | /** |
| 132 | * Queue a modification. |
| 133 | * |
| 134 | * @private |
| 135 | * @param {Object} modification Object describing the modification |
| 136 | * @param {string} modification.type Name of a method in ve.dm.TransactionProcessor.modifiers |
| 137 | * @param {Array} [modification.args] Arguments to pass to this method |
| 138 | * @throws {Error} Unrecognized modification type |
| 139 | */ |
| 140 | ve.dm.TransactionProcessor.prototype.queueModification = function ( modification ) { |
| 141 | if ( typeof ve.dm.TransactionProcessor.modifiers[ modification.type ] !== 'function' ) { |
| 142 | throw new Error( 'Unrecognized modification type ' + modification.type ); |
| 143 | } |
| 144 | this.modificationQueue.push( modification ); |
| 145 | }; |
| 146 | |
| 147 | /** |
| 148 | * Queue an undo function. If an exception is thrown while modifying, #rollbackModifications will |
| 149 | * invoke these functions in reverse order. |
| 150 | * |
| 151 | * @param {Function} func Undo function to add to the queue |
| 152 | */ |
| 153 | ve.dm.TransactionProcessor.prototype.queueUndoFunction = function ( func ) { |
| 154 | this.rollbackQueue.push( func ); |
| 155 | }; |
| 156 | |
| 157 | /** |
| 158 | * Apply all modifications queued through #queueModification, and add their rollback functions |
| 159 | * to this.rollbackQueue. |
| 160 | * |
| 161 | * @private |
| 162 | */ |
| 163 | ve.dm.TransactionProcessor.prototype.applyModifications = function () { |
| 164 | const modifications = this.modificationQueue; |
| 165 | |
| 166 | this.modificationQueue = []; |
| 167 | for ( let i = 0, len = modifications.length; i < len; i++ ) { |
| 168 | const modifier = ve.dm.TransactionProcessor.modifiers[ modifications[ i ].type ]; |
| 169 | modifier.apply( this, modifications[ i ].args || [] ); |
| 170 | } |
| 171 | }; |
| 172 | |
| 173 | /** |
| 174 | * Roll back all modifications that have been applied so far. This invokes the callbacks returned |
| 175 | * by the modifier functions. |
| 176 | * |
| 177 | * @private |
| 178 | */ |
| 179 | ve.dm.TransactionProcessor.prototype.rollbackModifications = function () { |
| 180 | const rollbacks = this.rollbackQueue; |
| 181 | this.rollbackQueue = []; |
| 182 | for ( let i = rollbacks.length - 1; i >= 0; i-- ) { |
| 183 | rollbacks[ i ](); |
| 184 | } |
| 185 | }; |
| 186 | |
| 187 | /** |
| 188 | * Queue an event to be emitted on a node. |
| 189 | * |
| 190 | * Duplicate events will be ignored only if all arguments match exactly (i.e. are reference-equal). |
| 191 | * |
| 192 | * @private |
| 193 | * @param {ve.dm.Node} node |
| 194 | * @param {string} name Event name |
| 195 | * @param {...any} [args] Additional arguments to be passed to the event when fired |
| 196 | */ |
| 197 | ve.dm.TransactionProcessor.prototype.queueEvent = function ( node, name, ...args ) { |
| 198 | this.eventQueue.push( { |
| 199 | node, |
| 200 | name, |
| 201 | args: args.concat( this.transaction ) |
| 202 | } ); |
| 203 | }; |
| 204 | |
| 205 | /** |
| 206 | * Emit all events queued through #queueEvent. |
| 207 | * |
| 208 | * @private |
| 209 | */ |
| 210 | ve.dm.TransactionProcessor.prototype.emitQueuedEvents = function () { |
| 211 | const queue = this.eventQueue; |
| 212 | this.eventQueue = []; |
| 213 | queue.forEach( ( event, i ) => { |
| 214 | // Check if this event is a duplicate of something we've already emitted |
| 215 | if ( !queue.slice( 0, i ).some( ( e ) => ve.compare( event, e ) ) ) { |
| 216 | event.node.emit( event.name, ...event.args ); |
| 217 | } |
| 218 | } ); |
| 219 | }; |
| 220 | |
| 221 | /** |
| 222 | * Advance the main data cursor. |
| 223 | * |
| 224 | * @private |
| 225 | * @param {number} increment Number of positions to increment the cursor by |
| 226 | */ |
| 227 | ve.dm.TransactionProcessor.prototype.advanceCursor = function ( increment ) { |
| 228 | this.cursor += increment; |
| 229 | }; |
| 230 | |
| 231 | /** |
| 232 | * Modifier methods. |
| 233 | * |
| 234 | * Each method executes a specific type of linear model modification, updates the model tree, and |
| 235 | * returns a function that undoes the linear model modification, in case we need to recover the |
| 236 | * previous linear model state. (The returned undo function does not undo the model tree update.) |
| 237 | * Methods are called in the context of a transaction processor, so they work similar to normal |
| 238 | * methods on the object. |
| 239 | * |
| 240 | * @class ve.dm.TransactionProcessor.modifiers |
| 241 | * @singleton |
| 242 | */ |
| 243 | |
| 244 | /** |
| 245 | * Splice data into / out of the data array, and synchronize the tree. |
| 246 | * |
| 247 | * For efficiency, this function modifies the splice operation objects (i.e. the elements |
| 248 | * of the splices array). It also relies on these objects not being modified by others later. |
| 249 | * |
| 250 | * @param {Object[]} splices Array of splice operations to execute. Properties: |
| 251 | * {number} splices[].offset Offset to remove/insert at (unadjusted) |
| 252 | * {number} splices[].removeLength Number of elements to remove |
| 253 | * {Array} splices[].insert Data to insert; for efficiency, objects are inserted without cloning |
| 254 | */ |
| 255 | ve.dm.TransactionProcessor.modifiers.splice = function ( splices ) { |
| 256 | const data = this.document.data; |
| 257 | |
| 258 | let lengthDiff = 0; |
| 259 | let i; |
| 260 | // We're about to do lots of things that can go wrong, so queue an undo function now |
| 261 | // that undoes all splices that we got to |
| 262 | this.queueUndoFunction( () => { |
| 263 | for ( let i2 = splices.length - 1; i2 >= 0; i2-- ) { |
| 264 | const s2 = splices[ i ]; |
| 265 | if ( s2.removedData !== undefined ) { |
| 266 | data.batchSplice( s2.offset, s2.insert.length, s2.removedData ); |
| 267 | } |
| 268 | } |
| 269 | } ); |
| 270 | |
| 271 | // Apply splices to the linmod and record how to undo them |
| 272 | for ( i = 0; i < splices.length; i++ ) { |
| 273 | const s = splices[ i ]; |
| 274 | |
| 275 | // Adjust s.offset for previous modifications that have already been synced to the tree; |
| 276 | // this value is used by the tree sync code later. |
| 277 | s.treeOffset = s.offset + this.adjustment; |
| 278 | // Also adjust s.offset for previous iterations of this loop (i.e. unsynced modifications); |
| 279 | // this is the value we need for the actual array splice. |
| 280 | s.offset = s.treeOffset + lengthDiff; |
| 281 | |
| 282 | // Perform the splice and put the removed data in s, for the undo function |
| 283 | s.removedData = data.batchSplice( s.offset, s.removeLength, s.insert ); |
| 284 | lengthDiff += s.insert.length - s.removeLength; |
| 285 | } |
| 286 | this.adjustment += lengthDiff; |
| 287 | }; |
| 288 | |
| 289 | /** |
| 290 | * Set an attribute at a given offset. |
| 291 | * |
| 292 | * @param {number} offset Offset in data array (unadjusted) |
| 293 | * @param {string} key Attribute name |
| 294 | * @param {any} value New attribute value |
| 295 | */ |
| 296 | ve.dm.TransactionProcessor.modifiers.setAttribute = function ( offset, key, value ) { |
| 297 | const data = this.document.data; |
| 298 | offset += this.adjustment; |
| 299 | |
| 300 | const oldItem = data.getData( offset ); |
| 301 | const oldValue = oldItem.attributes && oldItem.attributes[ key ]; |
| 302 | data.setAttributeAtOffset( offset, key, value ); |
| 303 | this.queueUndoFunction( () => { |
| 304 | data.setAttributeAtOffset( offset, key, oldValue ); |
| 305 | } ); |
| 306 | |
| 307 | const node = this.document.getDocumentNode().getNodeFromOffset( offset + 1 ); |
| 308 | // Update node element pointer |
| 309 | node.element = data.getData( offset ); |
| 310 | |
| 311 | this.queueEvent( node, 'attributeChange', key, oldValue, value ); |
| 312 | this.queueEvent( node, 'update', this.isStaging ); |
| 313 | }; |
| 314 | |
| 315 | /** |
| 316 | * Processing methods. |
| 317 | * |
| 318 | * Each method is specific to a type of action. Methods are called in the context of a transaction |
| 319 | * processor, so they work similar to normal methods on the object. |
| 320 | * |
| 321 | * @class ve.dm.TransactionProcessor.processors |
| 322 | * @singleton |
| 323 | */ |
| 324 | |
| 325 | /** |
| 326 | * Execute a retain operation. |
| 327 | * |
| 328 | * Called within the context of a transaction processor instance; moves the cursor by op.length |
| 329 | * |
| 330 | * @param {Object} op Operation object: |
| 331 | * @param {number} op.length Number of elements to retain |
| 332 | */ |
| 333 | ve.dm.TransactionProcessor.processors.retain = function ( op ) { |
| 334 | if ( !this.balanced ) { |
| 335 | // Track the depth of retained data when in the middle of an unbalanced replace |
| 336 | const retainedData = this.document.getData( new ve.Range( this.cursor, this.cursor + op.length ) ); |
| 337 | for ( let i = 0; i < retainedData.length; i++ ) { |
| 338 | const type = retainedData[ i ].type; |
| 339 | if ( type !== undefined ) { |
| 340 | this.retainDepth += type.charAt( 0 ) === '/' ? -1 : 1; |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | this.advanceCursor( op.length ); |
| 345 | }; |
| 346 | |
| 347 | /** |
| 348 | * Execute an attribute operation. |
| 349 | * |
| 350 | * This method is called within the context of a transaction processor instance. |
| 351 | * |
| 352 | * This sets the attribute named `op.key` on the element at `this.cursor` to `op.to`, or unsets it if |
| 353 | * `op.to === undefined`. `op.from` is not checked against the old value, but is used instead of `op.to` |
| 354 | * in reverse mode. So if `op.from` is incorrect, the transaction will commit fine, but won't roll |
| 355 | * back correctly. |
| 356 | * |
| 357 | * @param {Object} op Operation object |
| 358 | * @param {string} op.key Attribute name |
| 359 | * @param {any} op.from Old attribute value, or undefined if not previously set |
| 360 | * @param {any} op.to New attribute value, or undefined to unset |
| 361 | */ |
| 362 | ve.dm.TransactionProcessor.processors.attribute = function ( op ) { |
| 363 | if ( !this.document.data.isElementData( this.cursor ) ) { |
| 364 | throw new Error( 'Invalid element error, cannot set attributes on non-element data' ); |
| 365 | } |
| 366 | this.queueModification( { |
| 367 | type: 'setAttribute', |
| 368 | args: [ this.cursor, op.key, op.to ] |
| 369 | } ); |
| 370 | }; |
| 371 | |
| 372 | /** |
| 373 | * Verify a replace operation (the actual processing is now done in ve.dm.TreeModifier) |
| 374 | * |
| 375 | * @param {Object} op Operation object |
| 376 | * @param {Array} op.remove Linear model data to remove |
| 377 | * @param {Array} op.insert Linear model data to insert |
| 378 | */ |
| 379 | ve.dm.TransactionProcessor.processors.replace = function ( op ) { |
| 380 | // Track balancedness for verification purposes only |
| 381 | |
| 382 | // Walk through the remove and insert data |
| 383 | // and keep track of the element depth change (level) |
| 384 | // for each of these two separately. The model is |
| 385 | // only consistent if both levels are zero. |
| 386 | let i, type; |
| 387 | for ( i = 0; i < op.remove.length; i++ ) { |
| 388 | type = op.remove[ i ].type; |
| 389 | if ( type !== undefined ) { |
| 390 | if ( type.charAt( 0 ) === '/' ) { |
| 391 | // Closing element |
| 392 | this.replaceRemoveLevel--; |
| 393 | } else { |
| 394 | // Opening element |
| 395 | this.replaceRemoveLevel++; |
| 396 | } |
| 397 | } |
| 398 | } |
| 399 | for ( i = 0; i < op.insert.length; i++ ) { |
| 400 | type = op.insert[ i ].type; |
| 401 | if ( type !== undefined ) { |
| 402 | if ( type.charAt( 0 ) === '/' ) { |
| 403 | // Closing element |
| 404 | this.replaceInsertLevel--; |
| 405 | } else { |
| 406 | // Opening element |
| 407 | this.replaceInsertLevel++; |
| 408 | } |
| 409 | } |
| 410 | } |
| 411 | this.advanceCursor( op.remove.length ); |
| 412 | |
| 413 | this.balanced = |
| 414 | this.replaceRemoveLevel === 0 && |
| 415 | this.replaceInsertLevel === 0 && |
| 416 | this.retainDepth === 0; |
| 417 | }; |