578 lines
15 KiB
JavaScript
Raw Normal View History

import React, { useCallback, useEffect, useMemo, useReducer, useState } from 'react';
import { cloneDeep, get, isEmpty, isEqual, pick, set } from 'lodash';
import PropTypes from 'prop-types';
import { Prompt, useParams } from 'react-router-dom';
import {
LoadingIndicatorPage,
request,
useGlobalContext,
findMatchingPermissions,
useUser,
} from 'strapi-helper-plugin';
2019-10-30 14:47:12 +01:00
import EditViewDataManagerContext from '../../contexts/EditViewDataManager';
import { generatePermissionsObject } from '../../utils';
import pluginId from '../../pluginId';
import init from './init';
import reducer, { initialState } from './reducer';
import {
cleanData,
createDefaultForm,
createYupSchema,
getYupInnerErrors,
getFilesToUpload,
removePasswordFieldsFromData,
} from './utils';
2019-10-30 18:46:19 +01:00
const getRequestUrl = path => `/${pluginId}/explorer/${path}`;
2019-10-30 14:47:12 +01:00
const EditViewDataManagerProvider = ({
allLayoutData,
children,
isSingleType,
redirectToPreviousPage,
slug,
}) => {
2019-10-30 18:46:19 +01:00
const { id } = useParams();
const [reducerState, dispatch] = useReducer(reducer, initialState, init);
2019-10-30 18:46:19 +01:00
const {
formErrors,
initialData,
isLoading,
modifiedData,
2019-12-11 16:52:35 +01:00
modifiedDZName,
2019-10-30 18:46:19 +01:00
shouldShowLoadingState,
shouldCheckErrors,
2019-10-30 18:46:19 +01:00
} = reducerState.toJS();
const [isCreatingEntry, setIsCreatingEntry] = useState(id === 'create');
2019-10-30 18:46:19 +01:00
const currentContentTypeLayout = get(allLayoutData, ['contentType'], {});
const abortController = new AbortController();
const { signal } = abortController;
2019-12-16 15:06:51 +01:00
const { emitEvent, formatMessage } = useGlobalContext();
const userPermissions = useUser();
const generatedPermissions = useMemo(() => generatePermissionsObject(slug), [slug]);
console.log({ generatedPermissions });
const permissionsToApply = useMemo(() => {
const fieldsToPick = isCreatingEntry ? ['create'] : ['read', 'update'];
return pick(generatedPermissions, fieldsToPick);
}, [isCreatingEntry, generatedPermissions]);
console.log({ permissionsToApply });
const createMatchingPermissions = useMemo(
() =>
findMatchingPermissions(userPermissions, [
{
action: 'plugins::content-manager.explorer.create',
subject: slug,
},
]),
[userPermissions, slug]
);
// TODO
// const updateMatchingPermissions = useMemo(
// () =>
// findMatchingPermissions(userPermissions, [
// {
// action: 'plugins::content-manager.explorer.update',
// subject: slug,
// },
// ]),
// [slug, userPermissions]
// );
// const readMatchingPermissions = useMemo(
// () =>
// findMatchingPermissions(userPermissions, [
// {
// action: 'plugins::content-manager.explorer.read',
// subject: slug,
// },
// ]),
// [slug, userPermissions]
// );
console.log({ createMatchingPermissions });
2019-11-28 16:37:38 +01:00
useEffect(() => {
if (!isLoading) {
checkFormErrors();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [shouldCheckErrors]);
2019-10-30 18:46:19 +01:00
useEffect(() => {
const fetchData = async () => {
try {
const data = await request(getRequestUrl(`${slug}/${id || ''}`), {
2019-10-30 18:46:19 +01:00
method: 'GET',
signal,
});
dispatch({
type: 'GET_DATA_SUCCEEDED',
data: removePasswordFieldsFromData(
data,
allLayoutData.contentType,
allLayoutData.components
),
2019-10-30 18:46:19 +01:00
});
} catch (err) {
if (id && err.code !== 20) {
2019-10-30 18:46:19 +01:00
strapi.notification.error(`${pluginId}.error.record.fetch`);
}
if (!id && err.response.status === 404) {
setIsCreatingEntry(true);
}
2019-10-30 18:46:19 +01:00
}
};
const componentsDataStructure = Object.keys(allLayoutData.components).reduce((acc, current) => {
2019-11-07 14:06:50 +01:00
acc[current] = createDefaultForm(
get(allLayoutData, ['components', current, 'schema', 'attributes'], {}),
allLayoutData.components
);
2019-11-07 14:06:50 +01:00
return acc;
}, {});
2019-11-07 14:06:50 +01:00
const contentTypeDataStructure = createDefaultForm(
currentContentTypeLayout.schema.attributes,
allLayoutData.components
);
2019-10-30 18:46:19 +01:00
// Force state to be cleared when navigation from one entry to another
dispatch({ type: 'RESET_PROPS' });
2019-11-07 14:06:50 +01:00
dispatch({
type: 'SET_DEFAULT_DATA_STRUCTURES',
componentsDataStructure,
contentTypeDataStructure,
});
2019-10-30 18:46:19 +01:00
if (!isCreatingEntry) {
fetchData();
} else {
// Will create default form
2019-11-07 14:06:50 +01:00
dispatch({
type: 'SET_DEFAULT_MODIFIED_DATA_STRUCTURE',
contentTypeDataStructure,
});
2019-10-30 18:46:19 +01:00
}
return () => {
abortController.abort();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id, slug, isCreatingEntry]);
const addComponentToDynamicZone = useCallback((keys, componentUid, shouldCheckErrors = false) => {
2019-11-28 16:37:38 +01:00
emitEvent('addComponentToDynamicZone');
dispatch({
type: 'ADD_COMPONENT_TO_DYNAMIC_ZONE',
keys: keys.split('.'),
componentUid,
shouldCheckErrors,
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const addNonRepeatableComponentToField = useCallback((keys, componentUid) => {
dispatch({
type: 'ADD_NON_REPEATABLE_COMPONENT_TO_FIELD',
keys: keys.split('.'),
componentUid,
});
}, []);
const addRelation = useCallback(({ target: { name, value } }) => {
2019-10-30 15:06:38 +01:00
dispatch({
type: 'ADD_RELATION',
keys: name.split('.'),
value,
});
}, []);
2019-10-30 15:06:38 +01:00
const addRepeatableComponentToField = useCallback(
(keys, componentUid, shouldCheckErrors = false) => {
dispatch({
type: 'ADD_REPEATABLE_COMPONENT_TO_FIELD',
keys: keys.split('.'),
componentUid,
shouldCheckErrors,
});
},
[]
);
const checkFormErrors = async (dataToSet = {}) => {
const schema = createYupSchema(
currentContentTypeLayout,
{
components: get(allLayoutData, 'components', {}),
},
isCreatingEntry
);
let errors = {};
const updatedData = cloneDeep(modifiedData);
if (!isEmpty(updatedData)) {
set(updatedData, dataToSet.path, dataToSet.value);
}
try {
// Validate the form using yup
await schema.validate(updatedData, { abortEarly: false });
} catch (err) {
errors = getYupInnerErrors(err);
2019-12-11 16:52:35 +01:00
if (modifiedDZName) {
errors = Object.keys(errors).reduce((acc, current) => {
const dzName = current.split('.')[0];
if (dzName !== modifiedDZName) {
acc[current] = errors[current];
}
2019-12-11 16:52:35 +01:00
return acc;
}, {});
}
}
dispatch({
type: 'SET_ERRORS',
errors,
2019-11-05 11:51:04 +01:00
});
};
const handleChange = useCallback(
({ target: { name, value, type } }, shouldSetInitialValue = false) => {
let inputValue = value;
2019-10-30 15:06:38 +01:00
// Empty string is not a valid date,
// Set the date to null when it's empty
if (type === 'date' && value === '') {
inputValue = null;
}
2019-12-18 17:35:05 +01:00
if (type === 'password' && !value) {
dispatch({
type: 'REMOVE_PASSWORD_FIELD',
keys: name.split('.'),
});
return;
}
// Allow to reset enum
if (type === 'select-one' && value === '') {
inputValue = null;
}
2019-10-30 15:06:38 +01:00
// Allow to reset number input
if (type === 'number' && value === '') {
inputValue = null;
}
dispatch({
type: 'ON_CHANGE',
keys: name.split('.'),
value: inputValue,
shouldSetInitialValue,
});
},
[]
);
2019-10-30 15:06:38 +01:00
2019-10-30 18:46:19 +01:00
const handleSubmit = async e => {
e.preventDefault();
2019-10-30 18:46:19 +01:00
2019-11-08 13:04:17 +01:00
// Create yup schema
const schema = createYupSchema(
currentContentTypeLayout,
{
components: get(allLayoutData, 'components', {}),
},
isCreatingEntry
);
2019-10-30 18:46:19 +01:00
try {
// Validate the form using yup
await schema.validate(modifiedData, { abortEarly: false });
// Set the loading state in the plugin header
const filesToUpload = getFilesToUpload(modifiedData);
2019-11-08 13:04:17 +01:00
// Remove keys that are not needed
// Clean relations
const cleanedData = cleanData(
cloneDeep(modifiedData),
currentContentTypeLayout,
allLayoutData.components
);
const formData = new FormData();
formData.append('data', JSON.stringify(cleanedData));
Object.keys(filesToUpload).forEach(key => {
const files = filesToUpload[key];
files.forEach(file => {
formData.append(`files.${key}`, file);
});
});
// Change the request helper default headers so we can pass a FormData
const headers = {};
const method = isCreatingEntry ? 'POST' : 'PUT';
let endPoint;
// All endpoints for creation and edition are the same for both content types
// But, the id from the URL didn't exist for the single types.
// So, we use the id of the modified data if this one is setted.
if (isCreatingEntry) {
endPoint = slug;
} else if (modifiedData) {
endPoint = `${slug}/${modifiedData.id}`;
} else {
endPoint = `${slug}/${id}`;
}
2019-11-28 15:57:39 +01:00
emitEvent(isCreatingEntry ? 'willCreateEntry' : 'willEditEntry');
try {
// Time to actually send the data
await request(
getRequestUrl(endPoint),
{
method,
headers,
body: formData,
signal,
},
false,
false
);
2019-11-28 15:57:39 +01:00
emitEvent(isCreatingEntry ? 'didCreateEntry' : 'didEditEntry');
2019-12-16 15:06:51 +01:00
dispatch({
type: 'SUBMIT_SUCCESS',
});
strapi.notification.success(`${pluginId}.success.record.save`);
if (isSingleType) {
setIsCreatingEntry(false);
} else {
redirectToPreviousPage();
}
} catch (err) {
console.error({ err });
const error = get(
err,
['response', 'payload', 'message', '0', 'messages', '0', 'id'],
'SERVER ERROR'
);
setIsSubmitting(false);
2019-11-28 15:57:39 +01:00
emitEvent(isCreatingEntry ? 'didNotCreateEntry' : 'didNotEditEntry', {
error: err,
});
strapi.notification.error(error);
}
2019-10-30 18:46:19 +01:00
} catch (err) {
const errors = getYupInnerErrors(err);
console.error({ err, errors });
2019-10-30 18:46:19 +01:00
dispatch({
type: 'SUBMIT_ERRORS',
errors,
});
}
};
const shouldCheckDZErrors = useCallback(
dzName => {
const doesDZHaveError = Object.keys(formErrors).some(key => key.split('.')[0] === dzName);
const shouldCheckErrors = !isEmpty(formErrors) && doesDZHaveError;
return shouldCheckErrors;
},
[formErrors]
);
const moveComponentDown = useCallback(
(dynamicZoneName, currentIndex) => {
emitEvent('changeComponentsOrder');
dispatch({
type: 'MOVE_COMPONENT_DOWN',
dynamicZoneName,
currentIndex,
shouldCheckErrors: shouldCheckDZErrors(dynamicZoneName),
});
// eslint-disable-next-line react-hooks/exhaustive-deps
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[shouldCheckDZErrors]
);
const moveComponentUp = useCallback(
(dynamicZoneName, currentIndex) => {
emitEvent('changeComponentsOrder');
dispatch({
type: 'MOVE_COMPONENT_UP',
dynamicZoneName,
currentIndex,
shouldCheckErrors: shouldCheckDZErrors(dynamicZoneName),
});
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[shouldCheckDZErrors]
);
const moveComponentField = useCallback((pathToComponent, dragIndex, hoverIndex) => {
2019-11-05 17:50:22 +01:00
dispatch({
type: 'MOVE_COMPONENT_FIELD',
pathToComponent,
dragIndex,
hoverIndex,
});
}, []);
2019-11-05 17:50:22 +01:00
const moveRelation = useCallback((dragIndex, overIndex, name) => {
2019-10-30 15:06:38 +01:00
dispatch({
type: 'MOVE_FIELD',
dragIndex,
overIndex,
keys: name.split('.'),
});
}, []);
2019-10-30 15:06:38 +01:00
const onRemoveRelation = useCallback(keys => {
2019-10-30 15:06:38 +01:00
dispatch({
type: 'REMOVE_RELATION',
keys,
});
}, []);
2019-10-30 15:06:38 +01:00
const removeComponentFromDynamicZone = useCallback((dynamicZoneName, index) => {
2019-12-11 17:13:23 +01:00
emitEvent('removeComponentFromDynamicZone');
2019-11-06 16:29:19 +01:00
dispatch({
type: 'REMOVE_COMPONENT_FROM_DYNAMIC_ZONE',
dynamicZoneName,
index,
2019-12-11 17:13:23 +01:00
shouldCheckErrors: shouldCheckDZErrors(dynamicZoneName),
2019-11-06 16:29:19 +01:00
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const removeComponentFromField = useCallback((keys, componentUid) => {
dispatch({
type: 'REMOVE_COMPONENT_FROM_FIELD',
keys: keys.split('.'),
componentUid,
});
}, []);
const removeRepeatableField = useCallback((keys, componentUid) => {
2019-11-05 15:36:22 +01:00
dispatch({
type: 'REMOVE_REPEATABLE_FIELD',
keys: keys.split('.'),
componentUid,
});
}, []);
2019-11-05 15:36:22 +01:00
2019-10-30 19:06:40 +01:00
const setIsSubmitting = (value = true) => {
dispatch({ type: 'IS_SUBMITTING', value });
};
const deleteSuccess = () => {
dispatch({
type: 'DELETE_SUCCEEDED',
});
};
const resetData = () => {
dispatch({
type: 'RESET_DATA',
});
};
const clearData = () => {
if (isSingleType) {
setIsCreatingEntry(true);
}
dispatch({
type: 'SET_DEFAULT_MODIFIED_DATA_STRUCTURE',
contentTypeDataStructure: {},
});
};
const triggerFormValidation = () => {
dispatch({
type: 'TRIGGER_FORM_VALIDATION',
});
};
const showLoader = useMemo(() => {
return !isCreatingEntry && isLoading;
}, [isCreatingEntry, isLoading]);
2019-10-30 18:46:19 +01:00
return (
<EditViewDataManagerContext.Provider
2019-10-30 15:06:38 +01:00
value={{
addComponentToDynamicZone,
addNonRepeatableComponentToField,
2019-10-30 15:06:38 +01:00
addRelation,
2019-11-05 11:51:04 +01:00
addRepeatableComponentToField,
2019-11-04 09:00:59 +01:00
allLayoutData,
checkFormErrors,
clearData,
deleteSuccess,
2019-10-30 18:46:19 +01:00
formErrors,
2019-10-30 15:06:38 +01:00
initialData,
isCreatingEntry,
isSingleType,
2019-10-30 18:46:19 +01:00
layout: currentContentTypeLayout,
2019-10-30 15:06:38 +01:00
modifiedData,
2019-11-06 16:29:19 +01:00
moveComponentDown,
2019-11-05 17:50:22 +01:00
moveComponentField,
2019-11-06 16:29:19 +01:00
moveComponentUp,
2019-10-30 15:06:38 +01:00
moveRelation,
onChange: handleChange,
onRemoveRelation,
2019-10-30 19:06:40 +01:00
redirectToPreviousPage,
2019-11-06 16:29:19 +01:00
removeComponentFromDynamicZone,
removeComponentFromField,
2019-11-05 15:36:22 +01:00
removeRepeatableField,
resetData,
2019-10-30 19:06:40 +01:00
setIsSubmitting,
2019-10-30 18:46:19 +01:00
shouldShowLoadingState,
2019-10-30 19:06:40 +01:00
slug,
triggerFormValidation,
2019-10-30 15:06:38 +01:00
}}
>
2019-10-30 18:46:19 +01:00
{showLoader ? (
<LoadingIndicatorPage />
) : (
2019-12-16 15:06:51 +01:00
<>
<Prompt
when={!isEqual(modifiedData, initialData)}
message={formatMessage({ id: 'global.prompt.unsaved' })}
/>
<form onSubmit={handleSubmit}>{children}</form>
</>
2019-10-30 18:46:19 +01:00
)}
</EditViewDataManagerContext.Provider>
);
};
2019-10-30 19:06:40 +01:00
EditViewDataManagerProvider.defaultProps = {
redirectToPreviousPage: () => {},
};
EditViewDataManagerProvider.propTypes = {
2019-10-30 18:46:19 +01:00
allLayoutData: PropTypes.object.isRequired,
children: PropTypes.node.isRequired,
isSingleType: PropTypes.bool.isRequired,
2019-10-30 19:06:40 +01:00
redirectToPreviousPage: PropTypes.func,
2019-10-30 18:46:19 +01:00
slug: PropTypes.string.isRequired,
};
export default EditViewDataManagerProvider;