searchQueryReducer.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { DashboardQuery, SearchQueryParams, SearchAction, SearchLayout } from '../types';
  2. import {
  3. ADD_TAG,
  4. CLEAR_FILTERS,
  5. LAYOUT_CHANGE,
  6. QUERY_CHANGE,
  7. REMOVE_STARRED,
  8. REMOVE_TAG,
  9. SET_TAGS,
  10. DATASOURCE_CHANGE,
  11. TOGGLE_SORT,
  12. TOGGLE_STARRED,
  13. } from './actionTypes';
  14. export const defaultQuery: DashboardQuery = {
  15. query: '',
  16. tag: [],
  17. starred: false,
  18. skipRecent: false,
  19. skipStarred: false,
  20. folderIds: [],
  21. sort: null,
  22. layout: SearchLayout.Folders,
  23. prevSort: null,
  24. };
  25. export const defaultQueryParams: SearchQueryParams = {
  26. sort: null,
  27. starred: null,
  28. query: null,
  29. tag: null,
  30. layout: null,
  31. };
  32. export const queryReducer = (state: DashboardQuery, action: SearchAction) => {
  33. switch (action.type) {
  34. case QUERY_CHANGE:
  35. return { ...state, query: action.payload };
  36. case REMOVE_TAG:
  37. return { ...state, tag: state.tag.filter((t) => t !== action.payload) };
  38. case SET_TAGS:
  39. return { ...state, tag: action.payload };
  40. case ADD_TAG: {
  41. const tag = action.payload;
  42. return tag && !state.tag.includes(tag) ? { ...state, tag: [...state.tag, tag] } : state;
  43. }
  44. case DATASOURCE_CHANGE:
  45. return { ...state, datasource: action.payload };
  46. case TOGGLE_STARRED:
  47. return { ...state, starred: action.payload };
  48. case REMOVE_STARRED:
  49. return { ...state, starred: false };
  50. case CLEAR_FILTERS:
  51. return { ...state, query: '', tag: [], starred: false, sort: null };
  52. case TOGGLE_SORT: {
  53. const sort = action.payload;
  54. if (state.layout === SearchLayout.Folders) {
  55. return { ...state, sort, layout: SearchLayout.List };
  56. }
  57. return { ...state, sort };
  58. }
  59. case LAYOUT_CHANGE: {
  60. const layout = action.payload;
  61. if (state.sort && layout === SearchLayout.Folders) {
  62. return { ...state, layout, sort: null, prevSort: state.sort };
  63. }
  64. return { ...state, layout, sort: state.prevSort };
  65. }
  66. default:
  67. return state;
  68. }
  69. };