transactionReducer.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { AnyAction, createSlice, PayloadAction } from '@reduxjs/toolkit';
  2. import { TransactionStatus } from '../types';
  3. import {
  4. addVariable,
  5. changeVariableOrder,
  6. changeVariableProp,
  7. changeVariableType,
  8. duplicateVariable,
  9. removeVariable,
  10. } from './sharedReducer';
  11. export interface TransactionState {
  12. uid: string | undefined | null;
  13. status: TransactionStatus;
  14. isDirty: boolean;
  15. }
  16. export const initialTransactionState: TransactionState = {
  17. uid: null,
  18. status: TransactionStatus.NotStarted,
  19. isDirty: false,
  20. };
  21. const transactionSlice = createSlice({
  22. name: 'templating/transaction',
  23. initialState: initialTransactionState,
  24. reducers: {
  25. variablesInitTransaction: (state, action: PayloadAction<{ uid: string | undefined | null }>) => {
  26. state.uid = action.payload.uid;
  27. state.status = TransactionStatus.Fetching;
  28. },
  29. variablesCompleteTransaction: (state, action: PayloadAction<{ uid: string | undefined | null }>) => {
  30. if (state.uid !== action.payload.uid) {
  31. // this might be an action from a cancelled batch
  32. return;
  33. }
  34. state.status = TransactionStatus.Completed;
  35. },
  36. variablesClearTransaction: (state, action: PayloadAction<undefined>) => {
  37. state.uid = null;
  38. state.status = TransactionStatus.NotStarted;
  39. state.isDirty = false;
  40. },
  41. },
  42. extraReducers: (builder) =>
  43. builder.addMatcher(actionAffectsDirtyState, (state, action) => {
  44. if (state.status === TransactionStatus.Completed) {
  45. state.isDirty = true;
  46. }
  47. }),
  48. });
  49. function actionAffectsDirtyState(action: AnyAction): boolean {
  50. return (
  51. removeVariable.match(action) ||
  52. addVariable.match(action) ||
  53. changeVariableProp.match(action) ||
  54. changeVariableOrder.match(action) ||
  55. duplicateVariable.match(action) ||
  56. changeVariableType.match(action)
  57. );
  58. }
  59. export const { variablesInitTransaction, variablesClearTransaction, variablesCompleteTransaction } =
  60. transactionSlice.actions;
  61. export const transactionReducer = transactionSlice.reducer;