Debian Codegraph @

extensions/VisualEditor/lib/ve/src/dm/ve.dm.Surface.js

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel Surface class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * DataModel surface for a node within a document
9 *
10 * Methods do not check that ranges actually lie inside the surfaced node
11 *
12 * @class
13 * @mixes OO.EventEmitter
14 *
15 * @constructor
16 * @param {ve.dm.Document} doc Document model to create surface for
17 * @param {ve.dm.BranchNode} [attachedRoot] Branch node which is editable; default is document node
18 * @param {Object} [config] Configuration options
19 * @param {boolean} [config.sourceMode=false] Source editing mode
20 */
21 ve.dm.Surface = function VeDmSurface( doc, attachedRoot, config ) {
22 // Support old (doc, config) argument order
23 // TODO: Remove this once all callers are updated
24 if ( !config && ve.isPlainObject( attachedRoot ) ) {
25 config = attachedRoot;
26 attachedRoot = undefined;
27 }
28
29 config = config || {};
30
31 attachedRoot = attachedRoot || doc.getDocumentNode();
32 if ( !( attachedRoot instanceof ve.dm.BranchNode ) ) {
33 throw new Error( 'Expected ve.dm.BranchNode for attachedRoot' );
34 }
35 doc.setAttachedRoot( attachedRoot );
36
37 // Mixin constructors
38 OO.EventEmitter.call( this );
39
40 // Properties
41 this.documentModel = doc;
42 // Deprecated: Use getDocument().getAttachedRoot()
43 this.attachedRoot = attachedRoot;
44 this.sourceMode = !!config.sourceMode;
45 this.selection = new ve.dm.NullSelection();
46 // The selection before the most recent stack of changes was applied
47 this.selectionBefore = this.selection;
48 this.translatedSelection = null;
49 this.branchNodes = {};
50 this.selectedNode = null;
51 this.newTransactions = [];
52 this.stagingStack = [];
53 this.undoStack = [];
54 this.undoIndex = 0;
55 this.undoConflict = false;
56 this.historyTrackingInterval = null;
57 this.insertionAnnotations = new ve.dm.AnnotationSet( this.getDocument().getStore() );
58 this.selectedAnnotations = new ve.dm.AnnotationSet( this.getDocument().getStore() );
59 this.isCollapsed = null;
60 this.multiUser = false;
61 this.readOnly = false;
62 this.transacting = false;
63 this.queueingContextChanges = false;
64 this.contextChangeQueued = false;
65 this.authorId = null;
66 this.lastStoredChange = doc.getCompleteHistoryLength();
67 this.autosaveFailed = false;
68 this.autosavePrefix = '';
69 this.synchronizer = null;
70 this.storing = false;
71 this.setStorage( ve.init.platform.sessionStorage );
72
73 // Events
74 this.getDocument().connect( this, {
75 transact: 'onDocumentTransact',
76 precommit: 'onDocumentPreCommit'
77 } );
78 this.storeChangesListener = this.storeChanges.bind( this );
79 this.storeDocStorageListener = this.storeDocStorage.bind( this );
80 };
81
82 /* Inheritance */
83
84 OO.mixinClass( ve.dm.Surface, OO.EventEmitter );
85
86 /* Events */
87
88 /**
89 * @event ve.dm.Surface#select
90 * @param {ve.dm.Selection} selection
91 */
92
93 /**
94 * The selection was just set to a non-null selection
95 *
96 * @event ve.dm.Surface#focus
97 */
98
99 /**
100 * The selection was just set to a null selection
101 *
102 * @event ve.dm.Surface#blur
103 */
104
105 /**
106 * Emitted when a transaction has been processed on the document and the selection has been
107 * translated to account for that transaction. You should only use this event if you need
108 * to access the selection; in most cases, you should use {ve.dm.Document#event-transact}.
109 *
110 * @event ve.dm.Surface#documentUpdate
111 * @param {ve.dm.Transaction} tx Transaction that was processed on the document
112 */
113
114 /**
115 * @event ve.dm.Surface#contextChange
116 */
117
118 /**
119 * @event ve.dm.Surface#insertionAnnotationsChange
120 * @param {ve.dm.AnnotationSet} insertionAnnotations AnnotationSet being inserted
121 */
122
123 /**
124 * Emitted when the history stacks change, or the ability to use them changes.
125 *
126 * @event ve.dm.Surface#history
127 */
128
129 /**
130 * Emitted when the main undo stack changes (this.undoStack or this.undoIndex).
131 *
132 * @event ve.dm.Surface#undoStackChange
133 */
134
135 /**
136 * Auto-save failed to store a change
137 *
138 * @event ve.dm.Surface#autosaveFailed
139 */
140
141 /* Methods */
142
143 /**
144 * Set the read-only state of the surface
145 *
146 * @param {boolean} readOnly Make surface read-only
147 */
148 ve.dm.Surface.prototype.setReadOnly = function ( readOnly ) {
149 if ( !!readOnly !== this.readOnly ) {
150 this.readOnly = !!readOnly;
151 if ( readOnly ) {
152 this.stopHistoryTracking();
153 } else {
154 this.startHistoryTracking();
155 }
156 this.getDocument().setReadOnly( readOnly );
157 this.emit( 'contextChange' );
158 }
159 };
160
161 /**
162 * Check if the surface is read-only
163 *
164 * @return {boolean}
165 */
166 ve.dm.Surface.prototype.isReadOnly = function () {
167 return this.readOnly;
168 };
169
170 /**
171 * Initialize the surface model
172 *
173 * @fires ve.dm.Surface#contextChange
174 */
175 ve.dm.Surface.prototype.initialize = function () {
176 this.startHistoryTracking();
177 this.emit( 'contextChange' );
178 };
179
180 /**
181 * Get the DOM representation of the surface's current state.
182 *
183 * @return {HTMLDocument|string} HTML document (visual mode) or text (source mode)
184 */
185 ve.dm.Surface.prototype.getDom = function () {
186 if ( this.sourceMode ) {
187 return ve.dm.sourceConverter.getSourceTextFromModel( this.getDocument() );
188 } else {
189 return ve.dm.converter.getDomFromModel( this.getDocument() );
190 }
191 };
192
193 /**
194 * Get the HTML representation of the surface's current state.
195 *
196 * @return {string} HTML
197 */
198 ve.dm.Surface.prototype.getHtml = function () {
199 return this.sourceMode ?
200 this.getDom() :
201 ve.properInnerHtml( this.getDom().body );
202 };
203
204 /**
205 * Set the surface multi-user mode
206 *
207 * @param {boolean} multiUser Multi-user mode
208 */
209 ve.dm.Surface.prototype.setMultiUser = function ( multiUser ) {
210 this.multiUser = multiUser;
211 };
212
213 /**
214 * Check if the surface is in multi-user mode
215 *
216 * @return {boolean} Surface is in multi-user mode
217 */
218 ve.dm.Surface.prototype.isMultiUser = function () {
219 return this.multiUser;
220 };
221
222 /**
223 * Create a surface synchronizer.
224 *
225 * Must be created before the surface model is added to a view.
226 *
227 * @param {string} documentId Document ID
228 * @param {Object} [config] Configuration options
229 */
230 ve.dm.Surface.prototype.createSynchronizer = function ( documentId, config ) {
231 if ( this.synchronizer ) {
232 throw new Error( 'Synchronizer already set' );
233 }
234
235 this.setNullSelection();
236 this.setMultiUser( true );
237
238 this.synchronizer = new ve.dm.SurfaceSynchronizer( this, documentId, config );
239 };
240
241 /**
242 * Start tracking state changes in history.
243 */
244 ve.dm.Surface.prototype.startHistoryTracking = function () {
245 if ( this.readOnly ) {
246 return;
247 }
248 if ( this.historyTrackingInterval === null ) {
249 this.historyTrackingInterval = setInterval( this.breakpoint.bind( this ), 3000 );
250 }
251 };
252
253 /**
254 * Stop tracking state changes in history.
255 */
256 ve.dm.Surface.prototype.stopHistoryTracking = function () {
257 if ( this.readOnly ) {
258 return;
259 }
260 if ( this.historyTrackingInterval !== null ) {
261 clearInterval( this.historyTrackingInterval );
262 this.historyTrackingInterval = null;
263 }
264 };
265
266 /**
267 * Reset the timer for automatic history-tracking
268 */
269 ve.dm.Surface.prototype.resetHistoryTrackingInterval = function () {
270 this.stopHistoryTracking();
271 this.startHistoryTracking();
272 };
273
274 /**
275 * @typedef {Object} UndoStackItem
276 * @memberof ve.dm.Surface
277 * @property {number} start
278 * @property {ve.dm.Transaction[]} transactions
279 * @property {ve.dm.Selection} selection
280 * @property {ve.dm.Selection} selectionBefore
281 */
282
283 /**
284 * Get a list of all applied history states.
285 *
286 * @return {ve.dm.Surface.UndoStackItem[]} List of applied transaction stacks
287 */
288 ve.dm.Surface.prototype.getHistory = function () {
289 const appliedUndoStack = this.undoStack.slice( 0, this.undoStack.length - this.undoIndex );
290 if ( this.newTransactions.length > 0 ) {
291 appliedUndoStack.push( { transactions: this.newTransactions.slice( 0 ) } );
292 }
293 return appliedUndoStack;
294 };
295
296 /**
297 * If the surface in staging mode.
298 *
299 * @return {boolean} The surface in staging mode
300 */
301 ve.dm.Surface.prototype.isStaging = function () {
302 return this.stagingStack.length > 0;
303 };
304
305 /**
306 * @typedef {Object} StagingState
307 * @memberof ve.dm.Surface
308 * @property {ve.dm.Transaction[]} transactions Staging transactions
309 * @property {ve.dm.Selection} selectionBefore Selection before transactions were applied
310 * @property {boolean} allowUndo Allow undo while staging
311 */
312
313 /**
314 * Get the staging state at the current staging stack depth
315 *
316 * @return {ve.dm.Surface.StagingState|undefined} staging Staging state object, or undefined if not staging
317 */
318 ve.dm.Surface.prototype.getStaging = function () {
319 return this.stagingStack[ this.stagingStack.length - 1 ];
320 };
321
322 /**
323 * Undo is allowed at the current staging stack depth
324 *
325 * @return {boolean|undefined} Undo is allowed, or undefined if not staging
326 */
327 ve.dm.Surface.prototype.doesStagingAllowUndo = function () {
328 const staging = this.getStaging();
329 return staging && staging.allowUndo;
330 };
331
332 /**
333 * Get the staging transactions at the current staging stack depth
334 *
335 * The array is returned by reference so it can be pushed to.
336 *
337 * @return {ve.dm.Transaction[]|undefined} Staging transactions, or undefined if not staging
338 */
339 ve.dm.Surface.prototype.getStagingTransactions = function () {
340 const staging = this.getStaging();
341 return staging && staging.transactions;
342 };
343
344 /**
345 * Push another level of staging to the staging stack
346 *
347 * @param {boolean} [allowUndo=false] Allow undo while staging
348 * @fires ve.dm.Surface#history
349 */
350 ve.dm.Surface.prototype.pushStaging = function ( allowUndo ) {
351 // If we're starting staging stop history tracking
352 if ( !this.isStaging() ) {
353 if ( this.synchronizer ) {
354 this.synchronizer.pauseChanges();
355 }
356 // Set a breakpoint to make sure newTransactions is clear
357 this.breakpoint();
358 this.stopHistoryTracking();
359 this.emit( 'history' );
360 }
361 this.stagingStack.push( {
362 transactions: [],
363 // Will get overridden after the first transaction, but while the
364 // stack is empty, should be equal to the previous selectionBefore.
365 selectionBefore: this.isStaging() ? this.getStaging().selectionBefore : this.selectionBefore,
366 allowUndo: !!allowUndo
367 } );
368 };
369
370 /**
371 * Pop a level of staging from the staging stack
372 *
373 * @fires ve.dm.Surface#history
374 * @return {ve.dm.Transaction[]|undefined} Staging transactions, or undefined if not staging
375 */
376 ve.dm.Surface.prototype.popStaging = function () {
377 if ( !this.isStaging() ) {
378 return;
379 }
380
381 const staging = this.stagingStack.pop();
382 const transactions = staging.transactions;
383 const reverseTransactions = [];
384
385 // Not applying, so rollback transactions
386 for ( let i = transactions.length - 1; i >= 0; i-- ) {
387 const transaction = transactions[ i ].reversed();
388 reverseTransactions.push( transaction );
389 }
390 this.changeInternal( reverseTransactions, staging.selectionBefore, true );
391
392 if ( !this.isStaging() ) {
393 if ( this.synchronizer ) {
394 this.synchronizer.resumeChanges();
395 }
396 this.startHistoryTracking();
397 this.emit( 'history' );
398 }
399
400 return transactions;
401 };
402
403 /**
404 * Apply a level of staging from the staging stack
405 *
406 * @fires ve.dm.Surface#history
407 */
408 ve.dm.Surface.prototype.applyStaging = function () {
409 if ( !this.isStaging() ) {
410 return;
411 }
412
413 const staging = this.stagingStack.pop();
414
415 if ( this.isStaging() ) {
416 // Merge popped transactions into the current item in the staging stack
417 ve.batchPush( this.getStagingTransactions(), staging.transactions );
418 // If the current level has a null selectionBefore, copy that over too
419 if ( this.getStaging().selectionBefore.isNull() ) {
420 this.getStaging().selectionBefore = staging.selectionBefore;
421 }
422 } else {
423 this.truncateUndoStack();
424 // Move transactions to the undo stack
425 this.newTransactions = staging.transactions;
426 this.selectionBefore = staging.selectionBefore;
427 this.breakpoint();
428 }
429
430 if ( !this.isStaging() ) {
431 if ( this.synchronizer ) {
432 this.synchronizer.resumeChanges();
433 }
434 this.startHistoryTracking();
435 this.emit( 'history' );
436 }
437 };
438
439 /**
440 * Pop the staging stack until empty
441 *
442 * @return {ve.dm.Transaction[]|undefined} Staging transactions, or undefined if not staging
443 */
444 ve.dm.Surface.prototype.popAllStaging = function () {
445 if ( !this.isStaging() ) {
446 return;
447 }
448
449 const transactions = [];
450 while ( this.isStaging() ) {
451 ve.batchSplice( transactions, 0, 0, this.popStaging() );
452 }
453 return transactions;
454 };
455
456 /**
457 * Apply the staging stack until empty
458 */
459 ve.dm.Surface.prototype.applyAllStaging = function () {
460 while ( this.isStaging() ) {
461 this.applyStaging();
462 }
463 };
464
465 /**
466 * Get annotations that will be used upon insertion.
467 *
468 * @return {ve.dm.AnnotationSet} Insertion annotations
469 */
470 ve.dm.Surface.prototype.getInsertionAnnotations = function () {
471 return this.insertionAnnotations.clone();
472 };
473
474 /**
475 * Set annotations that will be used upon insertion.
476 *
477 * @param {ve.dm.AnnotationSet|null} annotations Insertion annotations to use or null to disable them
478 * @fires ve.dm.Surface#insertionAnnotationsChange
479 * @fires ve.dm.Surface#contextChange
480 */
481 ve.dm.Surface.prototype.setInsertionAnnotations = function ( annotations ) {
482 if ( this.readOnly ) {
483 return;
484 }
485 this.insertionAnnotations = annotations !== null ?
486 annotations.clone() :
487 new ve.dm.AnnotationSet( this.getDocument().getStore() );
488
489 this.emit( 'insertionAnnotationsChange', this.insertionAnnotations );
490 this.emit( 'contextChange' );
491 };
492
493 /**
494 * Add an annotation to be used upon insertion.
495 *
496 * @param {ve.dm.Annotation|ve.dm.AnnotationSet} annotations Insertion annotation to add
497 * @fires ve.dm.Surface#insertionAnnotationsChange
498 * @fires ve.dm.Surface#contextChange
499 */
500 ve.dm.Surface.prototype.addInsertionAnnotations = function ( annotations ) {
501 if ( this.readOnly ) {
502 return;
503 }
504 if ( annotations instanceof ve.dm.Annotation ) {
505 this.insertionAnnotations.push( annotations );
506 } else if ( annotations instanceof ve.dm.AnnotationSet ) {
507 this.insertionAnnotations.addSet( annotations );
508 } else {
509 throw new Error( 'Invalid annotations' );
510 }
511
512 this.emit( 'insertionAnnotationsChange', this.insertionAnnotations );
513 this.emit( 'contextChange' );
514 };
515
516 /**
517 * Remove an annotation from those that will be used upon insertion.
518 *
519 * @param {ve.dm.Annotation|ve.dm.AnnotationSet} annotations Insertion annotation to remove
520 * @fires ve.dm.Surface#insertionAnnotationsChange
521 * @fires ve.dm.Surface#contextChange
522 */
523 ve.dm.Surface.prototype.removeInsertionAnnotations = function ( annotations ) {
524 if ( this.readOnly ) {
525 return;
526 }
527 if ( annotations instanceof ve.dm.Annotation ) {
528 this.insertionAnnotations.remove( annotations );
529 } else if ( annotations instanceof ve.dm.AnnotationSet ) {
530 this.insertionAnnotations.removeSet( annotations );
531 } else {
532 throw new Error( 'Invalid annotations' );
533 }
534
535 this.emit( 'insertionAnnotationsChange', this.insertionAnnotations );
536 this.emit( 'contextChange' );
537 };
538
539 /**
540 * Check if redo is allowed in the current state.
541 *
542 * @return {boolean} Redo is allowed
543 */
544 ve.dm.Surface.prototype.canRedo = function () {
545 return this.undoIndex > 0 && !this.readOnly;
546 };
547
548 /**
549 * Check if undo is allowed in the current state.
550 *
551 * @return {boolean} Undo is allowed
552 */
553 ve.dm.Surface.prototype.canUndo = function () {
554 return this.hasBeenModified() && !this.readOnly && ( !this.isStaging() || this.doesStagingAllowUndo() ) && !this.undoConflict;
555 };
556
557 /**
558 * Check if the surface has been modified.
559 *
560 * This only checks if there are transactions which haven't been undone.
561 *
562 * @return {boolean} The surface has been modified
563 */
564 ve.dm.Surface.prototype.hasBeenModified = function () {
565 return this.undoStack.length - this.undoIndex > 0 || !!this.newTransactions.length;
566 };
567
568 /**
569 * Get the document model.
570 *
571 * @return {ve.dm.Document} Document model of the surface
572 */
573 ve.dm.Surface.prototype.getDocument = function () {
574 return this.documentModel;
575 };
576
577 /**
578 * Get the surfaced node
579 *
580 * @deprecated Use getDocument().getAttachedRoot()
581 * @return {ve.dm.BranchNode} The surfaced node
582 */
583 ve.dm.Surface.prototype.getAttachedRoot = function () {
584 OO.ui.warnDeprecation( 've.dm.Surface.getAttachedRoot() is deprecated. Use ve.dm.Surface.getDocument().getAttachedRoot() instead.' );
585 return this.attachedRoot;
586 };
587
588 /**
589 * Get the selection.
590 *
591 * @return {ve.dm.Selection} Current selection
592 */
593 ve.dm.Surface.prototype.getSelection = function () {
594 return this.selection;
595 };
596
597 /**
598 * Get the selection translated for the transaction that's being committed, if any.
599 *
600 * @return {ve.dm.Selection} Current selection translated for new transaction
601 */
602 ve.dm.Surface.prototype.getTranslatedSelection = function () {
603 return this.translatedSelection || this.selection;
604 };
605
606 /**
607 * Get a fragment for a selection.
608 *
609 * @param {ve.dm.Selection} [selection] Selection within target document, current selection used by default
610 * @param {boolean} [noAutoSelect] Don't update the surface's selection when making changes
611 * @param {boolean} [excludeInsertions] Exclude inserted content at the boundaries when updating range
612 * @return {ve.dm.SurfaceFragment} Surface fragment
613 */
614 ve.dm.Surface.prototype.getFragment = function ( selection, noAutoSelect, excludeInsertions ) {
615 selection = selection || this.selection;
616 // TODO: Use a factory pattern to generate fragments
617 return this.sourceMode ?
618 new ve.dm.SourceSurfaceFragment( this, selection, noAutoSelect, excludeInsertions ) :
619 new ve.dm.SurfaceFragment( this, selection, noAutoSelect, excludeInsertions );
620 };
621
622 /**
623 * Get a fragment for a linear selection's range.
624 *
625 * @param {ve.Range} range Selection's range
626 * @param {boolean} [noAutoSelect] Don't update the surface's selection when making changes
627 * @param {boolean} [excludeInsertions] Exclude inserted content at the boundaries when updating range
628 * @return {ve.dm.SurfaceFragment} Surface fragment
629 */
630 ve.dm.Surface.prototype.getLinearFragment = function ( range, noAutoSelect, excludeInsertions ) {
631 return this.getFragment( new ve.dm.LinearSelection( range ), noAutoSelect, excludeInsertions );
632 };
633
634 /**
635 * Prevent future states from being redone.
636 *
637 * Callers should eventually emit a 'history' event after using this method.
638 *
639 * @fires ve.dm.Surface#undoStackChange
640 */
641 ve.dm.Surface.prototype.truncateUndoStack = function () {
642 if ( this.undoIndex ) {
643 this.undoStack = this.undoStack.slice( 0, this.undoStack.length - this.undoIndex );
644 this.undoIndex = 0;
645 this.emit( 'undoStackChange' );
646 }
647 };
648
649 /**
650 * Start queueing up calls to #emitContextChange until #stopQueueingContextChanges is called.
651 * While queueing is active, contextChanges are also collapsed, so if #emitContextChange is called
652 * multiple times, only one contextChange event will be emitted by #stopQueueingContextChanges.
653 *
654 * this.emitContextChange(); // emits immediately
655 * this.startQueueingContextChanges();
656 * this.emitContextChange(); // doesn't emit
657 * this.emitContextChange(); // doesn't emit
658 * this.stopQueueingContextChanges(); // emits one contextChange event
659 *
660 * @private
661 */
662 ve.dm.Surface.prototype.startQueueingContextChanges = function () {
663 if ( !this.queueingContextChanges ) {
664 this.queueingContextChanges = true;
665 this.contextChangeQueued = false;
666 }
667 };
668
669 /**
670 * Emit a contextChange event. If #startQueueingContextChanges has been called, then the event
671 * is deferred until #stopQueueingContextChanges is called.
672 *
673 * @private
674 * @fires ve.dm.Surface#contextChange
675 */
676 ve.dm.Surface.prototype.emitContextChange = function () {
677 if ( this.queueingContextChanges ) {
678 this.contextChangeQueued = true;
679 } else {
680 this.emit( 'contextChange' );
681 }
682 };
683
684 /**
685 * Stop queueing contextChange events. If #emitContextChange was called previously, a contextChange
686 * event will now be emitted. Any future calls to #emitContextChange will once again emit the
687 * event immediately.
688 *
689 * @private
690 * @fires ve.dm.Surface#contextChange
691 */
692 ve.dm.Surface.prototype.stopQueueingContextChanges = function () {
693 if ( this.queueingContextChanges ) {
694 this.queueingContextChanges = false;
695 if ( this.contextChangeQueued ) {
696 this.contextChangeQueued = false;
697 this.emit( 'contextChange' );
698 }
699 }
700 };
701
702 /**
703 * Set a linear selection at a specified range on the model
704 *
705 * @param {ve.Range} range Range to create linear selection at
706 */
707 ve.dm.Surface.prototype.setLinearSelection = function ( range ) {
708 this.setSelection( new ve.dm.LinearSelection( range ) );
709 };
710
711 /**
712 * Set a null selection on the model
713 */
714 ve.dm.Surface.prototype.setNullSelection = function () {
715 this.setSelection( new ve.dm.NullSelection() );
716 };
717
718 /**
719 * Grows a range so that any partially selected links are totally selected
720 *
721 * @param {ve.Range} range The range to regularize
722 * @return {ve.Range} Regularized range, possibly object-identical to the original
723 */
724 ve.dm.Surface.prototype.fixupRangeForLinks = function ( range ) {
725 if ( range.isCollapsed() ) {
726 return range;
727 }
728
729 const linearData = this.getDocument().data;
730
731 function getLinks( offset ) {
732 return linearData.getAnnotationsFromOffset( offset ).filter( ( ann ) => ann.name === 'link' );
733 }
734
735 // Search for links at start/end that don't cover the whole range.
736 // Assume at most one such link at each end.
737 let start = range.start;
738 let end = range.end;
739 const rangeAnnotations = linearData.getAnnotationsFromRange( range );
740 const startLink = getLinks( start ).diffWith( rangeAnnotations ).getHash( 0 );
741 const endLink = getLinks( end ).diffWith( rangeAnnotations ).getHash( 0 );
742
743 if ( startLink === undefined && endLink === undefined ) {
744 return range;
745 }
746
747 if ( startLink !== undefined ) {
748 while ( start > 0 && getLinks( start - 1 ).containsHash( startLink ) ) {
749 start--;
750 }
751 }
752 if ( endLink !== undefined ) {
753 while ( end < linearData.getLength() && getLinks( end ).containsHash( endLink ) ) {
754 end++;
755 }
756 }
757
758 if ( range.isBackwards() ) {
759 return new ve.Range( end, start );
760 } else {
761 return new ve.Range( start, end );
762 }
763 };
764
765 /**
766 * Change the selection
767 *
768 * @param {ve.dm.Selection} selection New selection
769 *
770 * @fires ve.dm.Surface#select
771 * @fires ve.dm.Surface#focus
772 * @fires ve.dm.Surface#blur
773 */
774 ve.dm.Surface.prototype.setSelection = function ( selection ) {
775 const oldSelection = this.selection;
776 let maxOffset;
777 if (
778 selection instanceof ve.dm.LinearSelection &&
779 ( maxOffset = this.getDocument().getDocumentRange().end ) &&
780 maxOffset < selection.getRange().end
781 ) {
782 // Selection is out of range
783 ve.error( 'Attempted to set an out of bounds selection: ' + JSON.stringify( selection ) + ', adjusting' );
784 // Fix up the selection so things don't break if the caller subsequently
785 // tries to use the selection
786 selection = new ve.dm.LinearSelection( new ve.Range(
787 Math.min( maxOffset, selection.getRange().start ),
788 maxOffset
789 ) );
790 // TODO: Check table selections too
791 }
792 this.translatedSelection = null;
793
794 if ( this.transacting ) {
795 // Update the selection but don't do any processing
796 this.selection = selection;
797 return;
798 }
799
800 let selectionChange = false;
801 // this.selection needs to be updated before we call setInsertionAnnotations
802 if ( !oldSelection.equals( selection ) ) {
803 selectionChange = true;
804 this.selection = selection;
805 }
806
807 function intersectRanges( rangeA, rangeB ) {
808 const rangeStart = Math.max( rangeA.start, rangeB.start );
809 const rangeEnd = Math.min( rangeA.end, rangeB.end );
810
811 return new ve.Range(
812 rangeStart,
813 // If rangeStart > rangeEnd there is no overlap, just return
814 // a collapsed range at rangeStart (this shouldn't happen here)
815 Math.max( rangeStart, rangeEnd )
816 );
817 }
818
819 let range;
820 let selectedNode;
821 const branchNodes = {};
822 let contextChange = false;
823 if ( selection instanceof ve.dm.LinearSelection ) {
824 range = selection.getRange();
825
826 // Update branch nodes
827 branchNodes.start = this.getDocument().getBranchNodeFromOffset( range.start );
828 branchNodes.startRange = intersectRanges( branchNodes.start.getRange(), range );
829 if ( !range.isCollapsed() ) {
830 branchNodes.end = this.getDocument().getBranchNodeFromOffset( range.end );
831 branchNodes.endRange = intersectRanges( branchNodes.end.getRange(), range );
832 } else {
833 branchNodes.end = branchNodes.start;
834 branchNodes.endRange = branchNodes.startRange;
835 }
836 selectedNode = this.getSelectedNodeFromSelection( selection );
837
838 // Source mode optimization
839 if ( !this.sourceMode ) {
840 const linearData = this.getDocument().data;
841 // Reset insertionAnnotations based on the neighbouring document data
842 const insertionAnnotations = linearData.getInsertionAnnotationsFromRange( range );
843 // If there's *any* difference in insertion annotations (even order), then:
844 // * emit insertionAnnotationsChange
845 // * emit contextChange (TODO: is this desirable?)
846 if ( !insertionAnnotations.equalsInOrder( this.insertionAnnotations ) ) {
847 this.setInsertionAnnotations( insertionAnnotations );
848 }
849
850 let selectedAnnotations;
851 // Reset selectedAnnotations
852 if ( range.isCollapsed() ) {
853 selectedAnnotations = linearData.getAnnotationsFromOffset( range.start );
854 } else {
855 selectedAnnotations = linearData.getAnnotationsFromRange( range, true );
856 }
857 if ( !selectedAnnotations.compareTo( this.selectedAnnotations ) ) {
858 this.selectedAnnotations = selectedAnnotations;
859 contextChange = true;
860 }
861
862 // Did the annotations at the focus point of a non-collapsed selection
863 // change? (i.e. did the selection move in/out of an annotation as it
864 // expanded?)
865 if ( selectionChange && !range.isCollapsed() && oldSelection instanceof ve.dm.LinearSelection ) {
866 const rangeFocus = new ve.Range( range.to );
867 const oldRangeFocus = new ve.Range( oldSelection.getRange().to );
868 const focusRangeMovingBack = rangeFocus.to < oldRangeFocus.to;
869 // If we're moving back in the document, getInsertionAnnotationsFromRange
870 // needs to be told to fetch the annotations after the cursor, otherwise
871 // it'll trigger one position too soon.
872 if (
873 !linearData.getInsertionAnnotationsFromRange( rangeFocus, focusRangeMovingBack ).compareTo( linearData.getInsertionAnnotationsFromRange( oldRangeFocus, focusRangeMovingBack ) )
874 ) {
875 contextChange = true;
876 }
877 }
878 }
879 } else if ( selection instanceof ve.dm.TableSelection ) {
880 selectedNode = selection.getMatrixCells( this.getDocument() )[ 0 ].node;
881 contextChange = true;
882 } else if ( selection.isNull() ) {
883 contextChange = true;
884 }
885
886 if ( range && range.isCollapsed() !== this.isCollapsed ) {
887 // selectedAnnotations won't have changed if going from insertion annotations to
888 // selection of the same annotations, but some tools will consider that a context change
889 // (e.g. ClearAnnotationTool).
890 this.isCollapsed = range.isCollapsed();
891 contextChange = true;
892 }
893
894 // If branchNodes or selectedNode changed emit a contextChange
895 if (
896 selectedNode !== this.selectedNode ||
897 branchNodes.start !== this.branchNodes.start ||
898 branchNodes.end !== this.branchNodes.end
899 ) {
900 this.branchNodes = branchNodes;
901 this.selectedNode = selectedNode;
902 contextChange = true;
903 } else if (
904 branchNodes.startRange && this.branchNodes.startRange && (
905 branchNodes.startRange.isCollapsed() !== this.branchNodes.startRange.isCollapsed() ||
906 branchNodes.endRange.isCollapsed() !== this.branchNodes.endRange.isCollapsed()
907 )
908 ) {
909 // If the collapsed-ness of the selection within an edge node changes, the result of
910 // ve.dm.Surface#getSelectedLeafNodes could change, so emit a contextChange
911 this.branchNodes = branchNodes;
912 contextChange = true;
913 }
914
915 // If selection changed emit a select
916 if ( selectionChange ) {
917 this.emit( 'select', this.selection );
918 if ( oldSelection.isNull() ) {
919 this.emit( 'focus' );
920 }
921 if ( selection.isNull() ) {
922 this.emit( 'blur' );
923 }
924 }
925
926 if ( contextChange ) {
927 this.emitContextChange();
928 }
929
930 };
931
932 /**
933 * Apply a transactions and selection changes to the document.
934 *
935 * @param {ve.dm.Transaction|ve.dm.Transaction[]|null} transactions One or more transactions to
936 * process, or null to process none
937 * @param {ve.dm.Selection} [selection] Selection to apply
938 */
939 ve.dm.Surface.prototype.change = function ( transactions, selection ) {
940 this.changeInternal( transactions, selection, false );
941 };
942
943 /**
944 * Internal implementation of change(). Do not use this, use change() instead.
945 *
946 * @private
947 * @param {ve.dm.Transaction|ve.dm.Transaction[]|null} transactions
948 * @param {ve.dm.Selection} [selection]
949 * @param {boolean} [skipUndoStack=false] If true, do not modify the undo stack. Used by undo/redo
950 * @fires ve.dm.Surface#select
951 * @fires ve.dm.Surface#history
952 */
953 ve.dm.Surface.prototype.changeInternal = function ( transactions, selection, skipUndoStack ) {
954 const selectionBefore = this.selection;
955 let contextChange = false;
956
957 this.startQueueingContextChanges();
958
959 // Process transactions
960 if ( transactions && !this.readOnly ) {
961 if ( transactions instanceof ve.dm.Transaction ) {
962 transactions = [ transactions ];
963 }
964 this.transacting = true;
965 for ( let i = 0, len = transactions.length; i < len; i++ ) {
966 if ( !transactions[ i ].isNoOp() ) {
967 let committed;
968 // The .commit() call below indirectly invokes setSelection()
969 try {
970 committed = false;
971 this.getDocument().commit( transactions[ i ], this.isStaging() );
972 committed = true;
973 } finally {
974 if ( !committed ) {
975 this.stopQueueingContextChanges();
976 }
977 }
978 if ( !skipUndoStack ) {
979 if ( this.isStaging() ) {
980 if ( !this.getStagingTransactions().length ) {
981 this.getStaging().selectionBefore = selectionBefore;
982 }
983 this.getStagingTransactions().push( transactions[ i ] );
984 } else {
985 this.truncateUndoStack();
986 if ( !this.newTransactions.length ) {
987 this.selectionBefore = selectionBefore;
988 }
989 this.newTransactions.push( transactions[ i ] );
990 }
991 }
992 if ( transactions[ i ].hasElementAttributeOperations() ) {
993 contextChange = true;
994 }
995 }
996 }
997 this.transacting = false;
998 this.undoConflict = false;
999 this.emit( 'history' );
1000 }
1001 const selectionAfter = this.selection;
1002
1003 // Apply selection change
1004 if ( selection ) {
1005 this.setSelection( selection );
1006 } else if ( transactions ) {
1007 // Call setSelection() to trigger selection processing that was bypassed earlier
1008 this.setSelection( this.selection );
1009 }
1010
1011 // If the selection changed while applying the transactions but not while applying the
1012 // selection change, setSelection() won't have emitted a 'select' event. We don't want that
1013 // to happen, so emit one anyway.
1014 if (
1015 !selectionBefore.equals( selectionAfter ) &&
1016 selectionAfter.equals( this.selection )
1017 ) {
1018 this.emit( 'select', this.selection );
1019 }
1020
1021 if ( contextChange ) {
1022 this.emitContextChange();
1023 }
1024
1025 this.stopQueueingContextChanges();
1026 };
1027
1028 /**
1029 * Set a history state breakpoint.
1030 *
1031 * @return {boolean} A breakpoint was added
1032 * @fires ve.dm.Surface#undoStackChange
1033 */
1034 ve.dm.Surface.prototype.breakpoint = function () {
1035 if ( this.readOnly ) {
1036 return false;
1037 }
1038 let breakpointSet = false;
1039 this.resetHistoryTrackingInterval();
1040 if ( this.newTransactions.length > 0 ) {
1041 this.undoStack.push( {
1042 start: this.getDocument().getCompleteHistoryLength() - this.newTransactions.length,
1043 transactions: this.newTransactions,
1044 selection: this.selection,
1045 selectionBefore: this.selectionBefore
1046 } );
1047 this.newTransactions = [];
1048 this.emit( 'undoStackChange' );
1049 breakpointSet = true;
1050 }
1051 // Update selectionBefore even if nothing has changed
1052 this.selectionBefore = this.selection;
1053 return breakpointSet;
1054 };
1055
1056 /**
1057 * Step backwards in history.
1058 *
1059 * @fires ve.dm.Surface#undoStackChange
1060 * @fires ve.dm.Surface#history
1061 */
1062 ve.dm.Surface.prototype.undo = function () {
1063 if ( !this.canUndo() ) {
1064 return;
1065 }
1066
1067 if ( this.isStaging() ) {
1068 this.popAllStaging();
1069 }
1070
1071 this.breakpoint();
1072 this.undoIndex++;
1073
1074 const transactions = [];
1075 let item;
1076 if ( !this.isMultiUser() ) {
1077 item = this.undoStack[ this.undoStack.length - this.undoIndex ];
1078 if ( item ) {
1079 // Apply reversed transactions in reversed order
1080 for ( let i = item.transactions.length - 1; i >= 0; i-- ) {
1081 const transaction = item.transactions[ i ].reversed();
1082 transactions.push( transaction );
1083 }
1084 this.changeInternal( transactions, item.selectionBefore, true );
1085 this.emit( 'undoStackChange' );
1086 }
1087 } else {
1088 // Find the most recent stack item by this user
1089 while ( this.undoIndex <= this.undoStack.length ) {
1090 item = this.undoStack[ this.undoStack.length - this.undoIndex ];
1091 // Assume every transaction in the stack item has the same author (see ve.dm.Change#applyTo)
1092 const authorId = item.transactions[ 0 ].authorId;
1093 if ( authorId === null || authorId === this.getAuthorId() ) {
1094 break;
1095 }
1096 item = null;
1097 this.undoIndex++;
1098 }
1099 if ( item ) {
1100 const history = this.getDocument().getChangeSince( item.start + item.transactions.length );
1101 const done = new ve.dm.Change(
1102 item.start,
1103 item.transactions,
1104 // Undo cannot add store items, so we don't need to worry here
1105 item.transactions.map( () => new ve.dm.HashValueStore() ),
1106 {}
1107 );
1108 const result = ve.dm.Change.static.rebaseUncommittedChange( history, done.reversed() );
1109 if ( result.rejected ) {
1110 // Rebasing conflict: move pointer back and don't try again until next transaction
1111 this.undoIndex--;
1112 this.undoConflict = true;
1113 // Undo stack didn't change, but ability to undo did
1114 this.emit( 'history' );
1115 } else {
1116 const selection = item.selectionBefore.translateByChange( result.transposedHistory );
1117 // Undo cannot add store items, so we can safely apply just transactions
1118 this.changeInternal( result.rebased.transactions, selection, true );
1119 this.emit( 'undoStackChange' );
1120 }
1121 } else {
1122 // Undo stack didn't change, but ability to undo did
1123 this.emit( 'history' );
1124 }
1125 }
1126 };
1127
1128 /**
1129 * Step forwards in history.
1130 *
1131 * @fires ve.dm.Surface#undoStackChange
1132 */
1133 ve.dm.Surface.prototype.redo = function () {
1134 if ( !this.canRedo() ) {
1135 return;
1136 }
1137
1138 this.breakpoint();
1139
1140 const item = this.undoStack[ this.undoStack.length - this.undoIndex ];
1141 if ( item ) {
1142 this.undoIndex--;
1143 // ve.copy( item.transactions ) invokes .clone() on each transaction in item.transactions
1144 this.changeInternal( ve.copy( item.transactions ), item.selection, true );
1145 this.emit( 'undoStackChange' );
1146 }
1147 };
1148
1149 /**
1150 * Respond to transactions processed on the document by translating the selection and updating
1151 * other state.
1152 *
1153 * @param {ve.dm.Transaction} tx Transaction that was processed
1154 * @fires ve.dm.Surface#documentUpdate
1155 */
1156 ve.dm.Surface.prototype.onDocumentTransact = function ( tx ) {
1157 this.setSelection( this.getSelection().translateByTransactionWithAuthor( tx, this.authorId ) );
1158 this.emit( 'documentUpdate', tx );
1159 };
1160
1161 /**
1162 * Get the cached selected node covering the current selection, or null
1163 *
1164 * @return {ve.dm.Node|null} Selected node
1165 */
1166 ve.dm.Surface.prototype.getSelectedNode = function () {
1167 return this.selectedNode;
1168 };
1169
1170 /**
1171 * Get the selected node covering a specific selection, or null
1172 *
1173 * @param {ve.dm.Selection} [selection] Selection, defaults to the current selection
1174 * @return {ve.dm.Node|null} Selected node
1175 */
1176 ve.dm.Surface.prototype.getSelectedNodeFromSelection = function ( selection ) {
1177 selection = selection || this.getSelection();
1178
1179 if ( !( selection instanceof ve.dm.LinearSelection ) ) {
1180 return null;
1181 }
1182
1183 let selectedNode = null;
1184 const range = selection.getRange();
1185 if ( !range.isCollapsed() ) {
1186 const startNode = this.getDocument().documentNode.getNodeFromOffset( range.start + 1 );
1187 if ( startNode && startNode.getOuterRange().equalsSelection( range ) ) {
1188 selectedNode = startNode;
1189 }
1190 }
1191 return selectedNode;
1192 };
1193
1194 /**
1195 * Update translatedSelection early (before the commit actually occurs)
1196 *
1197 * This is so ve.ce.ContentBranchNode#getRenderedContents can consider the translated
1198 * selection for unicorn rendering.
1199 *
1200 * @param {ve.dm.Transaction} tx Transaction that's about to be committed
1201 */
1202 ve.dm.Surface.prototype.onDocumentPreCommit = function ( tx ) {
1203 this.translatedSelection = this.selection.translateByTransaction( tx );
1204 };
1205
1206 /**
1207 * Get a minimal set of ranges which have been modified by changes to the surface.
1208 *
1209 * @param {Object} [options] Options
1210 * @param {boolean} [options.includeCollapsed] Include collapsed ranges (removed content)
1211 * @param {boolean} [options.includeInternalList] Include changes within the internal list
1212 * @param {boolean} [options.excludeAnnotations] Exclude annotation-only changes
1213 * @param {boolean} [options.excludeAttributes] Exclude attribute changes
1214 * @return {ve.Range[]} Modified ranges
1215 */
1216 ve.dm.Surface.prototype.getModifiedRanges = function ( options ) {
1217 const doc = this.getDocument();
1218 const ranges = [];
1219
1220 options = options || {};
1221
1222 this.getHistory().forEach( ( stackItem ) => {
1223 stackItem.transactions.forEach( ( tx ) => {
1224 const newRange = tx.getModifiedRange( doc, options );
1225 // newRange will by null for no-ops
1226 if ( newRange ) {
1227 // Translate previous ranges by the current transaction
1228 ranges.forEach( ( range, i, arr ) => {
1229 arr[ i ] = tx.translateRange( range, true );
1230 } );
1231 if ( options.includeCollapsed || !newRange.isCollapsed() ) {
1232 ranges.push( newRange );
1233 }
1234 }
1235 } );
1236 } );
1237
1238 // Merge adjacent ranges
1239 const compactRanges = [];
1240 let lastRange = null;
1241 ranges
1242 .sort( ( a, b ) => a.start - b.start )
1243 .forEach( ( range ) => {
1244 if ( options.includeCollapsed || !range.isCollapsed() ) {
1245 if ( lastRange && lastRange.touchesRange( range ) ) {
1246 compactRanges.pop();
1247 range = lastRange.expand( range );
1248 }
1249 compactRanges.push( range );
1250 lastRange = range;
1251 }
1252 } );
1253
1254 return compactRanges;
1255 };
1256
1257 /**
1258 * Get a VE source-mode surface offset from a plaintext source offset.
1259 *
1260 * @param {number} offset Source text offset
1261 * @return {number} Surface offset
1262 * @throws {Error} Offset out of bounds
1263 */
1264 ve.dm.Surface.prototype.getOffsetFromSourceOffset = function ( offset ) {
1265 if ( offset < 0 ) {
1266 throw new Error( 'Offset out of bounds' );
1267 }
1268
1269 const lines = this.getDocument().getDocumentNode().getChildren();
1270 let lineOffset = 0,
1271 line = 0;
1272
1273 while ( lineOffset < offset + 1 ) {
1274 if ( !lines[ line ] || lines[ line ].isInternal() ) {
1275 throw new Error( 'Offset out of bounds' );
1276 }
1277 lineOffset += lines[ line ].getLength() + 1;
1278 line++;
1279 }
1280 return offset + line;
1281 };
1282
1283 /**
1284 * Get a plaintext source offset from a VE source-mode surface offset.
1285 *
1286 * @param {number} offset Surface offset
1287 * @return {number} Source text offset
1288 * @throws {Error} Offset out of bounds
1289 */
1290 ve.dm.Surface.prototype.getSourceOffsetFromOffset = function ( offset ) {
1291 if ( offset < 0 ) {
1292 throw new Error( 'Offset out of bounds' );
1293 }
1294
1295 const lines = this.getDocument().getDocumentNode().getChildren();
1296 let lineOffset = 0,
1297 line = 0;
1298
1299 while ( lineOffset < offset ) {
1300 if ( !lines[ line ] || lines[ line ].isInternal() ) {
1301 throw new Error( 'Offset out of bounds' );
1302 }
1303 lineOffset += lines[ line ].getOuterLength();
1304 line++;
1305 }
1306 return offset - line;
1307 };
1308
1309 /**
1310 * Get a VE source-mode surface range from plaintext source offsets.
1311 *
1312 * @param {number} from Source text from offset
1313 * @param {number} [to] Source text to offset, omit for a collapsed range
1314 * @return {ve.Range} Source surface offset
1315 */
1316 ve.dm.Surface.prototype.getRangeFromSourceOffsets = function ( from, to ) {
1317 const fromOffset = this.getOffsetFromSourceOffset( from );
1318 return new ve.Range(
1319 fromOffset,
1320 // Skip toOffset calculation if collapsed
1321 to === undefined || to === from ?
1322 fromOffset :
1323 this.getOffsetFromSourceOffset( to )
1324 );
1325 };
1326
1327 /**
1328 * Get the author ID
1329 *
1330 * @return {number} The author ID
1331 */
1332 ve.dm.Surface.prototype.getAuthorId = function () {
1333 return this.authorId;
1334 };
1335
1336 /**
1337 * Set the author ID
1338 *
1339 * @param {number} authorId The new author ID
1340 */
1341 ve.dm.Surface.prototype.setAuthorId = function ( authorId ) {
1342 this.authorId = authorId;
1343 };
1344
1345 /**
1346 * Store latest transactions into session storage
1347 *
1348 * @fires ve.dm.Surface#autosaveFailed
1349 */
1350 ve.dm.Surface.prototype.storeChanges = function () {
1351 if ( this.autosaveFailed ) {
1352 return;
1353 }
1354
1355 const dmDoc = this.getDocument();
1356 const change = dmDoc.getChangeSince( this.lastStoredChange );
1357 if ( !change.isEmpty() ) {
1358 const changes = this.storage.getObject( this.autosavePrefix + 've-changes' ) || [];
1359 changes.push( change );
1360 if ( this.storage.setObject( this.autosavePrefix + 've-changes', changes, this.storageExpiry ) ) {
1361 this.lastStoredChange = dmDoc.getCompleteHistoryLength();
1362 this.storage.setObject( this.autosavePrefix + 've-selection', this.getSelection(), this.storageExpiry );
1363 this.updateExpiry( [ 've-changes', 've-selection' ] );
1364 } else {
1365 // Auto-save failed probably because of memory limits
1366 // so flag it so we don't keep trying in vain.
1367 this.autosaveFailed = true;
1368 this.emit( 'autosaveFailed' );
1369 }
1370 }
1371 };
1372
1373 /**
1374 * Store persistent document storage into session storage
1375 */
1376 ve.dm.Surface.prototype.storeDocStorage = function () {
1377 if ( this.autosaveFailed ) {
1378 return;
1379 }
1380
1381 const dmDoc = this.getDocument();
1382 this.storage.setObject( this.autosavePrefix + 've-docstorage', dmDoc.getStorage(), this.storageExpiry );
1383 this.updateExpiry( [ 've-docstorage' ] );
1384 };
1385
1386 /**
1387 * Set an document ID for autosave.
1388 *
1389 * For session storage this is only required if there is more
1390 * than one document on the page.
1391 *
1392 * @param {string} docId Document ID.
1393 */
1394 ve.dm.Surface.prototype.setAutosaveDocId = function ( docId ) {
1395 this.autosavePrefix = docId + '/';
1396 };
1397
1398 /**
1399 * Set the storage interface for autosave
1400 *
1401 * @param {ve.init.ConflictableStorage} storage Storage interface
1402 * @param {number} [storageExpiry] Storage expiry time in seconds
1403 */
1404 ve.dm.Surface.prototype.setStorage = function ( storage, storageExpiry ) {
1405 if ( this.storing ) {
1406 throw new Error( 'Can\'t change storage interface after auto-save has stared' );
1407 }
1408 this.storage = storage;
1409 this.storageExpiry = storageExpiry;
1410
1411 let isLocalStorage = false;
1412 try {
1413 // Accessing window.localStorage can throw an exception when it is disabled
1414 // eslint-disable-next-line no-undef
1415 isLocalStorage = this.storage.store === window.localStorage;
1416 } catch ( e ) {}
1417
1418 if ( isLocalStorage ) {
1419 const conflictableKeys = {};
1420 conflictableKeys[ this.autosavePrefix + 've-docstate' ] = true;
1421 conflictableKeys[ this.autosavePrefix + 've-dochtml' ] = true;
1422 conflictableKeys[ this.autosavePrefix + 've-selection' ] = true;
1423 conflictableKeys[ this.autosavePrefix + 've-changes' ] = true;
1424 this.storage.addConflictableKeys( conflictableKeys );
1425 }
1426 };
1427
1428 /**
1429 * Start storing changes after every undoStackChange
1430 */
1431 ve.dm.Surface.prototype.startStoringChanges = function () {
1432 this.storing = true;
1433 this.on( 'undoStackChange', this.storeChangesListener );
1434 this.getDocument().on( 'storage', this.storeDocStorageListener );
1435 this.updateExpiry();
1436 };
1437
1438 /**
1439 * Stop storing changes
1440 */
1441 ve.dm.Surface.prototype.stopStoringChanges = function () {
1442 this.storing = false;
1443 this.off( 'undoStackChange', this.storeChangesListener );
1444 this.getDocument().off( 'storage', this.storeDocStorageListener );
1445 };
1446
1447 /**
1448 * Restore transactions from session storage
1449 *
1450 * @return {boolean} Some changes were restored
1451 * @throws {Error} Failed to restore auto-saved session
1452 */
1453 ve.dm.Surface.prototype.restoreChanges = function () {
1454 const changes = this.storage.getObject( this.autosavePrefix + 've-changes' ) || [];
1455 let restored = false;
1456
1457 try {
1458 changes.forEach( ( data ) => {
1459 const change = ve.dm.Change.static.unsafeDeserialize( data );
1460 change.applyTo( this, true );
1461 this.breakpoint();
1462 } );
1463 restored = !!changes.length;
1464
1465 this.getDocument().setStorage(
1466 this.storage.getObject( this.autosavePrefix + 've-docstorage' ) || {}
1467 );
1468
1469 let selection;
1470 try {
1471 selection = ve.dm.Selection.static.newFromJSON(
1472 this.storage.getObject( this.autosavePrefix + 've-selection' )
1473 );
1474 } catch ( e ) {
1475 // Didn't restore the selection, not a big deal.
1476 }
1477 if ( selection ) {
1478 // Wait for surface to observe selection change
1479 setTimeout( () => {
1480 this.setSelection( selection );
1481 } );
1482 }
1483 } catch ( e ) {
1484 throw new Error( 'Failed to restore auto-saved session: ' + e );
1485 }
1486
1487 this.lastStoredChange = this.getDocument().getCompleteHistoryLength();
1488
1489 return restored;
1490 };
1491
1492 /**
1493 * Store a snapshot of the current document state.
1494 *
1495 * If custom HTML is provided, the caller must manually set the
1496 * lastStoredChange pointer to the correct value.
1497 *
1498 * @param {Object} [state] JSONable object describing document state
1499 * @param {string} [html] Document HTML, will generate from current state if not provided
1500 * @return {boolean} Doc state was successfully stored
1501 */
1502 ve.dm.Surface.prototype.storeDocState = function ( state, html ) {
1503 // Clear any changes that may have stored up to this point
1504 this.removeDocStateAndChanges();
1505 if ( state ) {
1506 if ( !this.updateDocState( state ) ) {
1507 this.stopStoringChanges();
1508 return false;
1509 }
1510 }
1511 const useLatestHtml = html === undefined;
1512 // Store HTML separately to avoid wasteful JSON encoding
1513 if ( !this.storage.set( this.autosavePrefix + 've-dochtml', useLatestHtml ? this.getHtml() : html, this.storageExpiry ) ) {
1514 // If we failed to store the html, wipe the docstate
1515 this.storage.remove( this.autosavePrefix + 've-docstate' );
1516 this.stopStoringChanges();
1517 return false;
1518 }
1519 this.updateExpiry( [ 've-dochtml' ] );
1520
1521 if ( useLatestHtml ) {
1522 // If storing the latest HTML, reset the lastStoreChange pointer,
1523 // otherwise assume this will be handled by the caller.
1524 this.lastStoredChange = this.getDocument().getCompleteHistoryLength();
1525 }
1526
1527 return true;
1528 };
1529
1530 /**
1531 * Update stored document state metadata, without changing the HTML
1532 *
1533 * @param {Object} state Document state
1534 * @return {boolean} Document metadata was successfully stored
1535 */
1536 ve.dm.Surface.prototype.updateDocState = function ( state ) {
1537 if ( this.storage.set( this.autosavePrefix + 've-docstate', JSON.stringify( state ), this.storageExpiry ) ) {
1538 this.updateExpiry( [ 've-docstate' ] );
1539 return true;
1540 }
1541 return false;
1542 };
1543
1544 /**
1545 * Update the expiry value of keys in use
1546 *
1547 * @param {string[]} [skipKeys] Keys to skip (because they have just been updated)
1548 */
1549 ve.dm.Surface.prototype.updateExpiry = function ( skipKeys ) {
1550 if ( !this.storageExpiry ) {
1551 return;
1552 }
1553 skipKeys = skipKeys || [];
1554 [ 've-docstate', 've-dochtml', 've-selection', 've-changes' ].forEach( ( key ) => {
1555 if ( skipKeys.indexOf( key ) === -1 ) {
1556 this.storage.setExpires( this.autosavePrefix + key, this.storageExpiry );
1557 }
1558 } );
1559 };
1560
1561 /**
1562 * Remove the auto-saved document state and stashed changes
1563 */
1564 ve.dm.Surface.prototype.removeDocStateAndChanges = function () {
1565 this.storage.remove( this.autosavePrefix + 've-docstate' );
1566 this.storage.remove( this.autosavePrefix + 've-dochtml' );
1567 this.storage.remove( this.autosavePrefix + 've-selection' );
1568 this.storage.remove( this.autosavePrefix + 've-changes' );
1569 };