variablesReducer.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { createAction } from '@reduxjs/toolkit';
  2. import { AnyAction } from 'redux';
  3. import { variableAdapters } from '../adapters';
  4. import { VariableModel } from '../types';
  5. import { sharedReducer } from './sharedReducer';
  6. import { initialVariablesState, VariablesState } from './types';
  7. export const cleanVariables = createAction<undefined>('templating/cleanVariables');
  8. export const variablesReducer = (state: VariablesState = initialVariablesState, action: AnyAction): VariablesState => {
  9. if (cleanVariables.match(action)) {
  10. const globalVariables = Object.values(state).filter((v) => v.global);
  11. if (!globalVariables) {
  12. return initialVariablesState;
  13. }
  14. const variables = globalVariables.reduce((allVariables, state) => {
  15. allVariables[state.id] = state;
  16. return allVariables;
  17. }, {} as Record<string, VariableModel>);
  18. return variables;
  19. }
  20. if (action?.payload?.type && variableAdapters.getIfExists(action?.payload?.type)) {
  21. // Now that we know we are dealing with a payload that is addressed for an adapted variable let's reduce state:
  22. // Firstly call the sharedTemplatingReducer that handles all shared actions between variable types
  23. // Secondly call the specific variable type's reducer
  24. return variableAdapters.get(action.payload.type).reducer(sharedReducer(state, action), action);
  25. }
  26. return state;
  27. };