useDashboardSearch.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { KeyboardEvent, useReducer } from 'react';
  2. import { useDebounce } from 'react-use';
  3. import { locationUtil } from '@grafana/data';
  4. import { locationService } from '@grafana/runtime';
  5. import { MOVE_SELECTION_DOWN, MOVE_SELECTION_UP } from '../reducers/actionTypes';
  6. import { dashboardsSearchState, DashboardsSearchState, searchReducer } from '../reducers/dashboardSearch';
  7. import { DashboardQuery, DashboardSearchItemType, DashboardSection } from '../types';
  8. import { findSelected } from '../utils';
  9. import { reportDashboardListViewed } from './useManageDashboards';
  10. import { useSearch } from './useSearch';
  11. import { useShowDashboardPreviews } from './useShowDashboardPreviews';
  12. export const useDashboardSearch = (query: DashboardQuery, onCloseSearch: () => void) => {
  13. const reducer = useReducer(searchReducer, dashboardsSearchState);
  14. const { showPreviews, setShowPreviews, previewFeatureEnabled } = useShowDashboardPreviews();
  15. const {
  16. state: { results, loading },
  17. onToggleSection,
  18. dispatch,
  19. } = useSearch<DashboardsSearchState>(query, reducer, { queryParsing: true });
  20. useDebounce(
  21. () => {
  22. reportDashboardListViewed('dashboard_search', showPreviews, previewFeatureEnabled, {
  23. layout: query.layout,
  24. starred: query.starred,
  25. sortValue: query.sort?.value,
  26. query: query.query,
  27. tagCount: query.tag?.length,
  28. });
  29. },
  30. 1000,
  31. [
  32. showPreviews,
  33. previewFeatureEnabled,
  34. query.layout,
  35. query.starred,
  36. query.sort?.value,
  37. query.query?.length,
  38. query.tag?.length,
  39. ]
  40. );
  41. const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
  42. switch (event.key) {
  43. case 'Escape':
  44. onCloseSearch();
  45. break;
  46. case 'ArrowUp':
  47. dispatch({ type: MOVE_SELECTION_UP });
  48. break;
  49. case 'ArrowDown':
  50. dispatch({ type: MOVE_SELECTION_DOWN });
  51. break;
  52. case 'Enter':
  53. const selectedItem = findSelected(results);
  54. if (selectedItem) {
  55. if (selectedItem.type === DashboardSearchItemType.DashFolder) {
  56. onToggleSection(selectedItem as DashboardSection);
  57. } else {
  58. locationService.push(locationUtil.stripBaseFromUrl(selectedItem.url));
  59. // Delay closing to prevent current page flicker
  60. setTimeout(onCloseSearch, 0);
  61. }
  62. }
  63. }
  64. };
  65. return {
  66. results,
  67. loading,
  68. onToggleSection,
  69. onKeyDown,
  70. showPreviews,
  71. setShowPreviews,
  72. };
  73. };