reducer.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { createSlice, PayloadAction } from '@reduxjs/toolkit';
  2. import { map } from 'lodash';
  3. import { getInstanceState } from '../state/selectors';
  4. import { initialVariablesState, VariablePayload, VariablesState } from '../state/types';
  5. import { initialVariableModelState, IntervalVariableModel, VariableOption, VariableRefresh } from '../types';
  6. export const initialIntervalVariableModelState: IntervalVariableModel = {
  7. ...initialVariableModelState,
  8. type: 'interval',
  9. auto_count: 30,
  10. auto_min: '10s',
  11. options: [],
  12. auto: false,
  13. query: '1m,10m,30m,1h,6h,12h,1d,7d,14d,30d',
  14. refresh: VariableRefresh.onTimeRangeChanged,
  15. current: {} as VariableOption,
  16. };
  17. export const intervalVariableSlice = createSlice({
  18. name: 'templating/interval',
  19. initialState: initialVariablesState,
  20. reducers: {
  21. createIntervalOptions: (state: VariablesState, action: PayloadAction<VariablePayload>) => {
  22. const instanceState = getInstanceState<IntervalVariableModel>(state, action.payload.id);
  23. const options: VariableOption[] = map(instanceState.query.match(/(["'])(.*?)\1|\w+/g), (text) => {
  24. text = text.replace(/["']+/g, '');
  25. return { text: text.trim(), value: text.trim(), selected: false };
  26. });
  27. if (instanceState.auto) {
  28. // add auto option if missing
  29. if (options.length && options[0].text !== 'auto') {
  30. options.unshift({
  31. text: 'auto',
  32. value: '$__auto_interval_' + instanceState.name,
  33. selected: false,
  34. });
  35. }
  36. }
  37. instanceState.options = options;
  38. },
  39. },
  40. });
  41. export const intervalVariableReducer = intervalVariableSlice.reducer;
  42. export const { createIntervalOptions } = intervalVariableSlice.actions;