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