useLokiSyntax.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { useState, useEffect } from 'react';
  2. import Prism from 'prismjs';
  3. import { DataSourceStatus } from '@grafana/ui/src/types/datasource';
  4. import { AbsoluteTimeRange } from '@grafana/data';
  5. import LokiLanguageProvider from 'app/plugins/datasource/loki/language_provider';
  6. import { useLokiLabels } from 'app/plugins/datasource/loki/components/useLokiLabels';
  7. import { CascaderOption } from 'app/plugins/datasource/loki/components/LokiQueryFieldForm';
  8. import { useRefMounted } from 'app/core/hooks/useRefMounted';
  9. const PRISM_SYNTAX = 'promql';
  10. /**
  11. *
  12. * @param languageProvider
  13. * @description Initializes given language provider, exposes Loki syntax and enables loading label option values
  14. */
  15. export const useLokiSyntax = (
  16. languageProvider: LokiLanguageProvider,
  17. datasourceStatus: DataSourceStatus,
  18. absoluteRange: AbsoluteTimeRange
  19. ) => {
  20. const mounted = useRefMounted();
  21. // State
  22. const [languageProviderInitialized, setLanguageProviderInitilized] = useState(false);
  23. const [syntax, setSyntax] = useState(null);
  24. /**
  25. * Holds information about currently selected option from rc-cascader to perform effect
  26. * that loads option values not fetched yet. Based on that useLokiLabels hook decides whether or not
  27. * the option requires additional data fetching
  28. */
  29. const [activeOption, setActiveOption] = useState<CascaderOption[]>();
  30. const { logLabelOptions, setLogLabelOptions, refreshLabels } = useLokiLabels(
  31. languageProvider,
  32. languageProviderInitialized,
  33. activeOption,
  34. absoluteRange,
  35. datasourceStatus
  36. );
  37. // Async
  38. const initializeLanguageProvider = async () => {
  39. languageProvider.initialRange = absoluteRange;
  40. await languageProvider.start();
  41. Prism.languages[PRISM_SYNTAX] = languageProvider.getSyntax();
  42. if (mounted.current) {
  43. setLogLabelOptions(languageProvider.logLabelOptions);
  44. setSyntax(languageProvider.getSyntax());
  45. setLanguageProviderInitilized(true);
  46. }
  47. };
  48. // Effects
  49. useEffect(() => {
  50. initializeLanguageProvider();
  51. }, []);
  52. return {
  53. isSyntaxReady: languageProviderInitialized,
  54. syntax,
  55. logLabelOptions,
  56. setActiveOption,
  57. refreshLabels,
  58. };
  59. };