autosave.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. /**
  2. * @output wp-includes/js/autosave.js
  3. */
  4. /* global tinymce, wpCookies, autosaveL10n, switchEditors */
  5. // Back-compat.
  6. window.autosave = function() {
  7. return true;
  8. };
  9. /**
  10. * Adds autosave to the window object on dom ready.
  11. *
  12. * @since 3.9.0
  13. *
  14. * @param {jQuery} $ jQuery object.
  15. * @param {window} The window object.
  16. *
  17. */
  18. ( function( $, window ) {
  19. /**
  20. * Auto saves the post.
  21. *
  22. * @since 3.9.0
  23. *
  24. * @return {Object}
  25. * {{
  26. * getPostData: getPostData,
  27. * getCompareString: getCompareString,
  28. * disableButtons: disableButtons,
  29. * enableButtons: enableButtons,
  30. * local: ({hasStorage, getSavedPostData, save, suspend, resume}|*),
  31. * server: ({tempBlockSave, triggerSave, postChanged, suspend, resume}|*)
  32. * }}
  33. * The object with all functions for autosave.
  34. */
  35. function autosave() {
  36. var initialCompareString,
  37. initialCompareData = {},
  38. lastTriggerSave = 0,
  39. $document = $( document );
  40. /**
  41. * Sets the initial compare data.
  42. *
  43. * @since 5.6.1
  44. */
  45. function setInitialCompare() {
  46. initialCompareData = {
  47. post_title: $( '#title' ).val() || '',
  48. content: $( '#content' ).val() || '',
  49. excerpt: $( '#excerpt' ).val() || ''
  50. };
  51. initialCompareString = getCompareString( initialCompareData );
  52. }
  53. /**
  54. * Returns the data saved in both local and remote autosave.
  55. *
  56. * @since 3.9.0
  57. *
  58. * @param {string} type The type of autosave either local or remote.
  59. *
  60. * @return {Object} Object containing the post data.
  61. */
  62. function getPostData( type ) {
  63. var post_name, parent_id, data,
  64. time = ( new Date() ).getTime(),
  65. cats = [],
  66. editor = getEditor();
  67. // Don't run editor.save() more often than every 3 seconds.
  68. // It is resource intensive and might slow down typing in long posts on slow devices.
  69. if ( editor && editor.isDirty() && ! editor.isHidden() && time - 3000 > lastTriggerSave ) {
  70. editor.save();
  71. lastTriggerSave = time;
  72. }
  73. data = {
  74. post_id: $( '#post_ID' ).val() || 0,
  75. post_type: $( '#post_type' ).val() || '',
  76. post_author: $( '#post_author' ).val() || '',
  77. post_title: $( '#title' ).val() || '',
  78. content: $( '#content' ).val() || '',
  79. excerpt: $( '#excerpt' ).val() || ''
  80. };
  81. if ( type === 'local' ) {
  82. return data;
  83. }
  84. $( 'input[id^="in-category-"]:checked' ).each( function() {
  85. cats.push( this.value );
  86. });
  87. data.catslist = cats.join(',');
  88. if ( post_name = $( '#post_name' ).val() ) {
  89. data.post_name = post_name;
  90. }
  91. if ( parent_id = $( '#parent_id' ).val() ) {
  92. data.parent_id = parent_id;
  93. }
  94. if ( $( '#comment_status' ).prop( 'checked' ) ) {
  95. data.comment_status = 'open';
  96. }
  97. if ( $( '#ping_status' ).prop( 'checked' ) ) {
  98. data.ping_status = 'open';
  99. }
  100. if ( $( '#auto_draft' ).val() === '1' ) {
  101. data.auto_draft = '1';
  102. }
  103. return data;
  104. }
  105. /**
  106. * Concatenates the title, content and excerpt. This is used to track changes
  107. * when auto-saving.
  108. *
  109. * @since 3.9.0
  110. *
  111. * @param {Object} postData The object containing the post data.
  112. *
  113. * @return {string} A concatenated string with title, content and excerpt.
  114. */
  115. function getCompareString( postData ) {
  116. if ( typeof postData === 'object' ) {
  117. return ( postData.post_title || '' ) + '::' + ( postData.content || '' ) + '::' + ( postData.excerpt || '' );
  118. }
  119. return ( $('#title').val() || '' ) + '::' + ( $('#content').val() || '' ) + '::' + ( $('#excerpt').val() || '' );
  120. }
  121. /**
  122. * Disables save buttons.
  123. *
  124. * @since 3.9.0
  125. *
  126. * @return {void}
  127. */
  128. function disableButtons() {
  129. $document.trigger('autosave-disable-buttons');
  130. // Re-enable 5 sec later. Just gives autosave a head start to avoid collisions.
  131. setTimeout( enableButtons, 5000 );
  132. }
  133. /**
  134. * Enables save buttons.
  135. *
  136. * @since 3.9.0
  137. *
  138. * @return {void}
  139. */
  140. function enableButtons() {
  141. $document.trigger( 'autosave-enable-buttons' );
  142. }
  143. /**
  144. * Gets the content editor.
  145. *
  146. * @since 4.6.0
  147. *
  148. * @return {boolean|*} Returns either false if the editor is undefined,
  149. * or the instance of the content editor.
  150. */
  151. function getEditor() {
  152. return typeof tinymce !== 'undefined' && tinymce.get('content');
  153. }
  154. /**
  155. * Autosave in localStorage.
  156. *
  157. * @since 3.9.0
  158. *
  159. * @return {
  160. * {
  161. * hasStorage: *,
  162. * getSavedPostData: getSavedPostData,
  163. * save: save,
  164. * suspend: suspend,
  165. * resume: resume
  166. * }
  167. * }
  168. * The object with all functions for local storage autosave.
  169. */
  170. function autosaveLocal() {
  171. var blog_id, post_id, hasStorage, intervalTimer,
  172. lastCompareString,
  173. isSuspended = false;
  174. /**
  175. * Checks if the browser supports sessionStorage and it's not disabled.
  176. *
  177. * @since 3.9.0
  178. *
  179. * @return {boolean} True if the sessionStorage is supported and enabled.
  180. */
  181. function checkStorage() {
  182. var test = Math.random().toString(),
  183. result = false;
  184. try {
  185. window.sessionStorage.setItem( 'wp-test', test );
  186. result = window.sessionStorage.getItem( 'wp-test' ) === test;
  187. window.sessionStorage.removeItem( 'wp-test' );
  188. } catch(e) {}
  189. hasStorage = result;
  190. return result;
  191. }
  192. /**
  193. * Initializes the local storage.
  194. *
  195. * @since 3.9.0
  196. *
  197. * @return {boolean|Object} False if no sessionStorage in the browser or an Object
  198. * containing all postData for this blog.
  199. */
  200. function getStorage() {
  201. var stored_obj = false;
  202. // Separate local storage containers for each blog_id.
  203. if ( hasStorage && blog_id ) {
  204. stored_obj = sessionStorage.getItem( 'wp-autosave-' + blog_id );
  205. if ( stored_obj ) {
  206. stored_obj = JSON.parse( stored_obj );
  207. } else {
  208. stored_obj = {};
  209. }
  210. }
  211. return stored_obj;
  212. }
  213. /**
  214. * Sets the storage for this blog. Confirms that the data was saved
  215. * successfully.
  216. *
  217. * @since 3.9.0
  218. *
  219. * @return {boolean} True if the data was saved successfully, false if it wasn't saved.
  220. */
  221. function setStorage( stored_obj ) {
  222. var key;
  223. if ( hasStorage && blog_id ) {
  224. key = 'wp-autosave-' + blog_id;
  225. sessionStorage.setItem( key, JSON.stringify( stored_obj ) );
  226. return sessionStorage.getItem( key ) !== null;
  227. }
  228. return false;
  229. }
  230. /**
  231. * Gets the saved post data for the current post.
  232. *
  233. * @since 3.9.0
  234. *
  235. * @return {boolean|Object} False if no storage or no data or the postData as an Object.
  236. */
  237. function getSavedPostData() {
  238. var stored = getStorage();
  239. if ( ! stored || ! post_id ) {
  240. return false;
  241. }
  242. return stored[ 'post_' + post_id ] || false;
  243. }
  244. /**
  245. * Sets (save or delete) post data in the storage.
  246. *
  247. * If stored_data evaluates to 'false' the storage key for the current post will be removed.
  248. *
  249. * @since 3.9.0
  250. *
  251. * @param {Object|boolean|null} stored_data The post data to store or null/false/empty to delete the key.
  252. *
  253. * @return {boolean} True if data is stored, false if data was removed.
  254. */
  255. function setData( stored_data ) {
  256. var stored = getStorage();
  257. if ( ! stored || ! post_id ) {
  258. return false;
  259. }
  260. if ( stored_data ) {
  261. stored[ 'post_' + post_id ] = stored_data;
  262. } else if ( stored.hasOwnProperty( 'post_' + post_id ) ) {
  263. delete stored[ 'post_' + post_id ];
  264. } else {
  265. return false;
  266. }
  267. return setStorage( stored );
  268. }
  269. /**
  270. * Sets isSuspended to true.
  271. *
  272. * @since 3.9.0
  273. *
  274. * @return {void}
  275. */
  276. function suspend() {
  277. isSuspended = true;
  278. }
  279. /**
  280. * Sets isSuspended to false.
  281. *
  282. * @since 3.9.0
  283. *
  284. * @return {void}
  285. */
  286. function resume() {
  287. isSuspended = false;
  288. }
  289. /**
  290. * Saves post data for the current post.
  291. *
  292. * Runs on a 15 seconds interval, saves when there are differences in the post title or content.
  293. * When the optional data is provided, updates the last saved post data.
  294. *
  295. * @since 3.9.0
  296. *
  297. * @param {Object} data The post data for saving, minimum 'post_title' and 'content'.
  298. *
  299. * @return {boolean} Returns true when data has been saved, otherwise it returns false.
  300. */
  301. function save( data ) {
  302. var postData, compareString,
  303. result = false;
  304. if ( isSuspended || ! hasStorage ) {
  305. return false;
  306. }
  307. if ( data ) {
  308. postData = getSavedPostData() || {};
  309. $.extend( postData, data );
  310. } else {
  311. postData = getPostData('local');
  312. }
  313. compareString = getCompareString( postData );
  314. if ( typeof lastCompareString === 'undefined' ) {
  315. lastCompareString = initialCompareString;
  316. }
  317. // If the content, title and excerpt did not change since the last save, don't save again.
  318. if ( compareString === lastCompareString ) {
  319. return false;
  320. }
  321. postData.save_time = ( new Date() ).getTime();
  322. postData.status = $( '#post_status' ).val() || '';
  323. result = setData( postData );
  324. if ( result ) {
  325. lastCompareString = compareString;
  326. }
  327. return result;
  328. }
  329. /**
  330. * Initializes the auto save function.
  331. *
  332. * Checks whether the editor is active or not to use the editor events
  333. * to autosave, or uses the values from the elements to autosave.
  334. *
  335. * Runs on DOM ready.
  336. *
  337. * @since 3.9.0
  338. *
  339. * @return {void}
  340. */
  341. function run() {
  342. post_id = $('#post_ID').val() || 0;
  343. // Check if the local post data is different than the loaded post data.
  344. if ( $( '#wp-content-wrap' ).hasClass( 'tmce-active' ) ) {
  345. /*
  346. * If TinyMCE loads first, check the post 1.5 seconds after it is ready.
  347. * By this time the content has been loaded in the editor and 'saved' to the textarea.
  348. * This prevents false positives.
  349. */
  350. $document.on( 'tinymce-editor-init.autosave', function() {
  351. window.setTimeout( function() {
  352. checkPost();
  353. }, 1500 );
  354. });
  355. } else {
  356. checkPost();
  357. }
  358. // Save every 15 seconds.
  359. intervalTimer = window.setInterval( save, 15000 );
  360. $( 'form#post' ).on( 'submit.autosave-local', function() {
  361. var editor = getEditor(),
  362. post_id = $('#post_ID').val() || 0;
  363. if ( editor && ! editor.isHidden() ) {
  364. // Last onSubmit event in the editor, needs to run after the content has been moved to the textarea.
  365. editor.on( 'submit', function() {
  366. save({
  367. post_title: $( '#title' ).val() || '',
  368. content: $( '#content' ).val() || '',
  369. excerpt: $( '#excerpt' ).val() || ''
  370. });
  371. });
  372. } else {
  373. save({
  374. post_title: $( '#title' ).val() || '',
  375. content: $( '#content' ).val() || '',
  376. excerpt: $( '#excerpt' ).val() || ''
  377. });
  378. }
  379. var secure = ( 'https:' === window.location.protocol );
  380. wpCookies.set( 'wp-saving-post', post_id + '-check', 24 * 60 * 60, false, false, secure );
  381. });
  382. }
  383. /**
  384. * Compares 2 strings. Removes whitespaces in the strings before comparing them.
  385. *
  386. * @since 3.9.0
  387. *
  388. * @param {string} str1 The first string.
  389. * @param {string} str2 The second string.
  390. * @return {boolean} True if the strings are the same.
  391. */
  392. function compare( str1, str2 ) {
  393. function removeSpaces( string ) {
  394. return string.toString().replace(/[\x20\t\r\n\f]+/g, '');
  395. }
  396. return ( removeSpaces( str1 || '' ) === removeSpaces( str2 || '' ) );
  397. }
  398. /**
  399. * Checks if the saved data for the current post (if any) is different than the
  400. * loaded post data on the screen.
  401. *
  402. * Shows a standard message letting the user restore the post data if different.
  403. *
  404. * @since 3.9.0
  405. *
  406. * @return {void}
  407. */
  408. function checkPost() {
  409. var content, post_title, excerpt, $notice,
  410. postData = getSavedPostData(),
  411. cookie = wpCookies.get( 'wp-saving-post' ),
  412. $newerAutosaveNotice = $( '#has-newer-autosave' ).parent( '.notice' ),
  413. $headerEnd = $( '.wp-header-end' );
  414. if ( cookie === post_id + '-saved' ) {
  415. wpCookies.remove( 'wp-saving-post' );
  416. // The post was saved properly, remove old data and bail.
  417. setData( false );
  418. return;
  419. }
  420. if ( ! postData ) {
  421. return;
  422. }
  423. content = $( '#content' ).val() || '';
  424. post_title = $( '#title' ).val() || '';
  425. excerpt = $( '#excerpt' ).val() || '';
  426. if ( compare( content, postData.content ) && compare( post_title, postData.post_title ) &&
  427. compare( excerpt, postData.excerpt ) ) {
  428. return;
  429. }
  430. /*
  431. * If '.wp-header-end' is found, append the notices after it otherwise
  432. * after the first h1 or h2 heading found within the main content.
  433. */
  434. if ( ! $headerEnd.length ) {
  435. $headerEnd = $( '.wrap h1, .wrap h2' ).first();
  436. }
  437. $notice = $( '#local-storage-notice' )
  438. .insertAfter( $headerEnd )
  439. .addClass( 'notice-warning' );
  440. if ( $newerAutosaveNotice.length ) {
  441. // If there is a "server" autosave notice, hide it.
  442. // The data in the session storage is either the same or newer.
  443. $newerAutosaveNotice.slideUp( 150, function() {
  444. $notice.slideDown( 150 );
  445. });
  446. } else {
  447. $notice.slideDown( 200 );
  448. }
  449. $notice.find( '.restore-backup' ).on( 'click.autosave-local', function() {
  450. restorePost( postData );
  451. $notice.fadeTo( 250, 0, function() {
  452. $notice.slideUp( 150 );
  453. });
  454. });
  455. }
  456. /**
  457. * Restores the current title, content and excerpt from postData.
  458. *
  459. * @since 3.9.0
  460. *
  461. * @param {Object} postData The object containing all post data.
  462. *
  463. * @return {boolean} True if the post is restored.
  464. */
  465. function restorePost( postData ) {
  466. var editor;
  467. if ( postData ) {
  468. // Set the last saved data.
  469. lastCompareString = getCompareString( postData );
  470. if ( $( '#title' ).val() !== postData.post_title ) {
  471. $( '#title' ).trigger( 'focus' ).val( postData.post_title || '' );
  472. }
  473. $( '#excerpt' ).val( postData.excerpt || '' );
  474. editor = getEditor();
  475. if ( editor && ! editor.isHidden() && typeof switchEditors !== 'undefined' ) {
  476. if ( editor.settings.wpautop && postData.content ) {
  477. postData.content = switchEditors.wpautop( postData.content );
  478. }
  479. // Make sure there's an undo level in the editor.
  480. editor.undoManager.transact( function() {
  481. editor.setContent( postData.content || '' );
  482. editor.nodeChanged();
  483. });
  484. } else {
  485. // Make sure the Text editor is selected.
  486. $( '#content-html' ).trigger( 'click' );
  487. $( '#content' ).trigger( 'focus' );
  488. // Using document.execCommand() will let the user undo.
  489. document.execCommand( 'selectAll' );
  490. document.execCommand( 'insertText', false, postData.content || '' );
  491. }
  492. return true;
  493. }
  494. return false;
  495. }
  496. blog_id = typeof window.autosaveL10n !== 'undefined' && window.autosaveL10n.blog_id;
  497. /*
  498. * Check if the browser supports sessionStorage and it's not disabled,
  499. * then initialize and run checkPost().
  500. * Don't run if the post type supports neither 'editor' (textarea#content) nor 'excerpt'.
  501. */
  502. if ( checkStorage() && blog_id && ( $('#content').length || $('#excerpt').length ) ) {
  503. $( run );
  504. }
  505. return {
  506. hasStorage: hasStorage,
  507. getSavedPostData: getSavedPostData,
  508. save: save,
  509. suspend: suspend,
  510. resume: resume
  511. };
  512. }
  513. /**
  514. * Auto saves the post on the server.
  515. *
  516. * @since 3.9.0
  517. *
  518. * @return {Object} {
  519. * {
  520. * tempBlockSave: tempBlockSave,
  521. * triggerSave: triggerSave,
  522. * postChanged: postChanged,
  523. * suspend: suspend,
  524. * resume: resume
  525. * }
  526. * } The object all functions for autosave.
  527. */
  528. function autosaveServer() {
  529. var _blockSave, _blockSaveTimer, previousCompareString, lastCompareString,
  530. nextRun = 0,
  531. isSuspended = false;
  532. /**
  533. * Blocks saving for the next 10 seconds.
  534. *
  535. * @since 3.9.0
  536. *
  537. * @return {void}
  538. */
  539. function tempBlockSave() {
  540. _blockSave = true;
  541. window.clearTimeout( _blockSaveTimer );
  542. _blockSaveTimer = window.setTimeout( function() {
  543. _blockSave = false;
  544. }, 10000 );
  545. }
  546. /**
  547. * Sets isSuspended to true.
  548. *
  549. * @since 3.9.0
  550. *
  551. * @return {void}
  552. */
  553. function suspend() {
  554. isSuspended = true;
  555. }
  556. /**
  557. * Sets isSuspended to false.
  558. *
  559. * @since 3.9.0
  560. *
  561. * @return {void}
  562. */
  563. function resume() {
  564. isSuspended = false;
  565. }
  566. /**
  567. * Triggers the autosave with the post data.
  568. *
  569. * @since 3.9.0
  570. *
  571. * @param {Object} data The post data.
  572. *
  573. * @return {void}
  574. */
  575. function response( data ) {
  576. _schedule();
  577. _blockSave = false;
  578. lastCompareString = previousCompareString;
  579. previousCompareString = '';
  580. $document.trigger( 'after-autosave', [data] );
  581. enableButtons();
  582. if ( data.success ) {
  583. // No longer an auto-draft.
  584. $( '#auto_draft' ).val('');
  585. }
  586. }
  587. /**
  588. * Saves immediately.
  589. *
  590. * Resets the timing and tells heartbeat to connect now.
  591. *
  592. * @since 3.9.0
  593. *
  594. * @return {void}
  595. */
  596. function triggerSave() {
  597. nextRun = 0;
  598. wp.heartbeat.connectNow();
  599. }
  600. /**
  601. * Checks if the post content in the textarea has changed since page load.
  602. *
  603. * This also happens when TinyMCE is active and editor.save() is triggered by
  604. * wp.autosave.getPostData().
  605. *
  606. * @since 3.9.0
  607. *
  608. * @return {boolean} True if the post has been changed.
  609. */
  610. function postChanged() {
  611. var changed = false;
  612. // If there are TinyMCE instances, loop through them.
  613. if ( window.tinymce ) {
  614. window.tinymce.each( [ 'content', 'excerpt' ], function( field ) {
  615. var editor = window.tinymce.get( field );
  616. if ( ! editor || editor.isHidden() ) {
  617. if ( ( $( '#' + field ).val() || '' ) !== initialCompareData[ field ] ) {
  618. changed = true;
  619. // Break.
  620. return false;
  621. }
  622. } else if ( editor.isDirty() ) {
  623. changed = true;
  624. return false;
  625. }
  626. } );
  627. if ( ( $( '#title' ).val() || '' ) !== initialCompareData.post_title ) {
  628. changed = true;
  629. }
  630. return changed;
  631. }
  632. return getCompareString() !== initialCompareString;
  633. }
  634. /**
  635. * Checks if the post can be saved or not.
  636. *
  637. * If the post hasn't changed or it cannot be updated,
  638. * because the autosave is blocked or suspended, the function returns false.
  639. *
  640. * @since 3.9.0
  641. *
  642. * @return {Object} Returns the post data.
  643. */
  644. function save() {
  645. var postData, compareString;
  646. // window.autosave() used for back-compat.
  647. if ( isSuspended || _blockSave || ! window.autosave() ) {
  648. return false;
  649. }
  650. if ( ( new Date() ).getTime() < nextRun ) {
  651. return false;
  652. }
  653. postData = getPostData();
  654. compareString = getCompareString( postData );
  655. // First check.
  656. if ( typeof lastCompareString === 'undefined' ) {
  657. lastCompareString = initialCompareString;
  658. }
  659. // No change.
  660. if ( compareString === lastCompareString ) {
  661. return false;
  662. }
  663. previousCompareString = compareString;
  664. tempBlockSave();
  665. disableButtons();
  666. $document.trigger( 'wpcountwords', [ postData.content ] )
  667. .trigger( 'before-autosave', [ postData ] );
  668. postData._wpnonce = $( '#_wpnonce' ).val() || '';
  669. return postData;
  670. }
  671. /**
  672. * Sets the next run, based on the autosave interval.
  673. *
  674. * @private
  675. *
  676. * @since 3.9.0
  677. *
  678. * @return {void}
  679. */
  680. function _schedule() {
  681. nextRun = ( new Date() ).getTime() + ( autosaveL10n.autosaveInterval * 1000 ) || 60000;
  682. }
  683. /**
  684. * Sets the autosaveData on the autosave heartbeat.
  685. *
  686. * @since 3.9.0
  687. *
  688. * @return {void}
  689. */
  690. $( function() {
  691. _schedule();
  692. }).on( 'heartbeat-send.autosave', function( event, data ) {
  693. var autosaveData = save();
  694. if ( autosaveData ) {
  695. data.wp_autosave = autosaveData;
  696. }
  697. /**
  698. * Triggers the autosave of the post with the autosave data on the autosave
  699. * heartbeat.
  700. *
  701. * @since 3.9.0
  702. *
  703. * @return {void}
  704. */
  705. }).on( 'heartbeat-tick.autosave', function( event, data ) {
  706. if ( data.wp_autosave ) {
  707. response( data.wp_autosave );
  708. }
  709. /**
  710. * Disables buttons and throws a notice when the connection is lost.
  711. *
  712. * @since 3.9.0
  713. *
  714. * @return {void}
  715. */
  716. }).on( 'heartbeat-connection-lost.autosave', function( event, error, status ) {
  717. // When connection is lost, keep user from submitting changes.
  718. if ( 'timeout' === error || 603 === status ) {
  719. var $notice = $('#lost-connection-notice');
  720. if ( ! wp.autosave.local.hasStorage ) {
  721. $notice.find('.hide-if-no-sessionstorage').hide();
  722. }
  723. $notice.show();
  724. disableButtons();
  725. }
  726. /**
  727. * Enables buttons when the connection is restored.
  728. *
  729. * @since 3.9.0
  730. *
  731. * @return {void}
  732. */
  733. }).on( 'heartbeat-connection-restored.autosave', function() {
  734. $('#lost-connection-notice').hide();
  735. enableButtons();
  736. });
  737. return {
  738. tempBlockSave: tempBlockSave,
  739. triggerSave: triggerSave,
  740. postChanged: postChanged,
  741. suspend: suspend,
  742. resume: resume
  743. };
  744. }
  745. /**
  746. * Sets the autosave time out.
  747. *
  748. * Wait for TinyMCE to initialize plus 1 second. for any external css to finish loading,
  749. * then save to the textarea before setting initialCompareString.
  750. * This avoids any insignificant differences between the initial textarea content and the content
  751. * extracted from the editor.
  752. *
  753. * @since 3.9.0
  754. *
  755. * @return {void}
  756. */
  757. $( function() {
  758. // Set the initial compare string in case TinyMCE is not used or not loaded first.
  759. setInitialCompare();
  760. }).on( 'tinymce-editor-init.autosave', function( event, editor ) {
  761. // Reset the initialCompare data after the TinyMCE instances have been initialized.
  762. if ( 'content' === editor.id || 'excerpt' === editor.id ) {
  763. window.setTimeout( function() {
  764. editor.save();
  765. setInitialCompare();
  766. }, 1000 );
  767. }
  768. });
  769. return {
  770. getPostData: getPostData,
  771. getCompareString: getCompareString,
  772. disableButtons: disableButtons,
  773. enableButtons: enableButtons,
  774. local: autosaveLocal(),
  775. server: autosaveServer()
  776. };
  777. }
  778. /** @namespace wp */
  779. window.wp = window.wp || {};
  780. window.wp.autosave = autosave();
  781. }( jQuery, window ));