Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use auto-save for preview #1247

Merged
merged 19 commits into from
Apr 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 45 additions & 38 deletions assets/src/edit-story/app/api/apiProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,53 +46,59 @@ function APIProvider({ children }) {
[stories]
);

const getStorySaveData = ({
pages,
featuredMedia,
stylePresets,
publisherLogo,
autoAdvance,
defaultPageDuration,
...rest
}) => {
return {
story_data: {
version: DATA_VERSION,
pages,
autoAdvance,
defaultPageDuration,
},
featured_media: featuredMedia,
style_presets: stylePresets,
publisher_logo: publisherLogo,
...rest,
};
};

const saveStoryById = useCallback(
/**
* Fire REST API call to save story.
*
* @param {import('../../types').Story} story Story object.
* @return {Promise} Return apiFetch promise.
*/
({
storyId,
title,
status,
pages,
author,
slug,
date,
modified,
content,
excerpt,
featuredMedia,
password,
stylePresets,
publisherLogo,
autoAdvance,
defaultPageDuration,
}) => {
(story) => {
const { storyId } = story;
return apiFetch({
path: `${stories}/${storyId}`,
data: {
title,
status,
author,
password,
slug,
date,
modified,
content,
excerpt,
story_data: {
version: DATA_VERSION,
pages,
autoAdvance,
defaultPageDuration,
},
featured_media: featuredMedia,
style_presets: stylePresets,
publisher_logo: publisherLogo,
},
data: getStorySaveData(story),
method: 'POST',
});
},
[stories]
);

const autoSaveById = useCallback(
/**
* Fire REST API call to save story.
*
* @param {import('../../types').Story} story Story object.
* @return {Promise} Return apiFetch promise.
*/
(story) => {
const { storyId } = story;
return apiFetch({
path: `${stories}/${storyId}/autosaves`,
data: getStorySaveData(story),
method: 'POST',
});
},
Expand Down Expand Up @@ -225,6 +231,7 @@ function APIProvider({ children }) {

const state = {
actions: {
autoSaveById,
getStoryById,
getMedia,
getLinkMetadata,
Expand Down
112 changes: 112 additions & 0 deletions assets/src/edit-story/app/story/actions/test/useAutoSave.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* External dependencies
*/
import { renderHook, act } from '@testing-library/react-hooks';

/**
* Internal dependencies
*/
import APIContext from '../../../api/context';
import ConfigContext from '../../../config/context';
import useAutoSave from '../useAutoSave';
import getStoryMarkup from '../../../../output/utils/getStoryMarkup';

jest.mock('../../../../output/utils/getStoryMarkup', () => jest.fn());

function setup(args) {
const configValue = {
metadata: 'meta',
};
const autoSaveById = jest.fn();
const apiContextValue = {
actions: { autoSaveById },
};
const wrapper = (params) => (
<ConfigContext.Provider value={configValue}>
<APIContext.Provider value={apiContextValue}>
{params.children}
</APIContext.Provider>
</ConfigContext.Provider>
);
const { result } = renderHook(() => useAutoSave(args), { wrapper });
return {
autoSave: result.current.autoSave,
autoSaveById,
};
}

describe('useAutoSave', () => {
it('should properly call autoSaveById when using autoSave', () => {
getStoryMarkup.mockImplementation(() => {
return 'Hello World!';
});
const story = {
storyId: 1,
title: 'Story!',
author: 1,
slug: 'story',
publisherLogo: 1,
defaultPageDuration: 7,
status: 'publish',
date: '2020-04-10T07:06:26',
modified: '',
excerpt: '',
featuredMedia: 0,
password: '',
stylePresets: '',
};
const pages = [
{
type: 'page',
id: '2',
elements: [
{
id: '2',
type: 'text',
x: 0,
y: 0,
},
],
},
];
const { autoSave, autoSaveById } = setup({
storyId: 1,
story,
pages,
});

autoSaveById.mockImplementation(() => ({
finally(callback) {
callback();
},
}));

act(() => {
autoSave();
});
expect(autoSaveById).toHaveBeenCalledTimes(1);

const expected = {
...story,
pages,
content: 'Hello World!',
};
expect(autoSaveById).toHaveBeenCalledWith(expected);
});
});
60 changes: 60 additions & 0 deletions assets/src/edit-story/app/story/actions/useAutoSave.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* External dependencies
*/
import { useCallback, useState } from 'react';

/**
* Internal dependencies
*/
import { useAPI } from '../../api';
import { useConfig } from '../../config';
import getStoryPropsToSave from '../utils/getStoryPropsToSave';

/**
* Custom hook to auto-save a story.
*
* @param {Object} properties Properties to update.
* @param {number} properties.storyId Story post id.
* @param {Array} properties.pages Array of all pages.
* @param {Object} properties.story Story-global properties
* @return {Function} Function that can be called to save a story.
*/
function useAutoSave({ storyId, pages, story }) {
const {
actions: { autoSaveById },
} = useAPI();
const { metadata } = useConfig();
const [isAutoSaving, setIsAutoSaving] = useState(false);

const autoSave = useCallback(
(props) => {
setIsAutoSaving(true);
return autoSaveById({
storyId,
...getStoryPropsToSave({ story, pages, metadata }),
...props,
}).finally(() => setIsAutoSaving(false));
},
[story, pages, metadata, autoSaveById, storyId]
);

return { autoSave, isAutoSaving };
miina marked this conversation as resolved.
Show resolved Hide resolved
}

export default useAutoSave;
37 changes: 2 additions & 35 deletions assets/src/edit-story/app/story/actions/useSaveStory.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
* External dependencies
*/
import { useCallback, useState } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';

/**
* WordPress dependencies
Expand All @@ -31,24 +30,10 @@ import { __ } from '@wordpress/i18n';
import objectPick from '../../../utils/objectPick';
import { useAPI } from '../../api';
import { useConfig } from '../../config';
import OutputStory from '../../../output/story';
import useRefreshPostEditURL from '../../../utils/useRefreshPostEditURL';
import { useSnackbar } from '../../snackbar';
import usePreventWindowUnload from '../../../utils/usePreventWindowUnload';

/**
* Creates AMP HTML markup for saving to DB for rendering in the FE.
*
* @param {import('../../../types').Story} story Story object.
* @param {Array<Object>} pages List of pages.
* @param {Object} metadata Metadata.
* @return {Element} Story markup.
*/
const getStoryMarkup = (story, pages, metadata) => {
return renderToStaticMarkup(
<OutputStory story={story} pages={pages} metadata={metadata} />
);
};
import getStoryPropsToSave from '../utils/getStoryPropsToSave';

/**
* Custom hook to save story.
Expand All @@ -73,27 +58,9 @@ function useSaveStory({ storyId, pages, story, updateStory }) {
const saveStory = useCallback(
(props) => {
setIsSaving(true);
const propsToSave = objectPick(story, [
'title',
'status',
'author',
'date',
'modified',
'slug',
'excerpt',
'featuredMedia',
'password',
'publisherLogo',
'stylePresets',
'autoAdvance',
'defaultPageDuration',
]);
const content = getStoryMarkup(story, pages, metadata);
return saveStoryById({
storyId,
content,
pages,
...propsToSave,
...getStoryPropsToSave({ story, pages, metadata }),
...props,
})
.then((post) => {
Expand Down
10 changes: 9 additions & 1 deletion assets/src/edit-story/app/story/storyProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import useHistoryReplay from './effects/useHistoryReplay';
import usePageBackgrounds from './effects/usePageBackgrounds';
import useStoryReducer from './useStoryReducer';
import useDeleteStory from './actions/useDeleteStory';
import useAutoSave from './actions/useAutoSave';

function StoryProvider({ storyId, children }) {
const {
Expand Down Expand Up @@ -108,6 +109,12 @@ function StoryProvider({ storyId, children }) {
story,
updateStory,
});

const { autoSave, isAutoSaving } = useAutoSave({
storyId,
pages,
story,
});
const { deleteStory } = useDeleteStory({ storyId });

const state = {
Expand All @@ -123,11 +130,12 @@ function StoryProvider({ storyId, children }) {
story,
capabilities,
meta: {
isSaving,
isSaving: isSaving || isAutoSaving,
},
},
actions: {
...api,
autoSave,
saveStory,
deleteStory,
},
Expand Down
Loading