reducer.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { createAction } from '@reduxjs/toolkit';
  2. import { AnyAction } from 'redux';
  3. import { LoadingState } from '@grafana/data';
  4. import { LibraryElementDTO } from '../../types';
  5. export interface LibraryPanelsViewState {
  6. loadingState: LoadingState;
  7. libraryPanels: LibraryElementDTO[];
  8. totalCount: number;
  9. perPage: number;
  10. page: number;
  11. numberOfPages: number;
  12. currentPanelId?: string;
  13. }
  14. export const initialLibraryPanelsViewState: LibraryPanelsViewState = {
  15. loadingState: LoadingState.Loading,
  16. libraryPanels: [],
  17. totalCount: 0,
  18. perPage: 40,
  19. page: 1,
  20. numberOfPages: 0,
  21. currentPanelId: undefined,
  22. };
  23. export const initSearch = createAction('libraryPanels/view/initSearch');
  24. export const searchCompleted = createAction<
  25. Omit<LibraryPanelsViewState, 'currentPanelId' | 'searchString' | 'loadingState' | 'numberOfPages'>
  26. >('libraryPanels/view/searchCompleted');
  27. export const changePage = createAction<Pick<LibraryPanelsViewState, 'page'>>('libraryPanels/view/changePage');
  28. export const libraryPanelsViewReducer = (state: LibraryPanelsViewState, action: AnyAction) => {
  29. if (initSearch.match(action)) {
  30. return { ...state, loadingState: LoadingState.Loading };
  31. }
  32. if (searchCompleted.match(action)) {
  33. const { libraryPanels, page, perPage, totalCount } = action.payload;
  34. const numberOfPages = Math.ceil(totalCount / perPage);
  35. return {
  36. ...state,
  37. libraryPanels,
  38. perPage,
  39. totalCount,
  40. loadingState: LoadingState.Done,
  41. numberOfPages,
  42. page: page > numberOfPages ? page - 1 : page,
  43. };
  44. }
  45. if (changePage.match(action)) {
  46. return { ...state, page: action.payload.page };
  47. }
  48. return state;
  49. };