2019-10-30 13:56:20 +01:00
|
|
|
import React, { useReducer } from 'react';
|
|
|
|
// import { useHistory, useLocation, useParams } from 'react-router-dom';
|
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
// import { get } from 'lodash';
|
2019-10-30 14:47:12 +01:00
|
|
|
import EditViewDataManagerContext from '../../contexts/EditViewDataManager';
|
|
|
|
|
2019-10-30 13:56:20 +01:00
|
|
|
import init from './init';
|
|
|
|
import reducer, { initialState } from './reducer';
|
|
|
|
|
2019-10-30 14:47:12 +01:00
|
|
|
// const getRequestUrl = path => `/${pluginId}/explorer/${path}`;
|
|
|
|
|
|
|
|
const EditViewDataManagerProvider = ({ children, layout }) => {
|
2019-10-30 13:56:20 +01:00
|
|
|
const [reducerState, dispatch] = useReducer(reducer, initialState, init);
|
|
|
|
const { initialData, modifiedData } = reducerState.toJS();
|
|
|
|
|
2019-10-30 15:06:38 +01:00
|
|
|
const addRelation = ({ target: { name, value } }) => {
|
|
|
|
dispatch({
|
|
|
|
type: 'ADD_RELATION',
|
|
|
|
keys: name.split('.'),
|
|
|
|
value,
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
const handleChange = ({ target: { name, value, type } }) => {
|
|
|
|
let inputValue = value;
|
|
|
|
|
|
|
|
// Empty string is not a valid date,
|
|
|
|
// Set the date to null when it's empty
|
|
|
|
if (type === 'date' && value === '') {
|
|
|
|
inputValue = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
dispatch({
|
|
|
|
type: 'ON_CHANGE',
|
|
|
|
keys: name.split('.'),
|
|
|
|
value: inputValue,
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2019-10-30 13:56:20 +01:00
|
|
|
const handleSubmit = e => {
|
|
|
|
e.preventDefault();
|
|
|
|
dispatch({
|
|
|
|
type: 'SUBMIT_SUCCEEDED',
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2019-10-30 15:06:38 +01:00
|
|
|
const moveRelation = (dragIndex, overIndex, name) => {
|
|
|
|
dispatch({
|
|
|
|
type: 'MOVE_FIELD',
|
|
|
|
dragIndex,
|
|
|
|
overIndex,
|
|
|
|
keys: name.split('.'),
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
const onRemoveRelation = keys => {
|
|
|
|
dispatch({
|
|
|
|
type: 'REMOVE_RELATION',
|
|
|
|
keys,
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2019-10-30 13:56:20 +01:00
|
|
|
return (
|
|
|
|
<EditViewDataManagerContext.Provider
|
2019-10-30 15:06:38 +01:00
|
|
|
value={{
|
|
|
|
addRelation,
|
|
|
|
initialData,
|
|
|
|
layout,
|
|
|
|
modifiedData,
|
|
|
|
moveRelation,
|
|
|
|
onChange: handleChange,
|
|
|
|
onRemoveRelation,
|
|
|
|
}}
|
2019-10-30 13:56:20 +01:00
|
|
|
>
|
|
|
|
<form onSubmit={handleSubmit}>{children}</form>
|
|
|
|
</EditViewDataManagerContext.Provider>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
EditViewDataManagerProvider.defaultProps = {};
|
|
|
|
EditViewDataManagerProvider.propTypes = {
|
|
|
|
children: PropTypes.node.isRequired,
|
2019-10-30 14:47:12 +01:00
|
|
|
layout: PropTypes.object.isRequired,
|
2019-10-30 13:56:20 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
export default EditViewDataManagerProvider;
|