JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
vanilla ckeditor-3.5.3
[ckeditor.git] / _source / plugins / undo / plugin.js
1 /*\r
2 Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.\r
3 For licensing, see LICENSE.html or http://ckeditor.com/license\r
4 */\r
5 \r
6 /**\r
7  * @fileOverview Undo/Redo system for saving shapshot for document modification\r
8  *              and other recordable changes.\r
9  */\r
10 \r
11 (function()\r
12 {\r
13         CKEDITOR.plugins.add( 'undo',\r
14         {\r
15                 requires : [ 'selection', 'wysiwygarea' ],\r
16 \r
17                 init : function( editor )\r
18                 {\r
19                         var undoManager = new UndoManager( editor );\r
20 \r
21                         var undoCommand = editor.addCommand( 'undo',\r
22                                 {\r
23                                         exec : function()\r
24                                         {\r
25                                                 if ( undoManager.undo() )\r
26                                                 {\r
27                                                         editor.selectionChange();\r
28                                                         this.fire( 'afterUndo' );\r
29                                                 }\r
30                                         },\r
31                                         state : CKEDITOR.TRISTATE_DISABLED,\r
32                                         canUndo : false\r
33                                 });\r
34 \r
35                         var redoCommand = editor.addCommand( 'redo',\r
36                                 {\r
37                                         exec : function()\r
38                                         {\r
39                                                 if ( undoManager.redo() )\r
40                                                 {\r
41                                                         editor.selectionChange();\r
42                                                         this.fire( 'afterRedo' );\r
43                                                 }\r
44                                         },\r
45                                         state : CKEDITOR.TRISTATE_DISABLED,\r
46                                         canUndo : false\r
47                                 });\r
48 \r
49                         undoManager.onChange = function()\r
50                         {\r
51                                 undoCommand.setState( undoManager.undoable() ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED );\r
52                                 redoCommand.setState( undoManager.redoable() ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED );\r
53                         };\r
54 \r
55                         function recordCommand( event )\r
56                         {\r
57                                 // If the command hasn't been marked to not support undo.\r
58                                 if ( undoManager.enabled && event.data.command.canUndo !== false )\r
59                                         undoManager.save();\r
60                         }\r
61 \r
62                         // We'll save snapshots before and after executing a command.\r
63                         editor.on( 'beforeCommandExec', recordCommand );\r
64                         editor.on( 'afterCommandExec', recordCommand );\r
65 \r
66                         // Save snapshots before doing custom changes.\r
67                         editor.on( 'saveSnapshot', function()\r
68                                 {\r
69                                         undoManager.save();\r
70                                 });\r
71 \r
72                         // Registering keydown on every document recreation.(#3844)\r
73                         editor.on( 'contentDom', function()\r
74                                 {\r
75                                         editor.document.on( 'keydown', function( event )\r
76                                                 {\r
77                                                         // Do not capture CTRL hotkeys.\r
78                                                         if ( !event.data.$.ctrlKey && !event.data.$.metaKey )\r
79                                                                 undoManager.type( event );\r
80                                                 });\r
81                                 });\r
82 \r
83                         // Always save an undo snapshot - the previous mode might have\r
84                         // changed editor contents.\r
85                         editor.on( 'beforeModeUnload', function()\r
86                                 {\r
87                                         editor.mode == 'wysiwyg' && undoManager.save( true );\r
88                                 });\r
89 \r
90                         // Make the undo manager available only in wysiwyg mode.\r
91                         editor.on( 'mode', function()\r
92                                 {\r
93                                         undoManager.enabled = editor.mode == 'wysiwyg';\r
94                                         undoManager.onChange();\r
95                                 });\r
96 \r
97                         editor.ui.addButton( 'Undo',\r
98                                 {\r
99                                         label : editor.lang.undo,\r
100                                         command : 'undo'\r
101                                 });\r
102 \r
103                         editor.ui.addButton( 'Redo',\r
104                                 {\r
105                                         label : editor.lang.redo,\r
106                                         command : 'redo'\r
107                                 });\r
108 \r
109                         editor.resetUndo = function()\r
110                         {\r
111                                 // Reset the undo stack.\r
112                                 undoManager.reset();\r
113 \r
114                                 // Create the first image.\r
115                                 editor.fire( 'saveSnapshot' );\r
116                         };\r
117 \r
118                         /**\r
119                          * Update the undo stacks with any subsequent DOM changes after this call.\r
120                          * @name CKEDITOR.editor#updateUndo\r
121                          * @example\r
122                          * function()\r
123                          * {\r
124                          * editor.fire( 'updateSnapshot' );\r
125                          * ...\r
126                          *  // Ask to include subsequent (in this call stack) DOM changes to be\r
127                          * // considered as part of the first snapshot.\r
128                          *      editor.fire( 'updateSnapshot' );\r
129                          *      editor.document.body.append(...);\r
130                          * ...\r
131                          * }\r
132                          */\r
133                         editor.on( 'updateSnapshot', function()\r
134                         {\r
135                                 if ( undoManager.currentImage && new Image( editor ).equals( undoManager.currentImage ) )\r
136                                         setTimeout( function() { undoManager.update(); }, 0 );\r
137                         });\r
138                 }\r
139         });\r
140 \r
141         CKEDITOR.plugins.undo = {};\r
142 \r
143         /**\r
144          * Undo snapshot which represents the current document status.\r
145          * @name CKEDITOR.plugins.undo.Image\r
146          * @param editor The editor instance on which the image is created.\r
147          */\r
148         var Image = CKEDITOR.plugins.undo.Image = function( editor )\r
149         {\r
150                 this.editor = editor;\r
151 \r
152                 editor.fire( 'beforeUndoImage' );\r
153 \r
154                 var contents = editor.getSnapshot(),\r
155                         selection       = contents && editor.getSelection();\r
156 \r
157                 // In IE, we need to remove the expando attributes.\r
158                 CKEDITOR.env.ie && contents && ( contents = contents.replace( /\s+data-cke-expando=".*?"/g, '' ) );\r
159 \r
160                 this.contents   = contents;\r
161                 this.bookmarks  = selection && selection.createBookmarks2( true );\r
162 \r
163                 editor.fire( 'afterUndoImage' );\r
164         };\r
165 \r
166         // Attributes that browser may changing them when setting via innerHTML.\r
167         var protectedAttrs = /\b(?:href|src|name)="[^"]*?"/gi;\r
168 \r
169         Image.prototype =\r
170         {\r
171                 equals : function( otherImage, contentOnly )\r
172                 {\r
173 \r
174                         var thisContents = this.contents,\r
175                                 otherContents = otherImage.contents;\r
176 \r
177                         // For IE6/7 : Comparing only the protected attribute values but not the original ones.(#4522)\r
178                         if ( CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) )\r
179                         {\r
180                                 thisContents = thisContents.replace( protectedAttrs, '' );\r
181                                 otherContents = otherContents.replace( protectedAttrs, '' );\r
182                         }\r
183 \r
184                         if ( thisContents != otherContents )\r
185                                 return false;\r
186 \r
187                         if ( contentOnly )\r
188                                 return true;\r
189 \r
190                         var bookmarksA = this.bookmarks,\r
191                                 bookmarksB = otherImage.bookmarks;\r
192 \r
193                         if ( bookmarksA || bookmarksB )\r
194                         {\r
195                                 if ( !bookmarksA || !bookmarksB || bookmarksA.length != bookmarksB.length )\r
196                                         return false;\r
197 \r
198                                 for ( var i = 0 ; i < bookmarksA.length ; i++ )\r
199                                 {\r
200                                         var bookmarkA = bookmarksA[ i ],\r
201                                                 bookmarkB = bookmarksB[ i ];\r
202 \r
203                                         if (\r
204                                                 bookmarkA.startOffset != bookmarkB.startOffset ||\r
205                                                 bookmarkA.endOffset != bookmarkB.endOffset ||\r
206                                                 !CKEDITOR.tools.arrayCompare( bookmarkA.start, bookmarkB.start ) ||\r
207                                                 !CKEDITOR.tools.arrayCompare( bookmarkA.end, bookmarkB.end ) )\r
208                                         {\r
209                                                 return false;\r
210                                         }\r
211                                 }\r
212                         }\r
213 \r
214                         return true;\r
215                 }\r
216         };\r
217 \r
218         /**\r
219          * @constructor Main logic for Redo/Undo feature.\r
220          */\r
221         function UndoManager( editor )\r
222         {\r
223                 this.editor = editor;\r
224 \r
225                 // Reset the undo stack.\r
226                 this.reset();\r
227         }\r
228 \r
229 \r
230         var editingKeyCodes = { /*Backspace*/ 8:1, /*Delete*/ 46:1 },\r
231                 modifierKeyCodes = { /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1 },\r
232                 navigationKeyCodes = { 37:1, 38:1, 39:1, 40:1 };  // Arrows: L, T, R, B\r
233 \r
234         UndoManager.prototype =\r
235         {\r
236                 /**\r
237                  * Process undo system regard keystrikes.\r
238                  * @param {CKEDITOR.dom.event} event\r
239                  */\r
240                 type : function( event )\r
241                 {\r
242                         var keystroke = event && event.data.getKey(),\r
243                                 isModifierKey = keystroke in modifierKeyCodes,\r
244                                 isEditingKey = keystroke in editingKeyCodes,\r
245                                 wasEditingKey = this.lastKeystroke in editingKeyCodes,\r
246                                 sameAsLastEditingKey = isEditingKey && keystroke == this.lastKeystroke,\r
247                                 // Keystrokes which navigation through contents.\r
248                                 isReset = keystroke in navigationKeyCodes,\r
249                                 wasReset = this.lastKeystroke in navigationKeyCodes,\r
250 \r
251                                 // Keystrokes which just introduce new contents.\r
252                                 isContent = ( !isEditingKey && !isReset ),\r
253 \r
254                                 // Create undo snap for every different modifier key.\r
255                                 modifierSnapshot = ( isEditingKey && !sameAsLastEditingKey ),\r
256                                 // Create undo snap on the following cases:\r
257                                 // 1. Just start to type .\r
258                                 // 2. Typing some content after a modifier.\r
259                                 // 3. Typing some content after make a visible selection.\r
260                                 startedTyping = !( isModifierKey || this.typing )\r
261                                         || ( isContent && ( wasEditingKey || wasReset ) );\r
262 \r
263                         if ( startedTyping || modifierSnapshot )\r
264                         {\r
265                                 var beforeTypeImage = new Image( this.editor );\r
266 \r
267                                 // Use setTimeout, so we give the necessary time to the\r
268                                 // browser to insert the character into the DOM.\r
269                                 CKEDITOR.tools.setTimeout( function()\r
270                                         {\r
271                                                 var currentSnapshot = this.editor.getSnapshot();\r
272 \r
273                                                 // In IE, we need to remove the expando attributes.\r
274                                                 if ( CKEDITOR.env.ie )\r
275                                                         currentSnapshot = currentSnapshot.replace( /\s+data-cke-expando=".*?"/g, '' );\r
276 \r
277                                                 if ( beforeTypeImage.contents != currentSnapshot )\r
278                                                 {\r
279                                                         // It's safe to now indicate typing state.\r
280                                                         this.typing = true;\r
281 \r
282                                                         // This's a special save, with specified snapshot\r
283                                                         // and without auto 'fireChange'.\r
284                                                         if ( !this.save( false, beforeTypeImage, false ) )\r
285                                                                 // Drop future snapshots.\r
286                                                                 this.snapshots.splice( this.index + 1, this.snapshots.length - this.index - 1 );\r
287 \r
288                                                         this.hasUndo = true;\r
289                                                         this.hasRedo = false;\r
290 \r
291                                                         this.typesCount = 1;\r
292                                                         this.modifiersCount = 1;\r
293 \r
294                                                         this.onChange();\r
295                                                 }\r
296                                         },\r
297                                         0, this\r
298                                 );\r
299                         }\r
300 \r
301                         this.lastKeystroke = keystroke;\r
302 \r
303                         // Create undo snap after typed too much (over 25 times).\r
304                         if ( isEditingKey )\r
305                         {\r
306                                 this.typesCount = 0;\r
307                                 this.modifiersCount++;\r
308 \r
309                                 if ( this.modifiersCount > 25 )\r
310                                 {\r
311                                         this.save( false, null, false );\r
312                                         this.modifiersCount = 1;\r
313                                 }\r
314                         }\r
315                         else if ( !isReset )\r
316                         {\r
317                                 this.modifiersCount = 0;\r
318                                 this.typesCount++;\r
319 \r
320                                 if ( this.typesCount > 25 )\r
321                                 {\r
322                                         this.save( false, null, false );\r
323                                         this.typesCount = 1;\r
324                                 }\r
325                         }\r
326 \r
327                 },\r
328 \r
329                 reset : function()      // Reset the undo stack.\r
330                 {\r
331                         /**\r
332                          * Remember last pressed key.\r
333                          */\r
334                         this.lastKeystroke = 0;\r
335 \r
336                         /**\r
337                          * Stack for all the undo and redo snapshots, they're always created/removed\r
338                          * in consistency.\r
339                          */\r
340                         this.snapshots = [];\r
341 \r
342                         /**\r
343                          * Current snapshot history index.\r
344                          */\r
345                         this.index = -1;\r
346 \r
347                         this.limit = this.editor.config.undoStackSize || 20;\r
348 \r
349                         this.currentImage = null;\r
350 \r
351                         this.hasUndo = false;\r
352                         this.hasRedo = false;\r
353 \r
354                         this.resetType();\r
355                 },\r
356 \r
357                 /**\r
358                  * Reset all states about typing.\r
359                  * @see  UndoManager.type\r
360                  */\r
361                 resetType : function()\r
362                 {\r
363                         this.typing = false;\r
364                         delete this.lastKeystroke;\r
365                         this.typesCount = 0;\r
366                         this.modifiersCount = 0;\r
367                 },\r
368                 fireChange : function()\r
369                 {\r
370                         this.hasUndo = !!this.getNextImage( true );\r
371                         this.hasRedo = !!this.getNextImage( false );\r
372                         // Reset typing\r
373                         this.resetType();\r
374                         this.onChange();\r
375                 },\r
376 \r
377                 /**\r
378                  * Save a snapshot of document image for later retrieve.\r
379                  */\r
380                 save : function( onContentOnly, image, autoFireChange )\r
381                 {\r
382                         var snapshots = this.snapshots;\r
383 \r
384                         // Get a content image.\r
385                         if ( !image )\r
386                                 image = new Image( this.editor );\r
387 \r
388                         // Do nothing if it was not possible to retrieve an image.\r
389                         if ( image.contents === false )\r
390                                 return false;\r
391 \r
392                         // Check if this is a duplicate. In such case, do nothing.\r
393                         if ( this.currentImage && image.equals( this.currentImage, onContentOnly ) )\r
394                                 return false;\r
395 \r
396                         // Drop future snapshots.\r
397                         snapshots.splice( this.index + 1, snapshots.length - this.index - 1 );\r
398 \r
399                         // If we have reached the limit, remove the oldest one.\r
400                         if ( snapshots.length == this.limit )\r
401                                 snapshots.shift();\r
402 \r
403                         // Add the new image, updating the current index.\r
404                         this.index = snapshots.push( image ) - 1;\r
405 \r
406                         this.currentImage = image;\r
407 \r
408                         if ( autoFireChange !== false )\r
409                                 this.fireChange();\r
410                         return true;\r
411                 },\r
412 \r
413                 restoreImage : function( image )\r
414                 {\r
415                         this.editor.loadSnapshot( image.contents );\r
416 \r
417                         if ( image.bookmarks )\r
418                                 this.editor.getSelection().selectBookmarks( image.bookmarks );\r
419                         else if ( CKEDITOR.env.ie )\r
420                         {\r
421                                 // IE BUG: If I don't set the selection to *somewhere* after setting\r
422                                 // document contents, then IE would create an empty paragraph at the bottom\r
423                                 // the next time the document is modified.\r
424                                 var $range = this.editor.document.getBody().$.createTextRange();\r
425                                 $range.collapse( true );\r
426                                 $range.select();\r
427                         }\r
428 \r
429                         this.index = image.index;\r
430 \r
431                         // Update current image with the actual editor\r
432                         // content, since actualy content may differ from\r
433                         // the original snapshot due to dom change. (#4622)\r
434                         this.update();\r
435                         this.fireChange();\r
436                 },\r
437 \r
438                 // Get the closest available image.\r
439                 getNextImage : function( isUndo )\r
440                 {\r
441                         var snapshots = this.snapshots,\r
442                                 currentImage = this.currentImage,\r
443                                 image, i;\r
444 \r
445                         if ( currentImage )\r
446                         {\r
447                                 if ( isUndo )\r
448                                 {\r
449                                         for ( i = this.index - 1 ; i >= 0 ; i-- )\r
450                                         {\r
451                                                 image = snapshots[ i ];\r
452                                                 if ( !currentImage.equals( image, true ) )\r
453                                                 {\r
454                                                         image.index = i;\r
455                                                         return image;\r
456                                                 }\r
457                                         }\r
458                                 }\r
459                                 else\r
460                                 {\r
461                                         for ( i = this.index + 1 ; i < snapshots.length ; i++ )\r
462                                         {\r
463                                                 image = snapshots[ i ];\r
464                                                 if ( !currentImage.equals( image, true ) )\r
465                                                 {\r
466                                                         image.index = i;\r
467                                                         return image;\r
468                                                 }\r
469                                         }\r
470                                 }\r
471                         }\r
472 \r
473                         return null;\r
474                 },\r
475 \r
476                 /**\r
477                  * Check the current redo state.\r
478                  * @return {Boolean} Whether the document has previous state to\r
479                  *              retrieve.\r
480                  */\r
481                 redoable : function()\r
482                 {\r
483                         return this.enabled && this.hasRedo;\r
484                 },\r
485 \r
486                 /**\r
487                  * Check the current undo state.\r
488                  * @return {Boolean} Whether the document has future state to restore.\r
489                  */\r
490                 undoable : function()\r
491                 {\r
492                         return this.enabled && this.hasUndo;\r
493                 },\r
494 \r
495                 /**\r
496                  * Perform undo on current index.\r
497                  */\r
498                 undo : function()\r
499                 {\r
500                         if ( this.undoable() )\r
501                         {\r
502                                 this.save( true );\r
503 \r
504                                 var image = this.getNextImage( true );\r
505                                 if ( image )\r
506                                         return this.restoreImage( image ), true;\r
507                         }\r
508 \r
509                         return false;\r
510                 },\r
511 \r
512                 /**\r
513                  * Perform redo on current index.\r
514                  */\r
515                 redo : function()\r
516                 {\r
517                         if ( this.redoable() )\r
518                         {\r
519                                 // Try to save. If no changes have been made, the redo stack\r
520                                 // will not change, so it will still be redoable.\r
521                                 this.save( true );\r
522 \r
523                                 // If instead we had changes, we can't redo anymore.\r
524                                 if ( this.redoable() )\r
525                                 {\r
526                                         var image = this.getNextImage( false );\r
527                                         if ( image )\r
528                                                 return this.restoreImage( image ), true;\r
529                                 }\r
530                         }\r
531 \r
532                         return false;\r
533                 },\r
534 \r
535                 /**\r
536                  * Update the last snapshot of the undo stack with the current editor content.\r
537                  */\r
538                 update : function()\r
539                 {\r
540                         this.snapshots.splice( this.index, 1, ( this.currentImage = new Image( this.editor ) ) );\r
541                 }\r
542         };\r
543 })();\r
544 \r
545 /**\r
546  * The number of undo steps to be saved. The higher this setting value the more\r
547  * memory is used for it.\r
548  * @type Number\r
549  * @default 20\r
550  * @example\r
551  * config.undoStackSize = 50;\r
552  */\r
553 \r
554 /**\r
555  * Fired when the editor is about to save an undo snapshot. This event can be\r
556  * fired by plugins and customizations to make the editor saving undo snapshots.\r
557  * @name CKEDITOR.editor#saveSnapshot\r
558  * @event\r
559  */\r
560 \r
561 /**\r
562  * Fired before an undo image is to be taken. An undo image represents the\r
563  * editor state at some point. It's saved into an undo store, so the editor is\r
564  * able to recover the editor state on undo and redo operations.\r
565  * @name CKEDITOR.editor#beforeUndoImage\r
566  * @since 3.5.3\r
567  * @see CKEDITOR.editor#afterUndoImage\r
568  * @event\r
569  */\r
570 \r
571 /**\r
572  * Fired after an undo image is taken. An undo image represents the\r
573  * editor state at some point. It's saved into an undo store, so the editor is\r
574  * able to recover the editor state on undo and redo operations.\r
575  * @name CKEDITOR.editor#afterUndoImage\r
576  * @since 3.5.3\r
577  * @see CKEDITOR.editor#beforeUndoImage\r
578  * @event\r
579  */\r