useLokiSyntax.ts 2.1 KB

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