grafana/public/app/features/variables/adhoc/reducer.ts
Josh Hunt 081d6e9d3e
Typed variables pt5: Remove generics from getInstanceState (#53018)
* wip

* make diff easier to read

* Update template_srv getVariables to return new TypedVariableModel

* update VariableType to use the type from TypedVariableModel

* tidy things up

* Chore: Use type-accurate mock variables in tests

* Chore: Type VariableState to use TypedVariableModel

* fix typo

* remove type assertion from template_srv.getVariables

* use typescript/no-redeclare for compatibility with ts overloads

* remove generics from getVariable() and overload it to only return undefined based on arguments

* update usages of getVariable()

* Remove generic from getInstanceState

* update usages of getInstanceState

* fix lint
2022-08-10 16:06:49 +01:00

63 lines
2.1 KiB
TypeScript

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AdHocVariableFilter, AdHocVariableModel, initialVariableModelState } from 'app/features/variables/types';
import { getInstanceState } from '../state/selectors';
import { initialVariablesState, VariablePayload, VariablesState } from '../state/types';
export interface AdHocVariabelFilterUpdate {
index: number;
filter: AdHocVariableFilter;
}
export const initialAdHocVariableModelState: AdHocVariableModel = {
...initialVariableModelState,
type: 'adhoc',
datasource: null,
filters: [],
};
export const adHocVariableSlice = createSlice({
name: 'templating/adhoc',
initialState: initialVariablesState,
reducers: {
filterAdded: (state: VariablesState, action: PayloadAction<VariablePayload<AdHocVariableFilter>>) => {
const instanceState = getInstanceState(state, action.payload.id);
if (instanceState.type !== 'adhoc') {
return;
}
instanceState.filters.push(action.payload.data);
},
filterRemoved: (state: VariablesState, action: PayloadAction<VariablePayload<number>>) => {
const instanceState = getInstanceState(state, action.payload.id);
if (instanceState.type !== 'adhoc') {
return;
}
const index = action.payload.data;
instanceState.filters.splice(index, 1);
},
filterUpdated: (state: VariablesState, action: PayloadAction<VariablePayload<AdHocVariabelFilterUpdate>>) => {
const instanceState = getInstanceState(state, action.payload.id);
if (instanceState.type !== 'adhoc') {
return;
}
const { filter, index } = action.payload.data;
instanceState.filters[index] = filter;
},
filtersRestored: (state: VariablesState, action: PayloadAction<VariablePayload<AdHocVariableFilter[]>>) => {
const instanceState = getInstanceState(state, action.payload.id);
if (instanceState.type !== 'adhoc') {
return;
}
instanceState.filters = action.payload.data;
},
},
});
export const { filterAdded, filterRemoved, filterUpdated, filtersRestored } = adHocVariableSlice.actions;
export const adHocVariableReducer = adHocVariableSlice.reducer;