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(),
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.isDirty() && ! 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 function getEditor() {
92 return typeof tinymce !== 'undefined' && tinymce.get('content');
95 // Autosave in localStorage
96 function autosaveLocal() {
97 var blog_id, post_id, hasStorage, intervalTimer,
101 // Check if the browser supports sessionStorage and it's not disabled
102 function checkStorage() {
103 var test = Math.random().toString(),
107 window.sessionStorage.setItem( 'wp-test', test );
108 result = window.sessionStorage.getItem( 'wp-test' ) === test;
109 window.sessionStorage.removeItem( 'wp-test' );
117 * Initialize the local storage
119 * @return mixed False if no sessionStorage in the browser or an Object containing all postData for this blog
121 function getStorage() {
122 var stored_obj = false;
123 // Separate local storage containers for each blog_id
124 if ( hasStorage && blog_id ) {
125 stored_obj = sessionStorage.getItem( 'wp-autosave-' + blog_id );
128 stored_obj = JSON.parse( stored_obj );
138 * Set the storage for this blog
140 * Confirms that the data was saved successfully.
144 function setStorage( stored_obj ) {
147 if ( hasStorage && blog_id ) {
148 key = 'wp-autosave-' + blog_id;
149 sessionStorage.setItem( key, JSON.stringify( stored_obj ) );
150 return sessionStorage.getItem( key ) !== null;
157 * Get the saved post data for the current post
159 * @return mixed False if no storage or no data or the postData as an Object
161 function getSavedPostData() {
162 var stored = getStorage();
164 if ( ! stored || ! post_id ) {
168 return stored[ 'post_' + post_id ] || false;
172 * Set (save or delete) post data in the storage.
174 * If stored_data evaluates to 'false' the storage key for the current post will be removed
176 * $param stored_data The post data to store or null/false/empty to delete the key
179 function setData( stored_data ) {
180 var stored = getStorage();
182 if ( ! stored || ! post_id ) {
187 stored[ 'post_' + post_id ] = stored_data;
188 } else if ( stored.hasOwnProperty( 'post_' + post_id ) ) {
189 delete stored[ 'post_' + post_id ];
194 return setStorage( stored );
206 * Save post data for the current post
208 * Runs on a 15 sec. interval, saves when there are differences in the post title or content.
209 * When the optional data is provided, updates the last saved post data.
211 * $param data optional Object The post data for saving, minimum 'post_title' and 'content'
214 function save( data ) {
215 var postData, compareString,
218 if ( isSuspended || ! hasStorage ) {
223 postData = getSavedPostData() || {};
224 $.extend( postData, data );
226 postData = getPostData('local');
229 compareString = getCompareString( postData );
231 if ( typeof lastCompareString === 'undefined' ) {
232 lastCompareString = initialCompareString;
235 // If the content, title and excerpt did not change since the last save, don't save again
236 if ( compareString === lastCompareString ) {
240 postData.save_time = ( new Date() ).getTime();
241 postData.status = $( '#post_status' ).val() || '';
242 result = setData( postData );
245 lastCompareString = compareString;
253 post_id = $('#post_ID').val() || 0;
255 // Check if the local post data is different than the loaded post data.
256 if ( $( '#wp-content-wrap' ).hasClass( 'tmce-active' ) ) {
257 // If TinyMCE loads first, check the post 1.5 sec. after it is ready.
258 // By this time the content has been loaded in the editor and 'saved' to the textarea.
259 // This prevents false positives.
260 $document.on( 'tinymce-editor-init.autosave', function() {
261 window.setTimeout( function() {
269 // Save every 15 sec.
270 intervalTimer = window.setInterval( save, 15000 );
272 $( 'form#post' ).on( 'submit.autosave-local', function() {
273 var editor = getEditor(),
274 post_id = $('#post_ID').val() || 0;
276 if ( editor && ! editor.isHidden() ) {
277 // Last onSubmit event in the editor, needs to run after the content has been moved to the textarea.
278 editor.on( 'submit', function() {
280 post_title: $( '#title' ).val() || '',
281 content: $( '#content' ).val() || '',
282 excerpt: $( '#excerpt' ).val() || ''
287 post_title: $( '#title' ).val() || '',
288 content: $( '#content' ).val() || '',
289 excerpt: $( '#excerpt' ).val() || ''
293 var secure = ( 'https:' === window.location.protocol );
294 wpCookies.set( 'wp-saving-post', post_id + '-check', 24 * 60 * 60, false, false, secure );
298 // Strip whitespace and compare two strings
299 function compare( str1, str2 ) {
300 function removeSpaces( string ) {
301 return string.toString().replace(/[\x20\t\r\n\f]+/g, '');
304 return ( removeSpaces( str1 || '' ) === removeSpaces( str2 || '' ) );
308 * Check if the saved data for the current post (if any) is different than the loaded post data on the screen
310 * Shows a standard message letting the user restore the post data if different.
314 function checkPost() {
315 var content, post_title, excerpt, $notice,
316 postData = getSavedPostData(),
317 cookie = wpCookies.get( 'wp-saving-post' ),
318 $newerAutosaveNotice = $( '#has-newer-autosave' ).parent( '.notice' );
320 if ( cookie === post_id + '-saved' ) {
321 wpCookies.remove( 'wp-saving-post' );
322 // The post was saved properly, remove old data and bail
331 content = $( '#content' ).val() || '';
332 post_title = $( '#title' ).val() || '';
333 excerpt = $( '#excerpt' ).val() || '';
335 if ( compare( content, postData.content ) && compare( post_title, postData.post_title ) &&
336 compare( excerpt, postData.excerpt ) ) {
341 $notice = $( '#local-storage-notice' )
342 .insertAfter( $( '.wrap h1, .wrap h2' ).first() )
343 .addClass( 'notice-warning' );
345 if ( $newerAutosaveNotice.length ) {
346 // If there is a "server" autosave notice, hide it.
347 // The data in the session storage is either the same or newer.
348 $newerAutosaveNotice.slideUp( 150, function() {
349 $notice.slideDown( 150 );
352 $notice.slideDown( 200 );
355 $notice.find( '.restore-backup' ).on( 'click.autosave-local', function() {
356 restorePost( postData );
357 $notice.fadeTo( 250, 0, function() {
358 $notice.slideUp( 150 );
363 // Restore the current title, content and excerpt from postData.
364 function restorePost( postData ) {
368 // Set the last saved data
369 lastCompareString = getCompareString( postData );
371 if ( $( '#title' ).val() !== postData.post_title ) {
372 $( '#title' ).focus().val( postData.post_title || '' );
375 $( '#excerpt' ).val( postData.excerpt || '' );
376 editor = getEditor();
378 if ( editor && ! editor.isHidden() && typeof switchEditors !== 'undefined' ) {
379 if ( editor.settings.wpautop && postData.content ) {
380 postData.content = switchEditors.wpautop( postData.content );
383 // Make sure there's an undo level in the editor
384 editor.undoManager.transact( function() {
385 editor.setContent( postData.content || '' );
386 editor.nodeChanged();
389 // Make sure the Text editor is selected
390 $( '#content-html' ).click();
391 $( '#content' ).focus();
392 // Using document.execCommand() will let the user undo.
393 document.execCommand( 'selectAll' );
394 document.execCommand( 'insertText', false, postData.content || '' );
403 blog_id = typeof window.autosaveL10n !== 'undefined' && window.autosaveL10n.blog_id;
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 );
413 hasStorage: hasStorage,
414 getSavedPostData: getSavedPostData,
421 // Autosave on the server
422 function autosaveServer() {
423 var _blockSave, _blockSaveTimer, previousCompareString, lastCompareString,
427 // Block saving for the next 10 sec.
428 function tempBlockSave() {
430 window.clearTimeout( _blockSaveTimer );
432 _blockSaveTimer = window.setTimeout( function() {
445 // Runs on heartbeat-response
446 function response( data ) {
449 lastCompareString = previousCompareString;
450 previousCompareString = '';
452 $document.trigger( 'after-autosave', [data] );
455 if ( data.success ) {
456 // No longer an auto-draft
457 $( '#auto_draft' ).val('');
464 * Resets the timing and tells heartbeat to connect now
468 function triggerSave() {
470 wp.heartbeat.connectNow();
474 * Checks if the post content in the textarea has changed since page load.
476 * This also happens when TinyMCE is active and editor.save() is triggered by
477 * wp.autosave.getPostData().
481 function postChanged() {
482 return getCompareString() !== initialCompareString;
485 // Runs on 'heartbeat-send'
487 var postData, compareString;
489 // window.autosave() used for back-compat
490 if ( isSuspended || _blockSave || ! window.autosave() ) {
494 if ( ( new Date() ).getTime() < nextRun ) {
498 postData = getPostData();
499 compareString = getCompareString( postData );
502 if ( typeof lastCompareString === 'undefined' ) {
503 lastCompareString = initialCompareString;
507 if ( compareString === lastCompareString ) {
511 previousCompareString = compareString;
515 $document.trigger( 'wpcountwords', [ postData.content ] )
516 .trigger( 'before-autosave', [ postData ] );
518 postData._wpnonce = $( '#_wpnonce' ).val() || '';
523 function _schedule() {
524 nextRun = ( new Date() ).getTime() + ( autosaveL10n.autosaveInterval * 1000 ) || 60000;
527 $document.on( 'heartbeat-send.autosave', function( event, data ) {
528 var autosaveData = save();
530 if ( autosaveData ) {
531 data.wp_autosave = autosaveData;
533 }).on( 'heartbeat-tick.autosave', function( event, data ) {
534 if ( data.wp_autosave ) {
535 response( data.wp_autosave );
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');
542 if ( ! wp.autosave.local.hasStorage ) {
543 $notice.find('.hide-if-no-sessionstorage').hide();
549 }).on( 'heartbeat-connection-restored.autosave', function() {
550 $('#lost-connection-notice').hide();
552 }).ready( function() {
557 tempBlockSave: tempBlockSave,
558 triggerSave: triggerSave,
559 postChanged: postChanged,
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() {
573 initialCompareString = getCompareString();
576 }).ready( function() {
577 // Set the initial compare string in case TinyMCE is not used or not loaded first
578 initialCompareString = getCompareString();
582 getPostData: getPostData,
583 getCompareString: getCompareString,
584 disableButtons: disableButtons,
585 enableButtons: enableButtons,
586 local: autosaveLocal(),
587 server: autosaveServer()
591 window.wp = window.wp || {};
592 window.wp.autosave = autosave();
594 }( jQuery, window ));