0ffc293f5b8100032e143cea4c6115f653977904
[autoinstalls/wordpress.git] / wp-includes / js / autosave.js
1 /* global tinymce, wpCookies, autosaveL10n, switchEditors */
2 // Back-compat
3 window.autosave = function() {
4         return true;
5 };
6
7 ( function( $, window ) {
8         function autosave() {
9                 var initialCompareString,
10                 lastTriggerSave = 0,
11                 $document = $(document);
12
13                 /**
14                  * Returns the data saved in both local and remote autosave
15                  *
16                  * @return object Object containing the post data
17                  */
18                 function getPostData( type ) {
19                         var post_name, parent_id, data,
20                                 time = ( new Date() ).getTime(),
21                                 cats = [],
22                                 editor = typeof tinymce !== 'undefined' && tinymce.get('content');
23
24                         // Don't run editor.save() more often than every 3 sec.
25                         // It is resource intensive and might slow down typing in long posts on slow devices.
26                         if ( editor && ! editor.isHidden() && time - 3000 > lastTriggerSave ) {
27                                 editor.save();
28                                 lastTriggerSave = time;
29                         }
30
31                         data = {
32                                 post_id: $( '#post_ID' ).val() || 0,
33                                 post_type: $( '#post_type' ).val() || '',
34                                 post_author: $( '#post_author' ).val() || '',
35                                 post_title: $( '#title' ).val() || '',
36                                 content: $( '#content' ).val() || '',
37                                 excerpt: $( '#excerpt' ).val() || ''
38                         };
39
40                         if ( type === 'local' ) {
41                                 return data;
42                         }
43
44                         $( 'input[id^="in-category-"]:checked' ).each( function() {
45                                 cats.push( this.value );
46                         });
47                         data.catslist = cats.join(',');
48
49                         if ( post_name = $( '#post_name' ).val() ) {
50                                 data.post_name = post_name;
51                         }
52
53                         if ( parent_id = $( '#parent_id' ).val() ) {
54                                 data.parent_id = parent_id;
55                         }
56
57                         if ( $( '#comment_status' ).prop( 'checked' ) ) {
58                                 data.comment_status = 'open';
59                         }
60
61                         if ( $( '#ping_status' ).prop( 'checked' ) ) {
62                                 data.ping_status = 'open';
63                         }
64
65                         if ( $( '#auto_draft' ).val() === '1' ) {
66                                 data.auto_draft = '1';
67                         }
68
69                         return data;
70                 }
71
72                 // Concatenate title, content and excerpt. Used to track changes when auto-saving.
73                 function getCompareString( postData ) {
74                         if ( typeof postData === 'object' ) {
75                                 return ( postData.post_title || '' ) + '::' + ( postData.content || '' ) + '::' + ( postData.excerpt || '' );
76                         }
77
78                         return ( $('#title').val() || '' ) + '::' + ( $('#content').val() || '' ) + '::' + ( $('#excerpt').val() || '' );
79                 }
80
81                 function disableButtons() {
82                         $document.trigger('autosave-disable-buttons');
83                         // Re-enable 5 sec later. Just gives autosave a head start to avoid collisions.
84                         setTimeout( enableButtons, 5000 );
85                 }
86
87                 function enableButtons() {
88                         $document.trigger( 'autosave-enable-buttons' );
89                 }
90
91                 // Autosave in localStorage
92                 function autosaveLocal() {
93                         var restorePostData, undoPostData, blog_id, post_id, hasStorage, intervalTimer,
94                                 lastCompareString,
95                                 isSuspended = false;
96
97                         // Check if the browser supports sessionStorage and it's not disabled
98                         function checkStorage() {
99                                 var test = Math.random().toString(),
100                                         result = false;
101
102                                 try {
103                                         window.sessionStorage.setItem( 'wp-test', test );
104                                         result = window.sessionStorage.getItem( 'wp-test' ) === test;
105                                         window.sessionStorage.removeItem( 'wp-test' );
106                                 } catch(e) {}
107
108                                 hasStorage = result;
109                                 return result;
110                         }
111
112                         /**
113                          * Initialize the local storage
114                          *
115                          * @return mixed False if no sessionStorage in the browser or an Object containing all postData for this blog
116                          */
117                         function getStorage() {
118                                 var stored_obj = false;
119                                 // Separate local storage containers for each blog_id
120                                 if ( hasStorage && blog_id ) {
121                                         stored_obj = sessionStorage.getItem( 'wp-autosave-' + blog_id );
122
123                                         if ( stored_obj ) {
124                                                 stored_obj = JSON.parse( stored_obj );
125                                         } else {
126                                                 stored_obj = {};
127                                         }
128                                 }
129
130                                 return stored_obj;
131                         }
132
133                         /**
134                          * Set the storage for this blog
135                          *
136                          * Confirms that the data was saved successfully.
137                          *
138                          * @return bool
139                          */
140                         function setStorage( stored_obj ) {
141                                 var key;
142
143                                 if ( hasStorage && blog_id ) {
144                                         key = 'wp-autosave-' + blog_id;
145                                         sessionStorage.setItem( key, JSON.stringify( stored_obj ) );
146                                         return sessionStorage.getItem( key ) !== null;
147                                 }
148
149                                 return false;
150                         }
151
152                         /**
153                          * Get the saved post data for the current post
154                          *
155                          * @return mixed False if no storage or no data or the postData as an Object
156                          */
157                         function getSavedPostData() {
158                                 var stored = getStorage();
159
160                                 if ( ! stored || ! post_id ) {
161                                         return false;
162                                 }
163
164                                 return stored[ 'post_' + post_id ] || false;
165                         }
166
167                         /**
168                          * Set (save or delete) post data in the storage.
169                          *
170                          * If stored_data evaluates to 'false' the storage key for the current post will be removed
171                          *
172                          * $param stored_data The post data to store or null/false/empty to delete the key
173                          * @return bool
174                          */
175                         function setData( stored_data ) {
176                                 var stored = getStorage();
177
178                                 if ( ! stored || ! post_id ) {
179                                         return false;
180                                 }
181
182                                 if ( stored_data ) {
183                                         stored[ 'post_' + post_id ] = stored_data;
184                                 } else if ( stored.hasOwnProperty( 'post_' + post_id ) ) {
185                                         delete stored[ 'post_' + post_id ];
186                                 } else {
187                                         return false;
188                                 }
189
190                                 return setStorage( stored );
191                         }
192
193                         function suspend() {
194                                 isSuspended = true;
195                         }
196
197                         function resume() {
198                                 isSuspended = false;
199                         }
200
201                         /**
202                          * Save post data for the current post
203                          *
204                          * Runs on a 15 sec. interval, saves when there are differences in the post title or content.
205                          * When the optional data is provided, updates the last saved post data.
206                          *
207                          * $param data optional Object The post data for saving, minimum 'post_title' and 'content'
208                          * @return bool
209                          */
210                         function save( data ) {
211                                 var postData, compareString,
212                                         result = false;
213
214                                 if ( isSuspended || ! hasStorage ) {
215                                         return false;
216                                 }
217
218                                 if ( data ) {
219                                         postData = getSavedPostData() || {};
220                                         $.extend( postData, data );
221                                 } else {
222                                         postData = getPostData('local');
223                                 }
224
225                                 compareString = getCompareString( postData );
226
227                                 if ( typeof lastCompareString === 'undefined' ) {
228                                         lastCompareString = initialCompareString;
229                                 }
230
231                                 // If the content, title and excerpt did not change since the last save, don't save again
232                                 if ( compareString === lastCompareString ) {
233                                         return false;
234                                 }
235
236                                 postData.save_time = ( new Date() ).getTime();
237                                 postData.status = $( '#post_status' ).val() || '';
238                                 result = setData( postData );
239
240                                 if ( result ) {
241                                         lastCompareString = compareString;
242                                 }
243
244                                 return result;
245                         }
246
247                         // Run on DOM ready
248                         function run() {
249                                 post_id = $('#post_ID').val() || 0;
250
251                                 // Check if the local post data is different than the loaded post data.
252                                 if ( $( '#wp-content-wrap' ).hasClass( 'tmce-active' ) ) {
253                                         // If TinyMCE loads first, check the post 1.5 sec. after it is ready.
254                                         // By this time the content has been loaded in the editor and 'saved' to the textarea.
255                                         // This prevents false positives.
256                                         $document.on( 'tinymce-editor-init.autosave', function() {
257                                                 window.setTimeout( function() {
258                                                         checkPost();
259                                                 }, 1500 );
260                                         });
261                                 } else {
262                                         checkPost();
263                                 }
264
265                                 // Save every 15 sec.
266                                 intervalTimer = window.setInterval( save, 15000 );
267
268                                 $( 'form#post' ).on( 'submit.autosave-local', function() {
269                                         var editor = typeof tinymce !== 'undefined' && tinymce.get('content'),
270                                                 post_id = $('#post_ID').val() || 0;
271
272                                         if ( editor && ! editor.isHidden() ) {
273                                                 // Last onSubmit event in the editor, needs to run after the content has been moved to the textarea.
274                                                 editor.on( 'submit', function() {
275                                                         save({
276                                                                 post_title: $( '#title' ).val() || '',
277                                                                 content: $( '#content' ).val() || '',
278                                                                 excerpt: $( '#excerpt' ).val() || ''
279                                                         });
280                                                 });
281                                         } else {
282                                                 save({
283                                                         post_title: $( '#title' ).val() || '',
284                                                         content: $( '#content' ).val() || '',
285                                                         excerpt: $( '#excerpt' ).val() || ''
286                                                 });
287                                         }
288
289                                         var secure = ( 'https:' === window.location.protocol );
290                                         wpCookies.set( 'wp-saving-post', post_id + '-check', 24 * 60 * 60, false, false, secure );
291                                 });
292                         }
293
294                         // Strip whitespace and compare two strings
295                         function compare( str1, str2 ) {
296                                 function removeSpaces( string ) {
297                                         return string.toString().replace(/[\x20\t\r\n\f]+/g, '');
298                                 }
299
300                                 return ( removeSpaces( str1 || '' ) === removeSpaces( str2 || '' ) );
301                         }
302
303                         /**
304                          * Check if the saved data for the current post (if any) is different than the loaded post data on the screen
305                          *
306                          * Shows a standard message letting the user restore the post data if different.
307                          *
308                          * @return void
309                          */
310                         function checkPost() {
311                                 var content, post_title, excerpt, $notice,
312                                         postData = getSavedPostData(),
313                                         cookie = wpCookies.get( 'wp-saving-post' );
314
315                                 if ( cookie === post_id + '-saved' ) {
316                                         wpCookies.remove( 'wp-saving-post' );
317                                         // The post was saved properly, remove old data and bail
318                                         setData( false );
319                                         return;
320                                 }
321
322                                 if ( ! postData ) {
323                                         return;
324                                 }
325
326                                 // There is a newer autosave. Don't show two "restore" notices at the same time.
327                                 if ( $( '#has-newer-autosave' ).length ) {
328                                         return;
329                                 }
330
331                                 content = $( '#content' ).val() || '';
332                                 post_title = $( '#title' ).val() || '';
333                                 excerpt = $( '#excerpt' ).val() || '';
334
335                                 if ( compare( content, postData.content ) && compare( post_title, postData.post_title ) &&
336                                         compare( excerpt, postData.excerpt ) ) {
337
338                                         return;
339                                 }
340
341                                 restorePostData = postData;
342                                 undoPostData = {
343                                         content: content,
344                                         post_title: post_title,
345                                         excerpt: excerpt
346                                 };
347
348                                 $notice = $( '#local-storage-notice' )
349                                         .insertAfter( $( '.wrap' ).children( ':header' ).first() )
350                                         .addClass( 'notice-warning' )
351                                         .show();
352
353                                 $notice.on( 'click.autosave-local', function( event ) {
354                                         var $target = $( event.target );
355
356                                         if ( $target.hasClass( 'restore-backup' ) ) {
357                                                 restorePost( restorePostData );
358                                                 $target.parent().hide();
359                                                 $(this).find( 'p.undo-restore' ).show();
360                                                 $notice.removeClass( 'notice-warning' ).addClass( 'notice-success' );
361                                         } else if ( $target.hasClass( 'undo-restore-backup' ) ) {
362                                                 restorePost( undoPostData );
363                                                 $target.parent().hide();
364                                                 $(this).find( 'p.local-restore' ).show();
365                                                 $notice.removeClass( 'notice-success' ).addClass( 'notice-warning' );
366                                         }
367
368                                         event.preventDefault();
369                                 });
370                         }
371
372                         // Restore the current title, content and excerpt from postData.
373                         function restorePost( postData ) {
374                                 var editor;
375
376                                 if ( postData ) {
377                                         // Set the last saved data
378                                         lastCompareString = getCompareString( postData );
379
380                                         if ( $( '#title' ).val() !== postData.post_title ) {
381                                                 $( '#title' ).focus().val( postData.post_title || '' );
382                                         }
383
384                                         $( '#excerpt' ).val( postData.excerpt || '' );
385                                         editor = typeof tinymce !== 'undefined' && tinymce.get('content');
386
387                                         if ( editor && ! editor.isHidden() && typeof switchEditors !== 'undefined' ) {
388                                                 // Make sure there's an undo level in the editor
389                                                 editor.undoManager.add();
390                                                 editor.setContent( postData.content ? switchEditors.wpautop( postData.content ) : '' );
391                                         } else {
392                                                 // Make sure the Text editor is selected
393                                                 $( '#content-html' ).click();
394                                                 $( '#content' ).val( postData.content );
395                                         }
396
397                                         return true;
398                                 }
399
400                                 return false;
401                         }
402
403                         blog_id = typeof window.autosaveL10n !== 'undefined' && window.autosaveL10n.blog_id;
404
405                         // Check if the browser supports sessionStorage and it's not disabled,
406                         // then initialize and run checkPost().
407                         // Don't run if the post type supports neither 'editor' (textarea#content) nor 'excerpt'.
408                         if ( checkStorage() && blog_id && ( $('#content').length || $('#excerpt').length ) ) {
409                                 $document.ready( run );
410                         }
411
412                         return {
413                                 hasStorage: hasStorage,
414                                 getSavedPostData: getSavedPostData,
415                                 save: save,
416                                 suspend: suspend,
417                                 resume: resume
418                         };
419                 }
420
421                 // Autosave on the server
422                 function autosaveServer() {
423                         var _blockSave, _blockSaveTimer, previousCompareString, lastCompareString,
424                                 nextRun = 0,
425                                 isSuspended = false;
426
427                         // Block saving for the next 10 sec.
428                         function tempBlockSave() {
429                                 _blockSave = true;
430                                 window.clearTimeout( _blockSaveTimer );
431
432                                 _blockSaveTimer = window.setTimeout( function() {
433                                         _blockSave = false;
434                                 }, 10000 );
435                         }
436
437                         function suspend() {
438                                 isSuspended = true;
439                         }
440
441                         function resume() {
442                                 isSuspended = false;
443                         }
444
445                         // Runs on heartbeat-response
446                         function response( data ) {
447                                 _schedule();
448                                 _blockSave = false;
449                                 lastCompareString = previousCompareString;
450                                 previousCompareString = '';
451
452                                 $document.trigger( 'after-autosave', [data] );
453                                 enableButtons();
454
455                                 if ( data.success ) {
456                                         // No longer an auto-draft
457                                         $( '#auto_draft' ).val('');
458                                 }
459                         }
460
461                         /**
462                          * Save immediately
463                          *
464                          * Resets the timing and tells heartbeat to connect now
465                          *
466                          * @return void
467                          */
468                         function triggerSave() {
469                                 nextRun = 0;
470                                 wp.heartbeat.connectNow();
471                         }
472
473                         /**
474                          * Checks if the post content in the textarea has changed since page load.
475                          *
476                          * This also happens when TinyMCE is active and editor.save() is triggered by
477                          * wp.autosave.getPostData().
478                          *
479                          * @return bool
480                          */
481                         function postChanged() {
482                                 return getCompareString() !== initialCompareString;
483                         }
484
485                         // Runs on 'heartbeat-send'
486                         function save() {
487                                 var postData, compareString;
488
489                                 // window.autosave() used for back-compat
490                                 if ( isSuspended || _blockSave || ! window.autosave() ) {
491                                         return false;
492                                 }
493
494                                 if ( ( new Date() ).getTime() < nextRun ) {
495                                         return false;
496                                 }
497
498                                 postData = getPostData();
499                                 compareString = getCompareString( postData );
500
501                                 // First check
502                                 if ( typeof lastCompareString === 'undefined' ) {
503                                         lastCompareString = initialCompareString;
504                                 }
505
506                                 // No change
507                                 if ( compareString === lastCompareString ) {
508                                         return false;
509                                 }
510
511                                 previousCompareString = compareString;
512                                 tempBlockSave();
513                                 disableButtons();
514
515                                 $document.trigger( 'wpcountwords', [ postData.content ] )
516                                         .trigger( 'before-autosave', [ postData ] );
517
518                                 postData._wpnonce = $( '#_wpnonce' ).val() || '';
519
520                                 return postData;
521                         }
522
523                         function _schedule() {
524                                 nextRun = ( new Date() ).getTime() + ( autosaveL10n.autosaveInterval * 1000 ) || 60000;
525                         }
526
527                         $document.on( 'heartbeat-send.autosave', function( event, data ) {
528                                 var autosaveData = save();
529
530                                 if ( autosaveData ) {
531                                         data.wp_autosave = autosaveData;
532                                 }
533                         }).on( 'heartbeat-tick.autosave', function( event, data ) {
534                                 if ( data.wp_autosave ) {
535                                         response( data.wp_autosave );
536                                 }
537                         }).on( 'heartbeat-connection-lost.autosave', function( event, error, status ) {
538                                 // When connection is lost, keep user from submitting changes.
539                                 if ( 'timeout' === error || 603 === status ) {
540                                         var $notice = $('#lost-connection-notice');
541
542                                         if ( ! wp.autosave.local.hasStorage ) {
543                                                 $notice.find('.hide-if-no-sessionstorage').hide();
544                                         }
545
546                                         $notice.show();
547                                         disableButtons();
548                                 }
549                         }).on( 'heartbeat-connection-restored.autosave', function() {
550                                 $('#lost-connection-notice').hide();
551                                 enableButtons();
552                         }).ready( function() {
553                                 _schedule();
554                         });
555
556                         return {
557                                 tempBlockSave: tempBlockSave,
558                                 triggerSave: triggerSave,
559                                 postChanged: postChanged,
560                                 suspend: suspend,
561                                 resume: resume
562                         };
563                 }
564
565                 // Wait for TinyMCE to initialize plus 1 sec. for any external css to finish loading,
566                 // then 'save' to the textarea before setting initialCompareString.
567                 // This avoids any insignificant differences between the initial textarea content and the content
568                 // extracted from the editor.
569                 $document.on( 'tinymce-editor-init.autosave', function( event, editor ) {
570                         if ( editor.id === 'content' ) {
571                                 window.setTimeout( function() {
572                                         editor.save();
573                                         initialCompareString = getCompareString();
574                                 }, 1000 );
575                         }
576                 }).ready( function() {
577                         // Set the initial compare string in case TinyMCE is not used or not loaded first
578                         initialCompareString = getCompareString();
579                 });
580
581                 return {
582                         getPostData: getPostData,
583                         getCompareString: getCompareString,
584                         disableButtons: disableButtons,
585                         enableButtons: enableButtons,
586                         local: autosaveLocal(),
587                         server: autosaveServer()
588                 };
589         }
590
591         window.wp = window.wp || {};
592         window.wp.autosave = autosave();
593
594 }( jQuery, window ));