DashboardPicker.tsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import React, { PureComponent } from 'react';
  2. import { AsyncSelect } from '@grafana/ui';
  3. import { SelectableValue } from '@grafana/data';
  4. import { debounce } from 'lodash';
  5. import { getBackendSrv } from 'app/core/services/backend_srv';
  6. import { DashboardSearchHit, DashboardDTO } from 'app/types';
  7. export interface Props {
  8. className?: string;
  9. onSelected: (dashboard: DashboardDTO) => void;
  10. currentDashboardId: SelectableValue<number>;
  11. }
  12. export interface State {
  13. isLoading: boolean;
  14. }
  15. export class DashboardPicker extends PureComponent<Props, State> {
  16. debouncedSearch: any;
  17. constructor(props: Props) {
  18. super(props);
  19. this.state = {
  20. isLoading: false,
  21. };
  22. this.debouncedSearch = debounce(this.getDashboards, 300, {
  23. leading: true,
  24. trailing: true,
  25. });
  26. }
  27. getDashboards = (query = '') => {
  28. this.setState({ isLoading: true });
  29. return getBackendSrv()
  30. .search({ type: 'dash-db', query })
  31. .then((result: DashboardSearchHit[]) => {
  32. const dashboards = result.map((item: DashboardSearchHit) => {
  33. return {
  34. id: item.id,
  35. value: item.id,
  36. label: `${item.folderTitle ? item.folderTitle : 'General'}/${item.title}`,
  37. };
  38. });
  39. this.setState({ isLoading: false });
  40. return dashboards;
  41. });
  42. };
  43. render() {
  44. const { className, onSelected, currentDashboardId } = this.props;
  45. const { isLoading } = this.state;
  46. return (
  47. <div className="gf-form-inline">
  48. <div className="gf-form">
  49. <AsyncSelect
  50. className={className}
  51. isLoading={isLoading}
  52. isClearable={true}
  53. defaultOptions={true}
  54. loadOptions={this.debouncedSearch}
  55. onChange={onSelected}
  56. placeholder="Select dashboard"
  57. noOptionsMessage={() => 'No dashboards found'}
  58. value={currentDashboardId}
  59. />
  60. </div>
  61. </div>
  62. );
  63. }
  64. }