keyedVariablesReducer.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { PayloadAction } from '@reduxjs/toolkit';
  2. import { AnyAction } from 'redux';
  3. import { toStateKey } from '../utils';
  4. import { getTemplatingReducers, TemplatingState } from './reducers';
  5. import { variablesInitTransaction } from './transactionReducer';
  6. export interface KeyedVariablesState {
  7. lastKey?: string;
  8. keys: Record<string, TemplatingState>;
  9. }
  10. export const initialKeyedVariablesState: KeyedVariablesState = { keys: {} };
  11. export interface KeyedAction {
  12. key: string;
  13. action: PayloadAction<any>;
  14. }
  15. const keyedAction = (payload: KeyedAction) => ({
  16. type: `templating/keyed/${payload.action.type.replace(/^templating\//, '')}`,
  17. payload,
  18. });
  19. export function toKeyedAction(key: string, action: PayloadAction<any>): PayloadAction<KeyedAction> {
  20. const keyAsString = toStateKey(key);
  21. return keyedAction({ key: keyAsString, action });
  22. }
  23. const isKeyedAction = (action: AnyAction): action is PayloadAction<KeyedAction> => {
  24. return (
  25. typeof action.type === 'string' &&
  26. action.type.startsWith('templating/keyed') &&
  27. 'payload' in action &&
  28. typeof action.payload.key === 'string'
  29. );
  30. };
  31. export function keyedVariablesReducer(state = initialKeyedVariablesState, outerAction: AnyAction): KeyedVariablesState {
  32. if (isKeyedAction(outerAction)) {
  33. const { key, action } = outerAction.payload;
  34. const stringKey = toStateKey(key);
  35. const lastKey = variablesInitTransaction.match(action) ? stringKey : state.lastKey;
  36. const templatingReducers = getTemplatingReducers();
  37. const prevKeyState = state.keys[stringKey];
  38. const nextKeyState = templatingReducers(prevKeyState, action);
  39. return {
  40. ...state,
  41. lastKey,
  42. keys: {
  43. ...state.keys,
  44. [stringKey]: nextKeyState,
  45. },
  46. };
  47. }
  48. return state;
  49. }
  50. export default {
  51. templating: keyedVariablesReducer,
  52. };