1 /* global tinymce, wpCookies, autosaveL10n, switchEditors */
3 window.autosave = function() {
7 ( function( $, window ) {
9 var initialCompareString,
11 $document = $(document);
14 * Returns the data saved in both local and remote autosave
16 * @return object Object containing the post data
18 function getPostData( type ) {
19 var post_name, parent_id, data,
20 time = ( new Date() ).getTime(),
22 editor = typeof tinymce !== 'undefined' && tinymce.get('content');
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 ) {
28 lastTriggerSave = time;
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() || ''
40 if ( type === 'local' ) {
44 $( 'input[id^="in-category-"]:checked' ).each( function() {
45 cats.push( this.value );
47 data.catslist = cats.join(',');
49 if ( post_name = $( '#post_name' ).val() ) {
50 data.post_name = post_name;
53 if ( parent_id = $( '#parent_id' ).val() ) {
54 data.parent_id = parent_id;
57 if ( $( '#comment_status' ).prop( 'checked' ) ) {
58 data.comment_status = 'open';
61 if ( $( '#ping_status' ).prop( 'checked' ) ) {
62 data.ping_status = 'open';
65 if ( $( '#auto_draft' ).val() === '1' ) {
66 data.auto_draft = '1';
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 || '' );
78 return ( $('#title').val() || '' ) + '::' + ( $('#content').val() || '' ) + '::' + ( $('#excerpt').val() || '' );
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 );
87 function enableButtons() {
88 $document.trigger( 'autosave-enable-buttons' );
91 // Autosave in localStorage
92 function autosaveLocal() {
93 var restorePostData, undoPostData, blog_id, post_id, hasStorage, intervalTimer,
97 // Check if the browser supports sessionStorage and it's not disabled
98 function checkStorage() {
99 var test = Math.random().toString(),
103 window.sessionStorage.setItem( 'wp-test', test );
104 result = window.sessionStorage.getItem( 'wp-test' ) === test;
105 window.sessionStorage.removeItem( 'wp-test' );
113 * Initialize the local storage
115 * @return mixed False if no sessionStorage in the browser or an Object containing all postData for this blog
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 );
124 stored_obj = JSON.parse( stored_obj );
134 * Set the storage for this blog
136 * Confirms that the data was saved successfully.
140 function setStorage( stored_obj ) {
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;
153 * Get the saved post data for the current post
155 * @return mixed False if no storage or no data or the postData as an Object
157 function getSavedPostData() {
158 var stored = getStorage();
160 if ( ! stored || ! post_id ) {
164 return stored[ 'post_' + post_id ] || false;
168 * Set (save or delete) post data in the storage.
170 * If stored_data evaluates to 'false' the storage key for the current post will be removed
172 * $param stored_data The post data to store or null/false/empty to delete the key
175 function setData( stored_data ) {
176 var stored = getStorage();
178 if ( ! stored || ! post_id ) {
183 stored[ 'post_' + post_id ] = stored_data;
184 } else if ( stored.hasOwnProperty( 'post_' + post_id ) ) {
185 delete stored[ 'post_' + post_id ];
190 return setStorage( stored );
202 * Save post data for the current post
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.
207 * $param data optional Object The post data for saving, minimum 'post_title' and 'content'
210 function save( data ) {
211 var postData, compareString,
219 postData = getSavedPostData() || {};
220 $.extend( postData, data );
222 postData = getPostData('local');
225 compareString = getCompareString( postData );
227 if ( typeof lastCompareString === 'undefined' ) {
228 lastCompareString = initialCompareString;
231 // If the content, title and excerpt did not change since the last save, don't save again
232 if ( compareString === lastCompareString ) {
236 postData.save_time = ( new Date() ).getTime();
237 postData.status = $( '#post_status' ).val() || '';
238 result = setData( postData );
241 lastCompareString = compareString;
249 post_id = $('#post_ID').val() || 0;
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() {
265 // Save every 15 sec.
266 intervalTimer = window.setInterval( save, 15000 );
268 $( 'form#post' ).on( 'submit.autosave-local', function() {
269 var editor = typeof tinymce !== 'undefined' && tinymce.get('content'),
270 post_id = $('#post_ID').val() || 0;
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() {
276 post_title: $( '#title' ).val() || '',
277 content: $( '#content' ).val() || '',
278 excerpt: $( '#excerpt' ).val() || ''
283 post_title: $( '#title' ).val() || '',
284 content: $( '#content' ).val() || '',
285 excerpt: $( '#excerpt' ).val() || ''
289 wpCookies.set( 'wp-saving-post-' + post_id, 'check' );
293 // Strip whitespace and compare two strings
294 function compare( str1, str2 ) {
295 function removeSpaces( string ) {
296 return string.toString().replace(/[\x20\t\r\n\f]+/g, '');
299 return ( removeSpaces( str1 || '' ) === removeSpaces( str2 || '' ) );
303 * Check if the saved data for the current post (if any) is different than the loaded post data on the screen
305 * Shows a standard message letting the user restore the post data if different.
309 function checkPost() {
310 var content, post_title, excerpt, $notice,
311 postData = getSavedPostData(),
312 cookie = wpCookies.get( 'wp-saving-post-' + post_id );
319 wpCookies.remove( 'wp-saving-post-' + post_id );
321 if ( cookie === 'saved' ) {
322 // The post was saved properly, remove old data and bail
328 // There is a newer autosave. Don't show two "restore" notices at the same time.
329 if ( $( '#has-newer-autosave' ).length ) {
333 content = $( '#content' ).val() || '';
334 post_title = $( '#title' ).val() || '';
335 excerpt = $( '#excerpt' ).val() || '';
337 // cookie == 'check' means the post was not saved properly, always show #local-storage-notice
338 if ( cookie !== 'check' && compare( content, postData.content ) &&
339 compare( post_title, postData.post_title ) && compare( excerpt, postData.excerpt ) ) {
344 restorePostData = postData;
347 post_title: post_title,
351 $notice = $( '#local-storage-notice' );
352 $('.wrap h2').first().after( $notice.addClass( 'updated' ).show() );
354 $notice.on( 'click.autosave-local', function( event ) {
355 var $target = $( event.target );
357 if ( $target.hasClass( 'restore-backup' ) ) {
358 restorePost( restorePostData );
359 $target.parent().hide();
360 $(this).find( 'p.undo-restore' ).show();
361 } else if ( $target.hasClass( 'undo-restore-backup' ) ) {
362 restorePost( undoPostData );
363 $target.parent().hide();
364 $(this).find( 'p.local-restore' ).show();
367 event.preventDefault();
371 // Restore the current title, content and excerpt from postData.
372 function restorePost( postData ) {
376 // Set the last saved data
377 lastCompareString = getCompareString( postData );
379 if ( $( '#title' ).val() !== postData.post_title ) {
380 $( '#title' ).focus().val( postData.post_title || '' );
383 $( '#excerpt' ).val( postData.excerpt || '' );
384 editor = typeof tinymce !== 'undefined' && tinymce.get('content');
386 if ( editor && ! editor.isHidden() && typeof switchEditors !== 'undefined' ) {
387 // Make sure there's an undo level in the editor
388 editor.undoManager.add();
389 editor.setContent( postData.content ? switchEditors.wpautop( postData.content ) : '' );
391 // Make sure the Text editor is selected
392 $( '#content-html' ).click();
393 $( '#content' ).val( postData.content );
402 // Initialize and run checkPost() on loading the script (before TinyMCE init)
403 blog_id = typeof window.autosaveL10n !== 'undefined' && window.autosaveL10n.blog_id;
405 // Check if the browser supports sessionStorage and it's not disabled
406 if ( ! checkStorage() ) {
410 // Don't run if the post type supports neither 'editor' (textarea#content) nor 'excerpt'.
411 if ( ! blog_id || ( ! $('#content').length && ! $('#excerpt').length ) ) {
415 $document.ready( run );
418 hasStorage: hasStorage,
419 getSavedPostData: getSavedPostData,
426 // Autosave on the server
427 function autosaveServer() {
428 var _blockSave, _blockSaveTimer, previousCompareString, lastCompareString,
432 // Block saving for the next 10 sec.
433 function tempBlockSave() {
435 window.clearTimeout( _blockSaveTimer );
437 _blockSaveTimer = window.setTimeout( function() {
450 // Runs on heartbeat-response
451 function response( data ) {
454 lastCompareString = previousCompareString;
455 previousCompareString = '';
457 $document.trigger( 'after-autosave', [data] );
460 if ( data.success ) {
461 // No longer an auto-draft
462 $( '#auto_draft' ).val('');
469 * Resets the timing and tells heartbeat to connect now
473 function triggerSave() {
475 wp.heartbeat.connectNow();
479 * Checks if the post content in the textarea has changed since page load.
481 * This also happens when TinyMCE is active and editor.save() is triggered by
482 * wp.autosave.getPostData().
486 function postChanged() {
487 return getCompareString() !== initialCompareString;
490 // Runs on 'heartbeat-send'
492 var postData, compareString;
494 // window.autosave() used for back-compat
495 if ( isSuspended || _blockSave || ! window.autosave() ) {
499 if ( ( new Date() ).getTime() < nextRun ) {
503 postData = getPostData();
504 compareString = getCompareString( postData );
507 if ( typeof lastCompareString === 'undefined' ) {
508 lastCompareString = initialCompareString;
512 if ( compareString === lastCompareString ) {
516 previousCompareString = compareString;
520 $document.trigger( 'wpcountwords', [ postData.content ] )
521 .trigger( 'before-autosave', [ postData ] );
523 postData._wpnonce = $( '#_wpnonce' ).val() || '';
528 function _schedule() {
529 nextRun = ( new Date() ).getTime() + ( autosaveL10n.autosaveInterval * 1000 ) || 60000;
532 $document.on( 'heartbeat-send.autosave', function( event, data ) {
533 var autosaveData = save();
535 if ( autosaveData ) {
536 data.wp_autosave = autosaveData;
538 }).on( 'heartbeat-tick.autosave', function( event, data ) {
539 if ( data.wp_autosave ) {
540 response( data.wp_autosave );
542 }).on( 'heartbeat-connection-lost.autosave', function( event, error, status ) {
543 // When connection is lost, keep user from submitting changes.
544 if ( 'timeout' === error || 603 === status ) {
545 var $notice = $('#lost-connection-notice');
547 if ( ! wp.autosave.local.hasStorage ) {
548 $notice.find('.hide-if-no-sessionstorage').hide();
554 }).on( 'heartbeat-connection-restored.autosave', function() {
555 $('#lost-connection-notice').hide();
557 }).ready( function() {
562 tempBlockSave: tempBlockSave,
563 triggerSave: triggerSave,
564 postChanged: postChanged,
570 // Wait for TinyMCE to initialize plus 1 sec. for any external css to finish loading,
571 // then 'save' to the textarea before setting initialCompareString.
572 // This avoids any insignificant differences between the initial textarea content and the content
573 // extracted from the editor.
574 $document.on( 'tinymce-editor-init.autosave', function( event, editor ) {
575 if ( editor.id === 'content' ) {
576 window.setTimeout( function() {
578 initialCompareString = getCompareString();
581 }).ready( function() {
582 // Set the initial compare string in case TinyMCE is not used or not loaded first
583 initialCompareString = getCompareString();
587 getPostData: getPostData,
588 getCompareString: getCompareString,
589 disableButtons: disableButtons,
590 enableButtons: enableButtons,
591 local: autosaveLocal(),
592 server: autosaveServer()
596 window.wp = window.wp || {};
597 window.wp.autosave = autosave();
599 }( jQuery, window ));