2019-01-03 17:14:25 +03:00
|
|
|
import stringifyJSON from '../utils/stringifyJSON';
|
|
|
|
import { UPDATE_STATE, LIFTED_ACTION, EXPORT } from '../constants/actionTypes';
|
|
|
|
import { getActiveInstance } from '../reducers/instances';
|
2020-10-26 02:32:04 +03:00
|
|
|
import { Dispatch, MiddlewareAPI } from 'redux';
|
|
|
|
import { ExportRequest, StoreAction } from '../actions';
|
|
|
|
import { StoreState } from '../reducers';
|
2019-01-03 17:14:25 +03:00
|
|
|
|
2021-08-25 07:22:54 +03:00
|
|
|
let toExport: string | number | undefined;
|
2019-01-03 17:14:25 +03:00
|
|
|
|
2020-10-26 02:32:04 +03:00
|
|
|
function download(state: string) {
|
2019-01-03 17:14:25 +03:00
|
|
|
const blob = new Blob([state], { type: 'octet/stream' });
|
|
|
|
const href = window.URL.createObjectURL(blob);
|
|
|
|
const a = document.createElement('a');
|
2020-10-26 02:32:04 +03:00
|
|
|
a.style.display = 'none';
|
2019-01-03 17:14:25 +03:00
|
|
|
a.download = 'state.json';
|
|
|
|
a.href = href;
|
|
|
|
document.body.appendChild(a);
|
|
|
|
a.click();
|
|
|
|
setTimeout(() => {
|
|
|
|
document.body.removeChild(a);
|
|
|
|
window.URL.revokeObjectURL(href);
|
|
|
|
}, 0);
|
|
|
|
}
|
|
|
|
|
2021-06-18 06:56:36 +03:00
|
|
|
const exportState =
|
|
|
|
(store: MiddlewareAPI<Dispatch<StoreAction>, StoreState>) =>
|
|
|
|
(next: Dispatch<StoreAction>) =>
|
|
|
|
(action: StoreAction) => {
|
|
|
|
const result = next(action);
|
2019-01-03 17:14:25 +03:00
|
|
|
|
2021-06-18 06:56:36 +03:00
|
|
|
if (
|
|
|
|
toExport &&
|
|
|
|
action.type === UPDATE_STATE &&
|
|
|
|
action.request!.type === 'EXPORT'
|
|
|
|
) {
|
|
|
|
const request = action.request!;
|
|
|
|
const id = request.instanceId || request.id;
|
|
|
|
if (id === toExport) {
|
|
|
|
toExport = undefined;
|
|
|
|
download(
|
|
|
|
JSON.stringify(
|
|
|
|
{
|
|
|
|
payload: request.payload,
|
|
|
|
preloadedState: (request as ExportRequest).committedState,
|
|
|
|
},
|
|
|
|
null,
|
|
|
|
'\t'
|
|
|
|
)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
} else if (action.type === EXPORT) {
|
|
|
|
const instances = store.getState().instances;
|
|
|
|
const instanceId = getActiveInstance(instances);
|
|
|
|
const options = instances.options[instanceId];
|
|
|
|
if (options.features.export === true) {
|
|
|
|
download(
|
|
|
|
stringifyJSON(instances.states[instanceId], options.serialize)
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
toExport = instanceId;
|
|
|
|
next({ type: LIFTED_ACTION, message: 'EXPORT', toExport: true });
|
|
|
|
}
|
2019-01-03 17:14:25 +03:00
|
|
|
}
|
2021-06-18 06:56:36 +03:00
|
|
|
return result;
|
|
|
|
};
|
2019-01-03 17:14:25 +03:00
|
|
|
|
|
|
|
export default exportState;
|