Skip to content

Instantly share code, notes, and snippets.

@sankargorthi
Created September 18, 2019 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sankargorthi/d42015b06c8372530c43cc4159386013 to your computer and use it in GitHub Desktop.
Save sankargorthi/d42015b06c8372530c43cc4159386013 to your computer and use it in GitHub Desktop.
import { api } from '@cdm/cdms-data';
import { FeatureContext } from '@cdm/context';
import compact from 'lodash/compact';
import { useCallback, useContext, useReducer } from 'react';
import * as ACTION_TYPE from './actionTypes';
import reducer from './compareReducer';
import initialState from './initialState';
import Step2SecondVersion from './Step2SecondVersion';
export default function useComparisons(init, closeWizard, type) {
const { viewsEnabled } = useContext(FeatureContext);
let comparisonState = initialState;
if (type === 'all') {
comparisonState = {
...comparisonState,
activeStep: Step2SecondVersion.displayName,
comparison: type,
options: compact([...comparisonState.options, 'diffByStudy']),
};
}
const [state, dispatch] = useReducer(reducer, {
...comparisonState,
...init,
options: compact([...comparisonState.options, viewsEnabled ? 'views' : null]),
});
const cancelWizard = useCallback(() => {
dispatch({
type: ACTION_TYPE.CLOSE_WIZARD,
});
closeWizard();
}, [closeWizard]);
const nextStep = useCallback(
() =>
dispatch({
type: ACTION_TYPE.GO_NEXT,
}),
[],
);
const prevStep = useCallback(
() =>
dispatch({
type: ACTION_TYPE.GO_BACK,
}),
[],
);
const submit = useCallback(async () => {
const { leftStudyId, leftVersion, rightVersion, vault, rightStudyId, options } = state;
try {
await api.compareVersions({
leftVersion,
rightVersion,
rightStudyId,
leftStudyId,
options,
remote: vault !== 'current',
});
} finally {
cancelWizard();
}
}, [cancelWizard, state]);
const selectFirstVersion = useCallback(
(version) =>
dispatch({
version,
type: ACTION_TYPE.SELECT_FIRST,
}),
[],
);
const selectVault = useCallback(
(vault) =>
dispatch({
vault,
currentStudy: state.leftStudyId,
type: ACTION_TYPE.SELECT_VAULT,
}),
[state.leftStudyId],
);
const selectValidVersion = useCallback((validVersionPresent) => {
dispatch({
validVersionPresent,
type: ACTION_TYPE.NO_VALID_VERSION,
});
}, []);
const selectRightStudy = useCallback(
(studyId) =>
dispatch({
rightStudyId: studyId,
type: ACTION_TYPE.SELECT_RIGHT_STUDY,
}),
[],
);
const selectSecondVersion = useCallback(
(version) =>
dispatch({
version,
type: ACTION_TYPE.SELECT_SECOND,
}),
[],
);
const pickOptions = useCallback(
(options) =>
dispatch({
options,
type: ACTION_TYPE.PICK_OPTIONS,
}),
[],
);
return [
state,
{
cancelWizard,
pickOptions,
selectFirstVersion,
selectSecondVersion,
selectRightStudy,
selectVault,
selectValidVersion,
submit,
prevStep,
nextStep,
},
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment