getVariableQueryEditor.tsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import React, { useCallback } from 'react';
  2. import { DataQuery, DataSourceApi, DataSourceJsonData, QueryEditorProps, StandardVariableQuery } from '@grafana/data';
  3. import { getTemplateSrv } from '@grafana/runtime';
  4. import { importDataSourcePlugin } from '../../plugins/plugin_loader';
  5. import {
  6. hasCustomVariableSupport,
  7. hasDatasourceVariableSupport,
  8. hasLegacyVariableSupport,
  9. hasStandardVariableSupport,
  10. } from '../guard';
  11. import { VariableQueryEditorType } from '../types';
  12. import { LegacyVariableQueryEditor } from './LegacyVariableQueryEditor';
  13. export async function getVariableQueryEditor<
  14. TQuery extends DataQuery = DataQuery,
  15. TOptions extends DataSourceJsonData = DataSourceJsonData,
  16. VariableQuery extends DataQuery = TQuery
  17. >(
  18. datasource: DataSourceApi<TQuery, TOptions>,
  19. importDataSourcePluginFunc = importDataSourcePlugin
  20. ): Promise<VariableQueryEditorType> {
  21. if (hasCustomVariableSupport(datasource)) {
  22. return datasource.variables.editor;
  23. }
  24. if (hasDatasourceVariableSupport(datasource)) {
  25. const dsPlugin = await importDataSourcePluginFunc(datasource.meta!);
  26. if (!dsPlugin.components.QueryEditor) {
  27. throw new Error('Missing QueryEditor in plugin definition.');
  28. }
  29. return dsPlugin.components.QueryEditor ?? null;
  30. }
  31. if (hasStandardVariableSupport(datasource)) {
  32. return StandardVariableQueryEditor;
  33. }
  34. if (hasLegacyVariableSupport(datasource)) {
  35. const dsPlugin = await importDataSourcePluginFunc(datasource.meta!);
  36. return dsPlugin.components.VariableQueryEditor ?? LegacyVariableQueryEditor;
  37. }
  38. return null;
  39. }
  40. export function StandardVariableQueryEditor<
  41. TQuery extends DataQuery = DataQuery,
  42. TOptions extends DataSourceJsonData = DataSourceJsonData
  43. >({
  44. datasource: propsDatasource,
  45. query: propsQuery,
  46. onChange: propsOnChange,
  47. }: QueryEditorProps<any, TQuery, TOptions, StandardVariableQuery>) {
  48. const onChange = useCallback(
  49. (query: any) => {
  50. propsOnChange({ refId: 'StandardVariableQuery', query });
  51. },
  52. [propsOnChange]
  53. );
  54. return (
  55. <LegacyVariableQueryEditor
  56. query={propsQuery.query}
  57. onChange={onChange}
  58. datasource={propsDatasource}
  59. templateSrv={getTemplateSrv()}
  60. />
  61. );
  62. }