Skip to content
8 changes: 8 additions & 0 deletions packages/e2e-test-utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,10 @@ _Returns_

- `Promise`: Promise resolving with a boolean indicating if the focused block is the default block.

<a name="isOfflineMode" href="#isOfflineMode">#</a> **isOfflineMode**

Undocumented declaration.

<a name="loginUser" href="#loginUser">#</a> **loginUser**

Performs log in with specified username and password.
Expand Down Expand Up @@ -477,6 +481,10 @@ running the tests as (if we're not already that user).

Toggles the More Menu.

<a name="toggleOfflineMode" href="#toggleOfflineMode">#</a> **toggleOfflineMode**

Undocumented declaration.

<a name="toggleScreenOption" href="#toggleScreenOption">#</a> **toggleScreenOption**

Toggles the screen option with the given label.
Expand Down
1 change: 1 addition & 0 deletions packages/e2e-test-utils/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export { disableNavigationMode } from './keyboard-mode';
export { switchUserToAdmin } from './switch-user-to-admin';
export { switchUserToTest } from './switch-user-to-test';
export { toggleMoreMenu } from './toggle-more-menu';
export { toggleOfflineMode, isOfflineMode } from './offline-mode';
export { toggleScreenOption } from './toggle-screen-option';
export { transformBlockTo } from './transform-block-to';
export { uninstallPlugin } from './uninstall-plugin';
Expand Down
10 changes: 10 additions & 0 deletions packages/e2e-test-utils/src/offline-mode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
let _isOfflineMode = false;

export async function toggleOfflineMode( isOffline ) {
_isOfflineMode = isOffline;
page.setOfflineMode( isOffline );
}

export function isOfflineMode() {
return _isOfflineMode;
}
7 changes: 7 additions & 0 deletions packages/e2e-tests/config/setup-test-framework.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
activatePlugin,
clearLocalStorage,
enablePageDialogAccept,
isOfflineMode,
setBrowserViewport,
switchUserToAdmin,
switchUserToTest,
Expand Down Expand Up @@ -122,6 +123,12 @@ function observeConsoleLogging() {
return;
}

// Network errors are ignored only if we are intentionally testing
// offline mode.
if ( text.includes( 'net::ERR_INTERNET_DISCONNECTED' ) && isOfflineMode() ) {
return;
}

// A bug present in WordPress 5.2 will produce console warnings when
// loading the Dashicons font. These can be safely ignored, as they do
// not otherwise regress on application behavior. This logic should be
Expand Down
68 changes: 66 additions & 2 deletions packages/e2e-tests/specs/autosave.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,17 @@ import {
createNewPost,
getEditedPostContent,
pressKeyWithModifier,
publishPost,
saveDraft,
toggleOfflineMode,
} from '@wordpress/e2e-test-utils';

// Constant to override editor preference
const AUTOSAVE_INTERVAL_SECONDS = 5;

const AUTOSAVE_NOTICE_REMOTE = 'There is an autosave of this post that is more recent than the version below.';
const AUTOSAVE_NOTICE_LOCAL = 'The backup of this post in your browser is different from the version below.';

async function saveDraftWithKeyboard() {
return pressKeyWithModifier( 'primary', 's' );
}
Expand Down Expand Up @@ -90,12 +95,13 @@ describe( 'autosave', () => {
await saveDraftWithKeyboard();
await page.keyboard.type( ' after save' );

// Trigger local autosave
await page.evaluate( () => window.wp.data.dispatch( 'core/editor' ).__experimentalLocalAutosave() );
// Reload without saving on the server
await sleep( AUTOSAVE_INTERVAL_SECONDS + 1 );
await page.reload();

const notice = await page.$eval( '.components-notice__content', ( element ) => element.innerText );
expect( notice ).toContain( 'The backup of this post in your browser is different from the version below.' );
expect( notice ).toContain( AUTOSAVE_NOTICE_LOCAL );

expect( await getEditedPostContent() ).toEqual( wrapParagraph( 'before save' ) );
await page.click( '.components-notice__action' );
Expand Down Expand Up @@ -146,6 +152,64 @@ describe( 'autosave', () => {
expect( await page.$( '.components-notice__content' ) ).toBe( null );
} );

it( 'should clear local autosave after successful remote autosave', async () => {
await clickBlockAppender();
await page.keyboard.type( 'before save' );
await saveDraft();

await page.keyboard.type( 'after save' );

// Trigger local autosave
await page.evaluate( () => window.wp.data.dispatch( 'core/editor' ).__experimentalLocalAutosave() );
expect( await page.evaluate( () => window.sessionStorage.length ) ).toBe( 1 );
Comment thread
youknowriad marked this conversation as resolved.
Resolved

// Trigger remote autosave
await page.evaluate( () => window.wp.data.dispatch( 'core/editor' ).autosave() );
expect( await page.evaluate( () => window.sessionStorage.length ) ).toBe( 0 );
} );

it( 'shouldn\'t clear local autosave if remote autosave fails', async () => {
await clickBlockAppender();
await page.keyboard.type( 'before save' );
await saveDraft();

await page.keyboard.type( 'after save' );
await page.evaluate( () => window.wp.data.dispatch( 'core/editor' ).__experimentalLocalAutosave() );
expect( await page.evaluate( () => window.sessionStorage.length ) ).toBe( 1 );

toggleOfflineMode( true );

// Trigger remote autosave
await page.evaluate( () => window.wp.data.dispatch( 'core/editor' ).autosave() );
expect( await page.evaluate( () => window.sessionStorage.length ) ).toBe( 1 );

toggleOfflineMode( false );
} );

it( 'shouldn\'t conflict with server-side autosave', async () => {
await clickBlockAppender();
await page.keyboard.type( 'before publish' );
await publishPost();

await page.click( '.wp-block-paragraph' );
await page.keyboard.type( ' after publish' );

// Trigger remote autosave
await page.evaluate( () => window.wp.data.dispatch( 'core/editor' ).autosave() );
// Force conflicting local autosave
await page.evaluate( () => window.wp.data.dispatch( 'core/editor' ).__experimentalLocalAutosave() );
expect( await page.evaluate( () => window.sessionStorage.length ) ).toBe( 1 );

await page.reload();

// Only one autosave notice should be displayed.
await sleep( 2 );
const notices = await page.$$( '.components-notice' );
expect( notices.length ).toBe( 1 );
const notice = await page.$eval( '.components-notice__content', ( element ) => element.innerText );
expect( notice ).toContain( AUTOSAVE_NOTICE_REMOTE );
} );

afterAll( async () => {
await clearSessionStorage();
} );
Expand Down
120 changes: 54 additions & 66 deletions packages/editor/src/components/local-autosave-monitor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ import { parse } from '@wordpress/blocks';
* Internal dependencies
*/
import AutosaveMonitor from '../autosave-monitor';
import {
localAutosaveGet,
localAutosaveClear,
} from '../../store/controls';

const requestIdleCallback = window.requestIdleCallback ? window.requestIdleCallback : window.requestAnimationFrame;

Expand All @@ -37,49 +41,6 @@ const hasSessionStorageSupport = once( () => {
}
} );

/**
* Function returning a sessionStorage key to set or retrieve a given post's
* automatic session backup.
*
* Keys are crucially prefixed with 'wp-autosave-' so that wp-login.php's
* `loggedout` handler can clear sessionStorage of any user-private content.
*
* @see https://github.com/WordPress/wordpress-develop/blob/6dad32d2aed47e6c0cf2aee8410645f6d7aba6bd/src/wp-login.php#L103
*
* @param {string} postId Post ID.
* @return {string} sessionStorage key
*/
function postKey( postId ) {
return `wp-autosave-block-editor-post-${ postId }`;
}

/**
* Custom hook which returns a callback function to be invoked when a local
* autosave should occur.
*
* @return {Function} Callback function.
*/
function useAutosaveCallback() {
const {
postId,
getEditedPostAttribute,
} = useSelect( ( select ) => ( {
postId: select( 'core/editor' ).getCurrentPostId(),
getEditedPostAttribute: select( 'core/editor' ).getEditedPostAttribute,
} ) );

return useCallback( () => {
const saveToSessionStorage = () => {
window.sessionStorage.setItem( postKey( postId ), JSON.stringify( {
post_title: getEditedPostAttribute( 'title' ),
content: getEditedPostAttribute( 'content' ),
excerpt: getEditedPostAttribute( 'excerpt' ),
} ) );
};
requestIdleCallback( saveToSessionStorage );
}, [ postId ] );
}

/**
* Custom hook which manages the creation of a notice prompting the user to
* restore a local autosave, if one exists.
Expand All @@ -88,45 +49,62 @@ function useAutosaveNotice() {
const {
postId,
getEditedPostAttribute,
} = useSelect( ( select ) => ( {
postId: select( 'core/editor' ).getCurrentPostId(),
getEditedPostAttribute: select( 'core/editor' ).getEditedPostAttribute,
} ) );
remoteAutosave,
hasFetchedAutosave,
} = useSelect( ( select ) => {
const _postId = select( 'core/editor' ).getCurrentPostId();
Comment thread
youknowriad marked this conversation as resolved.
Resolved
const postType = select( 'core/editor' ).getCurrentPostType();
const user = select( 'core' ).getCurrentUser();
return {
postId: _postId,
getEditedPostAttribute: select( 'core/editor' ).getEditedPostAttribute,
remoteAutosave: select( 'core' ).getAutosave( postType, _postId, user.id ),
hasFetchedAutosave: select( 'core' ).hasFetchedAutosaves( postType, _postId ) && user.id,
};
} );

const { createWarningNotice, removeNotice } = useDispatch( 'core/notices' );
const { editPost, resetEditorBlocks } = useDispatch( 'core/editor' );

useEffect( () => {
let autosave = window.sessionStorage.getItem( postKey( postId ) );
if ( ! autosave ) {
if ( ! hasFetchedAutosave ) {
return;
}

let localAutosave = localAutosaveGet( postId );
if ( ! localAutosave ) {
return;
}

try {
autosave = JSON.parse( autosave );
localAutosave = JSON.parse( localAutosave );
} catch ( error ) {
// Not usable if it can't be parsed.
return;
}

const { post_title: title, content, excerpt } = autosave;
const { post_title: title, content, excerpt } = localAutosave;
const edits = { title, content, excerpt };

// Only display a notice if there is a difference between what has been
// saved and that which is stored in sessionStorage.
const hasDifference = Object.keys( edits ).some( ( key ) => {
return edits[ key ] !== getEditedPostAttribute( key );
} );

if ( ! hasDifference ) {
// If there is no difference, it can be safely ejected from storage.
window.sessionStorage.removeItem( postKey( postId ) );
{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this needed? a way to create a scope?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it was for scope, and to share the WIP quickly

// Only display a notice if there is a difference between what has been
// saved and that which is stored in sessionStorage.
const hasDifference = Object.keys( edits ).some( ( key ) => {
return edits[ key ] !== getEditedPostAttribute( key );
} );

if ( ! hasDifference ) {
// If there is no difference, it can be safely ejected from storage.
localAutosaveClear( postId );
return;
}
}

if ( remoteAutosave ) {
return;
}

const noticeId = uniqueId( 'wpEditorAutosaveRestore' );

createWarningNotice( __( 'The backup of this post in your browser is different from the version below.' ), {
id: noticeId,
actions: [
Expand All @@ -140,7 +118,7 @@ function useAutosaveNotice() {
},
],
} );
}, [ postId ] );
}, [ postId, hasFetchedAutosave ] );
}

/**
Expand All @@ -150,24 +128,34 @@ function useAutosavePurge() {
const {
postId,
isDirty,
isAutosaving,
didError,
} = useSelect( ( select ) => ( {
postId: select( 'core/editor' ).getCurrentPostId(),
postType: select( 'core/editor' ).getCurrentPostType(),
isDirty: select( 'core/editor' ).isEditedPostDirty(),
isAutosaving: select( 'core/editor' ).isAutosavingPost(),
didError: select( 'core/editor' ).didPostSaveRequestFail(),
} ) );

const lastIsDirty = useRef( isDirty );
const lastIsAutosaving = useRef( isAutosaving );

useEffect( () => {
if ( lastIsDirty.current && ! isDirty ) {
window.sessionStorage.removeItem( postKey( postId ) );
if ( lastIsAutosaving.current && ! isAutosaving && ! didError ) {
localAutosaveClear( postId );
}

lastIsDirty.current = isDirty;
}, [ isDirty ] );
lastIsAutosaving.current = isAutosaving;
}, [ isDirty, isAutosaving, didError ] );
}

function LocalAutosaveMonitor() {
const autosave = useAutosaveCallback();
const { __experimentalLocalAutosave } = useDispatch( 'core/editor' );
const autosave = useCallback( () => {
requestIdleCallback( __experimentalLocalAutosave );
}, [] );
useAutosaveNotice();
useAutosavePurge();

Expand Down
14 changes: 14 additions & 0 deletions packages/editor/src/store/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,20 @@ export function* autosave( options ) {
);
}

export function* __experimentalLocalAutosave() {
const post = yield select( STORE_KEY, 'getCurrentPost' );
const title = yield select( STORE_KEY, 'getEditedPostAttribute', 'title' );
const content = yield select( STORE_KEY, 'getEditedPostAttribute', 'content' );
const excerpt = yield select( STORE_KEY, 'getEditedPostAttribute', 'excerpt' );
yield {
type: 'LOCAL_AUTOSAVE_SET',
postId: post.id,
title,
content,
excerpt,
};
}

/**
* Returns an action object used in signalling that undo history should
* restore last popped state.
Expand Down
Loading