adapter.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { cloneDeep } from 'lodash';
  2. import { dispatch } from '../../../store/store';
  3. import { VariableAdapter } from '../adapters';
  4. import { optionPickerFactory } from '../pickers';
  5. import { setOptionAsCurrent, setOptionFromUrl } from '../state/actions';
  6. import { ConstantVariableModel } from '../types';
  7. import { toKeyedVariableIdentifier } from '../utils';
  8. import { ConstantVariableEditor } from './ConstantVariableEditor';
  9. import { updateConstantVariableOptions } from './actions';
  10. import { constantVariableReducer, initialConstantVariableModelState } from './reducer';
  11. export const createConstantVariableAdapter = (): VariableAdapter<ConstantVariableModel> => {
  12. return {
  13. id: 'constant',
  14. description: 'Define a hidden constant variable, useful for metric prefixes in dashboards you want to share.',
  15. name: 'Constant',
  16. initialState: initialConstantVariableModelState,
  17. reducer: constantVariableReducer,
  18. picker: optionPickerFactory<ConstantVariableModel>(),
  19. editor: ConstantVariableEditor,
  20. dependsOn: () => {
  21. return false;
  22. },
  23. setValue: async (variable, option, emitChanges = false) => {
  24. await dispatch(setOptionAsCurrent(toKeyedVariableIdentifier(variable), option, emitChanges));
  25. },
  26. setValueFromUrl: async (variable, urlValue) => {
  27. await dispatch(setOptionFromUrl(toKeyedVariableIdentifier(variable), urlValue));
  28. },
  29. updateOptions: async (variable) => {
  30. await dispatch(updateConstantVariableOptions(toKeyedVariableIdentifier(variable)));
  31. },
  32. getSaveModel: (variable) => {
  33. const { index, id, state, global, current, options, rootStateKey, ...rest } = cloneDeep(variable);
  34. return rest;
  35. },
  36. getValueForUrl: (variable) => {
  37. return variable.current.value;
  38. },
  39. beforeAdding: (model) => {
  40. const { current, options, query, ...rest } = cloneDeep(model);
  41. const option = { selected: true, text: query, value: query };
  42. return { ...rest, current: option, options: [option], query };
  43. },
  44. };
  45. };