reducer.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { createSlice, PayloadAction } from '@reduxjs/toolkit';
  2. import { ALL_VARIABLE_TEXT, ALL_VARIABLE_VALUE } from '../constants';
  3. import { getInstanceState } from '../state/selectors';
  4. import { initialVariablesState, VariablePayload, VariablesState } from '../state/types';
  5. import { CustomVariableModel, initialVariableModelState, VariableOption } from '../types';
  6. export const initialCustomVariableModelState: CustomVariableModel = {
  7. ...initialVariableModelState,
  8. type: 'custom',
  9. multi: false,
  10. includeAll: false,
  11. allValue: null,
  12. query: '',
  13. options: [],
  14. current: {} as VariableOption,
  15. };
  16. export const customVariableSlice = createSlice({
  17. name: 'templating/custom',
  18. initialState: initialVariablesState,
  19. reducers: {
  20. createCustomOptionsFromQuery: (state: VariablesState, action: PayloadAction<VariablePayload>) => {
  21. const instanceState = getInstanceState<CustomVariableModel>(state, action.payload.id);
  22. const { includeAll, query } = instanceState;
  23. const match = query.match(/(?:\\,|[^,])+/g) ?? [];
  24. const options = match.map((text) => {
  25. text = text.replace(/\\,/g, ',');
  26. const textMatch = /^(.+)\s:\s(.+)$/g.exec(text) ?? [];
  27. if (textMatch.length === 3) {
  28. const [, key, value] = textMatch;
  29. return { text: key.trim(), value: value.trim(), selected: false };
  30. } else {
  31. return { text: text.trim(), value: text.trim(), selected: false };
  32. }
  33. });
  34. if (includeAll) {
  35. options.unshift({ text: ALL_VARIABLE_TEXT, value: ALL_VARIABLE_VALUE, selected: false });
  36. }
  37. instanceState.options = options;
  38. },
  39. },
  40. });
  41. export const customVariableReducer = customVariableSlice.reducer;
  42. export const { createCustomOptionsFromQuery } = customVariableSlice.actions;