JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
fde581f07014eb0e599f49a164c0a4d6e0722a5c
[ckeditor.git] / _source / plugins / undo / plugin.js
1 /*\r
2 Copyright (c) 2003-2010, 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                 var contents = editor.getSnapshot(),\r
152                         selection       = contents && editor.getSelection();\r
153 \r
154                 // In IE, we need to remove the expando attributes.\r
155                 CKEDITOR.env.ie && contents && ( contents = contents.replace( /\s+_cke_expando=".*?"/g, '' ) );\r
156 \r
157                 this.contents   = contents;\r
158                 this.bookmarks  = selection && selection.createBookmarks2( true );\r
159         };\r
160 \r
161         // Attributes that browser may changing them when setting via innerHTML.\r
162         var protectedAttrs = /\b(?:href|src|name)="[^"]*?"/gi;\r
163 \r
164         Image.prototype =\r
165         {\r
166                 equals : function( otherImage, contentOnly )\r
167                 {\r
168 \r
169                         var thisContents = this.contents,\r
170                                 otherContents = otherImage.contents;\r
171 \r
172                         // For IE6/7 : Comparing only the protected attribute values but not the original ones.(#4522)\r
173                         if ( CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) )\r
174                         {\r
175                                 thisContents = thisContents.replace( protectedAttrs, '' );\r
176                                 otherContents = otherContents.replace( protectedAttrs, '' );\r
177                         }\r
178 \r
179                         if ( thisContents != otherContents )\r
180                                 return false;\r
181 \r
182                         if ( contentOnly )\r
183                                 return true;\r
184 \r
185                         var bookmarksA = this.bookmarks,\r
186                                 bookmarksB = otherImage.bookmarks;\r
187 \r
188                         if ( bookmarksA || bookmarksB )\r
189                         {\r
190                                 if ( !bookmarksA || !bookmarksB || bookmarksA.length != bookmarksB.length )\r
191                                         return false;\r
192 \r
193                                 for ( var i = 0 ; i < bookmarksA.length ; i++ )\r
194                                 {\r
195                                         var bookmarkA = bookmarksA[ i ],\r
196                                                 bookmarkB = bookmarksB[ i ];\r
197 \r
198                                         if (\r
199                                                 bookmarkA.startOffset != bookmarkB.startOffset ||\r
200                                                 bookmarkA.endOffset != bookmarkB.endOffset ||\r
201                                                 !CKEDITOR.tools.arrayCompare( bookmarkA.start, bookmarkB.start ) ||\r
202                                                 !CKEDITOR.tools.arrayCompare( bookmarkA.end, bookmarkB.end ) )\r
203                                         {\r
204                                                 return false;\r
205                                         }\r
206                                 }\r
207                         }\r
208 \r
209                         return true;\r
210                 }\r
211         };\r
212 \r
213         /**\r
214          * @constructor Main logic for Redo/Undo feature.\r
215          */\r
216         function UndoManager( editor )\r
217         {\r
218                 this.editor = editor;\r
219 \r
220                 // Reset the undo stack.\r
221                 this.reset();\r
222         }\r
223 \r
224 \r
225         var editingKeyCodes = { /*Backspace*/ 8:1, /*Delete*/ 46:1 },\r
226                 modifierKeyCodes = { /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1 },\r
227                 navigationKeyCodes = { 37:1, 38:1, 39:1, 40:1 };  // Arrows: L, T, R, B\r
228 \r
229         UndoManager.prototype =\r
230         {\r
231                 /**\r
232                  * Process undo system regard keystrikes.\r
233                  * @param {CKEDITOR.dom.event} event\r
234                  */\r
235                 type : function( event )\r
236                 {\r
237                         var keystroke = event && event.data.getKey(),\r
238                                 isModifierKey = keystroke in modifierKeyCodes,\r
239                                 isEditingKey = keystroke in editingKeyCodes,\r
240                                 wasEditingKey = this.lastKeystroke in editingKeyCodes,\r
241                                 sameAsLastEditingKey = isEditingKey && keystroke == this.lastKeystroke,\r
242                                 // Keystrokes which navigation through contents.\r
243                                 isReset = keystroke in navigationKeyCodes,\r
244                                 wasReset = this.lastKeystroke in navigationKeyCodes,\r
245 \r
246                                 // Keystrokes which just introduce new contents.\r
247                                 isContent = ( !isEditingKey && !isReset ),\r
248 \r
249                                 // Create undo snap for every different modifier key.\r
250                                 modifierSnapshot = ( isEditingKey && !sameAsLastEditingKey ),\r
251                                 // Create undo snap on the following cases:\r
252                                 // 1. Just start to type .\r
253                                 // 2. Typing some content after a modifier.\r
254                                 // 3. Typing some content after make a visible selection.\r
255                                 startedTyping = !( isModifierKey || this.typing )\r
256                                         || ( isContent && ( wasEditingKey || wasReset ) );\r
257 \r
258                         if ( startedTyping || modifierSnapshot )\r
259                         {\r
260                                 var beforeTypeImage = new Image( this.editor );\r
261 \r
262                                 // Use setTimeout, so we give the necessary time to the\r
263                                 // browser to insert the character into the DOM.\r
264                                 CKEDITOR.tools.setTimeout( function()\r
265                                         {\r
266                                                 var currentSnapshot = this.editor.getSnapshot();\r
267 \r
268                                                 // In IE, we need to remove the expando attributes.\r
269                                                 if ( CKEDITOR.env.ie )\r
270                                                         currentSnapshot = currentSnapshot.replace( /\s+_cke_expando=".*?"/g, '' );\r
271 \r
272                                                 if ( beforeTypeImage.contents != currentSnapshot )\r
273                                                 {\r
274                                                         // It's safe to now indicate typing state.\r
275                                                         this.typing = true;\r
276 \r
277                                                         // This's a special save, with specified snapshot\r
278                                                         // and without auto 'fireChange'.\r
279                                                         if ( !this.save( false, beforeTypeImage, false ) )\r
280                                                                 // Drop future snapshots.\r
281                                                                 this.snapshots.splice( this.index + 1, this.snapshots.length - this.index - 1 );\r
282 \r
283                                                         this.hasUndo = true;\r
284                                                         this.hasRedo = false;\r
285 \r
286                                                         this.typesCount = 1;\r
287                                                         this.modifiersCount = 1;\r
288 \r
289                                                         this.onChange();\r
290                                                 }\r
291                                         },\r
292                                         0, this\r
293                                 );\r
294                         }\r
295 \r
296                         this.lastKeystroke = keystroke;\r
297 \r
298                         // Create undo snap after typed too much (over 25 times).\r
299                         if ( isEditingKey )\r
300                         {\r
301                                 this.typesCount = 0;\r
302                                 this.modifiersCount++;\r
303 \r
304                                 if ( this.modifiersCount > 25 )\r
305                                 {\r
306                                         this.save( false, null, false );\r
307                                         this.modifiersCount = 1;\r
308                                 }\r
309                         }\r
310                         else if ( !isReset )\r
311                         {\r
312                                 this.modifiersCount = 0;\r
313                                 this.typesCount++;\r
314 \r
315                                 if ( this.typesCount > 25 )\r
316                                 {\r
317                                         this.save( false, null, false );\r
318                                         this.typesCount = 1;\r
319                                 }\r
320                         }\r
321 \r
322                 },\r
323 \r
324                 reset : function()      // Reset the undo stack.\r
325                 {\r
326                         /**\r
327                          * Remember last pressed key.\r
328                          */\r
329                         this.lastKeystroke = 0;\r
330 \r
331                         /**\r
332                          * Stack for all the undo and redo snapshots, they're always created/removed\r
333                          * in consistency.\r
334                          */\r
335                         this.snapshots = [];\r
336 \r
337                         /**\r
338                          * Current snapshot history index.\r
339                          */\r
340                         this.index = -1;\r
341 \r
342                         this.limit = this.editor.config.undoStackSize;\r
343 \r
344                         this.currentImage = null;\r
345 \r
346                         this.hasUndo = false;\r
347                         this.hasRedo = false;\r
348 \r
349                         this.resetType();\r
350                 },\r
351 \r
352                 /**\r
353                  * Reset all states about typing.\r
354                  * @see  UndoManager.type\r
355                  */\r
356                 resetType : function()\r
357                 {\r
358                         this.typing = false;\r
359                         delete this.lastKeystroke;\r
360                         this.typesCount = 0;\r
361                         this.modifiersCount = 0;\r
362                 },\r
363                 fireChange : function()\r
364                 {\r
365                         this.hasUndo = !!this.getNextImage( true );\r
366                         this.hasRedo = !!this.getNextImage( false );\r
367                         // Reset typing\r
368                         this.resetType();\r
369                         this.onChange();\r
370                 },\r
371 \r
372                 /**\r
373                  * Save a snapshot of document image for later retrieve.\r
374                  */\r
375                 save : function( onContentOnly, image, autoFireChange )\r
376                 {\r
377                         var snapshots = this.snapshots;\r
378 \r
379                         // Get a content image.\r
380                         if ( !image )\r
381                                 image = new Image( this.editor );\r
382 \r
383                         // Do nothing if it was not possible to retrieve an image.\r
384                         if ( image.contents === false )\r
385                                 return false;\r
386 \r
387                         // Check if this is a duplicate. In such case, do nothing.\r
388                         if ( this.currentImage && image.equals( this.currentImage, onContentOnly ) )\r
389                                 return false;\r
390 \r
391                         // Drop future snapshots.\r
392                         snapshots.splice( this.index + 1, snapshots.length - this.index - 1 );\r
393 \r
394                         // If we have reached the limit, remove the oldest one.\r
395                         if ( snapshots.length == this.limit )\r
396                                 snapshots.shift();\r
397 \r
398                         // Add the new image, updating the current index.\r
399                         this.index = snapshots.push( image ) - 1;\r
400 \r
401                         this.currentImage = image;\r
402 \r
403                         if ( autoFireChange !== false )\r
404                                 this.fireChange();\r
405                         return true;\r
406                 },\r
407 \r
408                 restoreImage : function( image )\r
409                 {\r
410                         this.editor.loadSnapshot( image.contents );\r
411 \r
412                         if ( image.bookmarks )\r
413                                 this.editor.getSelection().selectBookmarks( image.bookmarks );\r
414                         else if ( CKEDITOR.env.ie )\r
415                         {\r
416                                 // IE BUG: If I don't set the selection to *somewhere* after setting\r
417                                 // document contents, then IE would create an empty paragraph at the bottom\r
418                                 // the next time the document is modified.\r
419                                 var $range = this.editor.document.getBody().$.createTextRange();\r
420                                 $range.collapse( true );\r
421                                 $range.select();\r
422                         }\r
423 \r
424                         this.index = image.index;\r
425 \r
426                         // Update current image with the actual editor\r
427                         // content, since actualy content may differ from\r
428                         // the original snapshot due to dom change. (#4622)\r
429                         this.update();\r
430                         this.fireChange();\r
431                 },\r
432 \r
433                 // Get the closest available image.\r
434                 getNextImage : function( isUndo )\r
435                 {\r
436                         var snapshots = this.snapshots,\r
437                                 currentImage = this.currentImage,\r
438                                 image, i;\r
439 \r
440                         if ( currentImage )\r
441                         {\r
442                                 if ( isUndo )\r
443                                 {\r
444                                         for ( i = this.index - 1 ; i >= 0 ; i-- )\r
445                                         {\r
446                                                 image = snapshots[ i ];\r
447                                                 if ( !currentImage.equals( image, true ) )\r
448                                                 {\r
449                                                         image.index = i;\r
450                                                         return image;\r
451                                                 }\r
452                                         }\r
453                                 }\r
454                                 else\r
455                                 {\r
456                                         for ( i = this.index + 1 ; i < snapshots.length ; i++ )\r
457                                         {\r
458                                                 image = snapshots[ i ];\r
459                                                 if ( !currentImage.equals( image, true ) )\r
460                                                 {\r
461                                                         image.index = i;\r
462                                                         return image;\r
463                                                 }\r
464                                         }\r
465                                 }\r
466                         }\r
467 \r
468                         return null;\r
469                 },\r
470 \r
471                 /**\r
472                  * Check the current redo state.\r
473                  * @return {Boolean} Whether the document has previous state to\r
474                  *              retrieve.\r
475                  */\r
476                 redoable : function()\r
477                 {\r
478                         return this.enabled && this.hasRedo;\r
479                 },\r
480 \r
481                 /**\r
482                  * Check the current undo state.\r
483                  * @return {Boolean} Whether the document has future state to restore.\r
484                  */\r
485                 undoable : function()\r
486                 {\r
487                         return this.enabled && this.hasUndo;\r
488                 },\r
489 \r
490                 /**\r
491                  * Perform undo on current index.\r
492                  */\r
493                 undo : function()\r
494                 {\r
495                         if ( this.undoable() )\r
496                         {\r
497                                 this.save( true );\r
498 \r
499                                 var image = this.getNextImage( true );\r
500                                 if ( image )\r
501                                         return this.restoreImage( image ), true;\r
502                         }\r
503 \r
504                         return false;\r
505                 },\r
506 \r
507                 /**\r
508                  * Perform redo on current index.\r
509                  */\r
510                 redo : function()\r
511                 {\r
512                         if ( this.redoable() )\r
513                         {\r
514                                 // Try to save. If no changes have been made, the redo stack\r
515                                 // will not change, so it will still be redoable.\r
516                                 this.save( true );\r
517 \r
518                                 // If instead we had changes, we can't redo anymore.\r
519                                 if ( this.redoable() )\r
520                                 {\r
521                                         var image = this.getNextImage( false );\r
522                                         if ( image )\r
523                                                 return this.restoreImage( image ), true;\r
524                                 }\r
525                         }\r
526 \r
527                         return false;\r
528                 },\r
529 \r
530                 /**\r
531                  * Update the last snapshot of the undo stack with the current editor content.\r
532                  */\r
533                 update : function()\r
534                 {\r
535                         this.snapshots.splice( this.index, 1, ( this.currentImage = new Image( this.editor ) ) );\r
536                 }\r
537         };\r
538 })();\r
539 \r
540 /**\r
541  * The number of undo steps to be saved. The higher this setting value the more\r
542  * memory is used for it.\r
543  * @type Number\r
544  * @default 20\r
545  * @example\r
546  * config.undoStackSize = 50;\r
547  */\r
548 CKEDITOR.config.undoStackSize = 20;\r
549 \r
550 /**\r
551  * Fired when the editor is about to save an undo snapshot. This event can be\r
552  * fired by plugins and customizations to make the editor saving undo snapshots.\r
553  * @name CKEDITOR.editor#saveSnapshot\r
554  * @event\r
555  */\r